从Django视图调用REST API [英] Calling a REST API from django view

查看:64
本文介绍了从Django视图调用REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以从django视图进行RESTful api调用吗?

Is there any way to make a RESTful api call from django view?

我正在尝试从django视图沿URL传递标头和参数。我从一个半小时开始搜寻,但是找不到任何有趣的东西。

I am trying to pass header and parameters along a url from the django views. I am googling from half an hour but could not find anything interesting.

任何帮助将不胜感激

推荐答案

是的。您可以使用 urllib2.urlopen ,但我更喜欢请求

Yes of course there is. You could use urllib2.urlopen but I prefer 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')

请求库是urllib3之上的非常简单的API,您需要了解的所有信息可以在此处找到。

The requests library is a very simple API over the top of urllib3, everything you need to know about making a request using it can be found here.

这篇关于从Django视图调用REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