【问题标题】:Post request with multiple parameters using Twisted Web Client使用 Twisted Web Client 发布具有多个参数的请求
【发布时间】:2021-01-04 09:02:58
【问题描述】:

我想使用 Twisted Web Client 发送一个带有多个参数的 POST 请求:

  • 图片:图片
  • metadata : 带有元数据的 json 文档 我需要使用纯 Twisted,而不需要 Treq 和 requests 等外部库。

目前只能发送一个参数,尝试了几种方法都没有成功。

有人知道如何改变身体来实现这个目标吗?

from __future__ import print_function

from twisted.internet import reactor
from twisted.web.client import Agent
from twisted.web.http_headers import Headers

from bytesprod import BytesProducer

agent = Agent(reactor)
body = BytesProducer(b"hello, world")
d = agent.request(
    b'POST',
    b'http://httpbin.org/post',
    Headers({'User-Agent': ['Twisted Web Client Example'],
             'Content-Type': ['text/x-greeting']}),
    body)

def cbResponse(ignored):
    print('Response received')
d.addCallback(cbResponse)

def cbShutdown(ignored):
    reactor.stop()
d.addBoth(cbShutdown)

reactor.run()

【问题讨论】:

    标签: python twisted twisted.web


    【解决方案1】:

    您需要指定参数编码的方式。如果你想像浏览器表单一样提交它们,你需要对数据进行 application/x-www-form-urlencoded 或 multipart/form-data 编码。前者通常用于短数据 - 由于您的参数是“图像”,因此它可能并不短。所以你应该 multipart/form-data 数据。

    一旦你有了,你只需在请求头中声明它并将编码数据包含在正文中。

    例如,

    body = multipart_form_encoded_body_producer(your_form_fields))
    d = agent.request(
        b'POST',
        b'http://httpbin.org/post',
        Headers({'User-Agent': ['Twisted Web Client Example'],
                 'Content-Type': ['multipart/form-data']}),
        body)
    

    方便,treq 提供a multipart/form-data encoder

    所以multipart_form_encoded_body_producer(...) 可能看起来像:

    MultiPartProducer([
        ("image", image_data),
        ("metadata", some_metadata),
        ...
    ])
       
    

    您提到您不能使用 Treq。你没有提到原因。我建议使用 Treq 或至少找到另一个可以为您进行编码的库。如果由于某些不合理的原因您不能这样做,您将不得不自己实现 multipart/form-data 编码。它是reasonably well documented,当然还有多种实现您也可以用作参考和互操作性测试工具。

    【讨论】:

    • 它嵌入了很多资源的限制。 Treq 有很长的依赖项列表,在我们的测试中导入非常慢。我想使用纯扭曲的解决方案来避免这些问题。否则,我会很乐意使用 Treq....
    • 我会尽量使用raw.githubusercontent.com/twisted/treq/master/src/treq/…的源代码,两全其美。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 2019-07-17
    • 1970-01-01
    • 2019-03-18
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多