从django视图调用REST API

ippsafx7  于 2022-12-20  发布在  Go
关注(0)|答案(3)|浏览(148)

有什么方法可以从django视图中调用RESTful api吗?
我正在尝试从django视图中传递头文件和参数。我在谷歌上搜索了半个小时,但没有找到任何有趣的东西。
任何帮助都将不胜感激

vmdwslir

vmdwslir1#

是的,当然有。你可以用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,您需要了解的关于使用它进行请求的所有信息都可以在here中找到。

uplii1fm

uplii1fm2#

是的,我张贴我的源代码,它可能会帮助你

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')
i5desfxk

i5desfxk3#

## POST Data To Django Server using python script ##  
   def sendDataToServer(server_url, people_count,store_id, brand_id, time_slot, footfall_time):
        try:
            result = requests.post(url="url", data={"people_count": people_count, "store_id": store_id, "brand_id": brand_id,"time_slot": time_slot, "footfall_time": footfall_time})
            print(result)
            lJsonResult = result.json()
            if lJsonResult['ResponseCode'] == 200:
                print("Data Send")
                info("Data Sent to the server successfully: ")
    
        except Exception as e:
            print("Failed to send json to server....", e)

相关问题