相关疑难解决方法(0)

使用MultipartPostHandler使用Python POST表单数据

问题:使用Python的urllib2发布数据时,所有数据都经过URL编码并作为Content-Type发送:application/x-www-form-urlencoded.上传文件时,应将Content-Type设置为multipart/form-data,并将内容编码为MIME.这个问题的讨论在这里:http: //code.activestate.com/recipes/146306/

为了解决这个限制,一些敏锐的程序员创建了一个名为MultipartPostHandler的库,它创建了一个OpenerDirector,您可以使用urllib2来主要使用multipart/form-data自动POST.此库的副本位于:http: //peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html

我是Python的新手,无法让这个库工作.我基本上写了下面的代码.当我在本地HTTP代理中捕获它时,我可以看到数据仍然是URL编码的,而不是多部分MIME编码.请帮我弄清楚我做错了什么或更好的方法来完成这件事.谢谢 :-)

FROM_ADDR = 'my@email.com'

try:
    data = open(file, 'rb').read()
except:
    print "Error: could not open file %s for reading" % file
    print "Check permissions on the file or folder it resides in"
    sys.exit(1)

# Build the POST request
url = "http://somedomain.com/?action=analyze"       
post_data = {}
post_data['analysisType'] = 'file'
post_data['executable'] = data
post_data['notification'] = 'email'
post_data['email'] = FROM_ADDR

# MIME encode the POST payload
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
urllib2.install_opener(opener)
request = urllib2.Request(url, post_data)
request.set_proxy('127.0.0.1:8080', …
Run Code Online (Sandbox Code Playgroud)

python upload multipartform-data file urllib2

47
推荐指数
3
解决办法
6万
查看次数

打开python 3 urllib的调试输出

在python 2中,可以通过执行从urllib获取调试输出

import httplib
import urllib
httplib.HTTPConnection.debuglevel = 1
response = urllib.urlopen('http://example.com').read()
Run Code Online (Sandbox Code Playgroud)

但是,在python 3中,它似乎已被移动到

http.client.HTTPConnection.set_debuglevel(level)
Run Code Online (Sandbox Code Playgroud)

但是,我直接使用urllib而不是http.client.如何设置它以便我的http请求以这种方式显示调试信息?

这是我到目前为止使用的内容.如果我想获得调试信息,最好的方法是什么?

#Request Login page
cookiejar = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookiejar))
request = urllib.request.Request(options.uri)
add_std_headers(request)
response = opener.open(request)
response_string = response.read().decode("utf8")
# ...
Run Code Online (Sandbox Code Playgroud)

python debugging http urllib python-3.x

16
推荐指数
1
解决办法
1万
查看次数