使用Chris Atlee的python poster library有没有办法包含cookie处理? 我有python http登录代码,它适用于cookies:
cookiejar = cookielib.CookieJar()
urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
request = urllib2.Request(login_url, params)
result = urlOpener.open(request)
但是当我需要上传文件时,我不知道如何使用海报lib代码和cookie处理代码。海报lib似乎需要调用urllib2.urlopen()而不是一些自定义url开启器,就像上面的代码一样。
例如,我不知道如何在下面的python文件邮政编码中使用cookies:
register_openers()
params = {'file': open("test.txt", "rb"), 'name': 'upload test'}
datagen, headers = multipart_encode(params)
request = urllib2.Request(upload_url, datagen, headers)
result = urllib2.urlopen(request)
答案 0 :(得分:7)
我发送了一封电子邮件给Chris AtLee,询问我们是否可以获得一个基本的身份验证示例。他回答我的问题非常酷,甚至还发了一些我寄给他的代码。
要包含Cookie处理,您可以执行以下操作:
opener = poster.streaminghttp.register_openers()
opener.add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) # Add cookie handler
params = {'file': open("test.txt", "rb"), 'name': 'upload test'}
datagen, headers = poster.encode.multipart_encode(params)
request = urllib2.Request(upload_url, datagen, headers)
result = urllib2.urlopen(request)
要为请求添加基本身份验证,您只需执行此操作(我添加了base64编码行以获得完整性):
opener = poster.streaminghttp.register_openers()
params = {'file': open("test.txt", "rb"), 'name': 'upload test'}
datagen, headers = poster.encode.multipart_encode(params)
request = urllib2.Request(upload_url, datagen, headers)
auth = base64.encodestring('%s:%s' % ('username', 'password'))[:-1] # This is just standard un/pw encoding
request.add_header('Authorization', 'Basic %s' % auth ) # Add Auth header to request
result = urllib2.urlopen(request)
希望这会有所帮助。另一位非常感谢Chris AtLee。
答案 1 :(得分:1)
您无需修改原始源代码,只需手动安装所有必需的开启工具(无需调用register_openers()):
import urllib2
import cookielib
import poster
handlers = [poster.streaminghttp.StreamingHTTPHandler(),
poster.streaminghttp.StreamingHTTPRedirectHandler(),
urllib2.HTTPCookieProcessor(cookielib.CookieJar())]
urllib2.install_opener(urllib2.build_opener(*handlers))
datagen, headers = poster.encode.multipart_encode({"image1": open("DSC0001.jpg", "rb")})
request = urllib2.Request("http://localhost:5000/upload_image", datagen, headers)
print urllib2.urlopen(request).read()
答案 2 :(得分:0)
你试过这个:
cookiejar = cookielib.CookieJar()
urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
register_openers()
params = {'file': open("test.txt", "rb"), 'name': 'upload test'}
datagen, headers = multipart_encode(params)
request = urllib2.Request(upload_url, datagen, headers)
result = urlOpener.open(request)
答案 3 :(得分:0)
我已经想出如何做到这一点。我不确定这是不是最好的方法,但是它有效,所以我会分享它。要将海报库与Cookie一起使用,必须将urllib2.HTTPCookieProcessor
添加到poster.streaminghttp.register_openers()
内置的开启工具中。
基本上,修改poster.streaminghttp.register_openers()
看起来像下面的代码,如果你想要cookie处理,请传入cookiejar
对象。
def register_openers(cookiejar=None):
"""Register the streaming http handlers in the global urllib2 default
opener object.
Returns the created OpenerDirector object."""
handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler]
if hasattr(httplib, "HTTPS"):
handlers.append(StreamingHTTPSHandler)
if cookiejar:
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar), *handlers)
else:
opener = urllib2.build_opener(*handlers)
urllib2.install_opener(opener)
return opener
样本用法:
# Logging in
import urllib, urllib2, cookielib
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
cookiejar = cookielib.CookieJar()
loginOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
params = urllib.urlencode({'username':'admin', 'password':'default'})
login_url = "http://127.0.0.1:8000/account/login/"
request = urllib2.Request(login_url, params)
login = loginOpener.open(request)
# Upload File
# use the login cookie for file upload
register_openers(cookiejar=cookiejar)
params = {'entity_file': open("test.txt", "rb"),'name': 'test', 'action':'upload'}
upload_url = "http://127.0.0.1:8000/upload/"
datagen, headers = multipart_encode(params)
request = urllib2.Request(upload_url, datagen, headers)
result = urllib2.urlopen(request)