2016-11-08 38 views
3

在我的Django项目中,我需要在我的视图中将一些数据发布到第三方url并重定向到它提供的网页。例如,我可以简单地这样做将requests.models.Response转换为Django HttpResponse

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) 

不过,我想用这个第三方API作为一个包裹的SDK,像

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) 

和API代码:

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

但似乎HttpResponse(结果)不是正确的方式来将requests.models.Response实例转换为HttpResponse ...布局不好,还有一些更多的编码问题,等等......有没有一种正确的方法来转换请求resp onse到Django HttpResponse?


更新:

的HttpResponse(结果)工作,但页面的一些CSS丢失。这可能与使用请求有关。

+0

看看[MCVE(http://stackoverflow.com/help/mcve)请。 – Olian04

+0

感谢@ Olian04的建议。 (因为这是我第一次使用stackoverflow来提出问题)但是,完成的代码太长了,而不是真正的问题本身 - 从请求响应转换为HttpResponse。 –

回答

5

这应该工作:

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 
0

这可以帮助您:

requests.models.Response类,具有JSON()方法(根据documentation),该反序列化使用json.loads JSON响应转换为Python对象()。尝试打印下面,你可以访问你正在寻找的任何东西。

print yourResponse.json()