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.
Related
I have this project that I’ve been working on for a while:
In the views.py file, I scrape a lot of information from IMDB, with each call taking around 0.3 of a second. Meanwhile, my page will stand idle. I want to have it load the page and then finish up the call.
For instance, I want it to load the recommended movies after already showing the actors and actresses that played in both. Or in an index, I want to allow the user to type and then show the options to click on.
I’ve tried Celery with Redis, but Django can’t display asynchronous tasks.
How could I do this?
As you said, Django can't do that. My advice would be to divide and conquer:
First, write a view that just displays some HTML to load a JS script that can load your data asynchronously, using the render shortcut. A front-end framework like Vue can help you to hide the parts of your layout while your data loads.
Next, write views that just return the data using the JsonResponse object in Django, for example: one view to load the recommendations, one view to load the actor list.
Use XH requests to call your views and retrieve the information, using the Promise methods to make everything appear in sync.
Bonus: If you already have Celery in place, you can define a task that grabs all the data you need on the server, and create a view that polls the status of your task, and then call it using XHR every few milliseconds until your data (or part of it, that really depends on how you define your task) is ready.
I am making a website for a restaurant and they want to show their Yelp reviews. I configured and can retrieve data with the Yelp API. I have to query two things in order to get what I need. All in all this means the page takes 10-15 seconds to load, and I don't want to have to query the Yelp API everytime someone wants to see the page anyway.
yelp_api = YelpAPI('secretkey1', 'secretkey2')
business_results = yelp_api.business_query(id='secretbuisness', location='secretplace')
reviews_results = yelp_api.reviews_query(id='secretbuisness', location='secretplace')
return render(request, 'reviews.html', {'reviews_results': reviews_results, 'business_results': business_results})
Is there any way to make it so I can get the Yelp API data separate from the page request and store it somewhere ready to use, maybe updating every 5-10 minutes?
Sure, you can use background task to do this.
Choose one of the background task django apps:
Django Background Tasks (easy setup, easy use, not very feature rich but good for your problem)
Celery (feature rich, advanced setup, advanced use)
Make models for the results to store them in the database
Make an api request in an background task every hour or so and store the results in the models you created.
Show the results of the models in the html.
Alternatively you could do this in the html asynchronously with ajax (javascript).
So on the page, where you want to show the results, you could do an ajax request with javascript to the rest api of yelp and render the whole data with something like handlebars or other javascript rendering engines. Pay attention if you mix javascript template engines and django template syntax because django will probably render the javascript template. Here is the solution therefore: How to escape {{ or }} in django template?
I am using django to create an application that read data from sql server and show it on the webpage.
I want the content to change based on selected options from the drop down.
Basically I have written queries ion the model and I want my model to load content dynamically. How can I do that?
I am trying to use ajax.
Django won't care a whole lot about what you want to do there. Essentially, you want to create controller actions in Django that serve e.g. JSON representations of the data you want to display.
Your template then needs to include Javascript which makes the AJAX calls to retrieve data from those actions and display it on the page. You can either do this manually using just Javascript or jQuery or you can use a framework like AngularJS. The latter is heavier weight but will save you some effort if this about more than just a simple page.
There are plenty of tutorials on the web for using Django with jQuery or AngularJS which you should easily find using your favourite search engine.
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?
I want to benchmark the performance of a template website on a modified kernel. I want to use a website template that has 2-3 tiers (frontend, database etc), logic to create users and some logic to store/modify data for each user.
A quick search did not reveal any useful results as of yet.
I've little experience in web development and was hoping that stackoverflow can point me to something useful.
I would suggest taking a look at the Django framework:
http://docs.djangoproject.com/en/1.3/intro/
http://www.djangobook.com/en/2.0/
Django operates using a three tiered (Model, Template, View) design. The Model is the database access layer and will enable you to validate and store information about your users. The Template is the 'presentation layer' that will both determine the layout of your page through html, but has access to your view and its variables. The View is the portion that will contain all of the logic for the page - in a way it works as a median between your model and your template. The url your user visits will determine which view function you load.
If you are interested in the admin capabilities of the framework, take a look at:
http://www.djangobook.com/en/2.0/chapter06/
You could simply download and run one of the sample django applications like:
http://code.google.com/p/django-voting/
or
https://github.com/scrum8/django-job-board/
Or you could just create a clean django project and turn on the admin console.