コード例 #1
0
    def inner_run(self, *args, **options):
        threading = options.get('use_threading')
        shutdown_message = options.get('shutdown_message', '')
        quit_command = (sys.platform
                        == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'

        try:
            """
              handler = self.get_handler(*args, **options)
              basehttp.run(self.addr, int(self.port), handler,
                           ipv6=self.use_ipv6, threading=threading)
            """
            config = {
                'msg_conn':
                Mongrel2Connection('tcp://127.0.0.1:9999',
                                   'tcp://127.0.0.1:9998'),
                'handler_tuples': [(r'^/brubeck', DemoHandler)],
            }
            app = Brubeck(**config)
            app.run()

        # TODO: Catch IP/port errors here!

        except KeyboardInterrupt:
            if shutdown_message:
                self.stdout.write(shutdown_message)
            sys.exit(0)
コード例 #2
0
 def setUp(self):
     """ will get run for each test """
     config = {
         'mongrel2_pair': ('ipc://127.0.0.1:9999', 'ipc://127.0.0.1:9998'),
         'msg_conn': WSGIConnection()
     }
     self.app = Brubeck(**config)
コード例 #3
0
ファイル: application.py プロジェクト: gad2103/qoorateserver
    def __init__(self, settings_file, project_dir,
                 *args, **kwargs):
        """ Most of the parameters are dealt with by Brubeck,
            do a little before call to super
        """


        if project_dir == None:
            raise Exception('missing project_dir from config')
        else:
            self.project_dir = project_dir

        """load our settings"""
        if settings_file != None:
            self.settings = self.get_settings_from_file(settings_file)
        else:
            self.settings = {}

        # we may have overriden default mongrel2_pairs in settings
        #if 'mongrel2_pair' in self.settings:
        #    kwargs['mongrel2_pair'] = self.settings['mongrel2_pair']

        Brubeck.__init__(self, **kwargs)
コード例 #4
0
ファイル: proxy.py プロジェクト: pombredanne/openscrape
    it is ready.
    """

    def post(self):
        json_request = self.message.body
        try:
            # connect to backend
            sock = CONTEXT.socket(zmq.REQ)
            sock.connect(BACKEND_URI)
            #request_obj = ast.literal_eval(json_request)
            #sock.send_json(request_obj)
            sock.send(json_request)

            resp = sock.recv()
            self.headers['Content-Type'] = 'application/json'

            self.set_body(resp)
        except Exception as e:
            self.set_status(400,
                            status_msg="Invalid JSON Request: '%s', error '%s'"
                            % (json_request, e))

        return self.render()

config.update({
    'mongrel2_pair': (config[RECV_SPEC], config[SEND_SPEC]),
    'handler_tuples': [(r'^/request$', RequestHandler)] })

openscrape = Brubeck(**config)
openscrape.run()
コード例 #5
0
ファイル: server.py プロジェクト: talos/opengold
                self.set_status(204)
            else:
                self.set_status(400, 'Could not submit move')
        else:
            self.set_status(400, 'You are not in this game')

        return self.render()

###
#
# BRUBECK RUNNER
#
###
config = {
    'msg_conn': WSGIConnection(port=PORT),
    'handler_tuples': [(r'^/$', GameListHandler),
                       (r'^/create$', CreateGameHandler),
                       (r'^/(?P<game_name>[^/]+)$', ForwardToGameHandler),
                       (r'^/(?P<game_name>[^/]+)/$', GameHandler),
                       (r'^/(?P<game_name>[^/]+)/join$', JoinHandler),
                       (r'^/(?P<game_name>[^/]+)/start$', StartHandler),
                       (r'^/(?P<game_name>[^/]+)/move$', MoveHandler),
                       (r'^/(?P<game_name>[^/]+)/chat$', ChatHandler)],
    'cookie_secret': COOKIE_SECRET,
    'db_conn': redis.StrictRedis(db=DB),
    'template_loader': load_mustache_env('./templates')
}

opengold = Brubeck(**config)
opengold.run()
コード例 #6
0
###

# Instantiate database connection
db_conn = init_db_conn()

# Routing config
handler_tuples = [
    (r'^/login', AccountLoginHandler),
    (r'^/logout', AccountLogoutHandler),
    (r'^/create', AccountCreateHandler),
    (r'^/add_item', ListAddHandler),
    (r'^/api', APIListDisplayHandler),
    (r'^/$', ListDisplayHandler),
]

# Application config
config = {
    'msg_conn': Mongrel2Connection('tcp://127.0.0.1:9999','tcp://127.0.0.1:9998'),
    'handler_tuples': handler_tuples,
    'template_loader': load_jinja2_env('./templates'),
    'db_conn': db_conn,
    'login_url': '/login',
    'cookie_secret': 'OMGSOOOOOSECRET',
    'log_level': logging.DEBUG,
}


# Instantiate app instance
app = Brubeck(**config)
app.run()
コード例 #7
0
ファイル: todos.py プロジェクト: gone/todos

class TodosHandler(BaseHandler, Jinja2Rendering):
    def get(self):
        """A list display matching the parameters of a user's dashboard. The
        parameters essentially map to the variation in how `load_listitems` is
        called.
        """
        return self.render_template("todos.html")


###
### Configuration
###

# Routing config
handler_tuples = [(r"^/$", TodosHandler)]

# Application config
config = {
    "mongrel2_pair": ("ipc://127.0.0.1:9999", "ipc://127.0.0.1:9998"),
    "handler_tuples": handler_tuples,
    "template_loader": load_jinja2_env("."),
}


# Instantiate app instance
app = Brubeck(**config)
app.register_api(TodosAPI)
app.run()
コード例 #8
0
 def setUp(self):
     """ will get run for each test """
     config = {
         'mongrel2_pair': ('ipc://127.0.0.1:9999', 'ipc://127.0.0.1:9998')
     }
     self.app = Brubeck(**config)
コード例 #9
0
#!/usr/bin/env python

from brubeck.request_handling import Brubeck
from brubeck.templating import MakoRendering, load_mako_env
from brubeck.connections import Mongrel2Connection
import sys


class DemoHandler(MakoRendering):
    def get(self):
        name = self.get_argument('name', 'dude')
        context = {
            'name': name
        }
        return self.render_template('success.html', **context)

app = Brubeck(msg_conn=Mongrel2Connection('tcp://127.0.0.1:9999', 'tcp://127.0.0.1:9998'),
              handler_tuples=[(r'^/brubeck', DemoHandler)],
              template_loader=load_mako_env('./templates/mako'))
app.run()
コード例 #10
0
class TestRequestHandling(unittest.TestCase):
    """
    a test class for brubeck's request_handler
    """

    def setUp(self):
        """ will get run for each test """
        config = {
            'mongrel2_pair': ('ipc://127.0.0.1:9999', 'ipc://127.0.0.1:9998'),
            'msg_conn': WSGIConnection()
        }
        self.app = Brubeck(**config)
    ##
    ## our actual tests( test _xxxx_xxxx(self) ) 
    ##
    def test_add_route_rule_method(self):
	# Make sure we have no routes
        self.assertEqual(hasattr(self.app,'_routes'),False)

        # setup a route
        self.setup_route_with_method()

        # Make sure we have some routes
        self.assertEqual(hasattr(self.app,'_routes'),True)

        # Make sure we have exactly one route
        self.assertEqual(len(self.app._routes),1)

    def test_init_routes_with_methods(self):
        # Make sure we have no routes
        self.assertEqual(hasattr(self.app, '_routes'), False)

        # Create a tuple with routes with method handlers
        routes = [ (r'^/', simple_handler_method), (r'^/brubeck', simple_handler_method) ]
        # init our routes
        self.app.init_routes( routes )

        # Make sure we have two routes
        self.assertEqual(len(self.app._routes), 2)

    def test_init_routes_with_objects(self):
        # Make sure we have no routes
        self.assertEqual(hasattr(self.app, '_routes'), False)

        # Create a tuple of routes with object handlers
        routes = [(r'^/', SimpleWebHandlerObject), (r'^/brubeck', SimpleWebHandlerObject)]
        self.app.init_routes( routes )

        # Make sure we have two routes
        self.assertEqual(len(self.app._routes), 2)

    def test_init_routes_with_objects_and_methods(self):
        # Make sure we have no routes
        self.assertEqual(hasattr(self.app, '_routes'), False)

        # Create a tuple of routes with a method handler and an object handler
        routes = [(r'^/', SimpleWebHandlerObject), (r'^/brubeck', simple_handler_method)]
        self.app.init_routes( routes )

        # Make sure we have two routes
        self.assertEqual(len(self.app._routes), 2)

    def test_add_route_rule_object(self):
        # Make sure we have no routes
        self.assertEqual(hasattr(self.app,'_routes'),False)
        self.setup_route_with_object()

        # Make sure we have some routes
        self.assertEqual(hasattr(self.app,'_routes'),True)

        # Make sure we have exactly one route
        self.assertEqual(len(self.app._routes),1)

    def test_brubeck_handle_request_with_object(self):
        # set up our route
        self.setup_route_with_object()

        # Make sure we get a handler back when we request one
        message = MockMessage(path='/')
        handler = self.app.route_message(message)
        self.assertNotEqual(handler,None)

    def test_brubeck_handle_request_with_method(self):
        # We ran tests on this already, so assume it works
        self.setup_route_with_method()

        # Make sure we get a handler back when we request one
        message = MockMessage(path='/')
        handler = self.app.route_message(message)
        self.assertNotEqual(handler,None)

    def test_cookie_handling(self):
        # set our cookie key and values
        cookie_key = 'my_key'
        cookie_value = 'my_secret'

        # encode our cookie
        encoded_cookie = cookie_encode(cookie_value, cookie_key)

        # Make sure we do not contain our value (i.e. we are really encrypting)
        self.assertEqual(encoded_cookie.find(cookie_value) == -1, True)

        # Make sure we are an encoded cookie using the function
        self.assertEqual(cookie_is_encoded(encoded_cookie), True)

        # Make sure after decoding our cookie we are the same as the unencoded cookie
        decoded_cookie_value = cookie_decode(encoded_cookie, cookie_key)
        self.assertEqual(decoded_cookie_value, cookie_value)
    
    ##
    ## test a bunch of very simple requests making sure we get the expected results
    ##
    def test_web_request_handling_with_object(self):
        self.setup_route_with_object()
        result = route_message(self.app, Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT))
        response = http_response(result['body'], result['status_code'], result['status_msg'], result['headers'])
        self.assertEqual(FIXTURES.HTTP_RESPONSE_OBJECT_ROOT, response)

    def test_web_request_handling_with_method(self):
        self.setup_route_with_method()
        response = route_message(self.app, Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT))
        self.assertEqual(FIXTURES.HTTP_RESPONSE_METHOD_ROOT, response)

    def test_json_request_handling_with_object(self):
        self.app.add_route_rule(r'^/$',SimpleJSONHandlerObject)
        result = route_message(self.app, Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT))
        response = http_response(result['body'], result['status_code'], result['status_msg'], result['headers'])
        self.assertEqual(FIXTURES.HTTP_RESPONSE_JSON_OBJECT_ROOT, response)

    def test_request_with_cookie_handling_with_object(self):
        self.app.add_route_rule(r'^/$',CookieWebHandlerObject)
        result = route_message(self.app, Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT_WITH_COOKIE))
        response = http_response(result['body'], result['status_code'], result['status_msg'], result['headers'])
        self.assertEqual(FIXTURES.HTTP_RESPONSE_OBJECT_ROOT_WITH_COOKIE, response)

    def test_request_with_cookie_response_with_cookie_handling_with_object(self):
        self.app.add_route_rule(r'^/$',CookieWebHandlerObject)
        result = route_message(self.app, Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT_WITH_COOKIE))
        response = http_response(result['body'], result['status_code'], result['status_msg'], result['headers'])
        self.assertEqual(FIXTURES.HTTP_RESPONSE_OBJECT_ROOT_WITH_COOKIE, response)

    def test_request_without_cookie_response_with_cookie_handling_with_object(self):
        self.app.add_route_rule(r'^/$',CookieAddWebHandlerObject)
        result = route_message(self.app, Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT))
        response = http_response(result['body'], result['status_code'], result['status_msg'], result['headers'])
        self.assertEqual(FIXTURES.HTTP_RESPONSE_OBJECT_ROOT_WITH_COOKIE, response)

    def test_build_http_response(self):
        response = http_response(FIXTURES.TEST_BODY_OBJECT_HANDLER, 200, 'OK', dict())
        self.assertEqual(FIXTURES.HTTP_RESPONSE_OBJECT_ROOT, response)

    def test_handler_initialize_hook(self):
        ## create a handler that sets the expected body(and headers) in the initialize hook
        handler = InitializeHookWebHandlerObject(self.app, Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT))
        result = handler()
        response = http_response(result['body'], result['status_code'], result['status_msg'], result['headers'])
        self.assertEqual(response, FIXTURES.HTTP_RESPONSE_OBJECT_ROOT)

    def test_handler_prepare_hook(self):
        # create a handler that sets the expected body in the prepare hook
        handler = PrepareHookWebHandlerObject(self.app, Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT))
        result = handler()
        response = http_response(result['body'], result['status_code'], result['status_msg'], result['headers'])
        self.assertEqual(response, FIXTURES.HTTP_RESPONSE_OBJECT_ROOT)

    ##
    ## some simple helper functions to setup a route """
    ##
    def setup_route_with_object(self, url_pattern='^/$'):
        self.app.add_route_rule(url_pattern,SimpleWebHandlerObject)

    def setup_route_with_method(self, url_pattern='^/$'):
        method = simple_handler_method
        self.app.add_route_rule(url_pattern, method)
コード例 #11
0
#!/usr/bin/env python

import sys
from brubeck.request_handling import Brubeck
from brubeck.templating import MakoRendering, load_mako_env


class DemoHandler(MakoRendering):
    def get(self):
        name = self.get_argument('name', 'dude')
        context = {
            'name': name
        }
        return self.render_template('success.html', **context)

app = Brubeck(mongrel2_pair=('ipc://127.0.0.1:9999', 'ipc://127.0.0.1:9998'),
              handler_tuples=[(r'^/brubeck', DemoHandler)],
              template_loader=load_mako_env('./templates/mako'))
app.run()
コード例 #12
0
 def setUp(self):
     """ will get run for each test """
     config = {
         'mongrel2_pair': ('ipc://127.0.0.1:9999', 'ipc://127.0.0.1:9998')
     }
     self.app = Brubeck(**config)
コード例 #13
0
ファイル: server.py プロジェクト: talos/caustic-server
                status = 200
            else:
                status['error'] = "Instruction does not exist"
                status = 404

        if self.is_json_request():
            self.set_body(json.dumps(context))
            self.set_status(status)
            return self.render()
        else:
            return self.render_template('delete_instruction', _status_code=status, **context)

V_C = VALID_URL_CHARS
config = {
    'mongrel2_pair': (RECV_SPEC, SEND_SPEC),
    'handler_tuples': [
        (r'^/?$', IndexHandler),
        (r'^/([%s]+)/?$' % V_C, UserHandler),
        (r'^/([%s]+)/instructions/?$' % V_C, InstructionCollectionHandler),
        (r'^/([%s]+)/instructions/([%s]+)/?$' % (V_C, V_C), InstructionModelHandler),
        (r'^/([%s]+)/tagged/([%s]+)/?$' % (V_C, V_C), TagCollectionHandler)],
    'template_loader': load_mustache_env(TEMPLATE_DIR),
    'cookie_secret': COOKIE_SECRET,
}

app = Brubeck(**config)
db = get_db(DB_HOST, DB_PORT, DB_NAME)
app.users = Users(db)
app.instructions = Instructions(app.users, JsonGitRepository(JSON_GIT_DIR), db)
app.run()
コード例 #14
0
    Flush the database occasionally.
    """
    while True:
        chat.flush(db_conn)
        coro_lib.sleep(TIMEOUT)


#
# RUN BRUBECK RUN
#
config = {
    'msg_conn':
    WSGIConnection(port=PORT),
    'handler_tuples': [(r'^/$', IndexHandler), (r'^/rooms$', RoomsHandler),
                       (r'^/buffer$', BufferHandler),
                       (r'^/(?P<room>[^/]+)/?$', RoomHandler),
                       (r'^/(?P<room>[^/]+)/users$', UsersHandler),
                       (r'^/(?P<room>[^/]+)/messages$', MessagesHandler)],
    'cookie_secret':
    COOKIE_SECRET,
    'db_conn':
    redis.StrictRedis(db=DB),
    'template_loader':
    load_mustache_env(TEMPLATES_DIR)
}

onionchat = Brubeck(**config)
toilet = onionchat.pool.spawn(drain, onionchat.db_conn)
onionchat.run()
toilet.kill()
コード例 #15
0
        return self.render()

    def post(self, name):
        self.set_body('Take five post, {0} \n POST params: {1}\n'.format(
            name, self.message.arguments))
        return self.render()


def name_handler(application, message, name):
    return render('Take five, %s!' % (name), 200, 'OK', {})


urls = [('/class/<name>', NameHandler), ('/fun/<name>', name_handler),
        ('/', IndexHandler)]

config = {
    'msg_conn': WSGIConnection(),
    'handler_tuples': urls,
}

brubeck_app = Brubeck(**config)
app = SimpleURL(brubeck_app)


@app.add_route('/deco/<name>', method='GET')
def new_name_handler(application, message, name):
    return render('Take five, %s!' % (name), 200, 'OK', {})


app.run()
コード例 #16
0
import gevent
import time


class WaitHandler(WebMessageHandler):
    def get(self):
        """
        Do some "work" OAuthing.  Return.
        """
        start = time.time()
        ms = float(self.get_argument('ms', 1000))
        gevent.sleep(ms / 1000)

        duration = time.time() - start
        self.set_body("<p>Requested %s</p><p>Actual: %s</p>" %
                      (str(ms), str(duration * 1000)))
        return self.render()


app = Brubeck(
    **{
        'msg_conn': WSGIConnection(port=PORT),
        'handler_tuples': [
            (r'^/wait/?$', WaitHandler),
        ]
    })


def application(environ, callback):
    return app.msg_conn.process_message(app, environ, callback)
コード例 #17
0
ファイル: demo_noclasses.py プロジェクト: cleichner/brubeck
#!/usr/bin/env python

from brubeck.request_handling import Brubeck, http_response

app = Brubeck(mongrel2_pair=('ipc://127.0.0.1:9999',  # PULL requests <- M2
                             'ipc://127.0.0.1:9998')) # PUB responses -> M2

@app.add_route('^/brubeck', method='GET')
def foo(application, message):
    name = message.get_argument('name', 'dude')
    body = 'Take five, %s!' % name
    return http_response(body, 200, 'OK', {})
        
app.run()
コード例 #18
0
class TestRequestHandling(unittest.TestCase):
    """
    a test class for brubeck's request_handler
    """
    def setUp(self):
        """ will get run for each test """
        config = {
            'mongrel2_pair': ('ipc://127.0.0.1:9999', 'ipc://127.0.0.1:9998')
        }
        self.app = Brubeck(**config)

    ##
    ## our actual tests( test _xxxx_xxxx(self) )
    ##
    def test_add_route_rule_method(self):
        # Make sure we have no routes
        self.assertEqual(hasattr(self.app, '_routes'), False)

        # setup a route
        self.setup_route_with_method()

        # Make sure we have some routes
        self.assertEqual(hasattr(self.app, '_routes'), True)

        # Make sure we have exactly one route
        self.assertEqual(len(self.app._routes), 1)

    def test_init_routes_with_methods(self):
        # Make sure we have no routes
        self.assertEqual(hasattr(self.app, '_routes'), False)

        # Create a tuple with routes with method handlers
        routes = [(r'^/', simple_handler_method),
                  (r'^/brubeck', simple_handler_method)]
        # init our routes
        self.app.init_routes(routes)

        # Make sure we have two routes
        self.assertEqual(len(self.app._routes), 2)

    def test_init_routes_with_objects(self):
        # Make sure we have no routes
        self.assertEqual(hasattr(self.app, '_routes'), False)

        # Create a tuple of routes with object handlers
        routes = [(r'^/', SimpleWebHandlerObject),
                  (r'^/brubeck', SimpleWebHandlerObject)]
        self.app.init_routes(routes)

        # Make sure we have two routes
        self.assertEqual(len(self.app._routes), 2)

    def test_init_routes_with_objects_and_methods(self):
        # Make sure we have no routes
        self.assertEqual(hasattr(self.app, '_routes'), False)

        # Create a tuple of routes with a method handler and an object handler
        routes = [(r'^/', SimpleWebHandlerObject),
                  (r'^/brubeck', simple_handler_method)]
        self.app.init_routes(routes)

        # Make sure we have two routes
        self.assertEqual(len(self.app._routes), 2)

    def test_add_route_rule_object(self):
        # Make sure we have no routes
        self.assertEqual(hasattr(self.app, '_routes'), False)
        self.setup_route_with_object()

        # Make sure we have some routes
        self.assertEqual(hasattr(self.app, '_routes'), True)

        # Make sure we have exactly one route
        self.assertEqual(len(self.app._routes), 1)

    def test_brubeck_handle_request_with_object(self):
        # set up our route
        self.setup_route_with_object()

        # Make sure we get a handler back when we request one
        message = MockMessage(path='/')
        handler = self.app.route_message(message)
        self.assertNotEqual(handler, None)

    def test_brubeck_handle_request_with_method(self):
        # We ran tests on this already, so assume it works
        self.setup_route_with_method()

        # Make sure we get a handler back when we request one
        message = MockMessage(path='/')
        handler = self.app.route_message(message)
        self.assertNotEqual(handler, None)

    def test_cookie_handling(self):
        # set our cookie key and values
        cookie_key = 'my_key'
        cookie_value = 'my_secret'

        # encode our cookie
        encoded_cookie = cookie_encode(cookie_value, cookie_key)

        # Make sure we do not contain our value (i.e. we are really encrypting)
        self.assertEqual(encoded_cookie.find(cookie_value) == -1, True)

        # Make sure we are an encoded cookie using the function
        self.assertEqual(cookie_is_encoded(encoded_cookie), True)

        # Make sure after decoding our cookie we are the same as the unencoded cookie
        decoded_cookie_value = cookie_decode(encoded_cookie, cookie_key)
        self.assertEqual(decoded_cookie_value, cookie_value)

    ##
    ## test a bunch of very simple requests making sure we get the expected results
    ##
    def test_web_request_handling_with_object(self):
        self.setup_route_with_object()
        response = route_message(self.app,
                                 Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT))
        self.assertEqual(FIXTURES.HTTP_RESPONSE_OBJECT_ROOT, response)

    def test_web_request_handling_with_method(self):
        self.setup_route_with_method()
        response = route_message(self.app,
                                 Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT))
        self.assertEqual(FIXTURES.HTTP_RESPONSE_METHOD_ROOT, response)

    def test_json_request_handling_with_object(self):
        self.app.add_route_rule(r'^/$', SimpleJSONHandlerObject)
        response = route_message(self.app,
                                 Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT))
        self.assertEqual(FIXTURES.HTTP_RESPONSE_JSON_OBJECT_ROOT, response)

    def test_request_with_cookie_handling_with_object(self):
        self.app.add_route_rule(r'^/$', CookieWebHandlerObject)
        response = route_message(
            self.app,
            Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT_WITH_COOKIE))
        self.assertEqual(FIXTURES.HTTP_RESPONSE_OBJECT_ROOT_WITH_COOKIE,
                         response)

    def test_request_with_cookie_response_with_cookie_handling_with_object(
            self):
        self.app.add_route_rule(r'^/$', CookieWebHandlerObject)
        response = route_message(
            self.app,
            Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT_WITH_COOKIE))
        self.assertEqual(FIXTURES.HTTP_RESPONSE_OBJECT_ROOT_WITH_COOKIE,
                         response)

    def test_request_without_cookie_response_with_cookie_handling_with_object(
            self):
        self.app.add_route_rule(r'^/$', CookieAddWebHandlerObject)
        response = route_message(self.app,
                                 Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT))
        self.assertEqual(FIXTURES.HTTP_RESPONSE_OBJECT_ROOT_WITH_COOKIE,
                         response)

    def test_build_http_response(self):
        response = http_response(FIXTURES.TEST_BODY_OBJECT_HANDLER, 200, 'OK',
                                 dict())
        self.assertEqual(FIXTURES.HTTP_RESPONSE_OBJECT_ROOT, response)

    def test_handler_initialize_hook(self):
        ## create a handler that sets the expected body(and headers) in the initialize hook
        handler = InitializeHookWebHandlerObject(
            self.app, Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT))
        self.assertEqual(handler(), FIXTURES.HTTP_RESPONSE_OBJECT_ROOT)

    def test_handler_prepare_hook(self):
        # create a handler that sets the expected body in the prepare hook
        handler = PrepareHookWebHandlerObject(
            self.app, Request.parse_msg(FIXTURES.HTTP_REQUEST_ROOT))
        self.assertEqual(handler(), FIXTURES.HTTP_RESPONSE_OBJECT_ROOT)

    ##
    ## some simple helper functions to setup a route """
    ##
    def setup_route_with_object(self, url_pattern='^/$'):
        self.app.add_route_rule(url_pattern, SimpleWebHandlerObject)

    def setup_route_with_method(self, url_pattern='^/$'):
        method = simple_handler_method
        self.app.add_route_rule(url_pattern, method)
コード例 #19
0
ファイル: main.py プロジェクト: faruken/brubeck-twidder
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from brubeck.request_handling import Brubeck
from config import config

le_app = Brubeck(**config)

if __name__ == '__main__':
  le_app.run()
コード例 #20
0
ファイル: demo_noclass.py プロジェクト: kracekumar/simpleurl
#! /usr/bin/env python
#! -*- coding: utf-8 -*-

from simpleurl import SimpleURL
from brubeck.request_handling import Brubeck, render
from brubeck.connections import Mongrel2Connection

brubeck_app = Brubeck(msg_conn=Mongrel2Connection('tcp://127.0.0.1:9999',
                                          'tcp://127.0.0.1:9998'))
app = SimpleURL(brubeck_app)


def index(application, message):
    body = 'Take five index'
    return render(body, 200, 'OK', {})


def one(application, message):
    body = 'Take five one'
    return render(body, 200, 'OK', {})


@app.add_route('/all/', defaults={'ids': 1}, method=['GET', 'POST'])
@app.add_route('/all/<ids>', method=['GET', 'POST'])
def process(application, message, ids):
    body = 'Take five - %s' % (str(ids))
    return render(body, 200, 'OK', {})


@app.add_route('/float/<float:value>')
def check_float(application, message, value):
コード例 #21
0
#! /usr/bin/env python
#! -*- coding: utf-8 -*-

from simpleurl import SimpleURL
from brubeck.request_handling import Brubeck, render
from brubeck.connections import WSGIConnection

brubeck_app = Brubeck(msg_conn=WSGIConnection())
app = SimpleURL(brubeck_app)


def index(application, message):
    body = 'Take five index'
    return render(body, 200, 'OK', {})


def one(application, message):
    body = 'Take five one'
    return render(body, 200, 'OK', {})


@app.add_route('/all/', defaults={'ids': 1}, method=['GET', 'POST'])
@app.add_route('/all/<ids>', method=['GET', 'POST'])
def process(application, message, ids):
    body = 'Take five - %s' % (str(ids))
    return render(body, 200, 'OK', {})


@app.add_route('/float/<float:value>')
def check_float(application, message, value):
    return render("You passed float value:%s" % str(value), 200, 'OK', {})
コード例 #22
0
ファイル: server.py プロジェクト: talos/opengold
        return self.render()


###
#
# BRUBECK RUNNER
#
###
config = {
    'msg_conn':
    WSGIConnection(port=PORT),
    'handler_tuples': [(r'^/$', GameListHandler),
                       (r'^/create$', CreateGameHandler),
                       (r'^/(?P<game_name>[^/]+)$', ForwardToGameHandler),
                       (r'^/(?P<game_name>[^/]+)/$', GameHandler),
                       (r'^/(?P<game_name>[^/]+)/join$', JoinHandler),
                       (r'^/(?P<game_name>[^/]+)/start$', StartHandler),
                       (r'^/(?P<game_name>[^/]+)/move$', MoveHandler),
                       (r'^/(?P<game_name>[^/]+)/chat$', ChatHandler)],
    'cookie_secret':
    COOKIE_SECRET,
    'db_conn':
    redis.StrictRedis(db=DB),
    'template_loader':
    load_mustache_env('./templates')
}

opengold = Brubeck(**config)
opengold.run()
コード例 #23
0
class TodosHandler(Jinja2Rendering):
    def get(self):
        """A list display matching the parameters of a user's dashboard. The
        parameters essentially map to the variation in how `load_listitems` is
        called.
        """
        return self.render_template('todos.html')


###
### Configuration
###

# Routing config
handler_tuples = [
    (r'^/$', TodosHandler),
]

# Application config
config = {
    'msg_conn': Mongrel2Connection('tcp://127.0.0.1:9999',
                                   'tcp://127.0.0.1:9998'),
    'handler_tuples': handler_tuples,
    'template_loader': load_jinja2_env('./templates/autoapi'),
}

# Instantiate app instance
app = Brubeck(**config)
app.register_api(TodosAPI)
app.run()
コード例 #24
0
ファイル: server.py プロジェクト: Gazegirl/OnionChat
    """
    Flush the database occasionally.
    """
    while True:
        chat.flush(db_conn)
        coro_lib.sleep(TIMEOUT)


#
# RUN BRUBECK RUN
#
config = {
    "msg_conn": WSGIConnection(port=PORT),
    "handler_tuples": [
        (r"^/$", IndexHandler),
        (r"^/rooms$", RoomsHandler),
        (r"^/buffer$", BufferHandler),
        (r"^/(?P<room>[^/]+)/?$", RoomHandler),
        (r"^/(?P<room>[^/]+)/users$", UsersHandler),
        (r"^/(?P<room>[^/]+)/messages$", MessagesHandler),
    ],
    "cookie_secret": COOKIE_SECRET,
    "db_conn": redis.StrictRedis(db=DB),
    "template_loader": load_mustache_env(TEMPLATES_DIR),
}

onionchat = Brubeck(**config)
toilet = onionchat.pool.spawn(drain, onionchat.db_conn)
onionchat.run()
toilet.kill()
コード例 #25
0
#! /usr/bin/env python


from brubeck.request_handling import Brubeck, render
from brubeck.connections import Mongrel2Connection
from brubeck.templating import  load_jinja2_env, Jinja2Rendering


app = Brubeck(msg_conn=Mongrel2Connection('tcp://127.0.0.1:9999',
                                          'tcp://127.0.0.1:9998'),
              template_loader=load_jinja2_env('./templates/jinja2'))


@app.add_route('^/', method=['GET', 'POST'])
def index(application, message):
    name = message.get_argument('name', 'dude')
    context = {
        'name': name,
    }
    body = application.render_template('success.html', **context)
    return render(body, 200, 'OK', {})


app.run()