I'm creating a pretty large Django application and the whole front end works by making Javascript API calls to the back end and rendering the data, my only concern is the API I'm writing will also be used by other users from the command line or their own apps.
For front end to back end I'm just doing
if request.user.is_authenticated:
# Do shit
# Return Said shit but with JSON
How do I program in a way that this also works in a token based way? Or should every user have a default token that's used to make this API call?
How does a app like gcloud do this, I could pass objects to the django template, but I'm giving select options that make heavier API calls in the frontend. If there's a way I can move forward with this approach help will be much appreciated, and advice will be even more appreciated.
Related
I have an application created long back, now client want to expose its some of views as APIs without breaking existing functionality, so that they can directly consume APIs using REST Tools to see the reports.
Is there any easier way, I can convert my function to a REST View.
P.S - I kept code shorter here to keep question simple, but in fact, its much complex in the actual app.
eg.
URL : -
`path('/users', views.show_user_details, name='users'),`
VIEW
def show_user_details(request, user_id):
users = User.objects.all()
return render(request, "Users.html", {"users":users})
In REST Views, I want it to convert its input and output so that it can be accessible with same urls(or with little modifications), without much updating the existing views.
`path('rest/users', views.show_user_details, name='users'),` #-- I am ok to add new url like this, but without much change in existing view .
def show_user_details(request, user_id):
users = User.objects.all()
return JsonResponse({"users":users})
Due to the fact that a normal website visit is still a GET request and GET is just one of your usual REST actions, you'll probably want to prepare your own independent API endpoint. Check out django-rest-framework for that, and you might just feel at home for this task.
Not new to programming, but new to Django
Where do I place the code in my Django project that calls an external REST API?
In the simplest example: I have a form where the user enters their ZIP code and presses a "Check" button which tells if the customer's address can be serviced by the lawn care company.
Upon getting a response, I have to the JSON to determine if it's serviceable, and what kind of services, etc.
So I need to be able to send, and read responses.
Where do I do this?
There is no database involved, so I presume I don't use a model.
I don't think the "View" is a good spot
Where?!
Thanks!
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.
I'm building an app with a Django backend, Angular frontend, and a REST API using Django REST Framework for Angular to consume. When I was still working out backend stuff with a vanilla frontend, I used the provided Django authentication to handle user auth- but now that I'm creating a REST based app, I'm not sure how to approach authentication.
Since all user data will be either retrieved or submitted via the API, should API authentication be enough? If so, do I need to remove the existing Django authentication middleware?
Right now, when I try to hit API endpoints on an early version of the app, I'm directed to what looks like the normal Django login form. If I enter a valid username and password, it doesn't work- just prompts to login again. Would removing the basic Django authentication prevent this? I want to be prompted to login, however I'm not sure how to handle that with these technologies.
The package django-rest-auth seems useful, and the same group makes an Angular module- but the docs don't go much past installation and the provided endpoints. Ultimately, I think the core of this question is: how do I entirely switch authentication away from what's provided by Django to something like django-rest-auth or one of the other 3rd party packages recommended by DRF?
edit: I made this comment below, but I realized that I need to figure out how combined auth will work. I'm not building a single page app, so individual basic pages will be served from Django, but each page will hit various API endpoints to retrieve the data it needs. Is there a way to have something like django-rest-auth handle all authentication?
To anyone that stumbles onto this question, I couldn't figure out how to make the hybrid approach work. Having Django serve pages that each contained API calls seemed OK, but I never saw any requests made to the API- I believe due to some other security issues. I'm sure it's possible, but I decided to go for the single page app implementation after all to make things simpler.
I am in the midst of writing a web app in CherryPy. I have set it up so that it uses OpenID auth, and can successfully get user's ID/email address.
I would like to have it set so that whenever a page loads, it checks to see if the user is logged in, and if so displays some information about their login.
As I see it, the basic workflow should be like this:
Is there a userid stored in the current session? If so, we're golden.
If not, does the user have cookies with a userid and login token? If so, process them, invalidate the current token and assign a new one, and add the user information to the session. Once again, we're good.
If neither condition holds, display a "Login" link directing to my OpenID form.
Obviously, I could just include code (or a decorator) in every public page that would handle this. But that seems very... irritating.
I could also set up a default index method in each class, which would do this and then use a (page-by-page) helper method to display the rest of the content. But this seems like a nightmare when it comes to the occasional exposed method other than index.
So, my hope is this: is there a way in CherryPy to set some code to be run whenever a request is received? If so, I could use this to have it set up so that the current session always includes all the information I need.
Alternatively, is it safe to create a wrapper around the cherrypy.expose decorator, so that every exposed page also runs this code?
Or, failing either of those: I'm also open to suggestions of a different workflow. I haven't written this kind of system before, and am always open to advice.
Edit: I have included an answer below on how to accomplish what I want. However, if anybody has any workflow change suggestions, I would love the advice! Thanks all.
Nevermind, folks. Turns out that this isn't so bad to do; it is simply a matter of doing the following:
Write a function that does what I want.
Make the function in to a custom CherryPy Tool, set to the before_handler hook.
Enable that tool globally in my config.