Django file upload via API - django

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!

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.

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!

Related

Why django-rest-auth SocialLoginView is not working?

https://django-rest-auth.readthedocs.io/en/latest/installation.html here is the official docs about social login in django-rest-auth. they say the way to make the LoginView(GithubLogin, FacebookLogin, etc..) inheriting SocialLoginView like this.
from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from rest_auth.registration.views import SocialLoginView
class GithubLogin(SocialLoginView):
adapter_class = GitHubOAuth2Adapter
callback_url = CALLBACK_URL_YOU_SET_ON_GITHUB
client_class = OAuth2Client
but when i try to access the url with this as as.view(), they always say
{
"non_field_errors": [
"View is not defined, pass it as a context variable"
]
}
I tried the best. I have been suffering it for a few days. plz anybody save my life..
What's wrong with it? I've searched a lots but there wasn't any good answer for me.
So I've done a little digging and I discovered the problem.
The django-rest-auth package is no longer maintained and thus does not support modern versions of django rest framework. At the time of this post, up to version 3.10.3 of DRF is verified to work and I can verify that version 3.12.1 (and presumably onward) does not.
It looks like the project has been forked to dj-rest-auth and is receiving further support there. I would recommend migrating to that package.
You can read more about the decision to stop maintenance and fork to a new repository here.

Django: Generate PDFs

I am currently building a ticketing page using Django. I now have to find the 'best way' to generate a PDF ticket, which ticket buyers can download from our Server.
I looked into different ways and apps including ReportLab in the official documentation. The ticket will include personal information and I am also planning to include a Bar/QR code on the ticket. The question I am struggling with, is which of the available apps is for my purpose the best option. From my first understanding, ReportLab might not be the best solution and I might better generate the ticket from a HTML page.
Before I now dig deeper in documentations I wanted to ask you guys if you have some experience with my objective and can give me some recommendations?
In my case I've used wkhtmltopdf and pdfkit.
Read: https://learnbatta.com/blog/django-html-to-pdf-using-pdfkit-and-wkhtmltopdf-5/
If you want to generate pdf from an HTML page I would suggest you use PhantomJS for this.
Open URL in a subprocess using PhantomJS and direct output to the STDOUT:
import subprocess
proc = subprocess.Popen(
['phantomjs', 'rasterize.js', url, '/dev/stdout'],
stdout=subprocess.PIPE
)
Then create pdf from the STDOUT output:
import io
from PIL import Image
from tempfile import TemporaryFile
with TemporaryFile() as temp_pdf:
img = Image.open(io.BytesIO(proc.stdout.read()))
if img.mode == 'RGBA':
img = img.convert('RGB')
img.save(temp_pdf, "PDF", quality=100)

Profiling for Django + Tastypie

What is the best tool to do profiling on a Django app that uses Tastypie (all responses or JSON, so django_toolbar is no good in this case)?
One potential solution is to create a view which just renders TastyPie responses as HTML. This will allow django-debug-toolbar to output correct profiling data. The following is a fairly quick and dirty attempt at this.
In urls.py:
Just add the following line to your url patterns, but make sure it is only included if debugging is enabled.
(r'^api_profile/(?P<resource>.*)$', 'common.views.api_profile')
In common/views.py:
Place this view anywhere you want, I've put it in my common app.
from django.shortcuts import render_to_response
# Import the tastypie.api.Api object with which your api resources are registered.
from apps.api.urls import api
def api_profile(request, resource):
""" Allows easy profiling of API requests with django-debug-toolbar. """
context = {}
resource = resource.strip('/')
resource = api.canonical_resource_for(resource)
obj_list = resource.wrap_view('dispatch_list')(request)
response = resource.create_response(request, obj_list)
context['api_response'] = response
return render_to_response('common/api_profile.html', context)
In templates/common/api_profile.html:
Include a very simple template.
<body>
{{api_response}}
</body>
Now you could just navigate to '/api_profile/a_resource/' with django-debug-toolbar enabled and get profiling data for the generation of the a_resource list view. Request parameters can also be used, e.g. I've been profiling the request 'api_profile/posts/?limit=8&offset=16'.
I've never actually tried profiling a django application. But some time ago I've read an interesting article about this subject.
http://reinout.vanrees.org/weblog/2012/04/18/profiling-python.html
New Relic is good if you want to pay. You can also use hotshot profiler in https://github.com/shaunsephton/django-snippetscream for a quick peek at whats going on
I use this middleware -> https://djangosnippets.org/snippets/2126/
As the comment states, just
Install this by adding it to your MIDDLEWARE_CLASSES. It is active
if you are logged in as a superuser, or always when settings.DEBUG
is True.
To use it, pass 'profile=1' as a GET or POST parameter to any HTTP
request.
It will create an interactive HTML showing queries executed, time, methods... you should give it a try!

