程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python development and testing WebService (soap) -win

編輯:Python

WebService Is a cross programming language and cross operating system platform remote call technology .


> understand webservice

1. On the face of it ,WebService It's an application that exposes itself to the outside world through Web Calling API, In other words, it can be programmed through Web To call this application . We call this WebService Is called the client , And to provide this WebService Is called the server side .

2. At a deeper level ,WebService Is a new platform for building interoperable distributed applications , It's a platform , It's a set of standards . It defines how an application works in Web Interoperability on the Internet , You can use any language you like , Write on any platform you like Web service , As long as we can get through Web service Standards query and access these services .

3.Web Service It's a platform independent , Low coupling , Self contained 、 Based on programmable web Applications for , Open... Can be used XML( A subset of the standard generic markup language ) Standard to describe 、 Release 、 Find out 、 Coordinate and configure these applications , Applications for developing distributed, interoperable applications . [1]

4.Web Service technology , It can make different applications run on different machines without the aid of additional 、 Specialized third-party software or hardware , You can exchange data or integrate with each other . basis Web Service Between the application of specification implementation , Whatever language they use 、 What is the platform or internal protocol , Can exchange data with each other .Web Service It's self describing 、 Self contained available network modules , Can perform specific business functions .Web Service It's also easy to deploy , Because they are based on some conventional industry standards and some existing technologies , Such as a subset of the standard General Markup Language XML、HTTP.Web Service Reduce the cost of application interface .Web Service It provides a common mechanism for the integration of business processes among the whole enterprise or even multiple organizations .

> Web The three cores of service

  • 1、Soap:
    SOAP(Simple Object Access Protocol, Simple object access protocol ) It's based on xml The agreement , Used in step-by-step applications can recognize . in addition ,SOAP There is no programming language defined by itself , This makes SOAP It can be delivered to various remote systems in the form of messages .

    SOAP The transmission protocol used , It can be HTTP,SMTP,POP3,JMS.

    SOAP It includes 4 part :
    01.“SOAP encapsulation (Envelope)”:
    Define what a description information describes , Who sent it , Who should deal with him , And how to deal with their framework .

    02.“SOAP Encoding rules ”:
    An instance that represents the data type that the application needs to use .

    03.“SOAP RPC":
    Represents a protocol for calling and answering in a remote procedure .

    04.“SOPA binding ”:
    Exchange information using underlying protocols .

  • 2.WSDL:
    WSDL(Web Service Description Language,web Service description language ) It's a XML file , He defines a given in an abstract way independent of the concrete language web Relevant operations and messages of service recipients .

  • 3.UDDI:
    UDDI(Universal Description Discovery and Integration, Unified description of discovery and integration protocols ) It's a norm , Defines and web Release of service related information , Discover and manage .
    END

> understand wsdl file

Only understand wsdl File can be called soap Type of web service , Let's say YCS Project as an example wsdl file :

explain : First of all, we can see that the address of the service is :http://47.106.68.247/ycsyth/webservices/ycsbizService, Corresponding wsdl The address of the file is http://47.106.68.247/ycsyth/webservices/ycsbizService?wsdl, The prefix of the address is soap, Explain that this service is based on soap1.1 Version of , Then we can see that the name of the service is IYcsBizServiceService,IYcsBizServiceService The binding of Port by IYcsBizServicePort, Then we find IYcsBizServicePort The binding type is IYcsBizService(portType name=“IYcsBizService”), from IYcsBizService We can see that , Support a method called doService, About doService For specific parameter information, see complexType name=“doService”.

> Python Library selection

Server development :

