WebService开发: 服务端[Python] + 客户端[python & nodejs]

WebService是什么

WebService是一种跨编程语言和跨操作系统平台的远程调用技术。

跨编程语言:就是说服务端程序采用python编写,客户端程序则可以采用其他编程语言编写(nodejs、java等);
跨操作系统平台:就是说服务端程序和客户端程序可以在不同的操作系统上运行;
远程调用:就是一台计算机A上的程序可以调用另一台计算机B上一个对象的方法。eg: 银联提供给商场的pos刷卡系统、天气预报系统等;

SOAP协议是什么

WebService通过http协议发送请求和接收结果时,发送的请求内容和结果内容都是采用XML格式封装的,并增加一些特定的HTTP消息头以声明HTTP消息的内容格式。这些特定的HTTP消息头和XML内容格式就是SOAP协议。
简而言之,SOAP协议 = HTTP协议 + XML数据格式

WSDL是什么

好比我们去商店买东西,首先要知道商店里有什么东西可买,然后再来购买,商家的做法就是张贴广告海报。 WebService也一样,WebService客户端要调用一个WebService服务,首先要有知道这个服务的地址在哪,以及这个服务里有什么方 法可以调用,所以,WebService务器端首先要通过一个WSDL文件来说明自己家里有啥服务可以对外调用,服务是什么(服务中有哪些方法,方法接受 的参数是什么,返回值是什么),服务的网络地址用哪个url地址表示,服务通过什么方式来调用。

WSDL(Web Services Description Language)就是这样一个基于XML的语言,用于描述Web Service及其函数、参数和返回值。它是WebService客户端和服务器端都 能理解的标准格式。因为是基于XML的,所以WSDL既是机器可阅读的,又是人可阅读的,这将是一个很大的好处。一些最新的开发工具既能根据你的 Web service生成WSDL文档,又能导入WSDL文档,生成调用相应WebService的代理类代码。

WSDL 文件保存在Web服务器上,通过一个url地址就可以访问到它。客户端要调用一个WebService服务之前,要知道该服务的WSDL文件的地址。 WebService服务提供商可以通过两种方式来暴露它的WSDL文件地址:1.注册到UDDI服务器,以便被人查找;2.直接告诉给客户端调用者。

WebService开发

1.服务端开发(基于python—spyne库)

#!/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 修饰器将方法公开为远程过程调用,并声明其接收和返回的数据类型
from spyne.decorator import rpc
# spyne.service.ServiceBase是所有服务定义的基类
from spyne import ServiceBase
# 数据类型
from spyne import Integer, Unicode, Array, ComplexModel, Iterable, String
# soap1.1标准
from spyne.protocol.soap import Soap11
# 我们的服务是通过http进行传输的,WsgiApplication将包装Application实例
from spyne.server.wsgi import WsgiApplication
# python内置的wsgi服务器模块:wsgiref,用于创建wsgi服务
from wsgiref.simple_server import make_server

# step1: 自定义数据结构
class Person(ComplexModel):
    name = Unicode
    age = Integer

class PeopleResponse(ComplexModel):
    name = Person
    message = Unicode

# step2: 定义服务
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)
    # 指定日志记录器的名称,设置日志记录级别
    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:  创建wsgi服务
    server = make_server(host, port, wsgi_application)
    server.serve_forever()

2. 客户端开发(Python & Nodejs)

suds - Python client

需安装python第三方库suds:pip install suds-py3

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    client_requests_suds.py
    ~~~~~~~~~~~~~~~~~~~~~~~

    模拟客户端请求——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内容
# 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第三方库zeep:pip install zeep

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    client_requests_zeep.py
    ~~~~~~~~~~~~~~~~~~~~~~~

    模拟客户端请求——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 (亲测可用)

需安装node第三方库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("===============================================")

    // 调用say_hello方法 (亲测可行)
    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 参数结构
    let arg_1 =  {
        "persons": {
            "Person": [{"name": "zzz", "age": 23}, {"name": "aaa", "age": 18}
            ]
        }
    }
    // 调用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 参数结构
    let arg_2 = {
        persons: {
            string: ["aaa", "zzz"]
        }
    }
    // 调用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 参数结构
    let arg_3 = {
        person: {
            name: "aaa",
            age: 24
        }
    }
    // 调用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开发客户端,难点在于: complexType参数的构造
上述node客户端脚本执行结果如下:

# 结果:
<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.' } }
===============================================

源码:https://gitee.com/handsomeCzp/web-service-sample

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 229,908评论 6 541
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 99,324评论 3 429
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 178,018评论 0 383
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,675评论 1 317
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 72,417评论 6 412
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,783评论 1 329
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,779评论 3 446
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,960评论 0 290
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,522评论 1 335
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 41,267评论 3 358
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,471评论 1 374
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 39,009评论 5 363
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,698评论 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 35,099评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,386评论 1 294
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 52,204评论 3 398
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,436评论 2 378