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

查看:28
本文介绍了从 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天全站免登陆