Calling REST endpoints in views? - python

I am using the Django REST framework package. I have several endpoints that I've already built to return data. I am calling these endpoints within Ajax to retrieve data. However, if a user does not have JavaScript enabled and presses let's say a subscribe button or a follow button for example, the action would be handled in the views.py file for that specific POST request. Would it be better to handle the request manually by doing a simple query in the views.py or is it better to just hand it off to the endpoint for that specific request inside the views.py?
I know I can use serialization in views.py, but which would be better using serialization or manually writing the queries to add the rows?

Related

Django setup url parameter for certain requests only

So I'm trying to setup my Django view such that when they POST to an endpoint they don't need an url parameters, but when they call GET they require it
path('posts/', views.PostView.as_view(), name="post"),
path('posts/<int:count>/', views.PostView.as_view(), name="post"),
The issue with this is that it makes swagger messy and swagger with assume that url/posts/ you can POST and GET from, and url/posts// you can as well, but I only want to be able to POST to the first and GET from the 2nd. Is there a way to do this without creating separate view classes for them? Or is it better practice in this case to create separate view classes?

How can i update a django template in real time?

In this template i'm retrieving the price of Bitcoin from an API. At the actual moment, the price will be updated only when the page is refreshed, while i would like it to be updated without refreshing the whole page, dynamically.
This is my view:
def home(request):
symbol = "BTCUSDT"
tst = client.get_ticker(symbol=symbol)
test = tst['lastPrice']
context={"test":test}
return render(request,
"main/home.html", context
)
And the template's line looks something like this:
<h3> var: {{test}} </h3>
There are two problems here:
1) From the little i know, Django itself is not asynchronous, so i need to find a way to update that part of the template in real time, without having to refresh the whole page.
2) At the actual moment, the API is requested when the page is opened/refreshed, but to stream the price, it should be always running. I tried this (awful) solution: add a while true in the view, but of course it broke my code, executing only the part the while statement.
Any advice is appreciated :)
You should separate your frontend and backend in order to dynamically update the DOM contents without needing to render the whole DOM each time.
The responsibility of frontend would be to request and fetch the latest values when a user does an action that warrant a refresh or fetching of updated data. The request need to made asynchronously via e.g. AJAX. The newer JS frameworks e.g. React, Vue use virtual DOM that use an intermediate virtual DOM that they use to push the updates and finally update the real DOM in a single go; which makes them very performant.
The (Django) backend should expose an API that would take (AJAX) requests from backend for specific resources, and serve them.
A nice framework for Django is DRF (Django REST Framework), which exposes REST endpoints that you can call from frontend via AJAX and get reponse back so that the frontend can do necessary updates.
This is a failrly high level view, and is written to give you an idea that you can implement by digging deeper.

Is it possible to create a Django app which only reads data from external database and provides REST API?

In other words - I want to create a simple Django Rest Framework app which preferable doesn't need it's own database.
This Django API app should only provide data for some external frontend app (e.g. Angular/Webpack stack).
There is no technical difference between external and the own database as pointed out by Kalus D. any database which is online and the username and password of it is known (means provided in django's setting.py) is Django's database. There can be multiple Databases of this type. so that's it.
But I don't think you mean the above. I think What you mean is collect data from external APIs or web pages e.g Wikipedia Rest API. then process that data like filter it, combine different data or anything you like and then send it to the user.
then yes it is possible but you don't need DRF for it. DRF is mainly applicable when you want to serialize your won models data. you can just send response in JSON format insted of html without using DRF.

Create Django Model Instance using POST method in another Python Script

So I have a django app with some models which I can manipulate via admin and also through a client facing site, like add instances etc. However, I would like to try something a little different from that. I have a Python script that uses POST and JSON objects based on those self same models and I would like to be able to run it, connect to my django app server via a port and create new instances of my models (essentially without using Admin or my client page). Any ideas how I go about this?
If what the script does is simple, it may be easiest just to create a view which receives the JSON, processes it, and returns a JsonResponse.
e.g.
def create_object(request):
if request.method == 'POST':
data = json.loads(request.body)
# Do something with the data - e.g. create a model instance
MyModel.objects.create(**data)
return JsonResponse({'status': 'created'})
Alternatively, if the script does more complicated things or if you intended to expand it in future, you may be best to expose your site via a REST API using something such as Django Rest Framework.
With Django Rest Framework, you can fairly rapidly build CRUD based APIs around your models using components such as ModelViewSets and ModelSerializers and expose them over REST with minimal code.

How to use classic Django app with Django REST framework?

I want to use Django REST framework for my new project but I am not sure if I can do it efficiently. I would like to be able to integrate easily classical Django app in my API. However I don't know how I can proceed to make them respect the REST framework philosophy. Will I have to rewrite all the views or is there a more suitable solution?
"Normal" Django views (usually) return HTML pages.
Django-Rest-Framework views (usually) return JSON.
I am assuming you are looking for something more like a Single page application.
In this case you will have a main view that will be the bulk of the HTML page. This will be served from "standard" Django view returning HTML (which will likely include a fair bit of JavaScript).
Once the page is loaded the JavaScript code will makes requests to the DRF views. So when you interact with the page, JavaScript will request Json, and update (not reload) the page based on the contents of the JSON.
Does that make sense?

Categories