https://github.com/pycontribs/jira/issues/603 """ from spyne.application import Application from spyne.decorator import rpc from spyne.model.complex import Iterable from spyne.model.primitive.string import Unicode from spyne.protocol.soap import Soap11 from spyne.server.wsgi import WsgiApplication from spyne.service import ServiceBase class HelloWorldService(ServiceBase): @rpc(Unicode, _returns=Iterable(Unicode)) def hello(ctx, name): return f'Hello, {name}' application = Application([HelloWorldService], tns='spyne.examples.hello', in_protocol=Soap11(), out_protocol=Soap11() ) if __name__ == '__main__': from wsgiref.simple_server import make_server wsgi_app = WsgiApplication(application) server = make_server('0.0.0.0', 9100, wsgi_app) server.serve_forever()
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 # """pod being plain old data""" import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger('spyne.protocol.xml') logger.setLevel(logging.DEBUG) from spyne.application import Application from spyne.test.interop.server._service import services from spyne.protocol.http import HttpRpc from spyne.server.wsgi import WsgiApplication httprpc_soap_application = Application(services, 'spyne.test.interop.server.httprpc.pod', in_protocol=HttpRpc(), out_protocol=HttpRpc()) host = "127.0.0.1" port = 9751 def main(): try: from wsgiref.simple_server import make_server from wsgiref.validate import validator wsgi_application = WsgiApplication(httprpc_soap_application) server = make_server(host, port, validator(wsgi_application)) logger.info('Starting interop server at %s:%s.' % ('0.0.0.0', 9751)) logger.info('WSDL is at: /?wsdl')
''' Docstrings for service methods appear as documentation in the wsdl. <b>What fun!</b> @param name the name to say hello to @param the number of times to say hello @return the completed array ''' for i in range(times): yield u'Hello, %s' % name if __name__ == '__main__': from wsgiref.simple_server import make_server 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") application = Application([HelloWorldService], 'spyne.examples.hello.soap', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) wsgi_application = WsgiApplication(application) server = make_server('127.0.0.1', 8000, wsgi_application) server.serve_forever()
from protocol import SvgClock tns = 'spyne.examples.multiple_protocols' port = 9910 host = '127.0.0.1' class HelloWorldService(ServiceBase): @srpc(_returns=DateTime) def get_utc_time(): return datetime.utcnow() if __name__ == '__main__': rest = Application([HelloWorldService], tns=tns, in_protocol=HttpRpc(), out_protocol=HttpRpc()) xml = Application([HelloWorldService], tns=tns, in_protocol=HttpRpc(), out_protocol=XmlDocument()) soap = Application([HelloWorldService], tns=tns, in_protocol=HttpRpc(), out_protocol=Soap11()) html = Application([HelloWorldService], tns=tns, in_protocol=HttpRpc(),
def test_rpc(self): data = {"a": "b", "c": "d"} class KeyValuePair(ComplexModel): key = Unicode value = Unicode class Service(ServiceBase): @rpc(String(max_occurs='unbounded'), _returns=Array(KeyValuePair), _in_variable_names={'keys': 'key'}) def get_values(ctx, keys): for k in keys: yield KeyValuePair(key=k, value=data[k]) application = Application( [Service], in_protocol=MessagePackRpc(), out_protocol=MessagePackRpc(ignore_wrappers=False), name='Service', tns='tns') server = WsgiApplication(application) input_string = msgpack.packb([0, 0, "get_values", [["a", "c"]]]) input_stream = BytesIO(input_string) ret = server( { 'CONTENT_LENGTH': str(len(input_string)), 'CONTENT_TYPE': 'application/x-msgpack', 'HTTP_CONNECTION': 'close', 'HTTP_CONTENT_LENGTH': str(len(input_string)), 'HTTP_CONTENT_TYPE': 'application/x-msgpack', 'PATH_INFO': '/', 'QUERY_STRING': '', 'SERVER_NAME': 'localhost', 'SERVER_PORT': '7000', 'REQUEST_METHOD': 'POST', 'wsgi.url_scheme': 'http', 'wsgi.input': input_stream, }, start_response) ret = b''.join(ret) print(repr(ret)) print(msgpack.unpackb(ret)) s = msgpack.packb([ 1, 0, None, { 'get_valuesResponse': { 'get_valuesResult': [ { "KeyValuePair": { 'value': 'b', 'key': 'a' } }, { "KeyValuePair": { 'value': 'd', 'key': 'c' } }, ] } } ]) print(s) assert ret == s
# import logging logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.msgpack').setLevel(logging.DEBUG) logger = logging.getLogger('spyne.test.interop.server.msgpackrpc_http_basic') from spyne.test.interop.server import get_open_port from spyne.server.wsgi import WsgiApplication from spyne.test.interop.server._service import services from spyne.application import Application from spyne.protocol.msgpack import MessagePackRpc msgpackrpc_application = Application( services, 'spyne.test.interop.server', in_protocol=MessagePackRpc(validator='soft'), out_protocol=MessagePackRpc()) host = '127.0.0.1' port = [0] def main(): try: from wsgiref.simple_server import make_server from wsgiref.validate import validator if port[0] == 0: port[0] = get_open_port() wsgi_application = WsgiApplication(msgpackrpc_application)
class titi(MyClass): player = ('do') def __init__(self): print('toto') self.player = 're' @rpc(Unicode, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, name, times): # @NoSelf for i in range(times): # @UnusedVariable yield 'Hello, %s' % name application = Application([titi], tns='spyne.examples.hello', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) class Custom_RemoteProcedure(RemoteProcedureBase): def __call__(self, *args, **kwargs): # there's no point in having a client making the same request more than # once, so if there's more than just one context, it's rather a bug. # The comma-in-assignment trick is a pedantic way of getting the first # and the only variable from an iterable. so if there's more than one # element in the iterable, it'll fail miserably. self.ctx, = self.contexts self.get_out_object(self.ctx, args, kwargs) self.get_out_string(self.ctx) # self.ctx.out_string[0] = self.ctx.out_string[0].replace('tns:', '').replace('tns=', '') # self.ctx.out_string[0] = test_ok
from spyne.protocol.soap import Soap11 from spyne.server.django import DjangoApplication from spyne.service import ServiceBase from .models import Student class SoapService(ServiceBase): @rpc(Integer(nillable=False), _returns=Unicode) def student_details(ctx, student_id): return_value = "Student doesn't exist." try: student_info = Student.objects.get(student_id=student_id) return_value = 'Name: {}\nEmail: {}\nPhone Number: {}\nAddress: {}\nEntry points: {}'.format( student_info.fullname, student_info.email, student_info.phoneNumber, student_info.address, student_info.entryPoints) except: print("Details Not Available") return return_value soap_app = Application( [SoapService], tns='django.studentsSOAP_UI.student_register', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), ) django_soap_application = DjangoApplication(soap_app) student_soap = csrf_exempt(django_soap_application)
def __init__(self, nombre, costo): # don't forget to call parent class initializer super(BndBox, self).__init__() self.nombre = nombre self.costo = costo class SoapService(ServiceBase): @rpc(_returns=(Unicode)) def tomarplanes(ctx): planes = TipoPlan.objects.all() listaObjetos = [] for plan in planes: print(str(plan.nombre) + ":" + str(plan.costo)) listaObjetos.append(str(plan.nombre) + ":" + str(plan.costo)) return ', '.join(listaObjetos) soap_app = Application( [SoapService], tns='django.soap.requisitos', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), ) django_soap_application = DjangoApplication(soap_app) my_soap_application = csrf_exempt(django_soap_application) # Create your views here.
def test_complex_array(self): v = [ CM(i=1, s='a'), CM(i=2, s='b'), CM(i=3, s='c'), CM(i=4, s='d'), ] class SomeService(ServiceBase): @srpc(_returns=Array(CM)) def some_call(): return v app = Application([SomeService], 'tns', in_protocol=HttpRpc(), out_protocol=HtmlRowTable(field_type_name_attr=None)) server = WsgiApplication(app) out_string = call_wsgi_app_kwargs(server) show(html.fromstring(out_string), 'TestHtmlRowTable.test_complex_array') #FIXME: Needs a proper test with xpaths and all. assert out_string.decode('utf8') == \ '<div>' \ '<table class="CM">' \ '<tbody>' \ '<tr>' \ '<th class="i">i</th>' \ '<td class="i">1</td>' \ '</tr>' \ '<tr>' \ '<th class="s">s</th>' \ '<td class="s">a</td>' \ '</tr>' \ '</tbody>' \ '</table>' \ '<table class="CM">' \ '<tbody>' \ '<tr>' \ '<th class="i">i</th>' \ '<td class="i">2</td>' \ '</tr>' \ '<tr>' \ '<th class="s">s</th>' \ '<td class="s">b</td>' \ '</tr>' \ '</tbody>' \ '</table>' \ '<table class="CM">' \ '<tbody>' \ '<tr>' \ '<th class="i">i</th>' \ '<td class="i">3</td>' \ '</tr>' \ '<tr>' \ '<th class="s">s</th>' \ '<td class="s">c</td>' \ '</tr>' \ '</tbody>' \ '</table>' \ '<table class="CM">' \ '<tbody>' \ '<tr>' \ '<th class="i">i</th>' \ '<td class="i">4</td>' \ '</tr>' \ '<tr>' \ '<th class="s">s</th>' \ '<td class="s">d</td>' \ '</tr>' \ '</tbody>' \ '</table>' \ '</div>'
return SoapResponse(str_status='false', str_menssagem=msg) return SoapResponse(str_status='true', str_menssagem='Cancelamento realizado com sucesso') def _method_return_string(ctx): ctx.out_string[0] = ctx.out_string[0].replace(b'tns:', b'') SolicitacaoService.event_manager.add_listener('method_return_string', _method_return_string) soap_app = Application( [SolicitacaoService], tns=NS, in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), ) django_soap_application = DjangoApplication(soap_app) env = environ.Env() API_URL = env.str('API_URL', default=None) if API_URL: django_soap_application.doc.wsdl11.build_interface_document( API_URL + '/webserver/solicitacao-remessa/') solicitacao_application = csrf_exempt(django_soap_application)
def test_complex(self): class SomeService(ServiceBase): @srpc(CCM, _returns=CCM) def some_call(ccm): return ccm app = Application([SomeService], 'tns', in_protocol=HttpRpc(hier_delim="_"), out_protocol=HtmlRowTable(field_type_name_attr=None)) server = WsgiApplication(app) out_string = call_wsgi_app_kwargs(server, 'some_call', ccm_c_s='abc', ccm_c_i='123', ccm_i='456', ccm_s='def') elt = html.fromstring(out_string) show(elt, "TestHtmlRowTable.test_complex") # Here's what this is supposed to return """ <table class="CCM"> <tbody> <tr> <th class="i">i</th> <td class="i">456</td> </tr> <tr class="c"> <th class="c">c</th> <td class="c"> <table class="c"> <tbody> <tr> <th class="i">i</th> <td class="i">123</td> </tr> <tr> <th class="s">s</th> <td class="s">abc</td> </tr> </tbody> </table> </td> </tr> <tr> <th class="s">s</th> <td class="s">def</td> </tr> </tbody> </table> """ print(html.tostring(elt, pretty_print=True)) resp = elt.find_class('CCM') assert len(resp) == 1 assert elt.xpath('tbody/tr/th[@class="i"]/text()')[0] == 'i' assert elt.xpath('tbody/tr/td[@class="i"]/text()')[0] == '456' assert elt.xpath( 'tbody/tr/td[@class="c"]//th[@class="i"]/text()')[0] == 'i' assert elt.xpath( 'tbody/tr/td[@class="c"]//td[@class="i"]/text()')[0] == '123' assert elt.xpath( 'tbody/tr/td[@class="c"]//th[@class="s"]/text()')[0] == 's' assert elt.xpath( 'tbody/tr/td[@class="c"]//td[@class="s"]/text()')[0] == 'abc' assert elt.xpath('tbody/tr/th[@class="s"]/text()')[0] == 's' assert elt.xpath('tbody/tr/td[@class="s"]/text()')[0] == 'def'
def test_rpc(self): import sqlalchemy from sqlalchemy import sql class KeyValuePair(TableModel, self.DeclarativeBase): __tablename__ = 'key_value_store' __namespace__ = 'punk' key = Column(sqlalchemy.String(100), nullable=False, primary_key=True) value = Column(sqlalchemy.String, nullable=False) self.metadata.create_all(self.engine) import hashlib session = self.Session() for i in range(1, 10): key = str(i) m = hashlib.md5() m.update(key) value = m.hexdigest() session.add(KeyValuePair(key=key, value=value)) session.commit() from spyne.service import ServiceBase from spyne.model.complex import Array from spyne.model.primitive import String class Service(ServiceBase): @rpc(String(max_occurs='unbounded'), _returns=Array(KeyValuePair), _in_variable_names={ 'keys': 'key' } ) def get_values(ctx, keys): session = self.Session() return session.query(KeyValuePair).filter(sql.and_( KeyValuePair.key.in_(keys) )).order_by(KeyValuePair.key) application = Application([Service], in_protocol=HttpRpc(), out_protocol=Soap11(), name='Service', tns='tns' ) server = WsgiApplication(application) initial_ctx = WsgiMethodContext(server, { 'REQUEST_METHOD': 'GET', 'QUERY_STRING': 'key=1&key=2&key=3', 'PATH_INFO': '/get_values', 'SERVER_NAME': 'localhost', }, 'some-content-type') ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) i = 0 for e in ctx.out_document[0][0][0]: i+=1 key = str(i) m = hashlib.md5() m.update(key) value = m.hexdigest() _key = e.find('{%s}key' % KeyValuePair.get_namespace()) _value = e.find('{%s}value' % KeyValuePair.get_namespace()) print((_key, _key.text)) print((_value, _value.text)) self.assertEquals(_key.text, key) self.assertEquals(_value.text, value)
'requestId': { 'value': requestId, }, 'checkpoint': { 'value': False, }, 'destination': { 'value': False } } } headers = {'Content-type': 'application/json'} json_payload = json.dumps(payload) r = requests.post('http://localhost:8080/engine-rest/message', headers=headers, data=json_payload) if (r.status_code == 200 or r.status_code == 204): return 'Insurance Created' else: return 'Failed to Create Insurance' logistic_service = Application([LogisticService], tns='com.if4150.logistic', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) django_logistic_service = DjangoApplication(logistic_service) logistic_service = csrf_exempt(django_logistic_service)
""" Mutalyzer SOAP/1.1 web service. """ from __future__ import unicode_literals from spyne.application import Application from spyne.protocol.soap import Soap11 import mutalyzer from mutalyzer.services import rpc #: SOAP/1.1 application. application = Application([rpc.MutalyzerService], tns=mutalyzer.SOAP_NAMESPACE, in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), name='Mutalyzer')
aux.cliente = p.cliente if len(p.cliente.foto) > 3: aux.cliente.tipo = p.cliente.foto.split(".") aux.cliente.tipo = aux.cliente.tipo[len(aux.cliente.tipo) - 1] in_file = open(CLIENT_IMAGES + p.cliente.foto, "rb") d = in_file.read() fo = base64.b64encode(d) aux.cliente.foto = fo.decode('ascii') in_file.close() else: aux.cliente.foto = " " res.append(aux) return [True, res] else: return [False, []] soap_app = Application( [SoapService], tns='django.soap.service', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(polymorphic=True), ) def consulta(): django_soap_app = DjangoApplication(soap_app) my_soap = csrf_exempt(django_soap_app) return my_soap
def getSpyneApplications(wof_obj_1_0, wof_obj_1_1, templates=None): # wof_obj_1_0 = wof_1_0.WOF(dao, config_file) # wof_obj_1_1 = wof_1_1.WOF_1_1(dao,config_file) sensorNetwork = wof_obj_1_0.network.replace('/', '').lower() soap_app_1_0 = Application( [wml10(wof_obj_1_0, Unicode, _SERVICE_PARAMS["s_type"])], tns=_SERVICE_PARAMS["wml10_tns"], name=sensorNetwork + '_svc_' + _SERVICE_PARAMS["wml10_soap_name"], in_protocol=wofSoap11(validator='lxml'), out_protocol=Soap11(), ) rest_app_1_0 = Application( [wml10(wof_obj_1_0, AnyXml, _SERVICE_PARAMS["r_type"])], tns=_SERVICE_PARAMS["wml10_tns"], name=sensorNetwork + '_svc_' + _SERVICE_PARAMS["wml10_rest_name"], in_protocol=HttpRpc(validator='soft'), out_protocol=XmlDocument(), ) soap_app_1_1 = Application( [wml11(wof_obj_1_1, Unicode, _SERVICE_PARAMS["s_type"])], tns=_SERVICE_PARAMS["wml11_tns"], name=sensorNetwork + '_svc_' + _SERVICE_PARAMS["wml11_soap_name"], in_protocol=wofSoap11(validator='lxml'), out_protocol=Soap11(), ) rest_app_1_1 = Application( [wml11(wof_obj_1_1, AnyXml, _SERVICE_PARAMS["r_type"])], tns=_SERVICE_PARAMS["wml11_tns"], name=sensorNetwork + '_svc_' + _SERVICE_PARAMS["wml11_rest_name"], in_protocol=HttpRpc(validator='soft'), out_protocol=XmlDocument(), ) # need to update template to 1_1 object. # <gml:Definition gml:id="methodCode-{{ method_result.MethodID }}"> # File "\lib\site-packages\jinja2\environment.py", line 408, in getattr # return getattr(obj, attribute) # UndefinedError: 'method_result' is undefined rest_app_2 = Application( [wml2(wof_obj_1_0, Unicode, _SERVICE_PARAMS["r_type"])], tns=_SERVICE_PARAMS["wml11_tns"], name=sensorNetwork + '_svc_' + _SERVICE_PARAMS["wml11_rest_name"], in_protocol=HttpRpc(validator='soft'), # out_protocol=XmlDocument(), out_protocol=HttpRpc(mime_type='text/xml'), ) rest_wsgi_wrapper_1_0 = WsgiApplication(rest_app_1_0) soap_wsgi_wrapper_1_0 = WsgiApplication(soap_app_1_0) rest_wsgi_wrapper_1_1 = WsgiApplication(rest_app_1_1) soap_wsgi_wrapper_1_1 = WsgiApplication(soap_app_1_1) rest_wsgi_wrapper_2_0 = WsgiApplication(rest_app_2) spyneApps = { '/' + sensorNetwork + '/rest/1_0': rest_wsgi_wrapper_1_0, '/' + sensorNetwork + '/rest/1_1': rest_wsgi_wrapper_1_1, '/' + sensorNetwork + '/soap/cuahsi_1_0': soap_wsgi_wrapper_1_0, '/' + sensorNetwork + '/soap/cuahsi_1_1': soap_wsgi_wrapper_1_1, '/' + sensorNetwork + '/rest/2': rest_wsgi_wrapper_2_0, } templatesPath = None if templates is None: if wof_obj_1_1._config is not None: templatesPath = os.path.abspath(wof_obj_1_1._config.TEMPLATES) else: templatesPath = os.path.abspath(templates) if templatesPath: if not os.path.exists(templatesPath): logging.info('Templates path: {} NOT exists {}'.format( templatesPath, os.path.exists(templatesPath))) templatesPath = _TEMPLATES logging.info('default temnplate path: %s' % templatesPath) # needs to be service_baseURL. in config wof_obj_1_0.service_wsdl wsdl10 = WofWSDL_1_0(soap_wsgi_wrapper_1_0.doc.wsdl11.interface, templates=templatesPath, network=sensorNetwork, version=version) # soap_wsgi_wrapper_1_0._wsdl = wsdl10.build_interface_document('/'+ sensorNetwork+'/soap/wateroneflow',templatesPath) #.get_wsdl_1_0('/'+ sensorNetwork+'/soap/wateroneflow') # noqa soap_wsgi_wrapper_1_0.event_manager.add_listener( 'wsdl', wsdl10.on_get_wsdl_1_0_) # path: /{sensorNetwork}/soap/wateroneflow_1_1/.wsdl returns the WSDL. wsdl11 = WofWSDL_1_1(soap_wsgi_wrapper_1_1.doc.wsdl11.interface, templates=templatesPath, network=sensorNetwork, version=version) # soap_wsgi_wrapper_1_1._wsdl = wsdl11.build_interface_document('/'+ sensorNetwork+'/soap/wateroneflow_1_1',templatesPath) #.get_wsdl_1_0('/'+ sensorNetwork+'/soap/wateroneflow') # noqa soap_wsgi_wrapper_1_1.event_manager.add_listener( 'wsdl', wsdl11.on_get_wsdl_1_1_) return spyneApps
elif maxSendCount > 2000: return SendSmsReturn(errorMsg='maxSendCount should be lower than 2000', status=status.SEND_MAX_SEND_COUNT_EXCEEDED) else: return SendSmsReturn(status=0, existsNumberCount=exist_number_count, orderId=order_id) @rpc(UserCredential, Integer, _returns=GetReportReturn.customize(sub_name='return')) def getReportByOrderId(ctx, userCredential, orderIds): total_sent = randint(1, 2000) success_delivered = randint(10, total_sent) init_date = int(1000 * (time.time() - randint(1, 7200))) if userCredential.username is None: return GetReportReturn(errorMsg='Username is empty.', status=status.SEND_USERNAME_NOT_SPECIFIED) elif userCredential.password is None: return GetReportReturn(errorMsg='Password is empty.', status=status.SEND_PASSWORD_NOT_SPECIFIED) else: report_items = ReportItems(initDate=init_date, orderId=orderIds, successDelivered=success_delivered, totalSent=total_sent) result = GetReportReturn(status=0, reportItem=report_items) return result app = Application([SDPSimulator], 'localhost', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), ) lbs_sdp_service = csrf_exempt(DjangoApplication(app))
return retval def _on_method_call(ctx): if ctx.in_object is None: raise ArgumentError("RequestHeader is null") if not (ctx.in_header.user_name, ctx.in_header.session_id) in session_db: raise AuthenticationError(ctx.in_object.user_name) UserService.event_manager.add_listener('method_call', _on_method_call) if __name__=='__main__': from spyne.util.wsgi_wrapper import run_twisted logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) logging.getLogger('twisted').setLevel(logging.DEBUG) application = Application([AuthenticationService,UserService], tns='spyne.examples.authentication', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11() ) twisted_apps = [ (WsgiApplication(application), 'app'), ] sys.exit(run_twisted(twisted_apps, 8000))
class FibonanciService(ServiceBase): @srpc(UnsignedInteger, _returns=Iterable(UnsignedInteger)) def Fibonacci(n): a, b = 0, 1 while True: if a > n: return yield a a, b = b, a + b if __name__ == '__main__': import logging logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) app = Application( [FibonanciService], 'spyne.examples.hello.http', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), ) wsgi_app = WsgiApplication(app) server = make_server('127.0.0.1', 3333, wsgi_app) print("listening to http://127.0.0.1:3333") print("wsdl is at: http://localhost:3333/?wsdl") server.serve_forever()
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # from django.views.decorators.csrf import csrf_exempt from spyne.server.django import DjangoApplication from spyne.model.primitive import Unicode, Integer from spyne.model.complex import Iterable from spyne.service import ServiceBase from spyne.protocol.soap import Soap11 from spyne.application import Application from spyne.decorator import rpc class HelloWorldService(ServiceBase): @rpc(Unicode, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, name, times): for i in xrange(times): yield 'Hello, %s' % name app = Application( [HelloWorldService], 'spyne.examples.django', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), ) hello_world_service = csrf_exempt(DjangoApplication(app))
# import logging logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) logger = logging.getLogger('spyne.test.interop.server.soap_http_basic') from spyne.server.wsgi import WsgiApplication from spyne.test.interop.server._service import services from spyne.application import Application from spyne.protocol.soap import Soap12 soap12_application = Application(services, 'spyne.test.interop.server', in_protocol=Soap12(validator='lxml', cleanup_namespaces=True), out_protocol=Soap12()) host = '127.0.0.1' port = 9754 def main(): try: from wsgiref.simple_server import make_server from wsgiref.validate import validator wsgi_application = WsgiApplication(soap12_application) server = make_server(host, port, validator(wsgi_application))
def run(): time.sleep(seconds) client = make_service_client(replyto, self) client.woke_up('good morning', msgid=msgid) Thread(target=run).start() @srpc(String, _is_callback=True) def woke_up(message): pass if __name__=='__main__': logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) try: from wsgiref.simple_server import make_server except ImportError: logger.error("Error: example server code requires Python >= 2.5") application = Application([SleepingService], 'spyne.examples.async', interface=Wsdl11(), in_protocol=Soap11(), out_protocol=Soap11()) server = make_server('127.0.0.1', 7789, WsgiApplication(application)) logging.info("listening to http://127.0.0.1:7789") logging.info("wsdl is at: http://localhost:7789/?wsdl") server.serve_forever()
if CCTVName == 'CCTV1': yield 'Frank' yield 'Oat' elif CCTVName == 'CCTV2': yield 'Frank' elif CCTVName == 'CCTV3': yield 'None' else: None @srpc(_returns=Iterable(String)) def CCTVList(): yield 'CCTV01' yield 'CCTV02' yield 'CCTV03' application = Application([CCTVService], tns='spyne.examples.cctv', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) if __name__ == '__main__': # You can use any Wsgi server. Here, we chose # Python's built-in wsgi server but you're not # supposed to use it in production. from wsgiref.simple_server import make_server wsgi_app = WsgiApplication(application) server = make_server('127.0.0.1', 7789, wsgi_app) server.serve_forever()
from spyne.application import Application from spyne.protocol.msgpack import MessagePackRpc from spyne.service import ServiceBase from spyne.decorator import rpc from spyne.model.primitive import Unicode class RadianteRPC(ServiceBase): @rpc(_returns=Unicode) def whoami(ctx): return "Hello I am Seldon!" app = Application([RadianteRPC], tns="radiante.rpc", in_protocol=MessagePackRpc(validator="soft"), out_protocol=MessagePackRpc()) import logging logging.basicConfig(level=logging.DEBUG)
if not (userid in user_database): raise ResourceNotFoundError(userid) del user_database[userid] @srpc(_returns=Array(User)) def list_users(): global user_database return user_database.values() if __name__ == '__main__': from wsgiref.simple_server import make_server logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) application = Application([UserManager], 'spyne.examples.complex', interface=Wsdl11(), in_protocol=HttpRpc(), out_protocol=XmlDocument()) server = make_server('127.0.0.1', 8000, WsgiApplication(application)) logging.info("listening to http://127.0.0.1:8000") logging.info("wsdl is at: http://localhost:8000/?wsdl") server.serve_forever()
except FieldContainer.DoesNotExist: raise ResourceNotFoundError('Container') @rpc(Container, _returns=Container) def create_container(ctx, container): try: return FieldContainer.objects.create(**container.as_dict()) except IntegrityError: raise ResourceAlreadyExistsError('Container') class ExceptionHandlingService(DjangoServiceBase): """Service for testing exception handling.""" @rpc(_returns=Container) def raise_does_not_exist(ctx): return FieldContainer.objects.get(pk=-1) @rpc(_returns=Container) def raise_validation_error(ctx): raise ValidationError('Is not valid.') app = Application( [HelloWorldService, ContainerService, ExceptionHandlingService], 'spyne.examples.django', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), ) hello_world_service = csrf_exempt(DjangoApplication(app))
Infraction.objects.filter(id=id).delete() return 'Infraction ' + str(id) + ' as deleted' except ProtectedError as e: raise Fault(faultcode='400', faultstring=e.args[0]) @rpc(Integer, _returns=InfractionComplex) def find_infraction(self, id): try: infraction = Infraction.objects.get(pk=id) return infraction except IntegrityError as e: raise Fault(faultcode=str(e.args[0]), faultstring=e.args[1]) except Infraction.DoesNotExist: raise Fault(faultcode='404', faultstring=str('Infraction not exist')) soap_app = Application( [InfractionManagementService], tns='django.soap.example', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), ) def infraction_management(): django_soap_app = DjangoApplication(soap_app) infraction_soap_app = csrf_exempt(django_soap_app) return infraction_soap_app
import logging from spyne.application import Application from spyne.protocol.json import JsonDocument from spyne.server.wsgi import WsgiApplication from Service import * from util import * if __name__ == '__main__': # Python daemon boilerplate from wsgiref.simple_server import make_server logging.basicConfig(level=logging.DEBUG) application = Application( [OpenTSDBService], 'bucknell.server.sensor', in_protocol=JsonDocument(), out_protocol=JsonDocument(), ) wsgi_application = WsgiApplication(application) # More daemon boilerplate server = make_server(util.getIPAddress(), 8000, wsgi_application) logging.info("listening to http://{0}:8000".format(util.getIPAddress())) logging.info("wsdl is at: http://{0}:8000/?wsdl".format( util.getIPAddress())) server.serve_forever()
def setUp(self): self.app = Application([SOAPServiceWithHeader], 'tns', in_protocol=Soap11(), out_protocol=Soap11())