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

查看:30
本文介绍了为什么 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?

(第二个问题移至 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天全站免登陆