2016-11-08 10 views
3

私のDjangoプロジェクトでは、私のビューで第三者のURLにデータを取得/投稿し、それが提供するWebページにリダイレクトする必要があります。requests.models.ResponseからDjango HttpResponseに変換する

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

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のコードのように、ラップSDKとして、このサードパーティのAPIを使用したいしかし例えば、私は単に

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) 

ような何かを行うことができます

しかし、HttpResponse(result)はHttpResponseへのrequests.models.Responseインスタンスを変換する正しい方法ではないようです...レイアウトが悪く、エンコーディングの問題などいくつか...リクエストを変換する正しい方法がありますか?resp DjangoのHttpResponseにonse?


更新:

の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

これはあなたを助けるかもしれない:JSON()メソッド(documentationによる)json.loadsを使ってPythonオブジェクトにJSONレスポンスをデシリアライズ()は、

requests.models.Responseクラス。あなたはあなたが探しているものにアクセスすることができます。

print yourResponse.json() 
関連する問題