簡體   English   中英

使用python和Urllib2上傳文件時出現問題

[英]Problem uploading file using python and Urllib2

import os
import sys
import time
import base64
import hmac
import mimetypes
import urllib2
from hashlib import sha1
from poster.streaminghttp import register_openers

def read_data(file_object):
    while True:
        r = file_object.read(1 * 1024)
        print 'rrr',r
        if not r:
            print 'r'
            file_object.close()
            break
        yield r

def upload_file(filename, bucket):
    print 'start'
    length = os.stat(filename).st_size
    content_type = mimetypes.guess_type(filename)[0]
    date = time.strftime("%a, %d %b %Y %X GMT", time.gmtime())

print 'before'
register_openers()
print 'after'
input_file = open(filename, 'r')
print 'read mode'
data = read_data(input_file)
request = urllib2.Request(bucket, data=data)

request.add_header('Date', date)
request.add_header('Content-Type', content_type)
request.add_header('Content-Length', length)

request.get_method = lambda: 'PUT'
print 'before lamda'
urllib2.urlopen(request).read()

upload_file('C:\\test.pdf', "http://10.105.158.132:26938/DocLib1/ste.pdf")

上面的代碼用於流式傳輸和上傳數據。 流媒體運行良好。 上傳時,代碼會掛在以下代碼urllib2.urlopen(request).read()中

使用straceWireshark等網絡嗅探器來查找問題。

一個topstopper可能是您填充urllib2.Request的參數。

request = urllib2.Request(bucket, data=data)

第一個參數應為有效的URL。 從您的共享代碼來看,無論何時何地都沒有顯示存儲桶中帶有S3的URL。 這將導致urlopen失敗,因為它正在使用該調用的返回值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM