Cherrypy_handling请求 [英] Cherrypy_handling requests

查看:71
本文介绍了Cherrypy_handling请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了一段时间,但找不到答案.我知道cherrypy创建了一个新的线程来处理请求(GET,PUT,POST,DELETE等).

I've been searching for a while now but can't find an answere. I know that cherrypy creates a new thread for handling requests (GET, PUT, POST, DELETE etc).

现在我这样获取参数:

...
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def POST(self):
   Forum.lock_post.acquire()
   conn = self.io.psqlConnect(self.dict_psql)
   cur = conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor)
   params = cherrypy.request.json
   ...
   return some_dict

如您所见,我将线程锁定以避免在变量 params 上出现竞争状态.但这真的有必要吗?我问cos是否这样做,因此POST上的所有其他请求都必须等待.有没有更好的解决方案而不锁定整个POST?我在代码中多次使用了 params .

As you can see im locking the thread to avoid race condition on the variable params. But is this really necessary? I'm asking cos if i do it like this all the other requests on POST will have to wait. Is there any better solution without locking the whole POST? I'm using params several times along the code.

推荐答案

首先,CherryPy不会为每个请求创建一个新线程,它有一个预定的线程池(默认为10个),实际上是一个线程池线程可用于一次处理单个请求.

First a clarification, CherryPy doesn't create a new thread for each requests, it has a predetermined pool of threads (10 by default), from which indeed one thread can be used to handle a single request at a time.

关于是否应该锁定 cherrypy.request.json .您真的不知道,有一个称为线程局部变量"的概念,在该概念上,您可以根据哪个线程正在访问该对象而对其具有多个引用.( Python文档).

As for if you should lock cherrypy.request.json. You really don't, there is a concept called "thread locals" on which you can have multiple references to different objects depending on which thread is accessing such object. (python docs).

话虽如此...您应确保所编写的代码不会干扰其他线程的状态(您可以使用 cherrypy.thread_data 作为快速解决方案).

Having said that... you should make sure that the code that you write doesn't interfere with the state of the other threads (you can use the cherrypy.thread_data as a quick fix).

请查看cherrypy插件架构,如果您希望在线程之间共享资源,通常可以通过插件来实现:

Take a look into the cherrypy plugin architecture, if you want a resource to be shared among threads usually a plugin is the way to: http://docs.cherrypy.org/en/latest/extend.html#plugins

这篇关于Cherrypy_handling请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