Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从django fileupload将文件传递到远程服务器_Python_Django_Urllib2 - Fatal编程技术网

Python 从django fileupload将文件传递到远程服务器

Python 从django fileupload将文件传递到远程服务器,python,django,urllib2,Python,Django,Urllib2,我有一个Django表单和一个文件上传。在视图中,我希望通过urllib post请求将此文件传递给另一台服务器 我试着把这个文件放在一个普通的post变量中,就像这样 第一台服务器上的views.py: def loadfile(request): server_url = "foo" class UploadFileForm(forms.Form): filename = forms.FileField() context['fileform'] =

我有一个Django表单和一个文件上传。在视图中,我希望通过urllib post请求将此文件传递给另一台服务器

我试着把这个文件放在一个普通的post变量中,就像这样

第一台服务器上的views.py:

def loadfile(request):
    server_url = "foo"

    class UploadFileForm(forms.Form):
        filename = forms.FileField()
    context['fileform'] = UploadFileForm()

    #after button is pressed
    if request.method == 'POST':
        upload_file(context, server_url, request.FILES['filename'])

    return render_to_response("bar")

def upload_file(context, server_url, image_data):
    #create a temp file to store image on sever
    temp = tempfile.NamedTemporaryFile()
    for chunk in image_data.chunks():
        temp.write(chunk)
    temp.flush()

    #build filename
    origfilename = str(image_data)
    extention = origfilename[origfilename.rfind("."):]
    filename = uuid.uuid4().hex + extention            

    #encode image so it can be send
    with open(temp.name, "rb") as f:
        data = f.read()
        encoded_string = base64.urlsafe_b64encode(data)
        url = "http://" + server_url + "/uploadimage?filename=" + filename
        urllib2.urlopen(url, "img_data="+encoded_string)
    temp.close()
如果downsteam服务器也是django测试服务器,但使用nginx/uwsgi时,我会遇到“坏网关”错误,那么这是可行的。我认为这是因为uwsgi的缓冲区太小了。 因此,一个解决方案是提出适当的多部分post请求

问题是:如何在django fileupload请求的情况下轻松创建多部分urllib请求?

使用库:


我还没找到那个。工作起来很有魅力。也许我会用更多的urllib替换这个。
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)