Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I post a lot of data to Django?

I am trying to send of list of files to my Django Website. Each set is transmitted with the following info:

  • File name,
  • File size,
  • File location,
  • File type

Now, suppose I have 100 such sets of data, and I want to send it to my Django Website, what is the best method I Should use?

PS: I was thinking of using JSON, and then POST that JSON data to my Django URL. The data might then look like this:

{
  "files": [
    { "filename":"Movie1" , "filesize":"702", "filelocation":"C:/", "filetype":"avi" }, 
    { "filename":"Movie2" , "filesize":"800", "filelocation":"C:/", "filetype":"avi" }, 
    { "filename":"Movie3" , "filesize":"900", "filelocation":"C:/", "filetype":"avi" }
  ]
}
like image 724
Siddharth Gupta Avatar asked Oct 21 '22 22:10

Siddharth Gupta


1 Answers

I think sending json data to your server makes sense. Now to actually implement it, you would need your server to accept the http POST request that you will use to send the data about the files.

So, the server code may look like this:

urls.py:

import myapp
#  ...
urlpatterns = patterns('', url(r'^json/$',myapp.serve_json), #http://<site_url>/json/ will accept your post requests, myapp is the app containing view functions
                         #add other urls
                      )
#other code

views.py

import json
def serve_json(request):
    if request.method == 'POST':
        if 'files' in request.POST:
            file_list = json.loads(request.POST['files'])

            for file in file_list:
                #do something with each file dictionary in file_list
                #...
            return HttpResponse("Sample message") #You may return a message 
    raise Http404

Now in your Desktop application, once you have the list of the dictionaries of files, you may do this:

import urllib,json
data = urllib.urlencode({'files':json.dumps(file_dict)}) #file_dict has the list of stats about the files
response = urllib.urlopen('http://example.com/json/', data)
print response.read()

You may also look into urllib2 and httplib and use them in place of urllib.

like image 168
Nilanjan Basu Avatar answered Oct 27 '22 11:10

Nilanjan Basu