Search code examples
djangodjango-viewspython-requestsdjango-authenticationdjango-sessions

Alternative of Requests in django


In my project I'm trying to hit a url(which is running in same project) in my view.

so in simplest way I can explain here.

@login_required
def my_api_view(request):
    if requests.method == 'GET':
        # do stuff
        return JsonResponse()

# and its url is `/api/get-info/`

another view which is consuming above api

@login_required
def show_info(request):
    url = get_base_url  + /api/get-info/  # http://localhost:8000/api/get-info/
    r = requests.get(url)

    return HttpResponse(r.json())

Now I have to use same session (login required) so when I hit the url using requests it complains that user is not loggedin which is obviously correct.

How can I do this elegantly and efficienty. session use of logged in user. (I dont want to call the view as a function, I want to hit the api-url end point and consume.

PS: we have something similar in django Test self.client.get(...)


Solution

  • Just call that view function and pass the request object as parameter to it.

    @login_required
    def show_info(request):
        r = my_api_view(request)
        return HttpResponse(r.json())
    

    Or a better option would be to simply separate the logic into a separate function, as mentioned by @koniiiik in the comments.

    EDIT: Or if you really want to hit the URL endpoint, you can simply pass on the cookie values to the request you make.

    @login_required
    def show_info(request):
        url = get_base_url  + "/api/get-info/"  # http://localhost:8000/api/get-info/
        r = requests.get(url, cookies=request.COOKIES)
        return HttpResponse(r.json())