2014-03-04 148 views
0

我试图从Python客户端上传一些文件到Django网络应用程序。将文件从Python客户端上传到Django服务器

我可以通过使用表单来完成,但我不知道如何使用独立的Python应用程序来完成它。你能给我一些建议吗?

我建模文件在Django模型是这样的:

class Media(models.Model): 
    post = models.ForeignKey(Post) 
    name = models.CharField(max_length=50, blank=False,null=False) 
    mediafile = models.FileField(upload_to=media_file_name, blank=False,null=False) 

干杯。

回答

0

它实际上是工作,现在使用Python的请求模块

生病把代码为所有感兴趣...

Django的服务器...

urls.py

... 
url(r'^list/$', 'dataports.views.list', name='list'), 
... 

views.py

@csrf_exempt 
def list(request): 
    # Handle file upload 
    if request.method == 'POST': 
     print "upload file----------------------------------------------" 
     form = DocumentForm(request.POST, request.FILES) 
     if form.is_valid(): 
      print "otra vez.. es valido" 
      print request.FILES 

      newdoc = Jobpart(
           partfile = request.FILES['docfile'] 
      ) 
      newdoc.save() 

      # Redirect to the document list after POST 
      return HttpResponseRedirect(reverse('dataports.views.list')) 
    else: 
     #print "nooooupload file----------------------------------------------" 
     form = DocumentForm() # A empty, unbound form 


    # Render list page with the documents and the form 
    return render_to_response(
     'data_templates/list.html', 
     {'form': form}, 
     context_instance=RequestContext(request) 
    ) 

list.html

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="utf-8"> 
     <title>Minimal Django File Upload Example</title> 
    </head> 

    <body> 
     <!-- Upload form. Note enctype attribute! --> 
     <form action="{% url "list" %}" method="post" enctype="multipart/form-data"> 
      <p> 
       {{ form.docfile }} 
      </p> 
      <p><input type="submit" value="Upload" /></p> 
     </form> 

    </body> 

</html> 

现在在客户端。

client.py

import requests 
url = "http://localhost:8000/list/" 
response = requests.post(url,files={'docfile': open('test.txt','rb')}) 

现在你可以添加一些安全和东西。但它其实是一个很简单的例子..

谢谢大家!!!!

2

你想要做的是发送一个POST请求给Django应用程序发送一个文件。

您可以使用Python的标准库httplib module或第三方requests module。那最后一个环节,张贴展示了如何发布编码文件这可能是你所需要的文件上传。

希望这会有所帮助!

1

使用requests

with open('file') as f: 
    requests.post('http://some.url/upload', data=f) 
相关问题