Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django file upload via API

I'm new to django and been designing some basic models that contain FileFields.

Here is an example of my model:

class Sample(models.Model):
   pub_date   = models.DateTimeField('Publish Date', default=datetime.now)
   upfile     = models.FileField(upload_to='samples/')

I have tested the file upload via admin, but now I'm looking for other solutions to submit files via REST API. My first searches lead to Piston but most examples don't seem to involve models, only file upload to websites.

My objective is to parse directories, for example with os.walk, and submit the files and fill the model with the file info.

That said I'm looking for suggestions and leads in order to start investigating.

Thanks in advance!

like image 856
karamazov Avatar asked Jul 28 '26 05:07

karamazov


2 Answers

You probably shouldn't be looking to piston for new builds anymore. It's essentially unmaintained and has been for a while now. django-tastypie and django-rest-framework are your best bets, although there's also a bunch of less fully featured frameworks cropping up.

REST framework supports standard form-encoded file uploads, see http://django-rest-framework.org/api-guide/fields.html#filefield

I'm not sure about tastypie's support for file uploads.

like image 174
Tom Christie Avatar answered Jul 30 '26 19:07

Tom Christie


I've went back to the basics and decided to try creating a local script that reads calls File and the Sample Model. Since I will submit files directly from the same server, this solution immensely more simple than using a REST API, which delivers more flexibility than what I need.

This was my solution:

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import sys
sys.path.append('/opt/proj')
sys.path.append('/opt/proj/web')
from django import db
from django.core.files import File
from django.utils import timezone
from web.myapp.models import Sample

filesample = File(open(sys.argv[1],'rb'))
filesample.name = os.path.basename(filesample.name)
Sample(upfile=filesample, pub_date=timezone.now()).save()

Looking back this was incredibly simple, but I hope it can help someone with the same problem.

Feel free to comment. Thanks!

like image 43
karamazov Avatar answered Jul 30 '26 19:07

karamazov