Twisted Agent 不会从字节构建请求
Twisted Agent won't build request from bytes
我正在通过尝试构建 RSS 聚合器来学习 Twisted。当我尝试使用 Web 代理构建请求时,我被告知我没有以字节形式提供 url 参数:
[Failure instance: Traceback (failure with no frames): <class 'twisted.web._newclient.RequestGenerationFailed'>: [<twisted.python.failure.Failure builtins.TypeError: sequence item 0: expected a bytes-like object, str found>]
但我想我做到了:
from twisted.internet import reactor
from twisted.web.client import Agent
def request_sent(response):
print ('I got something!')
def request_failed(reason):
print (reason)
def feed_loader_main():
"""
Starts and manage the reactor
"""
agent = Agent(reactor)
d = agent.request(
'GET',
'http://www.example.com'.encode('utf8') ##### <- HERE
)
d.addCallback(request_sent)
d.addErrback(request_failed)
print ('Firing reactor!')
reactor.run()
if __name__ == '__main__':
feed_loader_main()
这里是 Twisted 黑魔法还是我的编码不好?
异常实际上并没有说您没有以字节形式提供 URL。它只是在某个地方说它想要字节并得到了 str (unicode)。
我猜你在 Python 3,因为我可以用你在 Python 3 而不是 Python 2 的代码复制你的异常。我不确定您使用的是哪个版本的 Twisted,但我怀疑这不是特定于 Twisted 版本的。尽管如此,在以后的问题中指定 Python 和 Twisted 的版本是个好主意。
您传递给 request
的另一个值是 "GET"
,在 Python 3 上,这是一个 str (unicode)。如果您对其进行编码(或者只是使用 b"..."
将其设为字节文字),那么异常就会消失。
我正在通过尝试构建 RSS 聚合器来学习 Twisted。当我尝试使用 Web 代理构建请求时,我被告知我没有以字节形式提供 url 参数:
[Failure instance: Traceback (failure with no frames): <class 'twisted.web._newclient.RequestGenerationFailed'>: [<twisted.python.failure.Failure builtins.TypeError: sequence item 0: expected a bytes-like object, str found>]
但我想我做到了:
from twisted.internet import reactor
from twisted.web.client import Agent
def request_sent(response):
print ('I got something!')
def request_failed(reason):
print (reason)
def feed_loader_main():
"""
Starts and manage the reactor
"""
agent = Agent(reactor)
d = agent.request(
'GET',
'http://www.example.com'.encode('utf8') ##### <- HERE
)
d.addCallback(request_sent)
d.addErrback(request_failed)
print ('Firing reactor!')
reactor.run()
if __name__ == '__main__':
feed_loader_main()
这里是 Twisted 黑魔法还是我的编码不好?
异常实际上并没有说您没有以字节形式提供 URL。它只是在某个地方说它想要字节并得到了 str (unicode)。
我猜你在 Python 3,因为我可以用你在 Python 3 而不是 Python 2 的代码复制你的异常。我不确定您使用的是哪个版本的 Twisted,但我怀疑这不是特定于 Twisted 版本的。尽管如此,在以后的问题中指定 Python 和 Twisted 的版本是个好主意。
您传递给 request
的另一个值是 "GET"
,在 Python 3 上,这是一个 str (unicode)。如果您对其进行编码(或者只是使用 b"..."
将其设为字节文字),那么异常就会消失。