How to write middleware for pyramid / pylons 2?

I want to use mongodb or redis for logging for users in the pyramid / pylons, but I can not find a document for creating midlines. How can I do it?

+4
source share
4 answers

Standard middleware

class LoggerMiddleware(object): '''WSGI middleware''' def __init__(self, application): self.app = application def __call__(self, environ, start_response): # write logs try: return self.app(environ, start_response) except Exception, e: # write logs pass finally: # write logs pass 

In the pyramid that creates the application code:

 from paste.httpserver import serve from pyramid.response import Response from pyramid.view import view_config @view_config() def hello(request): return Response('Hello') if __name__ == '__main__': from pyramid.config import Configurator config = Configurator() config.scan() app = config.make_wsgi_app() # Put middleware app = LoggerMiddleware(app) serve(app, host='0.0.0.0') 
+9
source

It is not possible to find any documents completely strange, since the Python documentation of the logging module is quite detailed and complete:

http://docs.python.org/library/logging.html#handler-objects

You need to implement your own MongoDBHandler and attach the emit () method using MongoDB via pimongo.

+2
source

Another option in this case is not to use middleware at all and just use the BeforeRequest event in the pyramid.

 from pyramid.events import NewRequest import logging def mylogger(event): request = event.request logging.info('request occurred') config.add_subscriber(mylogger, NewRequest) 
+1
source

In case someone stumbles upon this, you can use Tween, which acts as middleware. You can put an entry in a call method.

 class simple_tween_factory(object): def __init__(self, handler, registry): self.handler = handler self.registry = registry # one-time configuration code goes here def __call__(self, request): # code to be executed for each request before # the actual application code goes here response = self.handler(request) # code to be executed for each request after # the actual application code goes here return response 

https://docs.pylonsproject.org/projects/pyramid/en/latest/narr/hooks.html#registering-tweens

0
source

Source: https://habr.com/ru/post/1338906/


All Articles