WebService是什么
WebService是一種跨編程語(yǔ)言和跨操作系統(tǒng)平臺(tái)的遠(yuǎn)程調(diào)用技術(shù)。
跨編程語(yǔ)言:就是說(shuō)服務(wù)端程序采用python編寫辜伟,客戶端程序則可以采用其他編程語(yǔ)言編寫(nodejs、java等)筝野;
跨操作系統(tǒng)平臺(tái):就是說(shuō)服務(wù)端程序和客戶端程序可以在不同的操作系統(tǒng)上運(yùn)行嫌松;
遠(yuǎn)程調(diào)用:就是一臺(tái)計(jì)算機(jī)A上的程序可以調(diào)用另一臺(tái)計(jì)算機(jī)B上一個(gè)對(duì)象的方法。eg: 銀聯(lián)提供給商場(chǎng)的pos刷卡系統(tǒng)邑蒋、天氣預(yù)報(bào)系統(tǒng)等姓蜂;
SOAP協(xié)議是什么
WebService通過(guò)http協(xié)議發(fā)送請(qǐng)求和接收結(jié)果時(shí),發(fā)送的請(qǐng)求內(nèi)容和結(jié)果內(nèi)容都是采用XML格式封裝的医吊,并增加一些特定的HTTP消息頭以聲明HTTP消息的內(nèi)容格式钱慢。這些特定的HTTP消息頭和XML內(nèi)容格式就是SOAP協(xié)議。
簡(jiǎn)而言之卿堂,SOAP協(xié)議 = HTTP協(xié)議 + XML數(shù)據(jù)格式
WSDL是什么
好比我們?nèi)ド痰曩I東西束莫,首先要知道商店里有什么東西可買,然后再來(lái)購(gòu)買草描,商家的做法就是張貼廣告海報(bào)麦箍。 WebService也一樣,WebService客戶端要調(diào)用一個(gè)WebService服務(wù)陶珠,首先要有知道這個(gè)服務(wù)的地址在哪挟裂,以及這個(gè)服務(wù)里有什么方 法可以調(diào)用,所以揍诽,WebService務(wù)器端首先要通過(guò)一個(gè)WSDL文件來(lái)說(shuō)明自己家里有啥服務(wù)可以對(duì)外調(diào)用诀蓉,服務(wù)是什么(服務(wù)中有哪些方法,方法接受 的參數(shù)是什么暑脆,返回值是什么)渠啤,服務(wù)的網(wǎng)絡(luò)地址用哪個(gè)url地址表示,服務(wù)通過(guò)什么方式來(lái)調(diào)用添吗。
WSDL(Web Services Description Language)就是這樣一個(gè)基于XML的語(yǔ)言沥曹,用于描述Web Service及其函數(shù)、參數(shù)和返回值。它是WebService客戶端和服務(wù)器端都 能理解的標(biāo)準(zhǔn)格式妓美。因?yàn)槭腔赬ML的僵腺,所以WSDL既是機(jī)器可閱讀的,又是人可閱讀的壶栋,這將是一個(gè)很大的好處辰如。一些最新的開發(fā)工具既能根據(jù)你的 Web service生成WSDL文檔,又能導(dǎo)入WSDL文檔贵试,生成調(diào)用相應(yīng)WebService的代理類代碼琉兜。
WSDL 文件保存在Web服務(wù)器上,通過(guò)一個(gè)url地址就可以訪問(wèn)到它毙玻⊥泱客戶端要調(diào)用一個(gè)WebService服務(wù)之前,要知道該服務(wù)的WSDL文件的地址桑滩。 WebService服務(wù)提供商可以通過(guò)兩種方式來(lái)暴露它的WSDL文件地址:1.注冊(cè)到UDDI服務(wù)器梧疲,以便被人查找;2.直接告訴給客戶端調(diào)用者施符。
WebService開發(fā)
1.服務(wù)端開發(fā)(基于python—spyne庫(kù))
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
server.py
~~~~~~~~~~~~~~~~~~~~~~~
Description of this file
:author: nut
:copyright: (c) 2020, Comcat
:date created: 2020-12-02
:python version: 3.5
"""
# Application is the glue between one or more service definitions, interface and protocol choices.
from spyne.application import Application
# @rpc 修飾器將方法公開為遠(yuǎn)程過(guò)程調(diào)用,并聲明其接收和返回的數(shù)據(jù)類型
from spyne.decorator import rpc
# spyne.service.ServiceBase是所有服務(wù)定義的基類
from spyne import ServiceBase
# 數(shù)據(jù)類型
from spyne import Integer, Unicode, Array, ComplexModel, Iterable, String
# soap1.1標(biāo)準(zhǔn)
from spyne.protocol.soap import Soap11
# 我們的服務(wù)是通過(guò)http進(jìn)行傳輸?shù)睦拚遥琖sgiApplication將包裝Application實(shí)例
from spyne.server.wsgi import WsgiApplication
# python內(nèi)置的wsgi服務(wù)器模塊:wsgiref戳吝,用于創(chuàng)建wsgi服務(wù)
from wsgiref.simple_server import make_server
# step1: 自定義數(shù)據(jù)結(jié)構(gòu)
class Person(ComplexModel):
name = Unicode
age = Integer
class PeopleResponse(ComplexModel):
name = Person
message = Unicode
# step2: 定義服務(wù)
class HelloWorldService(ServiceBase):
@rpc(Unicode, Integer, _returns=Iterable(Unicode))
def say_hello(self, name, times):
for i in range(times):
yield "Hello %s, It's the %s time to meet you." % (name, i + 1)
@rpc(Array(Person), _returns=Iterable(Unicode))
def say_hello_1(self, persons):
print('-------say_hello_1()--------')
if not persons:
yield 'None'
for person in persons:
print('name is : %s, age is %s.' % (person.name, person.age))
yield 'name is : %s, age is %s.' % (person.name, person.age)
class HelloWorldService2(ServiceBase):
@rpc(Array(String), _returns=Iterable(Unicode))
def say_hello_2(self, persons):
if not persons:
yield 'None'
for person in persons:
yield person
@rpc(Person, _returns=PeopleResponse)
def say_hello_3(self, person):
if not person:
return {}
else:
# return PeopleResponse(name=People(**person))
return {
"name": person,
"message": 'name is : %s, age is %s.' % (person.name, person.age)
}
# step3:
application = Application([HelloWorldService, HelloWorldService2],
'spyne.examples.hello',
in_protocol=Soap11(validator='lxml'),
out_protocol=Soap11())
# step4:
wsgi_application = WsgiApplication(application)
if __name__ == '__main__':
import logging
host = '127.0.0.1'
port = 8902
logging.basicConfig(level=logging.DEBUG)
# 指定日志記錄器的名稱,設(shè)置日志記錄級(jí)別
logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)
logging.info("listening to http://127.0.0.1:8902")
logging.info("wsdl is at: http://localhost:8902/?wsdl")
# step5: 創(chuàng)建wsgi服務(wù)
server = make_server(host, port, wsgi_application)
server.serve_forever()
2. 客戶端開發(fā)(Python & Nodejs)
suds - Python client
需安裝python第三方庫(kù)suds:pip install suds-py3
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
client_requests_suds.py
~~~~~~~~~~~~~~~~~~~~~~~
模擬客戶端請(qǐng)求——suds版本
:author: nut
:copyright: (c) 2020, Comcat
:date created: 2020-12-01
:python version: 3.7
"""
from suds.client import Client
host = '127.0.0.1'
port = 8902
client = Client('http://%s:%s/?wsdl' % (host, port))
# print(client) # 打印wsdl內(nèi)容
# print('=' * 20)
persons = client.service.say_hello('zhangsan', 2)
print(persons)
print('-' * 20)
person = {}
person['name'] = 'zhangsan'
person['age'] = 23
persons = client.factory.create('PersonArray')
persons.Person.append(person)
persons.Person.append(person)
person = client.service.say_hello_1(persons)
print(person)
print('=' * 20)
persons = client.factory.create('stringArray')
persons.string.append('lisi')
persons.string.append('zhangsan')
person = client.service.say_hello_2(persons)
print(person)
print('=' * 20)
pers = {"name": u"張三", "age": 23}
result = client.service.say_hello_3(pers)
print(result)
zeep - Python client
需安裝python第三方庫(kù)zeep:pip install zeep
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
client_requests_zeep.py
~~~~~~~~~~~~~~~~~~~~~~~
模擬客戶端請(qǐng)求——zeep版本
:author: nut
:copyright: (c) 2020, Comcat
:date created: 2020-12-02
:python version: 3.5
"""
from zeep import Client
ip = '127.0.0.1'
port = 8901
client = Client("http://%s:%s/?wsdl" % (ip, port))
# print(client.wsdl.dump()) # 解析wsdl
# print('=' * 20)
### say_hello
r = client.service.say_hello('zhansgan', 3)
print(r)
print('-' * 20)
### say_hello_1
factory = client.type_factory("ns0")
person = factory.Person(name='zhangsan', age=23)
persons = factory.PersonArray([person, person])
r = client.service.say_hello_1(persons)
print(r)
print('-' * 20)
### say_hello_2
factory = client.type_factory("ns0")
persons = factory.stringArray(["zhansgan", "lisi"])
r = client.service.say_hello_2(persons)
print(r)
print('-' * 20)
### say_hello_3
# factory = client.type_factory("ns0")
person = {"name": u"張三", "age": 23}
r = client.service.say_hello_3(person)
print(r)
<strong-soap> - node client (親測(cè)可用)
需安裝node第三方庫(kù)strong-soap:npm install strong-soap
var soap = require("strong-soap").soap;
var ip = '127.0.0.1';
var port = 8901;
var WSDL_URL = "http://" + ip + ":" + port + "/?wsdl";
soap.createClient(WSDL_URL, {}, function (err, client) {
client.setEndpoint(WSDL_URL)
// console.log(client)
// console.log("===============================================")
// console.log(client.describe())
// console.log("===============================================")
// 調(diào)用say_hello方法 (親測(cè)可行)
client.say_hello({"name": "ccc", "times": 2}, function (err, result) {
console.log("<say_hello>Err: ")
console.log(err)
console.log("<say_hello>Result: ")
console.log(result)
console.log("===============================================")
})
// say_hello_1 參數(shù)結(jié)構(gòu)
let arg_1 = {
"persons": {
"Person": [{"name": "zzz", "age": 23}, {"name": "aaa", "age": 18}
]
}
}
// 調(diào)用say_hello_1方法 (傳參可行)
client.say_hello_1(arg_1, function (err, result) {
console.log("<say_hello_1>Err: ")
console.log(err)
console.log("<say_hello_1>Result: ")
console.log(result)
console.log("===============================================")
})
// say_hello_2 參數(shù)結(jié)構(gòu)
let arg_2 = {
persons: {
string: ["aaa", "zzz"]
}
}
// 調(diào)用say_hello_2方法 (傳參可行)
client.say_hello_2(arg_2, function (err, result) {
console.log("<say_hello_2>Err: ")
console.log(err)
console.log("<say_hello_2>Result: ")
console.log(result)
console.log("===============================================")
})
// say_hello_3 參數(shù)結(jié)構(gòu)
let arg_3 = {
person: {
name: "aaa",
age: 24
}
}
// 調(diào)用say_hello_3方法 (傳參可行)
client.say_hello_3(arg_3, function (err, result) {
console.log("<say_hello_3>Err: ")
console.log(err)
console.log("<say_hello_3>Result: ")
console.log(result)
console.log("===============================================")
})
})
node:strong-soap開發(fā)客戶端贯涎,難點(diǎn)在于: complexType參數(shù)的構(gòu)造听哭。
上述node客戶端腳本執(zhí)行結(jié)果如下:
# 結(jié)果:
<say_hello>Err:
null
<say_hello>Result:
{ say_helloResult:
{ string:
[ 'Hello ccc, It\'s the 1 time to meet you.',
'Hello ccc, It\'s the 2 time to meet you.' ] } }
===============================================
<say_hello_1>Err:
null
<say_hello_1>Result:
{ say_hello_1Result:
{ string: [ 'name is : zzz, age is 23.', 'name is : aaa, age is 18.' ] } }
===============================================
<say_hello_2>Err:
null
<say_hello_2>Result:
{ say_hello_2Result: { string: [ 'aaa', 'zzz' ] } }
===============================================
<say_hello_3>Err:
null
<say_hello_3>Result:
{ say_hello_3Result:
{ name: { name: 'aaa', age: 24 },
message: 'name is : aaa, age is 24.' } }
===============================================