How to register a model in django-tagging anywhere not in the applications?

Is it possible to register a model in django-tagging not in tagging app, nor in my app?
The standard way is to edit apps/myapp/models.py this way:
from apps import tagging
tagging.register(MyModel)
I want to keep both applications without changes, for example, to be able to pull new versions and just replace them. So I tried putting this into project settings.py, in the end, but of course this fails.
from apps.myapp.models import MyModel
from apps import tagging
tagging.register(MyModel)
(This fails when importing MyModel.)
Any other way?
You can't do that in settings.py, as the models haven't been set up yet. One possibility is to do it in urls.py - admin.autodiscover is already there, so this might be a good place for the call to tagging.register as well.
There has been quite a lot of discussion in the django-developers group about the correct place for this sort of thing, but as yet no firm policy has been reached.

Easy-to-use django captcha or registration app with captcha?

I want to implement user registration using captcha in Django.
The workflow of django-registration app is a great, but it doesn't have captcha.
What captcha would you recommend to use with it?
Are there some other variants of registration+captcha or useful links on the topic?
This should work with Django-1.1 and don't be too hard to install.
django-registration is pretty extendable. One way to extend it is to provide a custom registration form. I'd recommend to use reCaptcha, e.g. with the widget and form field from here (archived). Then it is as simple as writing a custom form class and registration backend (which is simpler than it sounds):
from registration.backends.default import DefaultBackend
from registration.forms import RegistrationForm
class RecaptchaRegistrationForm(RegistrationForm)
recaptcha = ReCaptchaField(label="I'm a human")
class RecaptchaRegistrationBackend(DefaultBackend):
def get_form_class(self, request):
return RecaptchaRegistrationForm
The last step is to tell django-registration to use your backend. That step is described in the docs (I couldn't find a HTML version of the docs, sorry)
I've just had this problem, but the solution is dead simple.
I'm using django-registration, and I want a reCAPTCHA field for user registration. In just 1 minute:
download django-recaptcha (pip install django-recaptcha)
install it on your project. That is, copy the "captcha" folder to your project, add "captcha" to INSTALLED_APPS and add your RECAPTCHA_PUBLIC_KEY and RECAPTCHA_PRIVATE_KEY keys to settings.py too (as described in the installation instructions)
open registration/forms.py and add this field inside class RegistrationForm(forms.Form):
captcha = ReCaptchaField()
you will also have to import:
from captcha.fields import ReCaptchaField
And that's it. Less than a minute.
For those like me arriving late to the thread, there are a bunch of solutions out there now, which are pretty easy to install:
http://code.google.com/p/django-simple-captcha/
http://code.google.com/p/django-captcha/
https://github.com/inueni/django-captcha-field
https://github.com/justquick/django-math-captcha
https://github.com/marconi/django-mollom which uses the third-party Mollom service (which provides captcha and spam-filtering services).
I've successfully setup Django Mollom and Django Simple Captcha, and the hardest part was yak shaving around installing PIL on my Mac. Implementing the code was as straightforward as the docs for each would suggest.