Reputation: 739
I'm trying to upload some files from a Python client to a Django web app.
I'm able to do it by using a form, but I don't know how to do it using a stand alone Python app. Can you give me some suggestions?
I'm modeling the files in a Django model like this:
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)
Cheers.
Upvotes: 1
Views: 2074
Reputation: 1
file = request.FILES['file']
load_file = FileSystemStorage()
filename = load_file.save(file.name, file) // saving in local directory and getting filename
data = {'name': name, 'address': address, 'age':age }
fr_data = None
with open(filepath ,'rb') as fr:
fr_data += fr.read()
url = 'http://127.0.0.1:8000/api/'
response = requests.post(url=url, data=data, files= {
'filefiledname': fr_data
}
)
Upvotes: -1
Reputation: 739
It is actually working right now using Python's requests module
Ill put the code for all interested...
Django server...
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>
Now in the client.
client.py
import requests
url = "http://localhost:8000/list/"
response = requests.post(url,files={'docfile': open('test.txt','rb')})
Now you are able to add some security and stuff.. But it is actually a very simple example..
Thank you all!!!!
Upvotes: 0
Reputation: 4775
Using requests:
with open('file') as f:
requests.post('http://some.url/upload', data=f)
Upvotes: 1
Reputation: 29794
What you want to do is to send a POST
request to the Django app sending a file within it.
You can use python's standard library httplib
module or the 3rd party requests
module.That last link posted shows how to post a multipart encoded file which is probably what you need.
Hope this helps!
Upvotes: 2