21

有没有办法从 django 视图进行 RESTful api 调用?

我正在尝试从 django 视图沿 url 传递标头和参数。我在谷歌上搜索了半个小时,但找不到任何有趣的东西。

任何帮助,将不胜感激

4

2 回答 2

38

是的,当然有。您可以使用urllib2.urlopen但我更喜欢requests

import requests

def my_django_view(request):
    if request.method == 'POST':
        r = requests.post('https://www.somedomain.com/some/url/save', params=request.POST)
    else:
        r = requests.get('https://www.somedomain.com/some/url/save', params=request.GET)
    if r.status_code == 200:
        return HttpResponse('Yay, it worked')
    return HttpResponse('Could not save data')

requests 库是 urllib3 之上的一个非常简单的 API,您可以在此处找到有关使用它发出请求的所有信息。

于 2012-07-26T07:21:49.427 回答
0

是的,我正在发布我的源代码,它可能会对您有所帮助

import requests
def my_django_view(request):
    url = "https://test"
    header = {
    "Content-Type":"application/json",
    "X-Client-Id":"6786787678f7dd8we77e787",
    "X-Client-Secret":"96777676767585",
    }
    payload = {   
    "subscriptionId" :"3456745",
    "planId" : "check",
    "returnUrl": "https://www.linkedin.com/in/itsharshyadav/" 
    }
    result = requests.post(url,  data=json.dumps(payload), headers=header)
    if result.status_code == 200:
        return HttpResponse('Successful')
    return HttpResponse('Something went wrong')

在获取 API 的情况下

import requests

def my_django_view(request):
    url = "https://test"
    header = {
    "Content-Type":"application/json",
    "X-Client-Id":"6786787678f7dd8we77e787",
    "X-Client-Secret":"96777676767585",
    }
    
    result = requests.get(url,headers=header)
    if result.status_code == 200:
        return HttpResponse('Successful')
    return HttpResponse('Something went wrong')
于 2022-01-05T07:50:20.663 回答