Django类视图+缓存+API聚合应用

Django类视图应用

1、应用的好处

1、能自动判断并执行类中的 get\post\put\delete方法,
2、不用在函数中根据request请求方法,通过if request.method 判断

2、创建类视图

1、在meviews.py中创建类视图: meview 继承自View类
2、在类中创建4个方法:
   def get(self,reqeust)   ----请求方法
   def post(self,request)  ----post方法,一般用于保存数据
   def put(self,request)  ----用于更新数据
   def delete(self,request)----用于删除记录
import  json
from django.http import HttpResponse,JsonResponse
from django.views import View
from django.views.decorators.csrf import csrf_exempt
​
#创建类继承自View
class meview(View):
    def get(self,request):
        return HttpResponse('This is request get method')
​
    def post(self,request):
        print(request.method)
        result ={
            'message': 'post method success.',
            'code':'200'
        }
        return JsonResponse(data=result,safe=False)
​
    def put(self,request):
        return HttpResponse('This is request put method')
​
    def delete(self,request):
        return HttpResponse('This is reqeust delete method')

3、Url路由器中添加内容

from django.contrib import admin
from django.urls import path
from django.conf.urls import url
​
from app import meviews
​
urlpatterns = [
    path('admin/', admin.site.urls),
    path('mee',meviews.meview.as_view()),
    #url(r'^mee/$',meviews.meview.as_view())
]
​
** 一定不要使用url正则表达式,否则易出错:**
** 一定要使有 path('mee',meviews.meview.as_view()) **
** 一定要使用类.as_view() **

4、注意事项

1、url路由器中使用path方法;
2、url中使用类名.as_view() 方法
3、Settings.py须禁用中间件:
MIDDLEWARE = [
    #'django.middleware.csrf.CsrfViewMiddleware', #此行禁用掉
]
4、禁用此中间件后,即在方法中可不使用
from django.views.decorators.csrf import csrf_exempt
​
@csrf_exempt
def get(reqeust):
    pass
中间件禁用的原因:
问题:页面访问时报错
Forbidden (CSRF cookie not set.): xxx
 
解决方法:
修改settings.py文件,注释掉
django.middleware.csrf.CsrfViewMiddleware',

如何读取YAML内容

1、项目结构

2、创建app.yaml文件

published:
  - app:
      category: life
      application: weather
      name: 天气
      publish_date: 2018-10-01
      url: /service/weather
      desc: this is a weather app.
  - app:
      category: life
      application: backup-image
      name: 图片备份
      publish_date: 2018-10-02
      url: /service/image
      desc: this is a backup image app.
  - app:
      category: life
      application: stock
      name: 股票
      publish_date: 2018-10-03
      url: /service/stock
      desc: this is a stock app.
​
  - app:
      category: life
      application: constellation
      name: 星座运势
      publish_date: 2018-10-03
      url: /service/constellation
      desc: this is a constellation app.
​
  - app:
      category: life
      application: joke
      name: 笑话
      publish_date: 2018-10-03
      url: /service/joke
      desc: this is a joke app.

3、读取文件内容 ---项目

项目路径: D:\Django\django_study
import os
import yaml
​
from django.http import JsonResponse
from django_study import settings
import utils.response
​
#初始化数据;
def init_app_data():
    #yaml文件路径
    data_file = os.path.join(settings.BASE_DIR, 'app.yaml')
    #读取文件内容
    with open(data_file, 'r', encoding='utf-8') as f:
        apps = yaml.load(f)
        return apps
​
#定义对外请求的方法或函数
def get_menu(request):
    #获取数据;
    global_app_data = init_app_data()
    published_apps = global_app_data['published']
    # return JsonResponse(data=published_apps, safe=False, status=200)
    response = utils.response.wrap_json_response(data=published_apps)
    return JsonResponse(data=response, safe=False)
​

4、效果

Request & Response

1、HTTP请求与Django Request 对象

HTTP请求需关注内容:
  请求方法                     headers
  请求参数                     cookies
  请求端信息
