Adi Krishnan
Adi Krishnan

Reputation: 155

To use an existing file for an external operation using Django

Requirement:

One of the functions of my web app is to upload a file from the Django server to a remote server. This file is not a part of the incoming request to the Django server. It is a test file already existing in a MEDIA or a STATIC location in Django.

Feasibility Test:

To test if this is possible, I'm trying to read a file from my Django application and spit its content out as HttpResponse.

Problem:

def test(request):
    text = open(os.path.join(settings.MEDIA_ROOT, '/media/file.txt', 'r').read()
    return HttpResponse(text)

File "/<LOCATION>/views.py", line 27
  return HttpResponse(text)
       ^

The above code gives me a Syntax error.

Questions:

  1. What am I missing in the code I pasted?
  2. What could be a good solution to the requirement? It is imperative that I upload and that feature I cannot change. I'm looking at options I might have for doing this kind of thing since I have not found the same on the web.

Any help would be greatly appreciated.

Upvotes: 0

Views: 42

Answers (1)

Gabe
Gabe

Reputation: 897

Answer 1: You forgot the closing paranthesis to join on the line above.

It should be:

open(os.path.join(settings.MEDIA_ROOT, '/media/file.txt'), 'r').read()

Answer 2: You can use httplib to upload a file (i.e. via POST request). Check out the example here (it's short and sweet):

http://code.activestate.com/recipes/146306/

Upvotes: 1

Related Questions