Example #1
0
    def __call__(self, environ, start_response):
        print environ

        if environ.get('PATH_INFO', None) == '/crossdomain.xml':
            response = """
            <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd"> 
            <cross-domain-policy> 
                <allow-access-from domain="*" /> 
            </cross-domain-policy> 
            """

            start_response('200 OK', [
                ('Content-Type', 'text/xml'),
                ('Content-Length', str(len(response))),
                ('Server', environ.get('REMOTE_HOST', '')),
            ])
            return [response]

        else:
            return WSGIGateway.__call__(self, environ, start_response)
Example #2
0
def render_amf(template_name, template_vars, **kwargs):
    assert 0

    # somehow we need to dummy out the services here, but im not sure how
    # yet
    def dummy(*args, **kw):
        return template_vars

    services = {
        'something.method': dummy,
    }

    # setup our server
    app = WSGIGateway(services)

    def start_request(*args, **kw):
        pass

    r = app(request.environ, start_request)
    return r
    def __call__(self, environ, start_response):
        print environ

        if environ.get('PATH_INFO', None) ==  '/crossdomain.xml':
            response = """
            <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd"> 
            <cross-domain-policy> 
                <allow-access-from domain="*" /> 
            </cross-domain-policy> 
            """            

            start_response('200 OK', [
                ('Content-Type', 'text/xml'),
                ('Content-Length', str(len(response))),
                ('Server', environ.get('REMOTE_HOST','')),
            ])
            return [response]

	else:
            return  WSGIGateway.__call__(self, environ, start_response)
Example #4
0
class WSGIServerTestCase(unittest.TestCase):
    def setUp(self):
        self.gw = WSGIGateway()
        self.executed = False

    def doRequest(self, request, start_response, **kwargs):
        kwargs.setdefault('REQUEST_METHOD', 'POST')
        kwargs.setdefault('CONTENT_LENGTH', str(len(request)))

        kwargs['wsgi.input'] = request

        def sr(status, headers):
            r = None

            if start_response:
                r = start_response(status, headers)

            self.executed = True

            return r

        return self.gw(kwargs, sr)

    def makeRequest(self, service, body, raw=False):
        if not raw:
            body = [body]

        e = remoting.Envelope(pyamf.AMF3)
        e['/1'] = remoting.Request(service, body=body)

        return remoting.encode(e)

    def test_request_method(self):
        def bad_response(status, headers):
            self.assertEqual(status, '400 Bad Request')
            self.executed = True

        self.gw({'REQUEST_METHOD': 'GET'}, bad_response)
        self.assertTrue(self.executed)

        self.assertRaises(KeyError, self.gw, {'REQUEST_METHOD': 'POST'},
            lambda *args: None)

    def test_bad_request(self):
        request = util.BufferedByteStream()
        request.write('Bad request')
        request.seek(0, 0)

        def start_response(status, headers):
            self.assertEqual(status, '400 Bad Request')

        self.doRequest(request, start_response)
        self.assertTrue(self.executed)

    def test_unknown_request(self):
        request = self.makeRequest('test.test', [], raw=True)

        def start_response(status, headers):
            self.executed = True
            self.assertEqual(status, '200 OK')
            self.assertTrue(('Content-Type', 'application/x-amf') in headers)

        response = self.doRequest(request, start_response)

        envelope = remoting.decode(''.join(response))

        message = envelope['/1']

        self.assertEqual(message.status, remoting.STATUS_ERROR)
        body = message.body

        self.assertTrue(isinstance(body, remoting.ErrorFault))
        self.assertEqual(body.code, 'Service.ResourceNotFound')
        self.assertTrue(self.executed)

    def test_eof_decode(self):
        request = util.BufferedByteStream()

        def start_response(status, headers):
            self.assertEqual(status, '400 Bad Request')
            self.assertTrue(('Content-Type', 'text/plain') in headers)

        response = self.doRequest(request, start_response)

        self.assertEqual(response, ['400 Bad Request\n\nThe request body was unable to be successfully decoded.'])
        self.assertTrue(self.executed)

    def _raiseException(self, e, *args, **kwargs):
        raise e()

    def _restoreDecode(self):
        remoting.decode = self.old_method

    def test_really_bad_decode(self):
        self.old_method = remoting.decode
        remoting.decode = lambda *args, **kwargs: self._raiseException(Exception, *args, **kwargs)
        self.addCleanup(self._restoreDecode)

        request = util.BufferedByteStream()

        def start_response(status, headers):
            self.assertEqual(status, '500 Internal Server Error')
            self.assertTrue(('Content-Type', 'text/plain') in headers)

        response = self.doRequest(request, start_response)

        self.assertEqual(response, ['500 Internal Server Error\n\nAn unexpec'
            'ted error occurred whilst decoding.'])
        self.assertTrue(self.executed)

    def test_expected_exceptions_decode(self):
        self.old_method = remoting.decode
        self.addCleanup(self._restoreDecode)
        request = util.BufferedByteStream()

        for x in (KeyboardInterrupt, SystemExit):
            remoting.decode = lambda *args, **kwargs: self._raiseException(x, *args, **kwargs)

            self.assertRaises(x, self.doRequest, request, None)

    def test_expose_request(self):
        self.gw.expose_request = True

        def echo(http_request, data):
            self.assertTrue('pyamf.request' in http_request)
            request = http_request['pyamf.request']

            self.assertTrue(isinstance(request, remoting.Request))

            self.assertEqual(request.target, 'echo')
            self.assertEqual(request.body, ['hello'])

        self.gw.addService(echo)
        self.doRequest(self.makeRequest('echo', 'hello'), None)

        self.assertTrue(self.executed)

    def test_timezone(self):
        import datetime

        td = datetime.timedelta(hours=-5)
        now = datetime.datetime.utcnow()

        def echo(d):
            self.assertEqual(d, now + td)

            return d

        self.gw.addService(echo)
        self.gw.timezone_offset = -18000

        response = self.doRequest(self.makeRequest('echo', now), None)
        envelope = remoting.decode(''.join(response))
        message = envelope['/1']

        self.assertEqual(message.body, now)
