似乎在请求完成之前,实际上并没有“更改”模块级别的变量。我需要立即更新它,以便其他请求可以知道该工作正在处理中。
这里是问题的示例:
import cherrypy
import time
@cherrypy.expose
class CherryPySleeps(object):
status = "not sleeping"
@cherrypy.tools.accept(media='text/plain')
def GET(self):
if CherryPySleeps.status == "not sleeping":
CherryPySleeps.status = "sleeping"
time.sleep(10)
CherryPySleeps.status = "not sleeping"
return "I finished sleeping"
else:
return "I am sleeping, shhh"
if __name__ == '__main__':
conf = {
'/': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.sessions.on': True,
'tools.response_headers.on': True,
'tools.response_headers.headers': [('Content-Type', 'text/plain')],
}
}
cherrypy.quickstart(CherryPySleeps(), '/', conf)
[当我打开2个浏览器选项卡时,在第一个页面上请求该页面,然后等待第二个,然后在第二个页面上请求该页面,每个选项卡上都有10秒的暂停,然后“我完成睡眠”。
我想让第二个选项卡快速响应,“我在睡觉,嘘”
如果要保证请求(线程)之间的某些同步性,则可以将锁用于读取和写入(或在if
条件下使用该锁)。顺便说一句,我无法复制您描述的确切条件(对我有用),但是至少锁应该保证,它将是一致的结果。
看这个例子:
import time
import threading
import cherrypy
@cherrypy.expose
class CherryPySleeps(object):
def __init__(self):
# share the same lock among read and write operations,
# the read is not "strictly" required, but you can use
# it to make sure there is no write happening at the
# same time
self._status_lock = threading.Lock()
# the internal status variable
self._status = "not sleeping"
@property
def status(self):
with self._status_lock:
return self._status
@status.setter
def status(self, new_status):
with self._status_lock:
self._status = new_status
@cherrypy.tools.accept(media='text/plain')
def GET(self):
if self.status == "not sleeping":
self.status = "sleeping"
time.sleep(10)
self.status = "not sleeping"
return "I finished sleeping"
else:
return "I am sleeping, shhh"
if __name__ == '__main__':
conf = {
'/': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.sessions.on': True,
'tools.response_headers.on': True,
'tools.response_headers.headers': [('Content-Type', 'text/plain')],
}
}
cherrypy.quickstart(CherryPySleeps(), '/', conf)
还有其他方法,可以使用CherryPy中的插件系统,但我认为对于此示例而言,这不是必需的。