in the light of Python Of WebService Development , The most discussed libraries by developers are soaplib( Official address :http://soaplib.github.io/soaplib/2_0/index.html), But from its official website , Its latest version “soaplib-2.0.0-beta2” from 2011 year 3 It will not be updated after it is released in January . By reading soaplib Official documents of , It can be seen that it has turned to a new project after it is no longer maintained :rpclib( Official address :http://github.com/arskom/rpclib) Carry out follow-up development , But in rpclib Of readme in , It introduces rpclib Has been renamed spyne, And will continue to update ,so, Then choose spyne Developed .

spyne Official documents :http://spyne.io/docs/2.10/index.html

spyne github:https://github.com/arskom/spyne

  • spyne install :
pip install spyne
  • lxml install :
pip install lxml

Or download and python Matching version installation package https://pypi.python.org/pypi/lxml/3.6.0 Installation , Such as lxml-3.6.0.win-amd64-py2.7.exe (md5)

Client development

Client calls WebService General application suds library .

Use reference documents :https://fedorahosted.org/suds/wiki/Documentation

  • suds install :
pip install suds

> Knowledge development

Spyne Introduction

  • Protocols: agreement
  • Protocols define the rules for transmission of structured data
  • Transports: transmission
  • Transports, also protocols themselves, encapsulate protocol data in their free-form data sections.
  • Models: Pattern
  • Types like Unicode, Integer or ByteArray are all models. They reside in the spyne.model package.
  • Interface Documents: Interface document
  • Interface documents provide a machine-readable description of the expected input and output of the exposed method calls.
  • Serializers: Serializing objects
  • Serializers are currently not distinguished in Spyne code. They are the protocol-specific representations of a serialized Python object.

How your code is wrapped?

  • step1:

  • Your code is inside @rpc-wrapped methods in ServiceBase subclasses.

  • step2:

  • The ServiceBase subclasses in turn are wrapped by an Application instance.

  • The Application instantiation is used to assign input and output protocols to the exposed methods.

  • step3:

  • The Application instance is finally wrapped by a client or server transport that takes the responsibility of moving the bits around.

  • step4:

  • Deploying the service using Soap via Wsgi


> Code instance –( structure 1)

Directory structure

webservice
client.py
serve.py

Use Python Implement the server

server.py Server startup file
# -*- coding: utf-8 -*-
"""
preference:
http://spyne.io/docs/2.10/index.html
https://github.com/arskom/spyne/blob/master/examples/helloworld_soap.py
This is a simple HelloWorld example to show the basics of writing
a webservice using spyne, starting a server, and creating a service
client.
Here's how to call it using suds:
#>>> from suds.client import Client
#>>> hello_client = Client('http://localhost:8000/?wsdl')
#>>> hello_client.service.say_hello('punk', 5)
(stringArray){
string[] =
"Hello, punk",
"Hello, punk",
"Hello, punk",
"Hello, punk",
"Hello, punk",
}
#>>>
"""
# Application is the glue between one or more service definitions, interface and protocol choices.
from spyne import Application
# @rpc decorator exposes methods as remote procedure calls
# and declares the data types it accepts and returns
from spyne import rpc
# spyne.service.ServiceBase is the base class for all service definitions.
from spyne import ServiceBase
# The names of the needed types for implementing this service should be self-explanatory.
from spyne import Iterable, Integer, Unicode
from spyne.protocol.soap import Soap11
# Our server is going to use HTTP as transport, It’s going to wrap the Application instance.
from spyne.server.wsgi import WsgiApplication
# step1: Defining a Spyne Service
class HelloWorldService(ServiceBase):
@rpc(Unicode, Integer, _returns=Iterable(Unicode))
def say_hello(self, name, times):
"""Docstrings for service methods appear as documentation in the wsdl.
<b>What fun!</b>
@param name: the name to say hello to
@param times: the number of times to say hello
@return When returning an iterable, you can use any type of python iterable. Here, we chose to use generators.
"""
for i in range(times):
yield u'Hello, %s' % name
# step2: Glue the service definition, input and output protocols
soap_app = Application([HelloWorldService], 'spyne.examples.hello.soap',
in_protocol=Soap11(validator='lxml'),
out_protocol=Soap11())
# step3: Wrap the Spyne application with its wsgi wrapper
wsgi_app = WsgiApplication(soap_app)
if __name__ == '__main__':
import logging
from wsgiref.simple_server import make_server
# configure the python logger to show debugging output
# logging.basicConfig(level=logging.DEBUG)
# logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)
# logging.info("listening to http://127.0.0.1:8000")
# logging.info("wsdl is at: http://localhost:8000/?wsdl")
# step4:Deploying the service using Soap via Wsgi
# register the WSGI application as the handler to the wsgi server, and run the http server
print('WebService Started')
server = make_server('127.0.0.1', 8000, wsgi_app)
server.serve_forever()

Inspection services

After the server runs ,

Visit the browser check service http://localhost:8000/?wsdl

Output in browser wsdl file :

Use Python Implement client

client.py Client interface
# -*- coding: utf-8 -*-
from suds.client import Client # Import suds.client Under the module of Client class
wsdl_url = "http://localhost:8000/?wsdl"
def say_hello_test(url, name, times):
client = Client(url) # Create a webservice Interface object
resp = client.service.say_hello(name, times)
print(resp)
# client.service.say_hello(name, times) # Call getMobileCodeInfo Method , And pass in parameters
# req = str(client.last_sent()) # Save request message , Because it returns an instance , So it's going to be converted to str
# response = str(client.last_received()) # Save the return message , The returned is also an instance
# print (req) # Print request message
# print (response) # Print the return message
if __name__ == '__main__':
say_hello_test(wsdl_url, 'Milton', 2)

The interface test

Activate the weapon

Execute client

The client results are as follows

(stringArray){
string[] =
"Hello, Milton",
"Hello, Milton",
}

> Code instance –( structure 2)

Directory structure

webservice
client
client.py
server
app.py
service.py

Use Python Implement the server

service.py Server startup file
# -*- coding: utf-8 -*-
"""
preference:
http://spyne.io/docs/2.10/index.html
https://github.com/arskom/spyne/blob/master/examples/helloworld_soap.py
This is a simple HelloWorld example to show the basics of writing
a webservice using spyne, starting a server, and creating a service
client.
Here's how to call it using suds:
#>>> from suds.client import Client
#>>> hello_client = Client('http://localhost:8000/?wsdl')
#>>> hello_client.service.say_hello('punk', 5)
(stringArray){
string[] =
"Hello, punk",
"Hello, punk",
"Hello, punk",
"Hello, punk",
"Hello, punk",
}
#>>>
"""
import json
import os
# Application is the glue between one or more service definitions, interface and protocol choices.
# An application is one or more service definitions 、 The glue between interface and protocol choice
from spyne import Application
# @rpc decorator exposes methods as remote procedure calls Decorators expose methods as remote procedure calls
# and declares the data types it accepts and returns And declare the data types it accepts and returns
from spyne import rpc
# spyne.service.ServiceBase is the base class for all service definitions.
from spyne import ServiceBase
# The names of the needed types for implementing this service should be self-explanatory.
# The name of the type required to implement the service should be self explanatory
from spyne import Iterable, Integer, Unicode
from spyne.protocol.soap import Soap11
# Our server is going to use HTTP as transport, It’s going to wrap the Application instance.
from spyne.server.wsgi import WsgiApplication
from app import PyWebService # Be careful : Reference herein app.py In file PyWebService class
#step1: Defining a Spyne Service
# class PyWebService(ServiceBase):
# @rpc(Unicode, Integer, _returns=Iterable(Unicode))
# def say_hello(self, name, times):
# """Docstrings for service methods appear as documentation in the wsdl.
# <b>What fun!</b>
# @param name: the name to say hello to
# @param times: the number of times to say hello
# @return When returning an iterable, you can use any type of python iterable. Here, we chose to use generators.
# """
# for i in range(times):
# return u'Hello, %s' % name
# step2: Glue the service definition, input and output protocols
soap_app = Application([PyWebService], 'PyWebService',
in_protocol=Soap11(validator='lxml'),
out_protocol=Soap11())
# step3: Wrap the Spyne application with its wsgi wrapper
wsgi_app = WsgiApplication(soap_app)
if __name__ == '__main__':
import logging
from wsgiref.simple_server import make_server
# configure the python logger to show debugging output
# logging.basicConfig(level=logging.DEBUG)
# logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG)
# logging.info("listening to http://127.0.0.1:8000")
# logging.info("wsdl is at: http://localhost:8000/?wsdl")
host = "127.0.0.1"
port = 8000
# step4:Deploying the service using Soap via Wsgi
# register the WSGI application as the handler to the wsgi server, and run the http server
server = make_server(host, port, wsgi_app)
print('WebService Started')
print('http://' + host + ':' + str(port) + '/?wsdl')
server.serve_forever()
app.py webservice Interface
# -*- coding: utf-8 -*-
import json
from spyne import ServiceBase, rpc, Double
from spyne import Integer, Unicode, String, Iterable
class User(object):
def __init__(self, age, user_name):
self.age = age
self.user_name = user_name
self.sex = 0
def get_user_list(self, current_page, page_size):
l = []
for i in range(10):
l.append({'age': self.age, 'sex': self.sex, 'user_name': self.user_name})
return l
user_mgr = User(18, 'Tom')
class PyWebService(ServiceBase):
...
@rpc(Unicode, Integer, _returns=Iterable(Unicode))
def say_hello(self, name, times):
"""Docstrings for service methods appear as documentation in the wsdl.
<b>What fun!</b>
@param name: the name to say hello to
@param times: the number of times to say hello
@return When returning an iterable, you can use any type of python iterable. Here, we chose to use generators.
"""
for i in range(times):
return u'Hello, %s' % name
@rpc(_returns=Unicode)
def get_version(self):
"""
Get system version
:return:
"""
return json.dumps({'version': 1.0})
@rpc(Integer, Integer, _returns=Unicode)
def get_user_list(self, current_page, page_size):
"""
Get the list of users
:return:
"""
return json.dumps(user_mgr.get_user_list(current_page, page_size))

Inspection services

After the server runs ,

Visit the browser check service http://localhost:8000/?wsdl

Output in browser wsdl file :

Use Python Implement client

client.py Client interface
# -*- coding: utf-8 -*-
import json
from suds.client import Client # Import suds.client Under the module of Client class
wsdl_url = "http://localhost:8000/?wsdl"
def client_operation(url, name, times):
client = Client(url) # Create a webservice Interface object
print(client) # View all the parameters carried by the defined methods and requests , Back to Methods The method defined in , Including the parameters and parameter types that the request needs to carry .
resp = client.service.get_version() # Call get_version Method , No parameter
print(json.loads(resp))
resp1 = client.service.say_hello(name, times) # Call getMobileCodeInfo Method , And pass in parameters
print(str(resp1))
resp2 = client.service.get_user_list(3,4)
print(json.loads(resp2))
if __name__ == '__main__':
client_operation(wsdl_url, 'Milton', 2)

The interface test

Activate the weapon

Execute client

The client results are as follows

Suds ( https://fedorahosted.org/suds/ ) version: 1.1.1
Service ( PyWebService ) tns="PyWebService"
Prefixes (1)
ns0 = "PyWebService"
Ports (1):
(Application)
Methods (3):
get_user_list(xs:integer current_page, xs:integer page_size)
get_version()
say_hello(xs:string name, xs:integer times)
Types (7):
get_user_list
get_user_listResponse
get_version
get_versionResponse
say_hello
say_helloResponse
stringArray
{'version': 1.0}
(stringArray){
string[] =
"H",
"e",
"l",
"l",
"o",
",",
" ",
"M",
"i",
"l",
"t",
"o",
"n",
}
[{'age': 18, 'sex': 0, 'user_name': 'Tom'}, {'age': 18, 'sex': 0, 'user_name': 'Tom'}, {'age': 18, 'sex': 0, 'user_name': 'Tom'}, {'age': 18, 'sex': 0, 'user_name': 'Tom'}, {'age': 18, 'sex': 0, 'user_name': 'Tom'}, {'age': 18, 'sex': 0, 'user_name': 'Tom'}, {'age': 18, 'sex': 0, 'user_name': 'Tom'}, {'age': 18, 'sex': 0, 'user_name': 'Tom'}, {'age': 18, 'sex': 0, 'user_name': 'Tom'}, {'age': 18, 'sex': 0, 'user_name': 'Tom'}]

Refer to the connection :
http://47.106.68.247/ycsyth/webservices/ycsbizService?wsdl
https://blog.csdn.net/qq_33196814/article/details/122303882
https://www.cnblogs.com/guanfuchang/p/5985070.html


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved