django app consuming rest api - where to put the code - django

I have an django app, a model which stores data entered via a web interface by a user.
I need to consume an third party REST api when viewing / saving a model instance. I know how to do this but, what I am unsure about is where this code should live with the django app.
my gut is to put this code with in the model class, but then you could also use a view... I am just not sure.
How has this been done before, there are lots of posts asking how to do this, but none stating best place to put the code.
any guidance would be gratefully received.
Cheers

This is a subjective question, so here is a subjective answer.
First of all, ensure that any code that interacts with this external REST API resides in a separate module. E.g, if you're grabbing word definitions from a dictionary API, all the code that talks to this API should ideally be in a separate dictionary module, which you can then import into your view.
Secondly, your models.py should merely declare your application's data model and define the operations on this model, and little else. They should not be concerned with request/response cycles, reading files, rendering templates, making HTTP calls, or anything else. By this logic, you should be making these REST API calls from your views and, if required, passing the returned data into your models.
And finally, think twice about making REST calls from your Django app. Python does synchronous (blocking) I/O by default, which means as long the app is waiting for the REST call to finish, it can't service any incoming HTTP requests. This is not an issue if you don't have too many users, but it's something to keep in mind for apps that need to scale. You might want to look into async I/O libraries for Python.

Related

Django Rest Framework communicating with mobile app instances

I would like to build a REST Service which exchanges JSON messages with instances of a mobile app for registering patron traffic in physical locations of (public and academic) libraries.
I plan on using Django Rest Framework, and using Django and DRF for the first time, have some questions (rather, recommendation requests). I have read the tutorials and followed some of them, and it looks very promising indeed.
As I am quite confident with Object oriented coding in Python, I will be using class based views. Any reason not to?
The intended usage of the system will include many different libraries with their own ids, users and properties. The data model behind is thus fairly complex, and implemented with MySQL. I feel I will have better control on the data exchange, updates inserts and selects, with custom SQL queries, and would like the DRF to handle mostly authentication and the routing of messages to and from the instances of the mobile app. Is this a misconception on my part, and would it be better to let DRF handle all database-involved aspects?
Given that I follow the custom SQL approach:
As (authenticated) user IDs are interwoven with the rest of the activities (e.g. we would like to know which of the authenticated users stands behind a certain registration of activity), it would seem "simple" to use a single database for both the business model itself and the DRF-controlled aspects. Is it recommended ? Are there any aspects that need to be considered here?
I have not found similar projects to be learning from. Anybody knows a similar project?
I know it is not very concrete, but hope to elevate my understanding a bit while endeavoring on the task.
Michael
I have tried to keep this as unopinionated as possible. Mostly reffering from Django's and DRF's documentation to make sure.
Class based views have some implicit code flows, need method overrides at some places. But since you are quite comfortable with Class based views, it is far more superior in the following ways: cleaner code, much more DRY compliant than function based, easier to extend, keeps your code base more maintainable as it grows.
Django's ORM is pretty powerful and if used correctly it can provide a vareity of capabilities.
Unless your authentication system is very complex and needs to scale independently, having everything in the same DB makes sense. The chatter reduces and you will be able to utilise powerful Django and DRF's features.

Do we need to render templates when using ReactJS as a front-end?

So I just created a website's front-end using ReactJS. Now all I need is a backend database that I will fetch data from using requests.
The question is whether I need to render templates using my backend or just use my server to make requests (eg get, post etc)
PS. I will be using Django as my backend.
Thank you everyone who will help me out.
Doing both is recommended. Based on the requirements and use cases we must use both ways to render.
For example, Some products use initial html as a Server side rendered page with all essential data required inserted as scripts and so on. This helps in loading primary content faster. If we are not following this in applications that require data initially. Then it might take more time to fetch React chunks, scripting and after seeing an API makes request, and then getting data and then displaying the primary content. So when a page needs more data (like More API calls) then server side rendering might be a good way.
For other scenarios like getting user details, All these can be done using React.
No, because you will use DRF (Django Rest Framework) to communicate between frontend and backend. Basically you will write your own APIs in the views.py that will respond with JSON data, at least in major of cases this will be enough. So, you don't need templates, since template are really Djangos' frontend, that you will not be using at all.
But, this heavily depends on what you are doing and what is your setup.

Django: implementing websockets to work with my existing MVT-based app (Channels seems to need me to throw out my entire existing code)

