Best approach to send requests in Django

I have Django web project based on REST API. My goal is to make views and send requests to my API. In many queries i should pass auth credentials, and as i use default Django auth system i need to pass token and session id. So now queries are done using requests lib like following:

#function to create full url for api
def create_api_request_url(request, reverse):
    return 'http://' + request.get_host() + reverse

#getting csrftoken and session id, return cookies and header, need for authorization 
class CookieManager:
    @staticmethod
    def get_auth_credentials(request):
        ses_id = request.session.session_key
        token = get_token(request)
        cookies = {'csrftoken': token,
                   'sessionid': ses_id}
        headers = {'X-CSRFToken': token}
        return {'cookies': cookies, 'headers': headers}


def some_view(request, pk):
    ...
    #create full api url
    url = create_api_request_url(request, reverse('Shopping Cart API:Cart'))
    #collect auth credentials from request object
    credentials = CookieManager.get_auth_credentials(request)
    #make request using import requests, provided data and auth credentials
    requests.post(url, {"amount": product_amount, "product": pk}, **credentials)

So i need to go into so many steps and use my own custom functions just to send request. Another problem stands behind get requests, for example to collect data from get request i need to be sure that request was correct, firstly i need to check status code but it is not a guarantee that request was correct, it could throw exception on runtime, so again i should do something like this:

url = create_api_request_url(request, reverse('Product API:Product Details', kwargs={'pk': pk}))
    product_response = requests.get(url)
    #product_response can be null or throw exception (for example if url is not valid or disabled) 
    if product_response.status_code == 200:
        product = product_response.json()

I'm not sure that it's a good approach to work with requests. Moreover i'm interested in URLs not only in my project which can be accessed using reverse(), but third party URLs too. Please suggest better way or resourse with information on this topic with "Django" approach.

Back to Top