Search code examples
pythondjangopython-requestsresponsehttpresponse

convert requests.models.Response to Django HttpResponse


In my Django project, I need to get/post some data to a third-party url in my view, and redirect to the web page it provides. For example, I can simply do something like

class TestView(TemplateView):
    def get(self, request, *args, **kwargs):
        data = {
            'order_id': 88888,
            'subject': 'haha',
            'rn_check': 'F',
            'app_pay': 'T',
        }
        url = 'http://some-third-party-api-url?order_id=88888&subject=haha&...'
        return HttpResponseRedirect(url)

However I want to use this third-party api as a wrapped SDK , like

class TestView(TemplateView):
    def get(self, request, *args, **kwargs):
        from sucre.alipay_sdk.base import Alipay
        from sucre.alipay_sdk import alipay_config
        from django.http import HttpResponse
        alipay = Alipay(alipay_config)
        data = {
            'order_id': 88888,
            'subject': 'haha',
            'rn_check': 'F',
            'app_pay': 'T',
        }
        '''alipay api is wrapped in a sdk'''
        '''and return a requests.models.Response instance'''
        result = alipay.api('pay', data)
        return HttpResponse(result)

and the api code:

def api(self, service, data):
    ''' some logics here '''
    import requests
    response = requests.get(url, data=data)
    return response

But seems HttpResponse(result) is not the correct way to convert a requests.models.Response instance to HttpResponse... The layout is bad, and some more encoding issues, etc...Is there a correct way to convert requests response to Django HttpResponse?


Updates:

HttpResponse(result) worked, but some css of the page was lost. This might be related with using requests.


Solution

  • This should works:

    from django.http import HttpResponse
    import requests
    
    requests_response = requests.get('/some-url/')
    
    django_response = HttpResponse(
        content=requests_response.content,
        status=requests_response.status_code,
        content_type=requests_response.headers['Content-Type']
    )
    
    return django_response