简体   繁体   English

将cURL命令转换为Python的urllib2

[英]Converting a cURL command to Python's urllib2

guys! 伙计们! I'm currently working with an API that uses the following cURL line: 我目前正在使用使用以下cURL行的API:

curl -vF "files[]=@file.zip" "http://s5.example.com/123"

I'm not interested in using other libraries such as pycurl, because I really only need to convert a line or two. 我对使用其他库(例如pycurl)不感兴趣,因为我只需要转换一两行即可。 I really appreciate your help! 非常感谢您的帮助!

This request posts the file contents in a file upload field. 该请求将文件内容发布到文件上载字段中。 The http body of a POST request uploading a file is tricky to assemble - for ordinary text fields, one can just send a dictionary in the "data=" parameter to a urllib2.urlopen call, and the fields will be posted. 上载文件的POST请求的http主体很难组合-对于普通的文本字段,只需将“ data =“参数中的字典发送给urllib2.urlopen调用,这些字段就会被发布。

File uploads, though, need to send a complex http body, with customized headers. 但是,文件上传需要发送带有自定义标头的复杂http正文。 I don't know if urllib2 can do this - but I found an example on how to do it using httplib and mimetypes (both part of Python's stdlib) - so you can pick the example code and reuse it on your project: 我不知道urllib2是否可以做到这一点-但我找到了一个有关如何使用httplib和mimetypes(均为Python stdlib的一部分)的示例-因此您可以选择示例代码并将其在项目中重用:

http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/ http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/

All you need is urlopen method of urllib module .. . 您只需要urllib模块的 urlopen方法即可。

Syntax: urllib2.urlopen(url[, data][, timeout]) 语法: urllib2.urlopen(URL [,data] [,timeout])

data is the string specifying additional stuff to send to the server data是指定要发送到服务器的其他内容的字符串

Example: 例:

import urllib
tlds = urllib.urlopen("http://data.iana.org/TLD/tlds-alpha-by-domain.txt").readlines()

this example shows a single line code to extract all tlds into aa list called tlds by crawling it from iana.org 此示例显示了一个单行代码,通过从iana.org进行爬网将所有tlds提取到一个名为tlds的列表中

For complex operations/options/parameters of urlopen method you can check the official documentation: http://docs.python.org/library/urllib2.html 对于urlopen方法的复杂操作/选项/参数,您可以查看官方文档: http : //docs.python.org/library/urllib2.html

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

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