python-3.x - Twisted - 请求未返回字节

标签 python-3.x twisted.web

我有基本的twister应用程序,但我不断收到这样的错误:

Request did not return bytes

Request:

Resource:

<main.MainPageDispatcher object at 0x7f049fa62be0>

Value:

'hello'

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

我的代码:

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()

最佳答案

在 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 字符串的字节表示形式

关于python-3.x - Twisted - 请求未返回字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47381475/

相关文章:

python - 我可以使用 Python SDK 对 Firebase Firestore 子项进行排序吗?

python - 调用 Request.finish 后在请求上调用 Twisted 错误 : Request. write

Python 扭曲 : Reverse Proxy to HTTPS API: Could not connect

python - 如何告诉 Twisted http 服务器忽略索引文件

javascript - 如果前四个字符是数字,则在字符串中插入字符

python - python 当关键字匹配两行时如何分割第二行?

client - 使用 HTTPretty 模拟 Twisted Web 客户端 HTTP 请求

python - 带有 web.twisted 的神秘 "Bus error"(代码在一台服务器上有效,在另一台服务器上无效)

python - 在 Bokeh 服务器中选择线条颜色

python - 作用域问题,可以访问对象属性但不能访问对象实例