Example #5
0
from pyamf.remoting.gateway.wsgi import WSGIGateway

import logging

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s')


def echo(data):
    return data


services = {
    'echo': echo,
    # Add other exposed functions here
}

application = WSGIGateway(services, logger=logging, debug=True)
Example #6
0
class WSGIServerTestCase(unittest.TestCase):
    def setUp(self):
        self.gw = WSGIGateway()
        self.executed = False

    def test_request_method(self):
        def bad_response(status, headers):
            self.executed = True
            self.assertEquals(status, '400 Bad Request')

        self.gw({'REQUEST_METHOD': 'GET'}, bad_response)
        self.assertTrue(self.executed)

        self.assertRaises(KeyError, self.gw, {'REQUEST_METHOD': 'POST'},
                          lambda *args: None)

    def test_bad_request(self):
        request = util.BufferedByteStream()
        request.write('Bad request')
        request.seek(0, 0)

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': str(len(request)),
            'wsgi.input': request
        }

        def start_response(status, headers):
            self.assertEquals(status, '400 Bad Request')
            self.executed = True

        self.gw(env, start_response)
        self.assertTrue(self.executed)

    def test_unknown_request(self):
        request = util.BufferedByteStream()
        request.write(
            '\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00'
            '\x02/1\x00\x00\x00\x14\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00'
            '\x00\x01\x61\x02\x00\x01\x61\x00\x00\x09')
        request.seek(0, 0)

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': str(len(request)),
            'wsgi.input': request
        }

        def start_response(status, headers):
            self.executed = True
            self.assertEquals(status, '200 OK')
            self.assertTrue(('Content-Type', 'application/x-amf') in headers)

        response = self.gw(env, start_response)
        envelope = remoting.decode(''.join(response))

        message = envelope['/1']

        self.assertEquals(message.status, remoting.STATUS_ERROR)
        body = message.body

        self.assertTrue(isinstance(body, remoting.ErrorFault))
        self.assertEquals(body.code, 'Service.ResourceNotFound')
        self.assertTrue(self.executed)

    def test_eof_decode(self):
        request = util.BufferedByteStream()

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': str(len(request)),
            'wsgi.input': request
        }

        def start_response(status, headers):
            self.executed = True
            self.assertEquals(status, '400 Bad Request')
            self.assertTrue(('Content-Type', 'text/plain') in headers)

        response = self.gw(env, start_response)

        self.assertEquals(response, [
            '400 Bad Request\n\nThe request body was unable to be successfully decoded.'
        ])
        self.assertTrue(self.executed)

    def _raiseException(self, e, *args, **kwargs):
        raise e()

    def test_really_bad_decode(self):
        self.old_method = remoting.decode
        remoting.decode = lambda *args, **kwargs: self._raiseException(
            Exception, *args, **kwargs)

        request = util.BufferedByteStream()

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': str(len(request)),
            'wsgi.input': request
        }

        def start_response(status, headers):
            self.executed = True
            self.assertEquals(status, '500 Internal Server Error')
            self.assertTrue(('Content-Type', 'text/plain') in headers)

        try:
            response = self.gw(env, start_response)
        except:
            remoting.decode = self.old_method

            raise

        remoting.decode = self.old_method

        self.assertEquals(response, [
            '500 Internal Server Error\n\nAn unexpec'
            'ted error occurred whilst decoding.'
        ])
        self.assertTrue(self.executed)

    def test_expected_exceptions_decode(self):
        self.old_method = remoting.decode

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': '0',
            'wsgi.input': util.BufferedByteStream()
        }

        try:
            for x in (KeyboardInterrupt, SystemExit):
                remoting.decode = lambda *args, **kwargs: self._raiseException(
                    x, *args, **kwargs)
                self.assertRaises(x, self.gw, env, lambda *args: args)
        except:
            remoting.decode = self.old_method

            raise

        remoting.decode = self.old_method

    def test_expose_request(self):
        self.gw.expose_request = True
        self.executed = False

        env = remoting.Envelope(pyamf.AMF0, pyamf.ClientTypes.Flash9)
        request = remoting.Request('echo', body=['hello'])
        env['/1'] = request

        request = remoting.encode(env)

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': str(len(request)),
            'wsgi.input': request
        }

        def echo(http_request, data):
            self.assertTrue('pyamf.request' in http_request)
            request = http_request['pyamf.request']

            self.assertTrue(isinstance(request, remoting.Request))

            self.assertEquals(request.target, 'echo')
            self.assertEquals(request.body, ['hello'])
            self.executed = True

            return data

        self.gw.addService(echo)

        response = self.gw(env, lambda *args: None)

        self.assertTrue(self.executed)

    def test_timezone(self):
        import datetime

        self.executed = False

        td = datetime.timedelta(hours=-5)
        now = datetime.datetime.utcnow()

        def echo(d):
            self.assertEquals(d, now + td)
            self.executed = True

            return d

        self.gw.addService(echo)
        self.gw.timezone_offset = -18000

        msg = remoting.Envelope(amfVersion=pyamf.AMF0, clientType=0)
        msg['/1'] = remoting.Request(target='echo', body=[now])

        stream = remoting.encode(msg)

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': str(len(stream)),
            'wsgi.input': stream
        }

        response = self.gw(env, lambda *args: None)
        envelope = remoting.decode(''.join(response))
        message = envelope['/1']

        self.assertEquals(message.body, now)
