forked from arskom/spyne
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_base.py
565 lines (439 loc) · 19.7 KB
/
_base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
#
# spyne - Copyright (C) Spyne contributors.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
#
import logging
logger = logging.getLogger(__name__)
from time import time
from copy import copy
from collections import deque
from spyne.const.xml_ns import DEFAULT_NS
from spyne.util.oset import oset
class BODY_STYLE_WRAPPED: pass
class BODY_STYLE_EMPTY: pass
class BODY_STYLE_BARE: pass
class AuxMethodContext(object):
"""Generic object that holds information specific to auxiliary methods"""
def __init__(self, parent, error):
self.parent = parent
"""Primary context that this method was bound to."""
self.error = error
"""Error from primary context (if any)."""
class TransportContext(object):
"""Generic object that holds transport-specific context information"""
def __init__(self, parent, transport, type=None):
self.parent = parent;
"""The MethodContext this object belongs to"""
self.itself = transport
"""The transport itself; i.e. a ServerBase instance."""
self.type = type
"""The protocol the transport uses."""
self.app = transport.app
self.request_encoding = None
"""General purpose variable to hold the string identifier of a request
encoding. It's nowadays usually 'utf-8', especially with http data"""
class ProtocolContext(object):
"""Generic object that holds transport-specific context information"""
def __init__(self, parent, transport, type=None):
self.parent = parent;
"""The MethodContext this object belongs to"""
self.itself = transport
"""The transport itself; i.e. a ServerBase instance."""
self.type = type
"""The protocol the transport uses."""
class EventContext(object):
"""Generic object that holds event-specific context information"""
def __init__(self, parent, event_id=None):
self.parent = parent
self.event_id = event_id
class MethodContext(object):
"""The base class for all RPC Contexts. Holds all information about the
current state of execution of a remote procedure call.
"""
frozen = False
def copy(self):
retval = copy(self)
if retval.transport is not None:
retval.transport.parent = retval
if retval.protocol is not None:
retval.protocol.parent = retval
if retval.event is not None:
retval.event.parent = retval
if retval.aux is not None:
retval.aux.parent = retval
return retval
@property
def method_name(self):
"""The public name of the method the ``method_request_string`` was
matched to.
"""
if self.descriptor is None:
return None
else:
return self.descriptor.name
def __init__(self, transport):
# metadata
self.call_start = time()
"""The time the rpc operation was initiated in seconds-since-epoch
format.
Useful for benchmarking purposes."""
self.call_end = None
"""The time the rpc operation was completed in seconds-since-epoch
format.
Useful for benchmarking purposes."""
self.app = transport.app
"""The parent application."""
self.udc = None
"""The user defined context. Use it to your liking."""
self.transport = TransportContext(self, transport)
"""The transport-specific context. Transport implementors can use this
to their liking."""
self.protocol = ProtocolContext(self, transport)
"""The protocol-specific context. Protocol implementors can use this
to their liking."""
self.event = EventContext(self)
"""Event-specific context. Use this as you want, preferably only in
events, as you'd probably want to separate the event data from the
method data."""
self.aux = None
"""Auxiliary-method specific context. You can use this to share data
between auxiliary sessions. This is not set in primary contexts.
"""
self.method_request_string = None
"""This is used to decide which native method to call. It is set by
the protocol classes."""
self.__descriptor = None
#
# Input
#
# stream
self.in_string = None
"""Incoming bytestream as a sequence of ``str`` or ``bytes`` instances."""
# parsed
self.in_document = None
"""Incoming document, what you get when you parse the incoming stream."""
self.in_header_doc = None
"""Incoming header document of the request."""
self.in_body_doc = None
"""Incoming body document of the request."""
# native
self.in_error = None
"""Native python error object. If this is set, either there was a
parsing error or the incoming document was representing an exception.
"""
self.in_header = None
"""Deserialized incoming header -- a native object."""
self.in_object = None
"""In the request (i.e. server) case, this contains the function
argument sequence for the function in the service definition class.
In the response (i.e. client) case, this contains the object returned
by the remote procedure call.
It's always a sequence of objects:
* ``[None]`` when the function has no output (client)/input (server)
types.
* A single-element list that wraps the return value when the
function has one return type defined,
* A tuple of return values in case of the function having more than
one return value.
The order of the argument sequence is in line with
``self.descriptor.in_message._type_info.keys()``.
"""
#
# Output
#
# native
self.out_object = None
"""In the response (i.e. server) case, this contains the native python
object(s) returned by the function in the service definition class.
In the request (i.e. client) case, this contains the function arguments
passed to the function call wrapper.
It's always a sequence of objects:
* ``[None]`` when the function has no output (server)/input (client)
types.
* A single-element list that wraps the return value when the
function has one return type defined,
* A tuple of return values in case of the function having more than
one return value.
The order of the argument sequence is in line with
``self.descriptor.out_message._type_info.keys()``.
"""
self.out_header = None
"""Native python object set by the function in the service definition
class."""
self.out_error = None
"""Native exception thrown by the function in the service definition
class."""
# parsed
self.out_body_doc = None
"""Serialized body object."""
self.out_header_doc = None
"""Serialized header object."""
self.out_document = None
"""out_body_doc and out_header_doc wrapped in the outgoing envelope"""
# stream
self.out_string = None
"""The pull interface to the outgoing bytestream. It's a sequence of
strings (which could also be a generator)."""
self.out_stream = None
"""The push interface to the outgoing bytestream. It's a file-like
object."""
#self.out_stream = None
#"""The push interface to the outgoing bytestream. It's a file-like
#object."""
self.function = None
"""The callable of the user code."""
self.locale = None
"""The locale the request will use when needed for things like date
formatting, html rendering and such."""
self.in_protocol = transport.app.in_protocol
"""The protocol that will be used to (de)serialize incoming input"""
self.out_protocol = transport.app.out_protocol
"""The protocol that will be used to (de)serialize outgoing input"""
self.frozen = True
"""When this is set, no new attribute can be added to this class
instance. This is mostly for internal use.
"""
self.app.event_manager.fire_event("method_context_created", self)
def get_descriptor(self):
return self.__descriptor
def set_descriptor(self, descriptor):
self.__descriptor = descriptor
self.function = descriptor.function
descriptor = property(get_descriptor, set_descriptor)
"""The :class:``MethodDescriptor`` object representing the current method.
It is only set when the incoming request was successfully mapped to a method
in the public interface. The contents of this property should not be changed
by the user code.
"""
# Deprecated. Use self.descriptor.service_class.
@property
def service_class(self):
if self.descriptor is not None:
return self.descriptor.service_class
def __setattr__(self, k, v):
if not self.frozen or k in self.__dict__ or k in \
('descriptor', 'out_protocol'):
object.__setattr__(self, k, v)
else:
raise ValueError("use the udc member for storing arbitrary data "
"in the method context")
def __repr__(self):
retval = deque()
for k, v in self.__dict__.items():
if isinstance(v, dict):
ret = deque(['{'])
items = sorted(v.items())
for k2, v2 in items:
ret.append('\t\t%r: %r,' % (k2, v2))
ret.append('\t}')
ret = '\n'.join(ret)
retval.append("\n\t%s=%s" % (k, ret))
else:
retval.append("\n\t%s=%r" % (k, v))
retval.append('\n)')
return ''.join((self.__class__.__name__, '(', ', '.join(retval), ')'))
def close(self):
self.call_end = time()
self.app.event_manager.fire_event("method_context_closed", self)
# break cycles
del self.udc
del self.event
del self.transport
del self.protocol
del self.out_object
def set_out_protocol(self, what):
self._out_protocol = what
def get_out_protocol(self):
return self._out_protocol
out_protocol = property(get_out_protocol, set_out_protocol)
class MethodDescriptor(object):
"""This class represents the method signature of an exposed service. It is
produced by the :func:`spyne.decorator.srpc` decorator.
"""
def __init__(self, function, in_message, out_message, doc,
is_callback=False, is_async=False, mtom=False, in_header=None,
out_header=None, faults=None,
port_type=None, no_ctx=False, udp=None, class_key=None,
aux=None, patterns=None, body_style=None, args=None,
operation_name=None, no_self=None, translations=None, when=None,
in_message_name_override=True, out_message_name_override=True,
service_class=None, href=None):
self.__real_function = function
"""The original callable for the user code."""
self.reset_function()
self.operation_name = operation_name
"""The base name of an operation without the request suffix, as
generated by the ``@srpc`` decorator."""
self.in_message = in_message
"""A :class:`spyne.model.complex.ComplexModel` subclass that defines the
input signature of the user function and that was automatically
generated by the ``@srpc`` decorator."""
self.name = None
"""The public name of the function. Equals to the type_name of the
in_message."""
if body_style is BODY_STYLE_BARE:
self.name = in_message.Attributes.sub_name
if self.name is None:
self.name = self.in_message.get_type_name()
self.out_message = out_message
"""A :class:`spyne.model.complex.ComplexModel` subclass that defines the
output signature of the user function and that was automatically
generated by the ``@srpc`` decorator."""
self.doc = doc
"""The function docstring."""
# these are not working, so they are not documented.
self.is_callback = is_callback
self.is_async = is_async
self.mtom = mtom
#"""Flag to indicate whether to use MTOM transport with SOAP."""
self.port_type = port_type
#"""The portType this function belongs to."""
self.in_header = in_header
"""An iterable of :class:`spyne.model.complex.ComplexModel`
subclasses to denote the types of header objects that this method can
accept."""
self.out_header = out_header
"""An iterable of :class:`spyne.model.complex.ComplexModel`
subclasses to denote the types of header objects that this method can
emit along with its return value."""
self.faults = faults
"""An iterable of :class:`spyne.model.fault.Fault` subclasses to denote
the types of exceptions that this method can throw."""
self.no_ctx = no_ctx
"""no_ctx: Boolean flag to denote whether the user code gets an
implicit :class:`spyne.MethodContext` instance as first argument."""
self.udp = udp
"""Short for "User Defined Properties", this is just an arbitrary python
object set by the user to pass arbitrary metadata via the ``@srpc``
decorator."""
self.class_key = class_key
""" The identifier of this method in its parent
:class:`spyne.service.ServiceBase` subclass."""
self.aux = aux
"""Value to indicate what kind of auxiliary method this is. (None means
primary)
Primary methods block the request as long as they're running. Their
return values are returned to the client. Auxiliary ones execute
asyncronously after the primary method returns, and their return values
are ignored by the rpc layer.
"""
self.patterns = patterns
"""This list stores patterns which will match this callable using
various elements of the request protocol.
Currently, the only object supported here is the
:class:`spyne.protocol.http.HttpPattern` object.
"""
self.body_style = body_style
"""One of (BODY_STYLE_EMPTY, BODY_STYLE_BARE, BODY_STYLE_WRAPPED)."""
self.args = args
"""A sequence of the names of the exposed arguments, or None."""
# FIXME: docstring yo.
self.no_self = no_self
"""FIXME: docstring yo."""
self.service_class = service_class
"""The ServiceBase subclass the method belongs to, if there's any."""
self.parent_class = None
"""The ComplexModel subclass the method belongs to. Only set for @mrpc
methods."""
# HATEOAS Stuff
self.translations = translations
"""None or a dict of locale-translation pairs."""
self.href = href
"""None or a dict of locale-translation pairs."""
self.when = when
"""None or a callable that takes the object instance and returns a
boolean value. If true, the object can process that action.
"""
self.in_message_name_override = in_message_name_override
"""When False, no mangling of in message name will be performed by later
stages of the interface generation. Naturally, it will be up to you to
resolve name clashes."""
self.out_message_name_override = out_message_name_override
"""When False, no mangling of out message name will be performed by
later stages of the interface generation. Naturally, it will be up to
you to resolve name clashes."""
def translate(self, locale, default):
"""
:param cls: class
:param locale: locale string
:param default: default string if no translation found
:returns: translated string
"""
if locale is None:
locale = 'en_US'
if self.translations is not None:
return self.translations.get(locale, default)
return default
@property
def key(self):
"""The function identifier in '{namespace}name' form."""
assert not (self.in_message.get_namespace() is DEFAULT_NS)
return '{%s}%s' % (
self.in_message.get_namespace(), self.in_message.get_type_name())
def reset_function(self, val=None):
if val != None:
self.__real_function = val
self.function = self.__real_function
class EventManager(object):
"""Spyne supports a simple event system that can be used to have repetitive
boilerplate code that has to run for every method call nicely tucked away
in one or more event handlers. The popular use-cases include things like
database transaction management, logging and measuring performance.
Various Spyne components support firing events at various stages during the
processing of a request, which are documented in the relevant classes.
The classes that support events are:
* :class:`spyne.application.Application`
* :class:`spyne.service.ServiceBase`
* :class:`spyne.protocol._base.ProtocolBase`
* :class:`spyne.server.wsgi.WsgiApplication`
The events are stored in an ordered set. This means that the events are ran
in the order they were added and adding a handler twice does not cause it to
run twice.
"""
def __init__(self, parent, handlers={}):
self.parent = parent
self.handlers = dict(handlers)
def add_listener(self, event_name, handler):
"""Register a handler for the given event name.
:param event_name: The event identifier, indicated by the documentation.
Usually, this is a string.
:param handler: A static python function that receives a single
MethodContext argument.
"""
handlers = self.handlers.get(event_name, oset())
handlers.add(handler)
self.handlers[event_name] = handlers
def fire_event(self, event_name, ctx):
"""Run all the handlers for a given event name.
:param event_name: The event identifier, indicated by the documentation.
Usually, this is a string.
:param ctx: The method context. Event-related data is conventionally
stored in ctx.event attribute.
"""
handlers = self.handlers.get(event_name, oset())
for handler in handlers:
handler(ctx)
class FakeContext(object):
def __init__(self, app=None, descriptor=None, out_object=None,
out_error=None, out_document=None, out_string=None):
self.app = app
self.descriptor = descriptor
self.out_error = out_error
self.out_object = out_object
self.out_document = out_document
self.out_string = out_string
self.protocol = type("ProtocolContext", (object,), {})()
self.transport = type("ProtocolContext", (object,), {})()