使用 python 和 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()
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")
the above code is for streaming and uploading the data. streaming is performing fine. While uploading, code hangs in following code
urllib2.urlopen(request).read()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个最引人注目的可能是填充 urllib2.Request 的参数。
第一个参数应该是有效的 URL。从您的共享代码来看,存储桶中似乎没有填充任何 S3 的 URL。这将导致 urlopen 失败,因为它正在使用该调用的返回值。
One showstopper may be your arguments populating the urllib2.Request
The first argument should be a valid URL. From your shared code it doesn't appeared bucket has been populated with the URL to S3 for wherever. That would cause urlopen to fail as it is using the returned value for that call.
使用strace或Wireshark等网络嗅探器来查找问题。
Use strace or a network sniffer like Wireshark for hunting the problem down.