Example #7
0
def echo(data):
    """
    Just return data back to the client.
    """
    return data


services = {'echo': echo, 'echo.echo': echo}

if __name__ == '__main__':
    import os
    from pyamf.remoting.gateway.wsgi import WSGIGateway
    from wsgiref import simple_server

    gw = WSGIGateway(services)

    httpd = simple_server.WSGIServer(
        ('localhost', 8000),
        simple_server.WSGIRequestHandler,
    )

    def app(environ, start_response):
        if environ['PATH_INFO'] == '/crossdomain.xml':
            fn = os.path.join(os.getcwd(), os.path.dirname(__file__),
                              'crossdomain.xml')

            fp = open(fn, 'rt')
            buffer = fp.readlines()
            fp.close()
Example #8
0
 def __call__(self, environ, start_response):
     return _WSGIGateway.__call__(self, environ, start_response)
Example #9
0
 def __init__(self, host, port, serviceName):
     services = {serviceName: self.echo}
     gw = WSGIGateway(services, logger=logging)
     self.httpd = WSGIServer((host, port), ServerRequestLogger)
     self.httpd.set_app(gw)
Example #10
0
def gateway(request):
    services = {'SimpleImgUtil': SimpleImgUtil}
    return WSGIGateway(services)
Example #11
0
def main():
    logging.info("Starting app")
    application = WSGIGateway(services)
    wsgiref.handlers.CGIHandler().run(application)
