class Plnt(object): def __init__(self, database_uri): self.database_engine = create_engine(database_uri) self._dispatch = local_manager.middleware(self.dispatch_request) self._dispatch = SharedDataMiddleware(self._dispatch, {'/shared': SHARED_DATA}) def init_database(self): metadata.create_all(self.database_engine) def bind_to_context(self): local.application = self def dispatch_request(self, environ, start_response): self.bind_to_context() local.request = request = Request(environ, start_response) local.url_adapter = adapter = url_map.bind_to_environ(environ) try: endpoint, values = adapter.match(request.path) response = endpoints[endpoint](request, **values) except HTTPException, e: response = e return ClosingIterator(response(environ, start_response), session.remove)
class MyApp(object): def __init__(self): local.application = self user = config.get('Database', 'user') pw = config.get('Database', 'pw') host = config.get('Database', 'host') db = config.get('Database', 'db') db_uri = 'postgres://%s:%s@%s/%s' % (user, pw, host, db) self.database_engine = create_engine(db_uri, convert_unicode=True) def init_database(self): metadata.create_all(self.database_engine) def dispatch(self, environ, start_response): local.application = self local.request = request = Request(environ) logging.info('[request %s]' % request) local.url_adapter = adapter = url_map.bind_to_environ( environ, server_name=domain) try: rule, args = adapter.match(return_rule=True) handler = import_string('myapp.views.' + rule.handler) response = handler(request, **args) except NotFound: error = {'title': '404 Not Found', 'msg': 'Please check URL.'} response = not_found(request, error) except HTTPException, e: response = e if not request.is_xhr: #fill in placeholder so caching works from myapp.views import placeholder if request.logged_in: header_bottom_right = placeholder.header(username=request.user) highlight = popup = '' else: header_bottom_right = placeholder.header() popup = placeholder.popup() try: highlight = placeholder.highlight(rule.endpoint) except: highlight = '' response.data = re.sub('{% header %}', header_bottom_right, response.data, 1) response.data = re.sub('{% highlight %}', highlight, response.data, 1) response.data = re.sub('{% popup %}', popup, response.data, 1) return ClosingIterator(response(environ, start_response), [session.remove, local_manager.cleanup])
def __call__(self, environ, start_response): cookie = parse_cookie(environ.get('HTTP_COOKIE', '')) sid = cookie.get(self.cookie_name, None) if sid is None: session = self.store.new() else: session = self.store.get(sid) environ[self.environ_key] = session def injecting_start_response(status, headers, exc_info=None): if session.should_save: self.store.save(session) headers.append(('Set-Cookie', dump_cookie(self.cookie_name, session.sid, self.cookie_age, self.cookie_expires, self.cookie_path, self.cookie_domain, self.cookie_secure, self.cookie_httponly))) return start_response(status, headers, exc_info) return ClosingIterator(self.app(environ, injecting_start_response), lambda: self.store.save_if_modified(session))
def dispatch_request(self, environ, start_response): """Dispatch an incoming request.""" # set up all the stuff we want to have for this request. That is # creating a request object, propagating the application to the # current context and instanciating the database session. self.bind_to_context() request = Request(environ) request.db_session = Session() request.bind_to_context() # get the current action from the url and normalize the page name # which is just the request path action_name = request.args.get('action') or 'show' page_name = u'_'.join( [x for x in request.path.strip('/').split() if x]) # redirect to the Main_Page if the user requested the index if not page_name: response = redirect(href('Main_Page')) # check special pages elif page_name.startswith('Special:'): if page_name[8:] not in pages: response = page_not_found(request, page_name) else: response = pages[page_name[8:]](request) # get the callback function for the requested action from the # action module. It's "on_" + the action name. If it doesn't # exists call the missing_action method from the same module. else: action = getattr(actions, 'on_' + action_name, None) if action is None: response = actions.missing_action(request, action_name) else: response = action(request, page_name) # make sure the session is removed properly return ClosingIterator(response(environ, start_response), Session.remove)
class HueSoundServer(object): def __init__(self, db_uri): local.application = self self.dispatch = SharedDataMiddleware(self.dispatch, {'/static': STATIC_PATH}) def __call__(self, environ, start_response): return self.dispatch(environ, start_response) def dispatch(self, environ, start_response): local.application = self request = Request(environ) local.url_adapter = adapter = url_map.bind_to_environ(environ) try: endpoint, values = adapter.match() endpoint, module = endpoint.split(' ') handler = getattr(views, endpoint) response = handler(request, **values) except HTTPException, e: response = e return ClosingIterator(response(environ, start_response), local_manager.cleanup)
class Bongo(object): def __init__(self): local.application = self storage_class = import_string(settings.SESSION_STORE) if not os.path.isdir(settings.SESSION_PATH): os.makedirs(settings.SESSION_PATH) self.dispatch = SessionMiddleware( self.dispatch, storage_class(path=settings.SESSION_PATH)) self.dispatch = SharedDataMiddleware(self.dispatch, { '/media': settings.MEDIA_ROOT, }) def __call__(self, environ, start_response): return self.dispatch(environ, start_response) def dispatch(self, environ, start_response): local.request = request = Request(environ) response = None for request_processor_name in settings.REQUEST_PROCESSORS: processor = import_string(request_processor_name)() response = processor.process_request(request) if response is not None: break if response is None: local.url_adapter = adapter = url_map.bind_to_environ(environ) try: endpoint, values = adapter.match() handler = getattr(views, endpoint) response = handler(request, **values) for request_processor_name in reversed( settings.REQUEST_PROCESSORS): processor = import_string(request_processor_name)() response = processor.process_response(request, response) except HTTPException, e: response = e return ClosingIterator(response(environ, start_response), [local_manager.cleanup])
def __call__(self, environ, start_response): """Minimal WSGI application for request dispatching.""" #: bind the application to the new context local self.bind_to_context() request = Request(environ) request.bind_to_context() ctx.url_adapter = urls = urlmap.bind_to_environ(environ) try: endpoint, args = urls.match(request.path) handler = get_controller(endpoint) resp = handler(**args) except NotFound: handler = get_controller('static/not_found') resp = handler() except HTTPException as e: resp = e.get_response(environ) else: expires = datetime.utcnow() + timedelta(days=31) if request.first_visit or request.session.should_save: request.session.save_cookie(resp, COOKIE_NAME, expires=expires) return ClosingIterator(resp(environ, start_response), self.cleanup_callbacks)
The WSGI request environment is encapsulated in a ``Request`` object, for convenience. The original WSGI environment and the URL adapter used to dispatch the request are both attached to the request, for use in application-level handler methods. """ adapter = self.__rule_map__.bind_to_environ(environ) try: endpoint, values = adapter.match() environ['wsgiorg.routing_args'] = ((), values) request = Request(adapter, environ) handler = getattr(self, endpoint) response = handler(request, **values) except HTTPException, e: response = e return ClosingIterator(response(environ, start_response)) class WebApplication(type): """Instances of this metaclass are given the following attributes: ``__rule_map__`` A ``werkzeug.routing.Map`` object for identifying the appropriate method for each request. The ``Map`` is populated using rules from both the class's own routable methods and from any parents that look like they might have rule definitions. ``__call__`` A WSGI entry point method that uses ``__rule_map__`` to route requests. If the class has a ``__rules__`` member, it's assumed to be a sequence of
urls = urlmap.bind_to_environ(environ) try: endpoint, args = urls.match(request.path) handler = get_controller(endpoint) resp = handler(**args) except NotFound: handler = get_controller('static/not_found') resp = handler() except HTTPException, e: resp = e.get_response(environ) else: expires = datetime.utcnow() + timedelta(days=31) if request.first_visit or request.session.should_save: request.session.save_cookie(resp, COOKIE_NAME, expires=expires) return ClosingIterator(resp(environ, start_response), [local._local_manager.cleanup, session.remove]) def make_app(dburi, secret_key, debug=False, shell=False): """Apply the used middlewares and create the application.""" static_path = os.path.join(os.path.dirname(__file__), 'static') app = LodgeIt(dburi, secret_key) if debug: app.engine.echo = True if not shell: # we don't need access to the shared data middleware in shell mode app = SharedDataMiddleware(app, {'/static': static_path}) return app
response = b.return_404() except InternalServerError: request.environ['wsgi.errors'].write(traceback.format_exc()) b = BaseController(request, adapter) response = b.return_500() except Forbidden: b = BaseController(request, adapter) response = b.return_403() except HTTPException, e: request.environ['wsgi.errors'].write(traceback.format_exc()) response = e finally: session.close() if response: self.save_session(request, response) return ClosingIterator(response(environ, start_response), [local_manager.cleanup]) def load_session(self, request): sid = request.cookies.get('foreman') if sid is None: request.session = self.session_store.new() else: request.session = self.session_store.get(sid) def save_session(self, request, response): if request.session.should_save: self.session_store.save(request.session) response.set_cookie('foreman', request.session.sid) def dispatch(self, request, adapter, endpoint, vars): ctrl_str, act_str = endpoint.split('.')
def __call__(self, environ, start_response): response = self._open(environ) return ClosingIterator(response(environ, start_response), [local_manager.cleanup])
class Shorty(object): def __init__(self, db_uri): local.application = self self.database_engine = create_engine(db_uri, convert_unicode=True) self.dispatch = SharedDataMiddleware(self.dispatch, {'/static': STATIC_PATH}) def init_database(self): metadata.create_all(self.database_engine) def dispatch(self, environ, start_response): local.application = self request = Request(environ) local.url_adapter = adapter = url_map.bind_to_environ(environ) try: endpoint, values = adapter.match() handler = getattr(views, endpoint) response = handler(request, **values) except NotFound, e: response = views.not_found(request) response.status_code = 404 except HTTPException, e: response = e return ClosingIterator(response(environ, start_response), [session.remove, local_manager.cleanup]) def __call__(self, environ, start_response): return self.dispatch(environ, start_response)
ctx.url_adapter = urls = urlmap.bind_to_environ(environ) try: endpoint, args = urls.match(request.path) handler = get_controller(endpoint) resp = handler(**args) except NotFound: handler = get_controller('static/not_found') resp = handler() except HTTPException, e: resp = e.get_response(environ) else: expires = datetime.utcnow() + timedelta(days=31) if request.first_visit or request.session.should_save: request.session.save_cookie(resp, COOKIE_NAME, expires=expires) return ClosingIterator(resp(environ, start_response), self.cleanup_callbacks) def make_app(dburi, secret_key, debug=False, shell=False): """Apply the used middlewares and create the application.""" static_path = os.path.join(os.path.dirname(__file__), 'static') app = LodgeIt(dburi, secret_key) if debug: app.engine.echo = True app.bind_to_context() if not shell: # we don't need access to the shared data middleware in shell mode app = SharedDataMiddleware(app, {'/static': static_path}) return app