为什么CherryPy对象属性在请求之间保持不变? [英] Why are CherryPy object attributes persistent between requests?

查看:63
本文介绍了为什么CherryPy对象属性在请求之间保持不变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为CherryPy应用程序编写调试方法.有问题的代码基本上(完全)等效于此:

I was writing debugging methods for my CherryPy application. The code in question was (very) basically equivalent to this:

import cherrypy

class Page:
    def index(self):
        try:
            self.body += 'okay'
        except AttributeError:
            self.body = 'okay'
        return self.body
    index.exposed = True

cherrypy.quickstart(Page(), config='root.conf')

我惊讶地发现,从请求到请求,self.body的输出都在增长.当我从一个客户端访问该页面,然后从另一个同时打开的客户端访问该页面,然后刷新这两个浏览器时,输出的字符串"okay"越来越多.在调试方法中,我还记录了特定于用户的信息(即会话数据),并且这些信息也显示在两个用户的输出中.

I was surprised to notice that from request to request, the output of self.body grew. When I visited the page from one client, and then from another concurrently-open client, and then refreshed the browsers for both, the output was an ever-increasing string of "okay"s. In my debugging method, I was also recording user-specific information (i.e. session data) and that, too, showed up in both users' output.

我认为这是因为python模块已加载到工作内存中,而不是针对每个请求都重新运行.

I'm assuming that's because the python module is loaded into working memory instead of being re-run for every request.

我的问题是:这如何工作?如何在请求之间保留self.debug,但不保留cherrypy.session和cherrypy.response?

My question is this: How does that work? How is it that self.debug is preserved from request to request, but cherrypy.session and cherrypy.response aren't?

有什么方法可以设置仅用于当前请求的对象属性?我知道我可以为每个请求覆盖self.body,但这似乎是临时的.在CherryPy中有标准的或内置的方法吗?

And is there any way to set an object attribute that will only be used for the current request? I know I can overwrite self.body per every request, but it seems a little ad-hoc. Is there a standard or built-in way of doing it in CherryPy?

(第二个问题移至推荐答案

synthesizerpatel的分析是正确的,但是如果您确实想根据请求存储一些数据,则将其作为属性存储在 cherrypy.request ,不在会话中. cherrypy.request .response 对象是每个请求的新对象,因此不必担心它们的任何属性会在请求中持久存在.这是做到这一点的规范方法.只要确保您不覆盖任何cherrypy的内部属性即可!例如, cherrypy.request.body 已经保留给您,例如POSTed JSON请求正文.

synthesizerpatel's analysis is correct, but if you really want to store some data per request, then store it as an attribute on cherrypy.request, not in the session. The cherrypy.request and .response objects are new for each request, so there's no fear that any of their attributes will persist across requests. That is the canonical way to do it. Just make sure you're not overwriting any of cherrypy's internal attributes! cherrypy.request.body, for example, is already reserved for handing you, say, a POSTed JSON request body.

有关范围界定工作原理的所有详细信息,最好的来源是

For all the details of exactly how the scoping works, the best source is the source code.

这篇关于为什么CherryPy对象属性在请求之间保持不变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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