Thursday, July 23, 2015

How to use Python Requests Module to upload images to Django Application?

I am developing a django application that primarily uses web browsers to upload scientific data that includes some image files.  Currently, the application works fine when Firefox or Chrome are used.  Both images and other data are correctly uploaded.

Occasionally users need to upload larger amounts of data, so I want to automate this using Python's Requests module.  My python program currently uploads non-image data, but Django is not receiving the image files.   This may be because I am not setting HTTP-headers correctly.

When the user agent is Firefox, requests received by Django include headers like:

  HTTP_ACCEPT_ENCODING   gzip, deflate
  HTTP_ACCEPT   text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

When the user agent is my standalone program, only:

  HTTP_ACCEPT_ENCODING   identity

My questions are:

  1) What HTTP-headers is Django expecting?

  2) Should I be gzipping the image files?

  3) What is the correct way to do this?

A code snippet from my standalone program follows.

==================================
# loop to get messages from console
while True:
   message = input("Enter msg string: ")
   filename= input("Enter filename (or blank): ")

   # GET
   print("--- GET upload_msg")
   # Create a GET request (but do don't sent it)
   req   = Request('GET', upload_msg_url, data= {})
   # Send request
   forms_dct    = get_response(req)

   # modify forms_dct from GET, and use in next get_response()
   forms_dct['message_str'] = message

   # open file for upload
   fobj = open(filename,'rb')
   # modify forms_dct from GET, and use in next get_response()
   forms_dct['photo'] = filename

   # Create files dictionary
   files_dct = {filename:fobj}

   # POST
   print("--- POST upload_msg")
   # Create a POST request (but do don't sent it)
   req   = Request('POST', upload_msg_url, data= forms_dct, files= files_dct)
   # Send request
   forms_dct   = get_response(req)

   # close file
   fobj.close()
==================================

Thanks.






--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/79a3f85c-b85a-44d1-b7d6-bf150eb35978%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment