简体   繁体   English

我应该如何将文本/纯文本数据传递给python的request.post?

[英]How should I pass text/plain data to python's requests.post?

I am trying to convert this curl command in python requests, but I am unsure about how I should pass the data: 我正在尝试在python请求中转换此curl命令,但不确定如何传递数据:

curl -X POST -u "apikey:{apikey}" \
    --header "Content-Type: text/plain" \
    --data "some plain text data" \
    "{url}"

I have tried to pass the string directly and to encode it with str.encode('utf-8') but I get an error 415 Unsupported Media Type 我尝试直接传递字符串,并使用str.encode('utf-8')对其进行编码,但出现错误415 Unsupported Media Type

This is my code: 这是我的代码:

text = "some random text"
resp = requests.post(url, data=text, headers={'Content-Type': 'text/plain'}, auth=('apikey', self.apikey))

[EDIT]: Solution is not to specify the headers in the request [编辑]:解决方案是不在请求中指定标题

Thanks a lot! 非常感谢!

When using requests library, it is usually a good idea not to set Content-Type header manually using headers= keyword. 使用requests库时,通常最好不要使用headers=关键字手动设置Content-Type头。

requests will set this header for you if it is needed (for example posting JSON will always result in Content-Type: application/json header). requests在需要时为您设置此标头(例如,发布JSON将始终导致Content-Type: application/json标头)。

Another reason for not setting this type of header manually is encoding , because sometimes you should specify something like Content-Type: text/plain; charset=utf-8 不手动设置这种类型的标头的另一个原因是编码 ,因为有时您应该指定类似Content-Type: text/plain; charset=utf-8 Content-Type: text/plain; charset=utf-8 . Content-Type: text/plain; charset=utf-8

One more important thing about Content-Type is that this header is not required for making POST requests. 关于Content-Type另一件重要事情是,发出POST请求时不需要此标头。 RFC 2616 : RFC 2616

Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. 任何包含实体主体的HTTP / 1.1消息都应包括定义该主体媒体类型的Content-Type头字段。 If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. 当且仅当Content-Type字段未提供媒体类型时,接收方可以通过检查其内容和/或用于标识资源的URI的名称扩展来尝试猜测媒体类型。 If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream". 如果媒体类型仍然未知,则接收者应将其视为“应用程序/八位字节流”类型。

So depending on the server type you're making request to, this header may be left empty. 因此,根据您要请求的服务器类型,此标头可能保留为空。


Sorry for this explanation being a bit vague. 抱歉,此说明有点含糊。 I cannot give you an exact explanation why this approach worked for you unless you provide target URL. 除非您提供目标URL,否则我无法确切解释为什么这种方法对您有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM