Calling a REST API from django view

前端 未结 1 1981
情书的邮戳
情书的邮戳 2020-11-30 14:07

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

I am trying to pass header and parameters along a url from the django views. I am googling from half an

相关标签:
1条回答
  • 2020-11-30 14:11

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

    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.

    0 讨论(0)
提交回复
热议问题