【问题标题】:Twisted - Request did not return bytesTwisted - 请求没有返回字节
【发布时间】:2017-11-19 20:07:56
【问题描述】:

我有基本的捻线器应用程序,但我不断收到类似的错误:

请求没有返回字节

请求:

资源:

ma​​in.MainPageDispatcher 对象位于 0x7f049fa62be0>

价值:

'你好'

在任何地方,即使在官方文档的示例中,我也看到返回了字符串,但它对我不起作用。如果我注释掉第一个返回并发送字节而不是字符串它正在工作。 谁能帮我理解它是如何工作的?如果它必须以字节为单位,那么为什么官方指南会返回字符串?

我的代码:

from twisted.web.server import Site
from twisted.web.static import File
from twisted.web.resource import Resource
from twisted.internet import reactor

class MainPageDispatcher(Resource):
    isLeaf = True
    def __init__(self):
        super().__init__()

    def render_GET(self, request):
        request.setHeader(b"content-type", b"text/html")
        return "hello"
        return bytes("hello", "utf-8")

root = MainPageDispatcher()
factory = Site(root)
reactor.listenTCP(8888, factory)
reactor.run()

【问题讨论】:

  • 似乎将 python 版本 2 移植到 3 问题。 Twisted 需要字节,我不会把它作为答案,因为我没有必要的信息,但如果有人遇到类似问题,总是返回字节(并假设官方文档可能在 python 2 中)。

标签: python-3.x twisted.web


【解决方案1】:

在python3中我正在使用:

def render_GET(self, request):
    request.setHeader("Content-Type", "text/html; charset=utf-8")
    return "<html>Hello, world!</html>".encode('utf-8')

str.encode('utf-8') 返回 Unicode 字符串的字节表示

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    相关资源
    最近更新 更多