I have an existing Django project in the sports domain with apps that are built on the Model-View-Template structure. Many of the models and views are fairly sophisticated and work well currently. Data from the database (scores etc) is combined with some incoming user inputs through forms (HTTP POST requests) to be displayed on a web page via templates.
However, I now need live data to be displayed to users and be automatically refreshed to all the users continuously, either because one of the users entered something new (in the front-end), or because the scores changed during the game (directly enters the back-end).
I've done some research on Stack Overflow as well as tutorials on Youtube/ rest of the web and it appears that for me to use Django Channels, I'd have to start from scratch and build everything ground-up, which I'd like to avoid. How do I use the websocket protocol for my Django app easily without having to completely rework everything that I've done so far?
You don't really need to start from scratch or anything. You just need to add a module using channels. I am assuming that currently, the data is fetched only when the page is refreshed. What you need to do is write a consumer that is used to send messages directly to the client via websocket. Then in the front you can update the widget with the scores on each message received in the websocket. You can also stream user actions through the websocket to the server which will then be broadcasted by the consumer to needed clients. You may not even need to change anything in the existing code.
It will be easier to understand how this works and how you can incorporate it to your project by reading the channels tutorials. It became clearer to me after reading it so I would advice you do the same

How to integrate Django Rest APIs with BackboneJS frontend for single page application

I am not able to comprehend what would be pros and cons of the following approaches in making a single page backbone application using RESTful APIs from Django Rest Framework.
Render the whole app from within Django's template.
Serve the backbone app from another server ie node server. With nginx in the front for both servers.
Serve the HTML/Templates and JS from a separate CDN.
What are the things to take care ie points of caution in each strategy. Is there any other way to tie them up which I am missing?
This is a very broad question, and really it has nothing to do with Django or Backbone. What you're really asking about is a "thick-client" architecture vs. a "thin-client" architecture. In other words, having your user interface rendered on the client vs. having it rendered on the server.
First, allow me to recap a few things to make sure we're on the same page. The "thin-client" approach is the traditional/old school model, and the model Django itself is based on. The server renders HTML, sends it to the client, and whenever the client wants to do something it sends data back to the server and asks for fresh HTML.
In contrast the more modern "thick-client" approach lets the client render all of the UI. Whenever the client needs to do something it makes an AJAX request to a (presumably REST-ful) API, powered by a library like Django REST Framework. That API just returns the relevant data, and leaves it up to the client to render it appropriately.
There are advantages and disadvantages to both approaches, but the thick-client approach is becoming more and more popular because:
network transactions are faster: because your server is only sending the exact JSON you need instead of a mess of HTML, the "payload" of the response is much smaller
you can fetch all data "behind the scenes"; this makes things appear faster to the user, and lets you implement UI paradigms (eg. infinite scroll) that a thin client can't
the client/server relationship is simpler, because the people writing server code never have to even think about HTML or any other presentation logic; they get to just focus on the data (which, being server engineers, is probably the part they're most interested in anyway)
This is why a lot of companies (including the one I work for) have all but abandoned Django proper in favor of API endpoints served by Django REST Framework.
So, if you want to go with a thick client architecture, Django should never serve anything except the very first HTML page (and even that could be served by ngnix if you wanted, since it's just static HTML). After that you'd use a Backbone.Router and Backbone.Views to render your site. Whenever you need new information from the server you'd fetch a Backbone.Model or Backbone.Collection (with its url property pointing to your Django REST Framework endpoint).
I can attest that this whole approach works great; the site I work on is very complex, with many endpoints, and Backbone + Django REST Framework handles it beautifully. The only (slightly) tricky part is caching: in the thin client approach the browser automatically caches pages for you, but since there are no "pages" in a thick client (just AJAX responses with data) there is no automatic caching. This means that if you want to cache data you'll need to do it yourself, for instance with a Backbone.Collection devoted to that purpose.
Hope that helps.
P.S. Back in the day Django REST Framework didn't handle Django authentication stuff (ie. logging in/out) quite the way we wanted, so we wound up serving one other page, our login page, from Django. However I'm pretty sure the current Django REST Framework handles authentication stuff much better now, so this likely won't be an issue for you.

Django - load new objects via ajax

In django app I need to periodically check for if new object of particular model are created.
I want to this by ajax.
I was thinking about something like this:
render current timestamp into template, load current objects.
Then, every x seconds do ajax request and ask for objects which are created later then this timestamp.
What do you think? Is there maybe a better way?
What you want is a way for the client to know whether something has changed in the server. Generally there are three ways to stimulate this subscriber/broadcaster, or pull/push, relationship. The first is Ajax long-polling, which is roughly what you described. The second is implemented via WebSocket, which unfortunately not all browser supports. The third is HTTP streaming, or a long polling at the HTTP level. All three are available in https://github.com/ziyan/django-comet
A newer technology is Webhooks, which allows you to subscribe to server changes via URL (http://en.wikipedia.org/wiki/Webhook). Check it out here for an early Django adaptation: https://github.com/johnboxall/django_webhooks