React-Rest app, where to fetch data from database - django

I have an App composed by back-end: Python with Django and Django REST, and front-end composed of React.
Right now I have Excel files with data, which I import with python in json format to the back-end, so they are available for a fetch in the front-end via REST-url like here.
I am now translating my data into a web-based-database to be queried into my app.
But I have questions regarding the structure of my app with this change.
I have url-based queries for my new database.
Should I continue to import the queries in the back-end REST framework and, from there, to React?
Or should I use the url-based queries directly inside my React, substituting the REST url calls?

You can get an idea by referring this url.
https://www.andreasreiterer.at/connect-react-app-rest-api/
this describing about how to bind data using REST APIs in react.

I have found some sources that presented me two ways of solving the problem
Case 1:
Have the JSON Query importation on server side in your back-end and pass this data to your API (REST in my case).
Basic source: https://www.valentinog.com/blog/tutorial-api-django-rest-react/
Pros:
Do not need to change the structure for the rest of my application. The data layer continues the same, as before I was working with an Excel file and now I just change to a JSON Query.
The connection between server-client continues to be straight forward
Credential systems can be applied more easily for the data will be stored in your API
Cons
Harder to implement
Connection between python and url queries must have individual settings (url-queries are usually browser-based, and some queries can't be performed in python)
Harder to debug
Case 2: Query data with a native fetch Javascript method and handle the data in client side.
Basic Sources:https://www.robinwieruch.de/react-fetching-data/
https://blog.hellojs.org/fetching-api-data-with-react-js-460fe8bbf8f2
Pros:
Faster and easier to implement
Easier to debug
Javascript handles queries in a simpler way than python
Cons:
Credential system can't be applied
Less secure/robust method
Double connection between client and server (client-queries and client-API), because the API would still be maintained to store local information.

Related

Integrating django-import-export with react

I have a postgresql database and I want to add data to it.
I want to upload an excel file containing the data and save it to database.
I have a backend server of django and a frontend server of React.
I am easily able to import the data from the excel sheet to database using django_import_export but from the django admin.
What I want is, to do this using React and for normal users(non superusers) also. Is there a way to integrate django_import_export with react? Any other way to implement this functionality is also apreciated.
Presumably your backend uses a REST API to handle requests from the frontend. So, you can write an API handler which receives the Excel data posted to it.
The Django API handler can create an import process to handle upload. Check the documentation for more information.
Note that if you are loading large files, then you might want to handle the upload asychronously. This is little more tricky, but you could look at Celery to help with this.

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.

ember-data save and find with postgrest

ember-data understands json-api natively ,if we have to integrate ember-data and its save() and find() methods with postgrest style REST calls, where do we need to do changes ?
Do we need to modify client side in ember or some server side logic for mapping with ember-data requirements.
So postgrest REST api calls look like these to get films and their title and competition.name from related table ->
http://localhost:3001/film?select=title,competition{name}
http://localhost:3001/users?select=email::text&id=eq.2&sign_in_count=eq.16
There are two questions here:
Is it better to transform to/from JSON API at the server or the client?
If transforming in the client, where do transforms to/from JSON API occur?
Is it better to transform to/from JSON API at the server or the client?
The first question is really a matter of preference. I personally prefer having the server emit and accept JSON API format because it allows you to ship fewer lines of JavaScript to the client and there's a tendency for multiple clients to communicate with the same server, so standardizing that makes for faster client application development.
For example, you might have two Ember clients (one general user-facing, one admin-facing), an iOS client, and perhaps another server all requesting to your PostgREST server.
That said, you can also think of the format that PostgREST uses as its own spec and have all the clients adhere to that.
If transforming in the client, where do transforms to/from JSON API occur?
Which brings us to question 2: How do you make Ember Data communicate with a server that does not use the JSON API standard?
This occurs in two places: The Adapter and the Serializer.
The Adapter translates requests for data into the appropriate URL where the data can be found (or added) and initiates requests.
So, "give me the photo with the ID of 22" (store.find('photo', 2)), will ask the adapter (assuming Photo #2 isn't already loaded), "hey, someone wants Photo #2, go fetch it please".
The Adapter will make the request and hand the response over to its Serializer.
The Serializer is responsible for translating the data that comes back into a format that Ember Data understands: JSON API.
Both Adapter and Serializer have methods you can implement to customize their behaviors.
In your case with PostgREST, the best places to start would be implementing your own findRecord on the Adapter and implementing your own normalizeResponse on the Serializer.
The docs for both explain the actions you need to take and what type of value you should return from each method.
These are two of the most basic interfaces. They don't provide a lot of functionality out of the box, but will help you become familiar with how these two objects interact.
Once you're comfortable with this basic interaction, check out the sample RestAdapter and RestSerializer for ideas on how to rely on some of the conventions Adapters and Serializers have to offer to clean up any custom code you've written.

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, REST and Angular Routes

I'm trying to wrap my head around combining a client-side framework like AngularJS with Django. One thing that's really confusing me is the issue of routes and REST.
I've been trying to read a lot about it online, but documentation is limited, especially in terms of Django being combined with Angular (little snippets here or there). I understand that I need to add a REST framework like TastyPie to make a robust REST interface in my app in order for Angular to plug in and grab resources.
However, I'm confused as to how to properly map out my routes in such a way that (1) my server-side app can render my single-page app (SPA) with angular plugged in (2) routes that are supposed to load information/render templates (angular) and retrieve data from the server (django) don't conflict. Like if I have someone going on my website and doing site.com/user/1234 - that route is associated with both the Angular route and the Django route - except one renders a template and the other spits out JSON based on what is retrieved from the DB/server.
In addition, by using the REST api, do I forego a lot of the advantages I have in terms of having ModelForms being synchronized with my Models, etc? Is there any way to maintain this with AngularJS or do I have to look towards an AngularJS substitute.
The question isn't really specific to Django - just a matter of understanding the relationship between back-end and front-end in an SPA.
Routes are not duplicated between the back-end and the front-end. Your Django routes should be set up like:
/api/foo
/api/bar
...
and one single route that delivers a single page full of HTML partials, e.g.
/
The rest of the routes will be defined in Angular, e.g.
/articles/234
/blog/date/slug
...
The Angular controllers that handle those public-facing routes will in turn make $http calls against the API URLs and each will deliver one Angular partial. So there is no duplication, no overlap.
To the second part of your question, you can still use the Django ORM model relationships when constructing your API data, but yes, you'll lose all of that Django goodness when building the front-end.
If you build your API right, all of the data you need in each view will be fully present in the JSON feed that Angular consumes in that view. So you're using the ORM for back-end data construction, but you can't just decide to traverse a model relationship in a template without first preparing the back-end data to provide data for it.
Yes, it's a very different way of thinking of things, and yes it's quite a bit more complex than doing straight Django (or Rails). That's the cost of building a web app rather than a web site.