Example #12
0
 
  @since: 0.1.0
  """
  
from wsgiref import simple_server

from pyamf.remoting.gateway.wsgi import WSGIGateway
   
class CalcService:
    def sum(self, a, b):
        return a + b
  
def auth(username, password):
    if username == 'jane' and password == 'doe':
        return True
        
    return False

httpd = simple_server.WSGIServer(('localhost', 8000), simple_server.WSGIRequestHandler)

gateway = WSGIGateway({'calc': CalcService}, authenticator=auth)

httpd.set_app(gateway)

print "Running Authentication AMF gateway on http://localhost:8000"

try:
    httpd.serve_forever()
except KeyboardInterrupt:
    pass
    
Example #13
0
def gateway(request):
    services = {
        'tweetutil':TweetUtil
    }
    return WSGIGateway(services)
Example #14
0
def main():
    gateway = WSGIGateway(services)

    util.run_wsgi_app(gateway)
Example #15
0
 def setUp(self):
     self.gw = WSGIGateway()
     self.executed = False
Example #16
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from werkzeug import run_simple

from pyamf.remoting.gateway.wsgi import WSGIGateway

import logging

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s')


def echo(data):
    return data


services = {'echo': echo}
gw = WSGIGateway(services, logger=logging, debug=True)

run_simple('localhost', 8080, gw, use_reloader=True)
Example #17
0
def main():
    """
    Create a WSGIGateway application and serve it.
    """
    # register class on the AMF namespace so that it is passed marshaled
    register_classes()

    # use a dict in leiu of sqlite or an actual database to store users
    # re passwords: plain-text in a production would be bad
    users = {
        'lenards': User('lenards', 'f00f00', '*****@*****.**'),
        'lisa': User('lisa', 'h1k3r', '*****@*****.**'),
    }
    testmap = """
<graph version="1.1">
 <node id="1">
    <data>
     <Task>
       <actualHours>NaN</actualHours>
       <assignedTo/>
       <committed>false</committed>
       <complexity>0</complexity>
       <date>null</date>
       <description/>
       <done>0</done>
       <estimatedHours>NaN</estimatedHours>
       <name>test</name>
       <priority>0</priority>
       <reviewed>false</reviewed>
     </Task>
    </data>
    <relations>
     <relation targetNodeId="2" type="child"/>
     <relation targetNodeId="3" type="child"/>
    </relations>
 </node>
 <node id="2">
    <data>
     <Task>
       <actualHours>0.1</actualHours>
       <assignedTo>V</assignedTo>
       <committed>false</committed>
       <complexity>0</complexity>
       <date>null</date>
       <description/>
       <done>1</done>
       <estimatedHours>0.2</estimatedHours>
       <name>task2</name>
       <priority>0</priority>
       <reviewed>false</reviewed>
     </Task>
    </data>
 </node>
 <node id="3">
    <data>
     <Task>
       <actualHours>NaN</actualHours>
       <assignedTo/>
       <committed>false</committed>
       <complexity>0</complexity>
       <date>null</date>
       <description/>
       <done>0</done>
       <estimatedHours>NaN</estimatedHours>
       <name>task3</name>
       <priority>0</priority>
       <reviewed>false</reviewed>
     </Task>
    </data>
 </node>
