Consuming External API Using Django Generic CBVs - python

If I want to consume an external API within a generic class based view in Django, can I add a method to the generic view including a get request? I need to pass parameters from the data model in the request payload in order to illicit a response, and I fundamentally do not understand how to do this. I was hoping someone could point me in the direction of a tutorial or something to help me out, as I have done hours of searching and I cannot find anything that is within an existing CBV.

Related

Convert Django Views to rest services

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.

How to do a Customer Logger for Django to Capture Response and Request

I'm looking into differen't ways to capture the response object, request object, and performance in Django to create a custom json elk logger that will build audit logs.
I'm not sure what approach is best to take here. I was looking at custom middleware but I've never done that.
I tried to look up if it was possible to use a decorator to do this but doesn't seem like it.
Also, I use the django rest framework so I also have to figure out how to integrate the middleware if thats the route or whatever solution to DRF as well.
Looking for suggestions.
If you use DRF, i advice you pckage - drf-tracking. Just add mixin LoggingMixin to you class like this:
class ProbeView(LoggingMixin, APIView):
...
And after this, each qyery for this view wiil be logged in database. Example:

What are the differences between Generics, Views, Viewsets and Mixins in Django?

I am new to Django and Django-Rest. I am confused about when I should use these? what are their advantages and disadvantages? I have only seen this- http://www.cdrf.co
The only thing I know is there are a lot of ways to do 1 thing. But this is totally unclear to me.
In Django, these four terms we use frequently for different purposes in the projects. I have tried to collect and share the actual meaning with the links to details description of each term. Please check if you find these helpful.
Generic views:
“Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.”
— Django Documentation
Read more details
Views:
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really. The view itself contains whatever arbitrary logic is necessary to return that response. This code can live anywhere you want, as long as it’s on your Python path. There’s no other requirement–no “magic,” so to speak. For the sake of putting the code somewhere, the convention is to put views in a file called views.py, placed in your project or application directory.
Read more details
Viewsets:
Django REST framework allows you to combine the logic for a set of related views in a single class, called a ViewSet. In other frameworks, you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
A ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides actions such as .list() and .create().
The method handlers for a ViewSet are only bound to the corresponding actions at the point of finalizing the view, using the .as_view() method.
Read more details
Mixins:
The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as .get() and .post(), directly. This allows for more flexible composition of behavior.
The mixin classes can be imported from rest_framework.mixins.
Read more details

Why view functions require a request parameter In Django?

Example from Django documentation:
def index(request):
return HttpResponse('<h1>hellworld!</h1>')
def detail(request, question_id):
return HttpResponse("Question: %s" % question_id)
Since the request argument is never used, why should I include it in each function signature?
The purpose of a web server is to reply to HTTP requests (In simple terms). Django being a web framework generates responses depending on the request that it receives.
The business logic of handling the requests is done by Django Views, it is their purpose. This is why Django supplies the request to the view function, so the code can access the request data and choose what actions it should take and which response it should send back (even though that specific view doesn't make use of it).
The decision of requiring the view to receive the request as an argument is an implementation decision made by Django developers, making it part of the interface the view has with the rest of the "system". Other frameworks might choose making it available globally and not suplying it to the views/controllers directly, but the merits of one or another approach is other discussion.
Many of the examples in Django's documentation (and any documentation, really) are necessarily contrived. They're simple because the complexity of a real example would take away from the point that's being made.
In real use cases, you'll frequently want access to the request object. You may want to know which User is attached to the request (request.user) or whether the request is a GET or a POST (request.method).
You can also inspect the headers (request.headers), decode the JSON object sent with a POST request (json.loads(request.body)), etc.
Those are just examples. In real world a programmer would want to find request GET arguments, decode JSON POST body, inspect headers, get user or session data, etc.

Is it possible to call different function of class based views through different actions in template

I am new to django and i ahve gone through all the docs of django. right now if we give some link in template and defined that link in urls.py i.e which view is going to handle that link. like this url(r'^dashboard/gift/$', login_required(CouponPageView.as_view())),
But i have this little doubt can i call different function of a view on clicking different links present in template.
The idea behind a class-based view is not to serve multiple resources (the targets of the links in your template). The idea is that the class-based view implements methods for the various HTTP methods (i.e. get, post, put, delete, head).
So you can server an HTTP GET of a certain URI using the SomeView.get() method, or you can handle a POST to the same resource from the post() method in the same SomeView class. This is helpful to support object oriented code, as the different methods on the object will typically share some resources.
If you want to handle different URL's, write different View classes. If their functionality is similar, use inheritance to prevent code duplication. If their functionality is almost identical, use parameters in the urlpattern.
I think you need to study the URL dispatcher a little more: https://docs.djangoproject.com/en/dev/topics/http/urls/

Categories