2009-11-06 61 views
2

使用Chris Atlee的python poster library有什麼方法可以包含cookie處理? 我有蟒蛇HTTP登錄碼,這與使用Cookie:如何使用python海報庫通過HTTP使用Cookie發佈文件

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打開器,就像上面的代碼一樣。

舉例來說,我不知道如何使用Cookie與下面的Python文件郵編:

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) 

回答

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。

+0

不要忘了關閉'test.txt'文件? – Vladius 2015-03-18 22:13:57

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) 
+0

我試過了。使用http://pastebin.com/f2e8ec53c上的python腳本,它無法上傳。腳本錯誤,我從腳本中獲得了一些回溯(http://pastebin.com/m6d7111f6),以及來自django開發服務器的這些回溯:http://pastebin.com/m62d1da24。我可能會把事情弄錯,但我認爲你的建議是不正確的。感謝您的幫助 – 2009-11-06 23:01:41

0

我已經想通了如何做這個。我不確定這是否是最好的解決方法,但它是有效的,所以我會分享它。爲了使用海報lib和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) 
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() 
相關問題