Django个人博客搭建教程---使用类视图手写一个API(一)

django-rest-framework框架虽然好用,但是具有很强的局限性,必须序列化模型类,那当我们在后台请求了其他接口,没有用到模型类,也就是数据不需要保存怎么办呢?只能手写了

一、类视图

这里调用了高德地图的天气API,提取了主要的有效信息

类视图中的get请求默认返回南京的实时天气信息,post请求根据请求城市代码返回对应城市的实时天气信息

post请求的请求体报文格式如下:

{
    "city":"710000"
}

请求地址如下:

http://www.guanacossj.com/JiaBlog/getweatherinfo/

 效果如下:

{
  "location": "台湾台湾省",
  "weather": "阴",
  "temperature": "26℃",
  "winddirection": "东北",
  "windpower": "≤3",
  "humidity": "63",
  "reporttime": "2019-09-29 10:49:22"
}

 

def queryweatherinfo():
    url = "https://restapi.amap.com/v3/weather/weatherInfo"
    key = '9bae4d790cfacdf4b54188b7758edf23'
    data = {'key': key, "city": '320100'}
    req = requests.post(url, data)
    return req.json()


class GetWeatherInfo(View):
    info = dict(queryweatherinfo())
    weatherinfo = info['lives'][0]
    result = {
        'location': weatherinfo['province'] + weatherinfo['city'],
        'weather': weatherinfo['weather'],
        'temperature': weatherinfo['temperature'] + '℃',
        'winddirection': weatherinfo['winddirection'],
        'windpower': weatherinfo['windpower'],
        'humidity': weatherinfo['humidity'],
        'reporttime': weatherinfo['reporttime'],
    }

    def get(self,request):
        return JsonResponse(
            self.result,
            json_dumps_params={'ensure_ascii':False}
        )

   
    def post(self,request):
        # 查询到的数据是二进制
        json_bytes = request.body
        # 需要进行解码,转成字符串
        json_str = json_bytes.decode()
        # 在把字符串转换成json字典
        weather_dict = json.loads(json_str)
        city = weather_dict.get('city')
        url = "https://restapi.amap.com/v3/weather/weatherInfo"
        key = '9bae4d790cfacdf4b54188b7758edf23'
        data = {'key': key, "city": city}
        req = requests.post(url, data)
        info = dict(req.json())
        weatherinfo = info['lives'][0]
        result = {
            'location': weatherinfo['province'] + weatherinfo['city'],
            'weather': weatherinfo['weather'],
            'temperature': weatherinfo['temperature'] + '℃',
            'winddirection': weatherinfo['winddirection'],
            'windpower': weatherinfo['windpower'],
            'humidity': weatherinfo['humidity'],
            'reporttime': weatherinfo['reporttime'],
        }
        return JsonResponse(
            result,
            json_dumps_params={'ensure_ascii': False}
        )

二、注意事项

这里涉及到post请求的跨域,本地问题不大,但是上了阿里云服务器,直接在post方法前面允许跨域就有问题了

这样不行

@csrf_exempt
def post(self,request):
    pass

一定要在urls.py中做修改

from django.views.decorators.csrf import csrf_exempt

url(r'^getweatherinfo/', csrf_exempt(views.GetWeatherInfo.as_view()),name='getweatherinfo'),

这个时候就不能再在post方法前面加

@csrf_exempt

亲测还是403

三、写个测试接口

import json
import time
import requests

url = 'http://127.0.0.1:8000/JiaBlog/getweatherinfo/'

timestamp = int(round((time.time() * 1000)))

data = {
    "city":"320100"
}


class queryweather:
    def __init__(self, url, data):
        self.url = url
        self.data = data

    def test_weather(self):
        r = requests.post(url=self.url, json=self.data,verify=False)
        print(json.dumps(r.json(), indent=1).encode('utf-8').decode('unicode_escape'))


if __name__ == "__main__":
    queryweather(url, data).test_weather()

 

你可能感兴趣的:(Django,django,类视图,api)