永远爱学习

导航

Django结合webservice

Django使用spyne写webservice

 

一、下载安装spyne

pip install spyne

二、

使用Django创建一个新的项目和app

urls

url(r'^information/', views.information_app),

 

views

# Create your views here.
#-*- coding: utf-8 -*-
import json

from django.shortcuts import HttpResponse
from django.views.decorators.csrf import csrf_exempt
# import logging
# logging.basicConfig(level=logging.DEBUG)
# from spyne import Application, rpc, ServiceBase,Integer, Unicode
from spyne import Application, rpc, ServiceBase, Unicode
from spyne import Iterable
from spyne.protocol.soap import Soap11
# from spyne.protocol.json import JsonDocument
from spyne.server.django import DjangoApplication


class HelloWorldService(ServiceBase):
@rpc(Unicode, _returns=Iterable(Unicode))
def ess_information(ctx, data):
dic = {"a":1,"b":2}
return HttpResponse(json.dumps(dic))

application = Application([HelloWorldService],
tns='spyne.examples.hello',
in_protocol=Soap11(validator='lxml'),
out_protocol=Soap11()
)

# This module resides in a package in your Django
# project.

information_app = csrf_exempt(DjangoApplication(application))

解释

@rpc(Unicode, Integer, _returns=Iterable(Unicode))    #如果上面在增加一个Integer,说明传入的第二个参数数组
def ess_information(ctx, data,num):    #传入的参数也需要变成两个

 

测试请求,我们使用suds来测试

安装suds模块

pip install suds-jurko

测试代码

复制代码
#-*- coding: utf-8 -*-
from suds.client import Client
import traceback

ip = "127.0.0.1"
port = "8000"
client = Client("http://%s:%s/information/?wsdl"%(ip, port))    #你请求的url

data = "HelloWord"

try:
    result = client.service.ess_information(data)
    print result
except:
    traceback.print_exc()
复制代码

如果像上面改成两个参数,则请求时也需要两个参数

result = client.service.ess_information(data,3)

posted on 2019-02-28 12:54  永远爱学习  阅读(1694)  评论(0)    收藏  举报