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

904 views
Skip to first unread message

Ted Thomas

unread,
Jul 23, 2015, 7:41:36 PM7/23/15
to Django users
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.






Ted Thomas

unread,
Jul 23, 2015, 10:10:00 PM7/23/15
to Django users, tdtho...@gmail.com

My Python code started working after I changed on line.

Changing:
     files_dct = {filename:fobj}
to:
    files_dct = {('photo',(filename, fobj,'image/jpg'))}

Now it works.  My conjecture about the need for different HTTP-headers was wrong.  The working code has not changed the headers received by Django.

I must say, the Requests module documentation is very opaque!

I made this change based on a guess while reading the docs about sending multiple files.  I can't say I understand what going on.

Please comment on the right way to do this. 




Reply all
Reply to author
Forward
0 new messages