开发者

Post-process request event in Pyramid/Pylons

开发者 https://www.devze.com 2023-02-11 05:10 出处:网络
Is there an event or some kind of work with middlelayer where the request is 开发者_JS百科already sent to the user, but we still have the information so we can do stuff on the DB later?As you probably

Is there an event or some kind of work with middlelayer where the request is 开发者_JS百科already sent to the user, but we still have the information so we can do stuff on the DB later?


As you probably already know about, you can do before request handing with: http://docs.pylonsproject.org/projects/pyramid/1.0/narr/events.html#configuring-an-event-listener-imperatively

To handle post-request stuff (without using middleware) you need to add a finished callback to the request which is demonstrated here: http://docs.pylonsproject.org/projects/pyramid/1.0/api/request.html#pyramid.request.Request.add_finished_callback

Of course that finished callback only occurs within the scope of one request. You can handle all requests by combining the two:

from pyramid.events import NewRequest

def do_something(request):
    # do something here
    pass

def setup_post_request(event):
    event.request.add_finished_callback(do_something)

config.add_subscriber(setup_post_request, NewRequest)


In Pylons, each controller can have a before and after methods you can define that's then called before/after the controller method called.

There's also the lib/base.py file which contains the controller call and you could add some custom code there, but it will be called on every request and can be dangerous if your code produces some errors.

I'm not sure in Pyramid.

If you do things in a custom middleware, you'll have access to the request and response objects, but not other material. You could in theory parse the .ini config for the db settings and such, but if it's really part of the app, I'd stick to a place there.

0

精彩评论

暂无评论...
验证码 换一张
取 消