How to execute asynchronous post-processing in CherryPy?

久未见 提交于 2020-01-01 03:21:11

问题


Context: Imagine that you have a standard CherryPy hello word app:

   def index(self):
      return "Hello world!"
   index.exposed = True

and you would like to do some post-processing, i.e. record request processing or just log the fact that we were called from specific IP. What you would do is probably:

def index(self):
   self.RunMyPostProcessing()
   return "Hello world!"
index.exposed = True

However, that will add to your request processing time. (btw. And probably you will use decorators, or even some more sophisticated method if you would like to call it on every function).

Question: Is there a way of creating a global threading aware queue (buffer) to which each request can write messages (events) that needs be logged, while some magic function will grab it and post-process? Would you know a pattern for such a thing?

I bet that CherryPy supports something like that :-)

Thank you in advance...


回答1:


The "global threading aware queue" is called Queue.Queue. I just added a recipe for this at http://tools.cherrypy.org/wiki/BackgroundTaskQueue




回答2:


As i was looking for this and it's now outdated, i found it useful to provide the correct (2012ish) answer. Simply add this at the beginning of the function that handles your url :

cherrypy.request.hooks.attach('on_end_request', mycallbackfunction)

There's more infos on hooks in the documentation but it's not very clear to me.




回答3:


An on_end_request custom tool may be what you want.



来源:https://stackoverflow.com/questions/1310959/how-to-execute-asynchronous-post-processing-in-cherrypy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!