</graph>
"""
    maps = [
        Map('1', "first Map", "2012-01-16", testmap, 0, 0),
        Map('2', "second Map", "2012-01-16", testmap, 0, 0),
        Map('3', "third Map", "2012-01-16", testmap, 0, 0),
        Map('4', "forth Map", "2012-01-16", testmap, 0, 0),
    ]
    # our gateway will have two services
    services = {
        'echo': EchoService,
        'user': UserService(users),
        'map': MapService(maps)
    }

    # setup our server
    application = WSGIGateway(services, logger=logging)
    httpd = simple_server.WSGIServer(host_info,
                                     simple_server.WSGIRequestHandler)
    httpd.set_app(application)

    try:
        # open for business
        print "Running Simple PyAMF gateway on http://%s:%d" % (host_info[0],
                                                                host_info[1])
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
Example #18
0
parser.add_option("--host",
                  default="localhost",
                  dest="host",
                  help="host address [default: %default]")
parser.add_option("--api-key",
                  default="123456789",
                  dest="api_key",
                  help="Ohloh API key [default: %default]")
(options, args) = parser.parse_args()

ohloh = UserAccount(options.api_key)
services = {'ohloh.account': ohloh.getAccount}

host = options.host
port = int(options.port)
gw = WSGIGateway(services, logger=logging)

httpd = simple_server.WSGIServer(
    (host, port),
    simple_server.WSGIRequestHandler,
)

httpd.set_app(gw)

print "Running Ohloh API AMF gateway on http://%s:%d" % (host, port)

try:
    httpd.serve_forever()
except KeyboardInterrupt:
    pass
Example #19
0
    (options, args) = parser.parse_args()

    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s')

    host = options.host
    port = int(options.port)

    # Start server
    print "Running SQLAlchemy AMF gateway on http://%s:%d" % (host, port)
    print "Press Ctrl-c to stop server."

    server = simple_server.WSGIServer((host, port),
                                      simple_server.WSGIRequestHandler)
    gateway = WSGIGateway(mapped_services, logger=logging)

    def app(environ, start_response):
        if environ['PATH_INFO'] == '/crossdomain.xml':
            fn = os.path.join(os.getcwd(), os.path.dirname(__file__),
                              'crossdomain.xml')

            fp = open(fn, 'rt')
            buffer = fp.readlines()
            fp.close()

            start_response('200 OK',
                           [('Content-Type', 'application/xml'),
                            ('Content-Length', str(len(''.join(buffer))))])

            return buffer
Example #20
0
from pyamf.remoting.gateway.wsgi import WSGIGateway

import service

# get platform specific shared object folder
path = service.default_folder()
filetype = "*.sol"

services = {'lso': service.SharedObjectService(path, filetype)}

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s')

application = WSGIGateway(services, logger=logging)

if __name__ == '__main__':
    from optparse import OptionParser
    from wsgiref import simple_server

    parser = OptionParser()
    parser.add_option("-p",
                      "--port",
                      default=8000,
                      dest="port",
                      help="port number [default: %default]")
    parser.add_option("--host",
                      default="localhost",
                      dest="host",
                      help="host address [default: %default]")
Example #21
0
services = {
    'server':im_server,
    'retail':retail
}

# Create a dictionary mapping the service namespaces to a function
# or class instance

# Create and start a thread pool,
wsgiThreadPool = ThreadPool()
wsgiThreadPool.start()

# ensuring that it will be stopped when the reactor shuts down
reactor.addSystemEventTrigger('after', 'shutdown', wsgiThreadPool.stop)

# PyAMF gateway
gateway = WSGIGateway(services, logger = logging, expose_request = False, debug = True)


# Create the WSGI resource
wsgiAppAsResource = WSGIResource(reactor, wsgiThreadPool, gateway)
site = server.Site(wsgiAppAsResource)


reactor.suggestThreadPoolSize(5000)
# Hooks for twistd
application = service.Application('Invoice Mananger Remoting Server')
#server = strports.service('tcp:8002', site)
#server.setServiceParent(application)

Example #22
0
if __name__ == '__main__':
    import sys, logging
    from pyamf.remoting.gateway.wsgi import WSGIGateway
    from wsgiref import simple_server

    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s')

    options = parse_args(sys.argv[1:])[0]
    service = {'service': SoftwareService(db.get_engine())}

    host = options.host
    port = int(options.port)

    gw = WSGIGateway(service, debug=True, logger=logging)

    httpd = simple_server.WSGIServer(
        (host, port),
        simple_server.WSGIRequestHandler,
    )

    httpd.set_app(gw)

    logging.info('Started RecordSet example server on http://%s:%s' %
                 (host, str(port)))

    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
Example #23
0
class WSGIServerTestCase(unittest.TestCase):
    def setUp(self):
        self.gw = WSGIGateway()
        self.executed = False

    def test_request_method(self):
        def bad_response(status, headers):
            self.executed = True
            self.assertEquals(status, '400 Bad Request')

        self.gw({'REQUEST_METHOD': 'GET'}, bad_response)
        self.assertTrue(self.executed)

        self.assertRaises(KeyError, self.gw, {'REQUEST_METHOD': 'POST'},
            lambda *args: None)

    def test_bad_request(self):
        request = util.BufferedByteStream()
        request.write('Bad request')
        request.seek(0, 0)

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': str(len(request)),
            'wsgi.input': request
        }

        def start_response(status, headers):
            self.assertEquals(status, '400 Bad Request')
            self.executed = True

        self.gw(env, start_response)
        self.assertTrue(self.executed)

    def test_unknown_request(self):
        request = util.BufferedByteStream()
        request.write('\x00\x00\x00\x00\x00\x01\x00\x09test.test\x00'
            '\x02/1\x00\x00\x00\x14\x0a\x00\x00\x00\x01\x08\x00\x00\x00\x00'
            '\x00\x01\x61\x02\x00\x01\x61\x00\x00\x09')
        request.seek(0, 0)

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': str(len(request)),
            'wsgi.input': request
        }

        def start_response(status, headers):
            self.executed = True
            self.assertEquals(status, '200 OK')
            self.assertTrue(('Content-Type', 'application/x-amf') in headers)

        response = self.gw(env, start_response)
        envelope = remoting.decode(''.join(response))

        message = envelope['/1']

        self.assertEquals(message.status, remoting.STATUS_ERROR)
        body = message.body

        self.assertTrue(isinstance(body, remoting.ErrorFault))
        self.assertEquals(body.code, 'Service.ResourceNotFound')
        self.assertTrue(self.executed)

    def test_eof_decode(self):
        request = util.BufferedByteStream()

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': str(len(request)),
            'wsgi.input': request
        }

        def start_response(status, headers):
            self.executed = True
            self.assertEquals(status, '400 Bad Request')
            self.assertTrue(('Content-Type', 'text/plain') in headers)

        response = self.gw(env, start_response)

        self.assertEquals(response, ['400 Bad Request\n\nThe request body was unable to be successfully decoded.'])
        self.assertTrue(self.executed)

    def _raiseException(self, e, *args, **kwargs):
        raise e()

    def test_really_bad_decode(self):
        self.old_method = remoting.decode
        remoting.decode = lambda *args, **kwargs: self._raiseException(Exception, *args, **kwargs)

        request = util.BufferedByteStream()

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': str(len(request)),
            'wsgi.input': request
        }

        def start_response(status, headers):
            self.executed = True
            self.assertEquals(status, '500 Internal Server Error')
            self.assertTrue(('Content-Type', 'text/plain') in headers)

        try:
            response = self.gw(env, start_response)
        except:
            remoting.decode = self.old_method

            raise

        remoting.decode = self.old_method

        self.assertEquals(response, ['500 Internal Server Error\n\nAn unexpec'
            'ted error occurred whilst decoding.'])
        self.assertTrue(self.executed)

    def test_expected_exceptions_decode(self):
        self.old_method = remoting.decode

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': '0',
            'wsgi.input': util.BufferedByteStream()
        }

        try:
            for x in (KeyboardInterrupt, SystemExit):
                remoting.decode = lambda *args, **kwargs: self._raiseException(x, *args, **kwargs)
                self.assertRaises(x, self.gw, env, lambda *args: args)
        except:
            remoting.decode = self.old_method

            raise

        remoting.decode = self.old_method

    def test_expose_request(self):
        self.gw.expose_request = True
        self.executed = False

        env = remoting.Envelope(pyamf.AMF3)
        request = remoting.Request('echo', body=['hello'])
        env['/1'] = request

        request = remoting.encode(env)

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': str(len(request)),
            'wsgi.input': request
        }

        def echo(http_request, data):
            self.assertTrue('pyamf.request' in http_request)
            request = http_request['pyamf.request']

            self.assertTrue(isinstance(request, remoting.Request))

            self.assertEquals(request.target, 'echo')
            self.assertEquals(request.body, ['hello'])
            self.executed = True

            return data

        self.gw.addService(echo)

        response = self.gw(env, lambda *args: None)

        self.assertTrue(self.executed)

    def test_timezone(self):
        import datetime

        self.executed = False

        td = datetime.timedelta(hours=-5)
        now = datetime.datetime.utcnow()

        def echo(d):
            self.assertEquals(d, now + td)
            self.executed = True

            return d

        self.gw.addService(echo)
        self.gw.timezone_offset = -18000

        msg = remoting.Envelope(amfVersion=pyamf.AMF0)
        msg['/1'] = remoting.Request(target='echo', body=[now])

        stream = remoting.encode(msg)

        env = {
            'REQUEST_METHOD': 'POST',
            'CONTENT_LENGTH': str(len(stream)),
            'wsgi.input': stream
        }

        response = self.gw(env, lambda *args: None)
        envelope = remoting.decode(''.join(response))
        message = envelope['/1']

        self.assertEquals(message.body, now)
Example #24
0
def main():
    application = WSGIGateway(services, authenticator=auth)
    wsgiref.handlers.CGIHandler().run(application)
Example #25
0
class WSGIServerTestCase(unittest.TestCase):
    def setUp(self):
        self.gw = WSGIGateway()
        self.executed = False

    def doRequest(self, request, start_response, **kwargs):
        kwargs.setdefault('REQUEST_METHOD', 'POST')
        kwargs.setdefault('CONTENT_LENGTH', str(len(request)))

        kwargs['wsgi.input'] = request

        def sr(status, headers):
            r = None

            if start_response:
                r = start_response(status, headers)

            self.executed = True

            return r

        return self.gw(kwargs, sr)

    def makeRequest(self, service, body, raw=False):
        if not raw:
            body = [body]

        e = remoting.Envelope(pyamf.AMF3)
        e['/1'] = remoting.Request(service, body=body)

        return remoting.encode(e)

    def test_request_method(self):
        def bad_response(status, headers):
            self.assertEqual(status, '400 Bad Request')
            self.executed = True

        self.gw({'REQUEST_METHOD': 'GET'}, bad_response)
        self.assertTrue(self.executed)

        self.assertRaises(KeyError, self.gw, {'REQUEST_METHOD': 'POST'},
                          lambda *args: None)

    def test_bad_request(self):
        request = util.BufferedByteStream()
        request.write('Bad request')
        request.seek(0, 0)

        def start_response(status, headers):
            self.assertEqual(status, '400 Bad Request')

        self.doRequest(request, start_response)
        self.assertTrue(self.executed)

    def test_unknown_request(self):
        request = self.makeRequest('test.test', [], raw=True)

        def start_response(status, headers):
            self.executed = True
            self.assertEqual(status, '200 OK')
            self.assertTrue(('Content-Type', 'application/x-amf') in headers)

        response = self.doRequest(request, start_response)

        envelope = remoting.decode(''.join(response))

        message = envelope['/1']

        self.assertEqual(message.status, remoting.STATUS_ERROR)
        body = message.body

        self.assertTrue(isinstance(body, remoting.ErrorFault))
        self.assertEqual(body.code, 'Service.ResourceNotFound')
        self.assertTrue(self.executed)

    def test_eof_decode(self):
        request = util.BufferedByteStream()

        def start_response(status, headers):
            self.assertEqual(status, '400 Bad Request')
            self.assertTrue(('Content-Type', 'text/plain') in headers)

        response = self.doRequest(request, start_response)

        self.assertEqual(response, [
            '400 Bad Request\n\nThe request body was unable to be successfully decoded.'
        ])
        self.assertTrue(self.executed)

    def _raiseException(self, e, *args, **kwargs):
        raise e()

    def _restoreDecode(self):
        remoting.decode = self.old_method

    def test_really_bad_decode(self):
        self.old_method = remoting.decode
        remoting.decode = lambda *args, **kwargs: self._raiseException(
            Exception, *args, **kwargs)
        self.addCleanup(self._restoreDecode)

        request = util.BufferedByteStream()

        def start_response(status, headers):
            self.assertEqual(status, '500 Internal Server Error')
            self.assertTrue(('Content-Type', 'text/plain') in headers)

        response = self.doRequest(request, start_response)

        self.assertEqual(response, [
            '500 Internal Server Error\n\nAn unexpec'
            'ted error occurred whilst decoding.'
        ])
        self.assertTrue(self.executed)

    def test_expected_exceptions_decode(self):
        self.old_method = remoting.decode
        self.addCleanup(self._restoreDecode)
        request = util.BufferedByteStream()

        for x in (KeyboardInterrupt, SystemExit):
            remoting.decode = lambda *args, **kwargs: self._raiseException(
                x, *args, **kwargs)

            self.assertRaises(x, self.doRequest, request, None)

    def test_expose_request(self):
        self.gw.expose_request = True

        def echo(http_request, data):
            self.assertTrue('pyamf.request' in http_request)
            request = http_request['pyamf.request']

            self.assertTrue(isinstance(request, remoting.Request))

            self.assertEqual(request.target, 'echo')
            self.assertEqual(request.body, ['hello'])

        self.gw.addService(echo)
        self.doRequest(self.makeRequest('echo', 'hello'), None)

        self.assertTrue(self.executed)

    def test_timezone(self):
        import datetime

        td = datetime.timedelta(hours=-5)
        now = datetime.datetime.utcnow()

        def echo(d):
            self.assertEqual(d, now + td)

            return d

        self.gw.addService(echo)
        self.gw.timezone_offset = -18000

        response = self.doRequest(self.makeRequest('echo', now), None)
        envelope = remoting.decode(''.join(response))
        message = envelope['/1']

        self.assertEqual(message.body, now)
Example #26
0
 def setUp(self):
     self.gw = WSGIGateway()
     self.executed = False
Example #27
0
import logging

from pyamf.remoting.gateway.wsgi import WSGIGateway

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s')


class Services(object):
    def echo(self, data):
        return "Turbogears gateway says:" + str(data)

    def sum(self, a, b):
        return a + b

    def scramble(self, text):
        from random import shuffle
        s = [x for x in text]
        shuffle(s)
        return ''.join(s)


# Expose our services
services = {"Services": Services()}

GatewayController = WSGIGateway(services, logger=logging, debug=True)