简体   繁体   English

如何在 CherryPy 中执行异步后处理?

[英]How to execute asynchronous post-processing in CherryPy?

Context: Imagine that you have a standard CherryPy hello word app:上下文:假设您有一个标准的 CherryPy hello word 应用程序:

   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.并且您想进行一些后处理,即记录请求处理或仅记录我们从特定 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 :-)我敢打赌 CherryPy 支持类似的东西 :-)

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.当我正在寻找这个并且它现在已经过时,我发现提供正确的(2012ish)答案很有用。 Simply add this at the beginning of the function that handles your url :只需在处理您的 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.文档中有更多关于钩子的信息,但我不太清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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