desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
''
def test_basic(self):
msg = remoting.Envelope(pyamf.AMF0) self.assertEqual(remoting.encode(msg).getvalue(), ('\x00' * 6)) msg = remoting.Envelope(pyamf.AMF3) self.assertEqual(remoting.encode(msg).getvalue(), ('\x00\x03' + ('\x00' * 4)))
'Test encoding of header.'
def test_header(self):
msg = remoting.Envelope(pyamf.AMF0) msg.headers['spam'] = (False, 'eggs') self.assertEqual(remoting.encode(msg).getvalue(), '\x00\x00\x00\x01\x00\x04spam\x00\x00\x00\x00\x00\n\x00\x00\x00\x02\x01\x00\x02\x00\x04eggs\x00\x00') msg = remoting.Envelope(pyamf.AMF0) msg.headers['spam'] = (True, ['a', 'b'...
'Test encoding of request body.'
def test_request(self):
msg = remoting.Envelope(pyamf.AMF0) msg['/1'] = remoting.Request('test.test', body=['hello']) self.assertEqual(len(msg), 1) x = msg['/1'] self.assertTrue(isinstance(x, remoting.Request)) self.assertEqual(x.envelope, msg) self.assertEqual(x.target, 'test.test') self.assertEqual(x.body, ['...
'Test encoding of request body.'
def test_response(self):
msg = remoting.Envelope(pyamf.AMF0) msg['/1'] = remoting.Response(body=[1, 2, 3]) self.assertEqual(len(msg), 1) x = msg['/1'] self.assertTrue(isinstance(x, remoting.Response)) self.assertEqual(x.envelope, msg) self.assertEqual(x.body, [1, 2, 3]) self.assertEqual(x.status, 0) self.ass...
'Ensure that the stream pointer is placed at the beginning.'
def test_stream_pos(self):
msg = remoting.Envelope(pyamf.AMF0) msg['/1'] = remoting.Response(body=[1, 2, 3]) stream = remoting.encode(msg) self.assertEqual(stream.tell(), 0)
'Ensure that the timezone offsets work as expected'
def test_timezone(self):
import datetime d = datetime.datetime(2009, 9, 24, 15, 52, 12) td = datetime.timedelta(hours=(-5)) msg = remoting.Envelope(pyamf.AMF0) msg['/1'] = remoting.Response(body=[d]) stream = remoting.encode(msg, timezone_offset=td).getvalue() self.assertEqual(stream, '\x00\x00\x00\x00\x00\x01\x00\x...
'Test to see if there is an empty key in the C{dict}. There is a design bug in Flash 9 which means that it cannot read this specific data. @bug: See U{http://www.docuverse.com/blog/donpark/2007/05/14/flash-9-amf3-bug} for more info.'
def test_empty_key_string(self):
def x(): y = pyamf.MixedArray() y.update({'': 1, 0: 1}) self.encode(y) self.failUnlessRaises(pyamf.EncodeError, x)
'Tests for ints that don\'t fit into 29bits. Reference: #519'
def test_29b_ints(self):
ints = [((amf3.MIN_29B_INT - 1), '\x05\xc1\xb0\x00\x00\x01\x00\x00\x00'), ((amf3.MAX_29B_INT + 1), '\x05A\xb0\x00\x00\x00\x00\x00\x00')] for (i, val) in ints: self.buf.truncate() self.encoder.writeElement(i) self.assertEqual(self.buf.getvalue(), val)
'Test to ensure that only C{dict} objects will be proxied correctly'
def test_proxy(self):
self.encoder.use_proxies = True bytes = '\n\x07;flex.messaging.io.ObjectProxy\n\x0b\x01\x01' self.assertEncoded(pyamf.ASObject(), bytes) self.assertEncoded({}, bytes)
'Test to ensure that if an IOError is raised by `readElement` that the original position of the stream is restored.'
def test_ioerror_buffer_position(self):
bytes = pyamf.encode(u'foo', [1, 2, 3], encoding=pyamf.AMF3).getvalue() self.buf.write(bytes[:(-1)]) self.buf.seek(0) self.decoder.readElement() self.assertEqual(self.buf.tell(), 5) self.assertRaises(IOError, self.decoder.readElement) self.assertEqual(self.buf.tell(), 5)
'Python <= 3 demand that kwargs keys be bytes instead of unicode/string.'
def test_kwargs(self):
def f(**kwargs): self.assertEqual(kwargs, {'spam': 'eggs'}) kwargs = self.decode('\n\x0b\x01 DCTB spam\x06 DCTB eggs\x01') f(**kwargs)
'Test to ensure anonymous class references with static attributes are encoded propertly'
def test_anonymous_class_references(self):
class Foo: class __amf__: static = ('name', 'id', 'description') x = Foo() x.id = 1 x.name = 'foo' x.description = None y = Foo() y.id = 2 y.name = 'bar' y.description = None self.encoder.writeElement([x, y]) self.assertEqual(self.buf.getvalue(), ' DCTB \x...
'This tests an object encoding with static properties and dynamic properties'
def test_combined(self):
pyamf.register_class(Spam, 'abc.xyz') self.buf.write('\n\x1b\x0fabc.xyz DCTB spam\x06 DCTB eggs\x07baz\x06\x07nat\x01') self.buf.seek(0, 0) obj = self.decoder.readElement() class_def = self.context.getClass(Spam) self.assertEqual(class_def.static_properties, ['spam']) self.assertTrue(isinsta...
'@see: #695'
def test_write_context(self):
obj = {'foo': 'bar'} b = amf3.ByteArray() b.writeObject(obj) bytes = b.getvalue() b.stream.truncate() b.writeObject(obj) self.assertEqual(b.getvalue(), bytes)
'@see: #695'
def test_read_context(self):
obj = {'foo': 'bar'} b = amf3.ByteArray() b.stream.write('\n\x0b\x01\x07foo\x06\x07bar\x01\n\x00') b.stream.seek(0) self.assertEqual(obj, b.readObject()) self.assertRaises(pyamf.ReferenceError, b.readObject)
'Test for dynamic property encoding.'
def test_dynamic(self):
alias = adapter.DjangoClassAlias(models.SimplestModel, 'Book') x = models.SimplestModel() x.spam = 'eggs' self.assertEqual(alias.getEncodableAttributes(x), {'spam': 'eggs', 'id': None}) alias.applyAttributes(x, {'spam': 'foo', 'id': None}) self.assertEqual(x.spam, 'foo')
'See #764'
def test_properties(self):
from django.db import models class Foob(models.Model, ): def _get_days(self): return 1 def _set_days(self, val): assert (1 == val) days = property(_get_days, _set_days) alias = adapter.DjangoClassAlias(Foob, 'Bar') x = Foob() self.assertEqual(x.days, 1...
'@see: #693'
def test_static_relation(self):
from pyamf import util pyamf.register_class(models.StaticRelation) alias = adapter.DjangoClassAlias(models.StaticRelation, static_attrs=('gak',)) alias.compile() self.assertTrue(('gak' in alias.relations)) self.assertTrue(('gak' in alias.decodable_properties)) self.assertTrue(('gak' in alias...
'See #556. Make sure that PK fields with a value of 0 are actually set to C{None}.'
def test_none(self):
alias = adapter.DjangoClassAlias(models.SimplestModel, None) x = models.SimplestModel() self.assertEqual(x.id, None) alias.applyAttributes(x, {'id': 0}) self.assertEqual(x.id, None)
'Ensure that Models without a primary key are correctly serialized. See #691.'
def test_no_pk(self):
instances = [models.NotSaved(name='a'), models.NotSaved(name='b')] encoded = pyamf.encode(instances, encoding=pyamf.AMF3).getvalue() decoded = pyamf.decode(encoded, encoding=pyamf.AMF3).next() self.assertEqual(decoded[0]['name'], 'a') self.assertEqual(decoded[1]['name'], 'b')
'Test to ensure that we observe the correct behaviour in the Django ORM.'
def test_not_referenced(self):
f = models.ParentReference() f.name = 'foo' b = models.ChildReference() b.name = 'bar' f.save() b.foo = f b.save() f.bar = b f.save() self.addCleanup(f.delete) self.addCleanup(b.delete) self.assertEqual(f.id, 1) foo = models.ParentReference.objects.select_related().ge...
'Ensure that sa_key and sa_lazy can be excluded'
def test_core_attrs(self):
a = adapter.SaMappedClassAlias(Address, exclude_attrs=['sa_lazy', 'sa_key']) u = Address() attrs = a.getEncodableAttributes(u) self.assertFalse(('sa_key' in attrs)) self.assertFalse(('sa_lazy' in attrs))
'Returns an AMF encoded representation of a L{db.Key} instance. @param key: The L{db.Key} to be encoded. @type key: L{db.Key} @param encoding: The AMF version.'
def encodeKey(self, key, encoding):
if hasattr(key, 'key'): try: key = key.key() except db.NotSavedError: key = None if (not key): if (encoding == pyamf.AMF3): return '\x01' return '\x05' k = str(key) if (encoding == pyamf.AMF3): return ('\x06%s%s' % (amf3.encode_...
'L{db.Query} instances get converted to lists ..'
def test_Query_type(self):
q = test_models.EmptyModel.all() self.assertTrue(isinstance(q, db.Query)) self.assertEncodes(q, '\n\x00\x00\x00\x00', encoding=pyamf.AMF0) self.assertEncodes(q, ' DCTB \x01\x01', encoding=pyamf.AMF3)
'Test the behaviour of the Google SDK not handling ints gracefully'
def test_behaviour(self):
self.assertRaises(db.BadValueError, setattr, self.f, 'f', 3) self.f.f = 3.0 self.assertEqual(self.f.f, 3.0)
'Pretend to look like an ElementTree object to try to fool PyAMF into encoding an xml type.'
def test_elementtree_tag(self):
class NotAnElement(object, ): items = (lambda self: []) def __iter__(self): return iter([]) foo = NotAnElement() foo.tag = 'foo' foo.text = 'bar' foo.tail = None self.assertEncoded(foo, '\x03', ('\x00\x04text\x02\x00\x03bar', '\x00\x04tail\x05', '\x00\x03tag\x02\x00\x...
'Test to ensure that if an IOError is raised by `readElement` that the original position of the stream is restored.'
def test_ioerror_buffer_position(self):
bytes = pyamf.encode(u'foo', [1, 2, 3], encoding=pyamf.AMF0).getvalue() self.buf.write(bytes[:(-1)]) self.buf.seek(0) self.decoder.readElement() self.assertEqual(self.buf.tell(), 6) self.assertRaises(IOError, self.decoder.readElement) self.assertEqual(self.buf.tell(), 6)
'Python <= 3 demand that kwargs keys be bytes instead of unicode/string.'
def test_kwargs(self):
def f(**kwargs): self.assertEqual(kwargs, {'a': 'a'}) kwargs = self.decode('\x03\x00\x01a\x02\x00\x01a\x00\x00 DCTB ') f(**kwargs)
'A classic GET on the xml server should return a NOT_ALLOWED.'
def test_invalid_method(self):
d = self.getPage(method='GET') d = self.assertFailure(d, error.Error) d.addCallback((lambda exc: self.assertEqual(int(exc.args[0]), http.NOT_ALLOWED))) return d
'See ticket #648'
def test_double_encode(self):
self.counter = 0 def service(): self.counter += 1 self.gw.addService(service) d = self.doRequest('service') def cb(result): self.assertEqual(self.counter, 1) return d.addCallback(cb)
'Return an L{twisted.AMF0RequestProcessor} attached to a gateway. Supply the gateway args/kwargs.'
def getProcessor(self, *args, **kwargs):
self.gw = twisted.TwistedGateway(*args, **kwargs) self.processor = twisted.AMF0RequestProcessor(self.gw) return self.processor
'Tests for L{pyamf.unregister_alias_type}'
def test_unregister(self):
class A(object, ): pass self.assertFalse((DummyAlias in pyamf.ALIAS_TYPES)) self.assertEqual(pyamf.unregister_alias_type(A), None) pyamf.register_alias_type(DummyAlias, A) self.assertTrue((DummyAlias in pyamf.ALIAS_TYPES.keys())) self.assertEqual(pyamf.unregister_alias_type(DummyAlias), ...
'@see: #585'
def test_dict(self):
d = dict() d['Spam'] = Spam r = pyamf.register_package(d, 'com.example', strict=False) self.assertEqual(len(r), 1) alias = r[Spam] self.assertTrue(isinstance(alias, pyamf.ClassAlias)) self.assertEqual(alias.klass, Spam) self.assertEqual(alias.alias, 'com.example.Spam')
'Inform the proxied service that this function has been called.'
def __call__(self, *args):
return self.service._call(self, *args)
'Returns the full service name, including the method name if there is one.'
def __str__(self):
service_name = str(self.service) if (self.name is not None): service_name = ('%s.%s' % (service_name, self.name)) return service_name
'Executed when a L{ServiceMethodProxy} is called. Adds a request to the underlying gateway.'
def _call(self, method_proxy, *args):
request = self._gw.addRequest(method_proxy, *args) if self._auto_execute: response = self._gw.execute_single(request) if (response.status == remoting.STATUS_ERROR): if hasattr(response.body, 'raiseException'): try: response.body.raiseException() ...
'This allows services to be \'called\' without a method name.'
def __call__(self, *args):
return self._call(ServiceMethodProxy(self, None), *args)
'Returns a string representation of the name of the service.'
def __str__(self):
return self._name
'A response has been received by the gateway'
def setResponse(self, response):
self.response = response self.result = self.response.body if isinstance(self.result, remoting.ErrorFault): self.result.raiseException()
'Returns the result of the called remote request. If the request has not yet been called, an C{AttributeError} exception is raised.'
def _get_result(self):
if (not hasattr(self, '_result')): raise AttributeError("'RequestWrapper' object has no attribute 'result'") return self._result
''
def _setUrl(self, url):
self.url = urlparse.urlparse(url) self._root_url = url if (not (self.url[0] in ('http', 'https'))): raise ValueError(('Unknown scheme %r' % (self.url[0],))) if self.logger: self.logger.info('Connecting to %r', self._root_url) self.logger.debug('Referer: %r', self.r...
'Set the proxy for all requests to use. @see: U{The Python Docs<http://docs.python.org/library/urllib2.html# urllib2.Request.set_proxy}'
def setProxy(self, host, type='http'):
self.proxy_args = (host, type)
'Sets a persistent header to send with each request. @param name: Header name.'
def addHeader(self, name, value, must_understand=False):
self.headers[name] = value self.headers.set_required(name, must_understand)
'Adds a header to the underlying HTTP connection.'
def addHTTPHeader(self, name, value):
self.http_headers[name] = value
'Deletes an HTTP header.'
def removeHTTPHeader(self, name):
del self.http_headers[name]
'Returns a L{ServiceProxy} for the supplied name. Sets up an object that can have method calls made to it that build the AMF requests. @rtype: L{ServiceProxy}'
def getService(self, name, auto_execute=True):
if (not isinstance(name, basestring)): raise TypeError('string type required') return ServiceProxy(self, name, auto_execute)
'Gets a request based on the id. :raise LookupError: Request not found.'
def getRequest(self, id_):
for request in self.requests: if (request.id == id_): return request raise LookupError(('Request %r not found' % (id_,)))
'Adds a request to be sent to the remoting gateway.'
def addRequest(self, service, *args):
wrapper = RequestWrapper(self, ('/%d' % self.request_number), service, *args) self.request_number += 1 self.requests.append(wrapper) if self.logger: self.logger.debug('Adding request %s%r', wrapper.service, args) return wrapper
'Removes a request from the pending request list.'
def removeRequest(self, service, *args):
if isinstance(service, RequestWrapper): if self.logger: self.logger.debug('Removing request: %s', self.requests[self.requests.index(service)]) del self.requests[self.requests.index(service)] return for request in self.requests: if ((request.service == service) a...
'Builds an AMF request {LEnvelope<pyamf.remoting.Envelope>} from a supplied list of requests.'
def getAMFRequest(self, requests):
envelope = remoting.Envelope(self.amf_version) if self.logger: self.logger.debug(('AMF version: %s' % self.amf_version)) for request in requests: service = request.service args = list(request.args) envelope[request.id] = remoting.Request(str(service), args) envelope...
'Builds, sends and handles the response to a single request, returning the response.'
def execute_single(self, request):
if self.logger: self.logger.debug('Executing single request: %s', request) self.removeRequest(request) body = remoting.encode(self.getAMFRequest([request]), strict=self.strict) http_request = urllib2.Request(self._root_url, body.getvalue(), self._get_execute_headers()) if self.proxy...
'Builds, sends and handles the responses to all requests listed in C{self.requests}.'
def execute(self):
requests = self.requests[:] for r in requests: self.removeRequest(r) body = remoting.encode(self.getAMFRequest(requests), strict=self.strict) http_request = urllib2.Request(self._root_url, body.getvalue(), self._get_execute_headers()) if self.proxy_args: http_request.set_proxy(*self....
'Gets and handles the HTTP response from the remote gateway.'
def _getResponse(self, http_request):
if self.logger: self.logger.debug('Sending POST request to %s', self._root_url) try: fbh = self.opener(http_request) except urllib2.URLError as e: if self.logger: self.logger.exception('Failed request for %s', self._root_url) raise remoting.Re...
'Sets authentication credentials for accessing the remote gateway.'
def setCredentials(self, username, password):
self.addHeader('Credentials', dict(userid=username.decode('utf-8'), password=password.decode('utf-8')), True)
'@raise KeyError: Unknown header found.'
def is_required(self, idx):
if (not (idx in self)): raise KeyError(('Unknown header %s' % str(idx))) return (idx in self.required)
'@raise KeyError: Unknown header found.'
def set_required(self, idx, value=True):
if (not (idx in self)): raise KeyError(('Unknown header %s' % str(idx))) if (not (idx in self.required)): self.required.append(idx)
'Raises an exception based on the fault object. There is no traceback available.'
def raiseException(self):
raise get_exception_from_fault(self), self.description, None
'Builds an error response. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} @return: The AMF response @rtype: L{Response<pyamf.remoting.Response>}'
def buildErrorResponse(self, request, error=None):
if (error is not None): (cls, e, tb) = error else: (cls, e, tb) = sys.exc_info() return generate_error(request, cls, e, tb, self.gateway.debug)
'@raise ServerCallFailed: Unknown request.'
def _getBody(self, amf_request, ro_request, **kwargs):
if isinstance(ro_request, messaging.CommandMessage): return self._processCommandMessage(amf_request, ro_request, **kwargs) elif isinstance(ro_request, messaging.RemotingMessage): return self._processRemotingMessage(amf_request, ro_request, **kwargs) elif isinstance(ro_request, messaging.Asyn...
'@raise ServerCallFailed: Unknown Command operation. @raise ServerCallFailed: Authorization is not supported in RemoteObject.'
def _processCommandMessage(self, amf_request, ro_request, **kwargs):
ro_response = generate_acknowledgement(ro_request) if (ro_request.operation == messaging.CommandMessage.PING_OPERATION): ro_response.body = True return remoting.Response(ro_response) elif (ro_request.operation == messaging.CommandMessage.LOGIN_OPERATION): raise ServerCallFailed('Auth...
'Processes an AMF3 Remote Object request. @param amf_request: The request to be processed. @type amf_request: L{Request<pyamf.remoting.Request>} @return: The response to the request. @rtype: L{Response<pyamf.remoting.Response>}'
def __call__(self, amf_request, **kwargs):
ro_request = amf_request.body[0] try: return self._getBody(amf_request, ro_request, **kwargs) except (KeyboardInterrupt, SystemExit): raise except: return remoting.Response(self.buildErrorResponse(ro_request), status=remoting.STATUS_ERROR)
'Calls the underlying service method. @return: A C{Deferred} that will contain the AMF L{Response}. @rtype: C{twisted.internet.defer.Deferred}'
def __call__(self, request, *args, **kwargs):
try: service_request = self.gateway.getServiceRequest(request, request.target) except gateway.UnknownServiceError: return defer.succeed(self.buildErrorResponse(request)) response = remoting.Response(None) deferred_response = defer.Deferred() def eb(failure): errMesg = ('%s: ...
'Calls the underlying service method. @return: A C{deferred} that will contain the AMF L{Response}. @rtype: C{Deferred<twisted.internet.defer.Deferred>}'
def __call__(self, amf_request, **kwargs):
deferred_response = defer.Deferred() ro_request = amf_request.body[0] def cb(amf_response): deferred_response.callback(amf_response) def eb(failure): errMesg = ('%s: %s' % (failure.type, failure.getErrorMessage())) if self.gateway.logger: self.gateway.logger.error(...
'Finalises the request. @param request: The HTTP Request. @type request: C{http.Request} @param status: The HTTP status code. @type status: C{int} @param content: The content of the response. @type content: C{str} @param mimetype: The MIME type of the request. @type mimetype: C{str}'
def _finaliseRequest(self, request, status, content, mimetype='text/plain'):
request.setResponseCode(status) request.setHeader('Content-Type', mimetype) request.setHeader('Content-Length', str(len(content))) request.setHeader('Server', gateway.SERVER_NAME) request.write(content) request.finish()
'Read remoting request from the client. @type request: The HTTP Request. @param request: C{twisted.web.http.Request}'
def render_POST(self, request):
def handleDecodeError(failure): '\n Return HTTP 400 Bad Request.\n ' errMesg = ('%s: %s' % (failure.type, failure.getErrorMessage())) if self.logger: self.logger.error(err...
'Determines the request processor, based on the request. @param request: The AMF message. @type request: L{Request<pyamf.remoting.Request>}'
def getProcessor(self, request):
if (request.target == 'null'): return AMF3RequestProcessor(self) return AMF0RequestProcessor(self)
'Processes the AMF request, returning an AMF L{Response}. @param http_request: The underlying HTTP Request @type http_request: C{twisted.web.http.Request} @param amf_request: The AMF Request. @type amf_request: L{Envelope<pyamf.remoting.Envelope>}'
def getResponse(self, http_request, amf_request):
response = remoting.Envelope(amf_request.amfVersion) dl = [] def cb(body, name): response[name] = body for (name, message) in amf_request: processor = self.getProcessor(message) http_request.amf_request = message d = defer.maybeDeferred(processor, message, http_request=ht...
'Processes an authentication request. If no authenticator is supplied, then authentication succeeds. @return: C{Deferred}. @rtype: C{twisted.internet.defer.Deferred}'
def authenticateRequest(self, service_request, username, password, **kwargs):
authenticator = self.getAuthenticator(service_request) if self.logger: self.logger.debug(('Authenticator expands to: %r' % authenticator)) if (authenticator is None): return defer.succeed(True) args = (username, password) if hasattr(authenticator, '_pyamf_expose_request'): ...
'Preprocesses a request.'
def preprocessRequest(self, service_request, *args, **kwargs):
processor = self.getPreprocessor(service_request) if self.logger: self.logger.debug(('Preprocessor expands to: %r' % processor)) if (processor is None): return args = ((service_request,) + args) if hasattr(processor, '_pyamf_expose_request'): http_request = kwargs.ge...
'@raise InvalidServiceMethodError: Calls to private methods are not allowed. @raise UnknownServiceMethodError: Unknown method. @raise InvalidServiceMethodError: Service method must be callable.'
def _get_service_func(self, method, params):
service = None if isinstance(self.service, (type, types.ClassType)): service = self.service() else: service = self.service if (method is not None): method = str(method) if method.startswith('_'): raise InvalidServiceMethodError('Calls to private metho...
'Executes the service. If the service is a class, it will be instantiated. @param method: The method to call on the service. @type method: C{None} or C{mixed} @param params: The params to pass to the service. @type params: C{list} or C{tuple} @return: The result of the execution. @rtype: C{mixed}'
def __call__(self, method, params):
func = self._get_service_func(method, params) return func(*params)
'Gets a C{dict} of valid method callables for the underlying service object.'
def getMethods(self):
callables = {} for name in dir(self.service): method = getattr(self.service, name) if (name.startswith('_') or (not python.callable(method))): continue callables[name] = method return callables
'Adds a service to the gateway. @param service: The service to add to the gateway. @type service: C{callable}, class instance, or a module @param name: The name of the service. @type name: C{str} @raise pyamf.remoting.RemotingError: Service already exists. @raise TypeError: C{service} cannot be a scalar value. @raise T...
def addService(self, service, name=None, description=None, authenticator=None, expose_request=None, preprocessor=None):
if isinstance(service, (int, long, float, basestring)): raise TypeError('Service cannot be a scalar value') allowed_types = (types.ModuleType, types.FunctionType, types.DictType, types.MethodType, types.InstanceType, types.ObjectType) if ((not python.callable(service)) and (not isinst...
'Removes a service from the gateway. @param service: Either the name or t of the service to remove from the gateway, or . @type service: C{callable} or a class instance @raise NameError: Service not found.'
def removeService(self, service):
for (name, wrapper) in self.services.iteritems(): if (service in (name, wrapper.service)): del self.services[name] return raise NameError(('Service %r not found' % (service,)))
'Returns a service based on the message. @raise UnknownServiceError: Unknown service. @param request: The AMF request. @type request: L{Request<pyamf.remoting.Request>} @rtype: L{ServiceRequest}'
def getServiceRequest(self, request, target):
try: return self._request_class(request.envelope, self.services[target], None) except KeyError: pass try: sp = target.split('.') (name, meth) = ('.'.join(sp[:(-1)]), sp[(-1)]) return self._request_class(request.envelope, self.services[name], meth) except (ValueErr...
'Returns request processor. @param request: The AMF message. @type request: L{Request<remoting.Request>}'
def getProcessor(self, request):
if ((request.target == 'null') or (not request.target)): from pyamf.remoting import amf3 return amf3.RequestProcessor(self) else: from pyamf.remoting import amf0 return amf0.RequestProcessor(self)
'Returns the response to the request. Any implementing gateway must define this function. @param amf_request: The AMF request. @type amf_request: L{Envelope<pyamf.remoting.Envelope>} @return: The AMF response. @rtype: L{Envelope<pyamf.remoting.Envelope>}'
def getResponse(self, amf_request):
raise NotImplementedError
'Decides whether the underlying http request should be exposed as the first argument to the method call. This is granular, looking at the service method first, then at the service level and finally checking the gateway. @rtype: C{bool}'
def mustExposeRequest(self, service_request):
expose_request = service_request.service.mustExposeRequest(service_request) if (expose_request is None): if (self.expose_request is None): return False return self.expose_request return expose_request
'Gets an authenticator callable based on the service_request. This is granular, looking at the service method first, then at the service level and finally to see if there is a global authenticator function for the gateway. Returns C{None} if one could not be found.'
def getAuthenticator(self, service_request):
auth = service_request.service.getAuthenticator(service_request) if (auth is None): return self.authenticator return auth
'Processes an authentication request. If no authenticator is supplied, then authentication succeeds. @return: Returns a C{bool} based on the result of authorization. A value of C{False} will stop processing the request and return an error to the client. @rtype: C{bool}'
def authenticateRequest(self, service_request, username, password, **kwargs):
authenticator = self.getAuthenticator(service_request) if (authenticator is None): return True args = (username, password) if hasattr(authenticator, '_pyamf_expose_request'): http_request = kwargs.get('http_request', None) args = ((http_request,) + args) return (authenticator...
'Gets a preprocessor callable based on the service_request. This is granular, looking at the service method first, then at the service level and finally to see if there is a global preprocessor function for the gateway. Returns C{None} if one could not be found.'
def getPreprocessor(self, service_request):
preproc = service_request.service.getPreprocessor(service_request) if (preproc is None): return self.preprocessor return preproc
'Preprocesses a request.'
def preprocessRequest(self, service_request, *args, **kwargs):
processor = self.getPreprocessor(service_request) if (processor is None): return args = ((service_request,) + args) if hasattr(processor, '_pyamf_expose_request'): http_request = kwargs.get('http_request', None) args = ((http_request,) + args) return processor(*args)
'Executes the service_request call'
def callServiceRequest(self, service_request, *args, **kwargs):
if self.mustExposeRequest(service_request): http_request = kwargs.get('http_request', None) args = ((http_request,) + args) return service_request(*args)
'Processes the AMF request, returning an AMF response. @param http_request: The underlying HTTP Request. @type http_request: U{HTTPRequest<http://docs.djangoproject.com /en/dev/ref/request-response/#httprequest-objects>} @param request: The AMF Request. @type request: L{Envelope<pyamf.remoting.Envelope>} @rtype: L{Enve...
def getResponse(self, http_request, request):
response = remoting.Envelope(request.amfVersion) for (name, message) in request: http_request.amf_request = message processor = self.getProcessor(message) response[name] = processor(message, http_request=http_request) return response
'Processes and dispatches the request.'
def __call__(self, http_request):
if (http_request.method != 'POST'): return http.HttpResponseNotAllowed(['POST']) stream = None timezone_offset = self._get_timezone_offset() try: request = remoting.decode(http_request.raw_post_data, strict=self.strict, logger=self.logger, timezone_offset=timezone_offset) except (pya...
'Processes the AMF request, returning an AMF response. @param request: The AMF Request. @type request: L{Envelope<pyamf.remoting.Envelope>} @rtype: L{Envelope<pyamf.remoting.Envelope>} @return: The AMF Response.'
def getResponse(self, request, environ):
response = remoting.Envelope(request.amfVersion) for (name, message) in request: processor = self.getProcessor(message) environ['pyamf.request'] = message response[name] = processor(message, http_request=environ) return response
'Return HTTP 400 Bad Request.'
def badRequestMethod(self, environ, start_response):
response = ('400 Bad Request\n\nTo access this PyAMF gateway you must use POST requests (%s received)' % environ['REQUEST_METHOD']) start_response('400 Bad Request', [('Content-Type', 'text/plain'), ('Content-Length', str(len(response))), ('Server', gateway.SERVER_NA...
'@rtype: C{StringIO} @return: File-like object.'
def __call__(self, environ, start_response):
if (environ['REQUEST_METHOD'] != 'POST'): return self.badRequestMethod(environ, start_response) body = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH'])) stream = None timezone_offset = self._get_timezone_offset() try: request = remoting.decode(body, strict=self.strict, logge...
'Processes the AMF request, returning an AMF response. :param request: The AMF Request. :type request: :class:`Envelope<pyamf.remoting.Envelope>` :rtype: :class:`Envelope<pyamf.remoting.Envelope>` :return: The AMF Response.'
def getResponse(self, request):
response = remoting.Envelope(request.amfVersion) for (name, message) in request: self.request.amf_request = message processor = self.getProcessor(message) response[name] = processor(message, http_request=self.request) return response
'Authenticates the request against the service. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>}'
def authenticateRequest(self, request, service_request, *args, **kwargs):
username = password = None if ('Credentials' in request.headers): cred = request.headers['Credentials'] username = cred['userid'] password = cred['password'] return self.gateway.authenticateRequest(service_request, username, password, *args, **kwargs)
'Builds an error response. @param request: The AMF request @type request: L{Request<pyamf.remoting.Request>} @return: The AMF response @rtype: L{Response<pyamf.remoting.Response>}'
def buildErrorResponse(self, request, error=None):
if (error is not None): (cls, e, tb) = error else: (cls, e, tb) = sys.exc_info() return remoting.Response(build_fault(cls, e, tb, self.gateway.debug), status=remoting.STATUS_ERROR)
'Processes an AMF0 request. @param request: The request to be processed. @type request: L{Request<pyamf.remoting.Request>} @return: The response to the request. @rtype: L{Response<pyamf.remoting.Response>}'
def __call__(self, request, *args, **kwargs):
response = remoting.Response(None) try: service_request = self.gateway.getServiceRequest(request, request.target) except gateway.UnknownServiceError: return self.buildErrorResponse(request) try: authd = self.authenticateRequest(request, service_request, *args, **kwargs) excep...
'This compiles the alias into a form that can be of most benefit to the en/decoder.'
def compile(self):
if self._compiled: return self.decodable_properties = set() self.encodable_properties = set() self.inherited_dynamic = None self.inherited_sealed = None self.bases = [] self.exclude_attrs = set((self.exclude_attrs or [])) self.readonly_attrs = set((self.readonly_attrs or [])) ...
'This function is used to check if the class being aliased fits certain criteria. The default is to check that C{__new__} is available or the C{__init__} constructor does not need additional arguments. If this is the case then L{TypeError} will be raised. @since: 0.4'
def checkClass(self, klass):
if (hasattr(klass, '__new__') and hasattr(klass.__new__, '__call__')): return if (not (hasattr(klass, '__init__') and hasattr(klass.__init__, '__call__'))): return klass_func = klass.__init__.im_func if (not hasattr(klass_func, 'func_code')): return if klass_func.func_default...
'Must return a C{dict} of attributes to be encoded, even if its empty. @param codec: An optional argument that will contain the encoder instance calling this function. @since: 0.5'
def getEncodableAttributes(self, obj, codec=None):
if (not self._compiled): self.compile() if self.is_dict: return dict(obj) if (self.shortcut_encode and self.dynamic): return obj.__dict__.copy() attrs = {} if self.static_attrs: for attr in self.static_attrs: attrs[attr] = getattr(obj, attr, pyamf.Undefine...
'Returns a dictionary of attributes for C{obj} that has been filtered, based on the supplied C{attrs}. This allows for fine grain control over what will finally end up on the object or not. @param obj: The object that will recieve the attributes. @param attrs: The C{attrs} dictionary that has been decoded. @param codec...
def getDecodableAttributes(self, obj, attrs, codec=None):
if (not self._compiled): self.compile() changed = False props = set(attrs.keys()) if self.static_attrs: missing_attrs = self.static_attrs_set.difference(props) if missing_attrs: raise AttributeError(('Static attributes %r expected when decoding %r' %...
'Applies the collection of attributes C{attrs} to aliased object C{obj}. Called when decoding reading aliased objects from an AMF byte stream. Override this to provide fine grain control of application of attributes to C{obj}. @param codec: An optional argument that will contain the en/decoder instance calling this fun...
def applyAttributes(self, obj, attrs, codec=None):
if (not self._compiled): self.compile() if self.shortcut_decode: if self.is_dict: obj.update(attrs) return if (not self.sealed): obj.__dict__.update(attrs) return else: attrs = self.getDecodableAttributes(obj, attrs, codec=codec...
'Creates an instance of the klass. @return: Instance of C{self.klass}.'
def createInstance(self, codec=None):
if (type(self.klass) is type): return self.klass.__new__(self.klass) return self.klass()
'@since: 0.5'
def decodeSmallAttribute(self, attr, input):
obj = input.readObject() if (attr in ['timestamp', 'timeToLive']): return pyamf.util.get_datetime((obj / 1000.0)) return obj
'@since: 0.5'
def encodeSmallAttribute(self, attr):
obj = getattr(self, attr) if (not obj): return obj if (attr in ['timestamp', 'timeToLive']): return (pyamf.util.get_timestamp(obj) * 1000.0) elif (attr in ['clientId', 'messageId']): if isinstance(obj, uuid.UUID): return None return obj