简体   繁体   中英

How to execute asynchronous post-processing in CherryPy?

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, ie 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...

“全局线程感知队列”称为 Queue.Queue。

on_end_request自定义工具可能就是您想要的。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM