python 模擬表單上傳文件

轉載: http://oldj.net/article/python-upload-file-via-form-post/

最近要用 Python 模擬表單上傳文件,搜索了一下常見的解決方案。

如果只是要模擬提交一個不包含文件字段的表單,實現起來是很簡單的,但涉及到文件上傳就有一點小複雜,需要自己對文件進行編碼,或者使用第三方模塊。


如果機器上有 PycURL,那麼可以使用 PycURL 來上傳文件。不過, PycURL 需要用到 curl;

比如 這兒 的 2 樓有人貼出了一個將文件進行編碼之後再 POST 的方法,另外還有 MultipartPostHandlerurllib2_fileposter 等第三方模塊。但 MultipartPostHandler 這個模塊似乎比較老了,urllib2_file 我試用了一下遇到錯誤沒有成功,這兒我想介紹的是另外一個第三方模塊 poster。


如果機器上安裝了 Python 的 setuptools,可以通過下面的命令來安裝 poster:

1
easy_install poster

裝完之後,就可以像下面這樣上傳文件了:

from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
 
# 在 urllib2 上註冊 http 流處理句柄
register_openers()
 
# 開始對文件 "DSC0001.jpg" 的 multiart/form-data 編碼
# "image1" 是參數的名字,一般通過 HTML 中的 <input> 標籤的 name 參數設置
 
# headers 包含必須的 Content-Type 和 Content-Length
# datagen 是一個生成器對象,返回編碼過後的參數
datagen, headers = multipart_encode({"image1": open("DSC0001.jpg", "rb")})
 
# 創建請求對象
request = urllib2.Request("http://localhost:5000/upload_image", datagen, headers)
# 實際執行請求並取得返回
print urllib2.urlopen(request).read()



很簡單,文件就上傳完成了。

其中那個 register_openers() 相當於以下操作:

from poster.encode import multipart_encode
from poster.streaminghttp import StreamingHTTPHandler, StreamingHTTPRedirectHandler, StreamingHTTPSHandler
 
handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler, StreamingHTTPSHandler]
opener = urllib2.build_opener(*handlers)
urllib2.install_opener(opener)



另外,poster 也可以攜帶 cookie,比如:



opener = poster.streaminghttp.register_openers()
opener.add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
 
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)



這樣,通過表單 POST 的方式上傳文件就方便多了。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章