1

I'm currently trying to post a file to a service endpoint, written in django.

I can find a bunch of examples like this (exert from here):

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/success/url/')
     ........

but how do I make a request using either the test client or urllib which can pass files to the server when it isn't coming from an HTML form? I'm currently trying to urlencode the file contents into a json string and then pass that along; but that is proving to be cumbersome.

IN ADDITION TO ANSWER BELOW:

  1. Don't forget to make your service csrf exempt
  2. Don't set the content type or set it explicitly to multipart.
  3. Consult this for info on how to handle incoming files in your view.
1

1 Answer 1

1

As Goin says, with Requests, you could do this:

>>> r = requests.post('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json
{u'private_gists': 419, u'total_private_repos': 77, ...}

This in urllib2 would be:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib2

gh_url = 'https://api.github.com'

req = urllib2.Request(gh_url)

password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, gh_url, 'user', 'pass')

auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)

urllib2.install_opener(opener)

handler = urllib2.urlopen(req)

print handler.getcode()
print handler.headers.getheader('content-type')

Source: github

Posting a multipart-encoded file would be easy in requests. From the official docs:

>>> url = '/your/recieving/end'
>>> files = {'report.xls': open('report.xls', 'rb')}

>>> r = requests.post(url, files=files)
>>> r.text # response json
Sign up to request clarification or add additional context in comments.

5 Comments

How could I use this to post a file/contents of a file to a django service? Also, what would the view look like which parses the file from the response?
Sadly, I don't know django much :( .. but check my update to the answer. Is that the kind of thing you're looking for?
I think you've gotten me closer. I didn't know about the openers in urllib2, so I'm looking into that now.
Actually, I think I get it know. I'll give it a shot and accept assuming it works for me.
Thanks again! I've updated my answer with a little extra info needed to tie all of this together but it works like a charm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.