exception handling while using django and django rest framework - python

While using django and django rest framework and strictly using the frame work code.
Example,
using a router connected to a view set to a serializer into a model.
What I mean is no custom code, other than what is required to feed into the django rest frameworks code, do we not need exceptions?
I ask because in all the code examples I have seen, I have yet to see a try catch block.
thank you

Generally, there will be some type of error thrown if the data is in the incorrect format or doesn't contain correct values such as a wrong data type or invalid primary key on some request. The Django REST Framework serializers take care of these kinds of errors by raising ValidationErrors and keeping track of errors in serializer.Serializer._errors. The DRF framework presents these errors back to the user in a suitable format, for example:
{"detail": "Method 'DELETE' not allowed."}
when a user tried to send a HTTP DELETE request. More information on how DRF handles different exceptions can be found here.
As for code that you write yourself within views, serializers, models etc. that is up to you to try/except and handle however you deem necessary. Often in a serializer, you might use raise ValidationError(yourError) and in a view you might return Response(yourError, status=400).
Hope I've helped.

Related

How to programatically post to Django Rest Framework endpoint?

I've got an endpoint built with Django Rest Framework. I now want to separate the ingress and the parsing. So I created an endpoint which basically writes the received string of data to a textfield in. I now create a management command which continuously loops over that table and parses the contents.
So I get the I raw string from the ingress table, and I now want to post this to the DRF endpoint programmatically. I've done this many times in my unit tests. But I'm unsure how I can do this from the management command. I can use the same code as I do for test requests, but it seems weird to use testing code in production.
People might suggest to manually use the serializer, but there's also things happening in the viewset which I need.
Does anybody have a good idea how I would be able to do this?

React JS Frontend with DRF backend authentication

Have developed a pretty decent API utilizing Django and Django Rest Framework to make my data available for consumption. Decided to build a React JS front end to be a little more dynamic than the standard Django templates. I have numerous views within DRF which work fine, I'm able to make calls against them and get or post to them no problem. Currently I'm working on implementing a login capability for the React frontend so that users will be given access to a couple protected views and will be presented with information relevant to them.
Maybe I'm not understanding what is supposed to be happening, web development isn't exactly my area of expertise. Have referenced the Django documentation a bunch trying to understand sessions and session authentication. I have a 'login' view which is taking a username and password provided to it, searching for a related 'User' record based off of the username and attempting to leverage the django.contrib.auth login method; this all seems to be working, the user is getting authenticated. After this step, I'm pretty much completely lost as to what is supposed to happen.
In my React component, I've attempted sending the username as a 'session' attribute in the header, I've tried including the csrftoken in the headers, I've tried to just enable 'withCredentials' in the callout. Really not sure what I'm supposed to be doing here. Is my login view supposed to be returning some attribute that I would then store in the react components to include in calls to protected views?
Been stuck on this for a while and am getting lost in reading documentation.
Thanks

fetch data from 3rd party API - Single Responsibility Principle in Django

What's the most elegant way to fetch data from an external API if I want to be faithful to the Single Responsibility Principle? Where/when exactly should it be made?
Assuming I've got a POST /foo endpoint which after being called should somehow trigger a call to the external API and fetch/save some data from it in my local DB.
Should I add the call in the view? Or the Model?
I usually add any external API calls into dedicated services.py module (same level as your models.py that you're planning to save results into or common app if any of the existing are not logically related)
Inside that module you can use class called smth like MyExtarnalService and add all needed methods for fetching, posting, removing etc. just like you would do with drf api view.
Also remember to handle exceptions properly (timeouts, connection errors, error response codes) by defining custom error exception classes.

Should I save user backend in database in Django?

I'm creating a Django website that supports both local login backend and LDAP login (through django-auth-ldap), and maybe more in the future.
I'm getting into Django login and backends sutff and have a couple of questions - mainly is there any reason Django doesn't keep user creation backend in the database? Shouldn't user A be linked (and by linked I mean a field on User model) with the backend django.contrib.auth.backends.ModelBackend for safety/convince reason?
I'm getting around to creating a custom user model, and was thinking about adding such field. The ability to unambiguously know which backend was/is used to create/login the user sounds logically for me, but the fact that Django doesn't have that by default, and that I can't find anything similar on the Internet has me worried that I didn't think of a really good reason for why it's done the way it is.
Thanks in advance,
Paweł
Django doesn't need that info. Once the user is authenticated, and django has a User model, it doesn't care what backend authenticated it. The User model data is stored in one source. The User model (whether the default or custom) is consistent and has the same attributes, functionality and behaviour across the entire django project and schema. Nothing in the out-of-the-box django deals with different user models.
You may extend this with AbstractBaseUser, but managing really different users across the same project, especially with the core django modules, is a strech.
Django uses the User model a lot, and you will have to manually locate each place it does, and provide your own router to the correct backend. There is no API for this (like, say, db routers), it's going to be a mess of hacks that will probably even messier with each upgrade.
Django does support, in addition to the custom user model, "authentication backends". Some of the functionality your are looking for is available and exposed with this option, in a formal API. So you probably want to stick with that.
see:https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#authentication-backends

Bypassing Django CSRF Protection using external POST Request

I have a Python program that needs to be able to send data to my website (built with Django). This data will then be taken and displayed on a certain part of the website. The problem I'm having is that the CSRF protection built into Django blocks my POST request. From what I understand, this is usually avoided by adding {%csrf_token} to whatever form the POST request is being sent to. My problem is that I'm trying to send the POST request to a .cgi script rather than a form. Does anybody know how I could bypass the CSRF protection (preferably without removing it completely although this is an option.)
You should use the csrf_exempt decorator to avoid csrf protection in certains view.
You can read the docs for more information
In case you are using class based views, I'd recommend django-braces which uses a mixin to achieve this, as well as providing other extremely useful mixins.

Categories

Resources