当前位置: 代码迷 >> python >> 如何在Django中使用Web API
  详细解决方案

如何在Django中使用Web API

热度:14   发布时间:2023-06-14 08:46:18.0

有此用于天气的网络API: :

每当我尝试研究如何在Django中使用Web API时,都会重定向到REST-这不是构建API的方法吗? 我不想那样做。

如果我只是想了解有关在Django中使用API??的信息,我应该去哪里?

我不确定如何在视图中进行设置。

我试过了:

from urllib2 import Request

接着

r = Request('http://samples.openweathermap.org/data/2.5/weather?zip={0},us&appid=0b7f3cd153bc12d3accb83f9682bccbb'.format(zipcode))
json_object = r.read()

但这似乎没有用。

你可以这样

import urllib2
url = 'http://samples.openweathermap.org/data/2.5/weather?zip={0},us&appid=0b7f3cd153bc12d3accb83f9682bccbb'.format(zipcode) # if zipcode is defined
response = urllib2.urlopen(url)
response.read()

使用API??意味着将GET,POST,PUT等请求发送到某些服务器。 为此,您可以使用python的requests模块。 像这样:

### Installation
pip install requests

### Usage
import requests
url = 'http://samples.openweathermap.org/data/2.5/weather?zip={0},us&appid=0b7f3cd153bc12d3accb83f9682bccbb'.format(zipcode)
req = requests.get(url)

### if json response is coming
response = req.json()

### else
response = req.content

有关更多信息,