制作天气接口API服务器【完】

结构

backend:
- apis:
  - views:
      weather.py
    __init__.py
    admin.py
    apps.py
    models.py
    urls.py
- backend:
  __init__.py
  settings.py
  urls.py
  version_1_0.py
  wsgi.py
- resources: # 资源
  - images:  # 图片资源
- test:  # 测试
- thirdparty:  # 第三方工具
- utils:       # 工具类
  response.py
  weather_parse.py
- app.yaml
- manage.py

response.py 封装数据
有些时候我们需要对数据再进行一定修改,写入一些信息啥的再进行返回。

class ReturnCode:
    SUCCESS = 200
    FAILED = -100
    RESOURCE_NOT_EXISTS = 404
    UNAUTHORIZED = 500
    BROKEN_AUTHORIZED_DATA = 501
    WRONG_PARAMS = 101

    @classmethod
    def message(cls, code):
        if code == cls.SUCCESS:
            return 'success'
        elif code == cls.FAILED:
            return 'failed'
        elif code == cls.UNAUTHORIZED:
            return 'unauthorized'
        elif code == cls.WRONG_PARAMS:
            return 'wrong params'
        elif code == cls.RESOURCE_NOT_EXISTS:
            return 'resource_not_exists'
        else:
            return ''

# Mixin模式,使用Mixin可通过继承类直接使用它的方法
class CommonResponseMixin(object):
    @classmethod
    def wrap_json_response(cls, data=None, code=None, message=None):
        response = {}
        if not code:
            code = ReturnCode.SUCCESS
        if not message:
            message = ReturnCode.message(code)
        if data:
            response['data'] = data
        response['result_code'] = code
        response['message'] = message
        return response

weather.py 处理请求

from django.http import HttpResponse, JsonResponse
from utils.weather_parse import WeatherParse  # 导入第一部分写的天气模块
from utils.response import CommonResponseMixin  # 处理数据封装
from django.views import View  
import json

# 使用类视图进行http请求方法逻辑分离
# 使用Mixin可通过继承类直接使用它的方法
class WeatherView(View, CommonResponseMixin):
    def get(self, request):   # 只需实现post方法即可,前台使用post方法请求数据
        pass

    def post(self, request):
        data = []
        received_body = request.body
        received_body = json.loads(received_body)
        cities = received_body.get('cities')
        for city in cities:
            result = WeatherParse().get_weather_now(city)
            data.append(result)
        data = self.wrap_json_response(data=data)  # 数据封装
        return JsonResponse(data=data, safe=False, json_dumps_params={'ensure_ascii': False})

路由逻辑
bakend.settings.py

......
ROOT_URLCONF = 'backend.urls'
......

bakend.urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('api/v1.0/', include('backend.version_1_0'))
]

bakend.version_1_0.py

from django.urls import path, include

urlpatterns = [
    path('service/', include('apis.urls')),
]

apis.urls.py

from django.urls import path
from .views import weather, menu, image

urlpatterns = [   
    path('weather', weather.WeatherView.as_view()),
]

运行测试:

python manage.py runserver

制作天气接口API服务器【完】_第1张图片
天气接口API服务器制作完成,就差个前端展示啦

你可能感兴趣的:(Python)