简体   繁体   中英

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.

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 (ie via POST request). Check out the example here (it's short and sweet):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM