Reputation: 1139
In my django app I am receiving a request with JSON like this:
{
"item1": false,
"item2": false,
"item3": "value",
"url": "http://downloadlink.example.net"
}
I have to save all data except url by which I just need to download text file and save it on server. How can I do the download part?
Code in view:
class Collect(View):
@csrf_exempt
def dispatch(self, request, *args, **kwargs):
return super(Collect, self).dispatch(request, *args, **kwargs)
def post(self, request):
data = json.loads(request.body.decode())
try:
item1 = data["item1"]
item2 = data["item2"]
item3 = data["item3"]
url = data["url"]
new_row = ModelName(
item1=item1,
item2=item2,
item3=item3,
)
new_row.save()
except Error:
return HttpResponse("Unable to save")
return HttpResponse("Saved")
Upvotes: 2
Views: 4316
Reputation: 819
I think best practice solution is using celery because requesting another server while user is waiting is inappropriate and delays the user and sometimes it may take little long for bigger files. You can read the docs for more. I highly recommend it!
Upvotes: 0
Reputation: 314
So basically you can use urllib library and specifically its urlretrieve function to save the file in the temp folder locally first, then you can save it anywhere you want.
import urllib
response = urllib.urlretrieve(url)
contents = open(response[0]).read()
f = open('filename.ext','w')
f.write(contents)
f.close()
That is the basic example of how to save files from links. When you are saving files you should include the full path, so make sure to create a BASE_DIR constant in your settings file. You can go further and create a FileField or ImageField tables in your db, read here for more examples.
Upvotes: 4