Django Request 对象
1、请求方法----Request对象的method属性
2、客户端信息--Request对象的META属性
3、Cookies---Request对象的COOKIES属性
4、请求参数---Request对象中的QueryDict(字典
​

 

2、HTTP应答与Django Response对象

HTTP应答与Django Response对象关系
状态码 ---Response对象的status属性
应答内容---HttpResponse对象的content属性
       --JsonResponse对象的data属性
延申的子类:--JsonResonse,FileResponse
内容格式
1、JsonResponse的属性:  data,safe、status
如: return JsonResponse(data=published_apps, safe=False, status=200)
** safe = False表示不检查json对象,默认将任务的python对象转为json
** safe = True 表示只能转换为字典对象

3、实点:实现天气查询应用

4、聚合API的应用--类视图+Get方法

import json
from django.http import HttpResponse,JsonResponse,FileResponse
from django.views import View
from thirdparty import juhe
​
#定义类视图
class weatherView(View):
​
    def get(self,request):
        city= request.GET.get('city')
        data = juhe.weather(city)
        return JsonResponse(data=data,status =200)

4.1 POSMAN中GET请求测试效果

4.2 聚合API+类视图+POST方法

​
import json
from django.http import HttpResponse,JsonResponse,FileResponse
from django.views import View
from thirdparty import juhe
​
#定义类视图
class weatherView(View):
    #get方法
    def get(self,request):
        city= request.GET.get('city')
        data = juhe.weather(city)
        return JsonResponse(data=data,status =200)
​
    #POST方法:请求参数为城市列表
    def post(self,reqeust):
        received_body = reqeust.body
​
        #需要使用json解码
        received_body = json.loads(received_body)
        cities = received_body.get('cities')
        response_dara = []
        for city in cities:
            result = juhe.weather(city)
            result['city'] = city
            response_dara.append(result)
 #因响应的是response_dara 列表,故需要添加 safe = False参数
        return JsonResponse(data=response_dara,safe=False,status=200)
​
​

4.3 POSMAN中POST请求效果

5、注意事项

restful是一种代码规范,主要有:
​
1.域名中都是名词,根据情况可设复数形式,
2.根据method种类设定不同功能
    get:获取查询数据  返回表
    post:增加新数据  返回新对象
    delete:删除数据   空
    put/patch:表示修改数据  新对象
​
3.都是https协议进行 API与用户的通信协议,总是使用HTTPs协议
4.将版本号放在请求头中
5 .将API部署在专用域名
-2域名
  https://api.example.com :尽量将API部署在专用域名(会存在跨域问题) 
  https://example.org/api/:API很简单(我推荐)
  
6.过滤通过在url传参的形式实现过滤条件
7.状态码
   1.服务器正在请求
   2.处理成功
   3.重定向
   4,客户端错误
   5:服务端错误
   8:错误信息以error作为key
   9;返回数据携带url链接
   10.针对不同操作返回不同数据格式
   
CBV执行过程
  1,url文件会执行  .as_views()会作为一个函数地址来存放
  2.收到请求后对应的函数地址调用,使得View里的                         dispatch(request,*args,**kwargs)方法函数
    执行如果请求方式在列表里并 如果在视图函数中定
    义了该方法就执行方法
 
4 drf框架按装和简单使用
    -在原来django框架的基础上多做了一些事   
    -安装:pip3 install djangorestframework   
    -这个东西其实就是一个app   
    -只要用drf,以后写的都是cbv   
    -drf提供的:
        序列化组件
        视图组件
        解析器
        认证组件
        权限组件
        频率组件
        分页器
        响应器
        url控制器
        版本控制
5 APIView的源码执行流程 
   -比如get请求来了,执行View的as_view方法内部的view闭包函数,view闭包函数中执行了dispatch方法,      
   -现在再执行dispatch,就已经不是View的dispatch,是APIView的dispatch方法了      
   补充
     装饰器其实就是一个函数
   
   补充:
      urlencode编码   
      formdata编码   
      json编码:request.POST是没有值,只能从body中取出,直接处理   -urlencode和formdata编码,request.POST
 #如果转列表,一定要写safe=false
 # return  JsonResponse(ll,safe=False,json_dumps_params={'ensure_ascii':False})
​

Django 缓存的应用

1、Settings配置文件设置

#缓存配置
CACHES = {
    'default': {
        # 1. MemCache
        # 'BACKEND': jango.core.cache.backends.memcached.MemcachedCache',
        # 'LOCATION': '127.0.0.1:11211',
​
        # 2. DB Cache
        # 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        # 'LOCATION': 'my_cache_table',
​
        # 3. Filesystem Cache
        # 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        # 'LOCATION': '/var/tmp/django_cache',
​
        # 4. Local Mem Cache  基于内存的缓存
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'backend-cache'
    }
}

2、环境创建

import django
from django_study import settings
from django.core.cache import cache
​
#创建缓存环境,放在py文件首部
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
​

3、详细代码

----以下为menu.py 完整内容----
import os
import yaml
import django
​
from django.http import JsonResponse
​
from django_study import settings
from django.core.cache import cache
​
​
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()
​
​
def init_app_data():
    data_file = os.path.join(settings.BASE_DIR, 'app.yaml')
    with open(data_file, 'r', encoding='utf-8') as f:
        apps = yaml.load(f)
        return apps
​
def get_cache_menu(request):
    published_apps = cache.get('published')
    #判断缓存是否有内容
    if not published_apps:
        print('cahce1=', cache.get('published'))
        global_app_data = init_app_data()
        cache.set('published',global_app_data,300)
        published_apps = global_app_data['published']
    print('cahce2=', cache.get('published'))
    return JsonResponse(data=published_apps, safe=False, status=200)
​
​

聚合API知多少

1、地址为:https://www.juhe.cn/

2、需要申请和付费

https://www.juhe.cn/docs

​
天气预报初次申请为500次
AppKey:
​
https://www.juhe.cn/myData
​
交通地理:
appkey: 
https://www.juhe.cn/ucenter/datacenter/apiApply/15
​

3、天气的聚合API http://v.juhe.cn/weather/index

 

我的数据:

 

---以下为juhe.py ----内容
​
import json
import requests
​
def weather(cityname):
    key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    api = 'http://v.juhe.cn/weather/index'
    params = 'cityname=%s&key=%s' % (cityname, key)
    url = api + '?' + params
    print(url)
    response = requests.get(url=url)
    json_data = json.loads(response.text)
    print(json_data)
    result = json_data.get('result')
    sk = result.get('sk')
    response = dict()
    response['temperature'] = sk.get('temp')
    response['wind_direction'] = sk.get('wind_direction')
    response['wind_strength'] = sk.get('wind_strength')
    response['humidity'] = sk.get('humidity')  # 湿度
    response['time'] = sk.get('time')
    return response
​
if __name__ == '__main__':
    data = weather('深圳')
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值