gpt4 book ai didi

python - 为什么 Twisted 认为我调用了两次 request.finish() 而我没有?

转载 作者:太空狗 更新时间:2023-10-29 18:30:00 26 4
gpt4 key购买 nike

这是我在使用 Twisted.web 时遇到的一个烦人的问题。基本上,我有一个继承自 twisted.web.resource.Resource 并向 Mako 模板添加一些默认内容的类:

from twisted.web.resource import Resource
from mako.lookup import TemplateLookup
from project.session import SessionData
from project.security import make_nonce


class Page(Resource):

template = ""

def display(self, request, **kwargs):
session = SessionData(request.getSession())

if self.template:
templates = TemplateLookup(directories=['templates'])
template = templates.get_template(self.template)
return template.render(user=session.user,
info=session.info,
current_path=request.path,
nonce=make_nonce(session),
**kwargs)
else:
return ""

然后,我将问题缩小到这个小类(我测试过),我编写了一个继承自 Page 的资源:

class Test(pages.Page):
def render_GET(self, request):
return "<form method='post'><input type='submit'></form>"
def render_POST(self, request):
request.redirect("/test")
request.finish()

我想指出,在所有其他情况下,如果 request.finish() 不是函数的最后一行,那么我会立即返回之后。

无论如何,我将此类添加到位于 /test 的站点,当我导航到那里时,我会看到一个提交按钮。我单击提交按钮,在控制台中我得到:

C:\Python26\lib\site-packages\twisted\web\server.py:200: UserWarning: Warning! request.finish called twice.  self.finish()

But, I get this ONLY the first time I submit the page. Every other time, it's fine. I would just ignore this, but it's been nagging at me, and I can't for the life of me figure out why it's doing this at all, and why only the first time the page is submitted. I can't seem to find anything online, and even dropping print statements and tracebacks in the request.finish() code didn't reveal anything.

edit

This morning I tried adding a second request.finish() line to the resource, and it still only gave me the error one time. I suppose it will only warn about it in a resource once -- maybe per run of the program, or per session, I'm not sure. In any case, I changed it to:

class Test(pages.Page):
def render_GET(self, request):
return "<form method='post'><input type='submit'></form>"
def render_POST(self, request):
request.redirect("/test")
request.finish()
request.finish()

一次只收到两条消息。我仍然不知道为什么我不能在没有它说我完成了两次的情况下重定向请求(因为我不能在没有 request.finish() 的情况下重定向)。

最佳答案

简答


它必须是:

request.redirect("/test")
request.finish()
return twisted.web.server.NOT_DONE_YET

长答案


我决定筛选一些 Twisted 源代码。我首先在 request.finish() 被调用两次时打印错误的区域添加了回溯:

def finish(self):
import traceback #here
"""
Indicate that all response data has been written to this L{Request}.
"""
if self._disconnected:
raise RuntimeError(
"Request.finish called on a request after its connection was lost; "
"use Request.notifyFinish to keep track of this.")
if self.finished:
warnings.warn("Warning! request.finish called twice.", stacklevel=2)
traceback.print_stack() #here
return
#....
...  File "C:\Python26\lib\site-packages\twisted\web\server.py", line 200, in render    self.finish()  File "C:\Python26\lib\site-packages\twisted\web\http.py", line 904, in finish    traceback.print_stack()

I went in and checked out render in twisted.web.server and found this:

    if body == NOT_DONE_YET:
return
if type(body) is not types.StringType:
body = resource.ErrorPage(
http.INTERNAL_SERVER_ERROR,
"Request did not return a string",
"Request: " + html.PRE(reflect.safe_repr(self)) + "<br />" +
"Resource: " + html.PRE(reflect.safe_repr(resrc)) + "<br />" +
"Value: " + html.PRE(reflect.safe_repr(body))).render(self)

if self.method == "HEAD":
if len(body) > 0:
# This is a Bad Thing (RFC 2616, 9.4)
log.msg("Warning: HEAD request %s for resource %s is"
" returning a message body."
" I think I'll eat it."
% (self, resrc))
self.setHeader('content-length', str(len(body)))
self.write('')
else:
self.setHeader('content-length', str(len(body)))
self.write(body)
self.finish()

body 是渲染资源的结果,所以一旦 body 被填充,在我的问题中给出的例子中,finish 有已在此请求对象上调用(因为 self 从此方法传递到资源的呈现方法)。

通过查看这段代码,很明显通过返回 NOT_DONE_YET 我可以避免警告。

我也可以将该方法的最后一行更改为:

if not self.finished:
self.finish()

但是,为了不修改库,简短的回答是:

在调用 request.redirect() 之后,您必须调用 request.finish() 然后返回 twisted.web.server.NOT_DONE_YET

更多


我找到了一些 documentation对这个。它与重定向请求无关,而是使用 request.write() 呈现资源。它说调用 request.finish() 然后返回 NOT_DONE_YET。通过查看 render() 中的代码,我可以明白为什么会这样。

关于python - 为什么 Twisted 认为我调用了两次 request.finish() 而我没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3254965/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com