1  importlib与dir知识

# importlib简介动态导入字符串模块
# 常规导入
from ss.aa import b
from ss import a
print(b,type(b))
#<module 'ss.aa.b' from 'F:\\python37\\pythonfiles\\ss\\aa\\b.py'> #<class 'module'> # importlib动态导入py文件模块
import importlib
mod=importlib.import_module('ss.aa.b')
print(mod,type(mod))
#<module 'ss.aa.b' from 'F:\\python37\\pythonfiles\\ss\\aa\\b.py'> #<class 'module'>
print(dir(a))

2  手写配置文件

#默认配置setting包下的init.py内部
import os
from setting import settings #settings.py 内部 AAA=NONE
class setting:
def __init__(self):
user_setting=os.environ.get('user_setting')
for key in dir(settings):
if key.isupper():
setattr(self,key,getattr(settings,key))
import importlib
mod=importlib.import_module(user_setting)
for key in dir(mod):
if key.isupper():
setattr(self,key,getattr(mod,key))
setting_obj=setting() #用户user_setting包下的setting.py 内部 AAA="aaa" #run.py执行文件
import os
os.environ.setdefault('user_setting','user_setting.user_setting')
from setting import setting_obj
print(setting_obj.AAA)

3 配置查找顺序

 1先找类里的 2再找setting里用户配置的 3最后找默认django.conf.setting内默认的

4  drf分页器

from paginnator import models
from rest_framework.viewsets import ViewSetMixin
from rest_framework.views import APIView
from paginnator import myserverlize
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination,CursorPagination
from rest_framework.response import Response
# 普通分页器 #当前页的数据 序列化 返回
class Book(ViewSetMixin,APIView): #半自动路由控制
def list(self,request,*args,**kwargs):
books=models.Book.objects.all()
p=PageNumberPagination()
#每页显示不超过
p.max_page_size=10
#每页默认显示几条
p.page_size=2
#第几页
p.page_query_param='aaa'
#第几页显示几条(修改默认显示)
p.page_size_query_param = 'bbb'
# 当前页对象
p_now=p.paginate_queryset(books,request,view=self)
# 序列化
p_now_now=myserverlize.Myserializers(p_now,many=True)
# 返回分页器自带的Response(上下页链接,总条数,当前页数据)
# return p.get_paginated_response(data=p_now_now.data)
#返回当前页数据
return Response(p_now_now.data)
def list_one(self,request,*args,**kwargs):
#查看某条数据,1条数据
pass # 偏移分页器
class Book(ViewSetMixin,APIView): #半自动路由控制
def list(self,request,*args,**kwargs):
books=models.Book.objects.all()
p=LimitOffsetPagination()
# 默认显示几条
p.default_limit=3
# 最大显示条数
p.max_limit =10
# p.limit_query_param = 'limit'
# 偏移(?limit=13&offset=3) 从4算起显示10条
# p.offset_query_param = 'offset'
# 当前页数据
p_now=p.paginate_queryset(books,request,view=self)
p_now_now=myserverlize.Myserializers(p_now,many=True)
return Response(p_now_now.data)
def list_one(self,request,*args,**kwargs):
#查看某条数据,1条数据
pass
#加密分页器
#http://127.0.0.1:8000/book/?cursor=cD0xMg%3D%3D
class Book(ViewSetMixin,APIView): #半自动路由控制
def list(self,request,*args,**kwargs):
books=models.Book.objects.all()
p=CursorPagination()
p.ordering='id'
p.page_size=4
p.cursor_query_param = 'cursor'
p_now=p.paginate_queryset(books,request,view=self)
p_now_now=myserverlize.Myserializers(p_now,many=True)
return p.get_paginated_response(p_now_now.data)
def list_one(self,request,*args,**kwargs):
#查看某条数据,1条数据
pass

3种分页器

#第一种 ?page=4&page_size=100 每页显示100条
class PageNumberPagination(BasePagination):
"""
A simple page number based style that supports page numbers as
query parameters. For example: http://api.example.org/accounts/?page=4
http://api.example.org/accounts/?page=4&page_size=100
"""
page_size = api_settings.PAGE_SIZE #?page=4 每页显示4条
page_query_param = 'page'
page_size_query_param = None # ?page=4&page_size=100 每页显示100条
max_page_size = None #第二种 ?offset=3&limit=13 从4算起显示13条
class LimitOffsetPagination(BasePagination):
"""
A limit/offset based style. For example: http://api.example.org/accounts/?limit=100
http://api.example.org/accounts/?offset=400&limit=100
"""
default_limit = api_settings.PAGE_SIZE
limit_query_param = 'limit'
offset_query_param = 'offset'
max_limit = None #第三种 ?cursor=cD0xMg%3D%3D
class CursorPagination(BasePagination):
"""
The cursor pagination implementation is necessarily complex.
For an overview of the position/offset style we use, see this post:
https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api
"""
cursor_query_param = 'cursor'
page_size = api_settings.PAGE_SIZE
ordering = '-created'
page_size_query_param = None
max_page_size = None
#自带的获取当前页数据
def paginate_queryset(self, queryset, request, view=None):
pass
#自带的返回 一个带上下链接 总统条数 当前数据
def get_paginated_response(self, data):
return Response(OrderedDict([
('next', self.get_next_link()),
('previous', self.get_previous_link()),
('results', data)
]))

5 drf版本控制

class BaseVersioning(object):
default_version = api_settings.DEFAULT_VERSION
allowed_versions = api_settings.ALLOWED_VERSIONS
version_param = api_settings.VERSION_PARAM #
DEFAULTS={
# Versioning
'DEFAULT_VERSION': None,
'ALLOWED_VERSIONS': None,
'VERSION_PARAM': 'version',
}

BaseVersioning部分源码

class URLPathVersioning(BaseVersioning):
"""
To the client this is the same style as `NamespaceVersioning`.
The difference is in the backend - this implementation uses
Django's URL keyword arguments to determine the version. An example URL conf for two views that accept two different versions. urlpatterns = [
url(r'^(?P<version>[v1|v2]+)/users/$', users_list, name='users-list'),
url(r'^(?P<version>[v1|v2]+)/users/(?P<pk>[0-9]+)/$', users_detail, name='users-detail')
] GET /1.0/something/ HTTP/1.1
Host: example.com
Accept: application/json
"""
def determine_version(self, request, *args, **kwargs):
version = kwargs.get(self.version_param, self.default_version)
if not self.is_allowed_version(version):
raise exceptions.NotFound(self.invalid_version_message)
return version

URLPathVersioning部分源码

class QueryParameterVersioning(BaseVersioning):
"""
GET /something/?version=0.1 HTTP/1.1
Host: example.com
Accept: application/json
"""
def determine_version(self, request, *args, **kwargs):
version = request.query_params.get(self.version_param, self.default_version)
if not self.is_allowed_version(version):
raise exceptions.NotFound(self.invalid_version_message)
return version

QueryParameterVersioning部分源码

    def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
# Determine the API version, if versioning is in use.
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme

dispacth

分析:1view对象 2从dispacth进入到版本类 3版本类在进入到基板类取到默认设置返回 得到

request.version, request.versioning_scheme = version, scheme #版本v1(默认version) ,版本类名(默认NONE)

使用

#URLPathVersioning(url)
url(r'(?P<version>[v1|v2|v3]+)/book/',views.Book.as_view({'get':'list'}) ),
#URLPathVersioning(view)

class Book(ViewSetMixin,APIView): #半自动路由控制
versioning_class=URLPathVersioning
def list(self,request,*args,**kwargs):
books=models.Book.objects.all()
p=CursorPagination()
p.ordering='id'
p.page_size=4
p.cursor_query_param = 'cursor'
p_now=p.paginate_queryset(books,request,view=self)
p_now_now=myserverlize.Myserializers(p_now,many=True)
return p.get_paginated_response(p_now_now.data)
#setting配置
REST_FRAMEWORK = {
# 每页显示两条
'PAGE_SIZE':10,
# 'DEFAULT_VERSIONING_CLASS':'', #全局设置
'VERSION_PARAM':'version',
'DEFAULT_VERSION':'v1',
'ALLOWED_VERSIONS': ['v1', 'v2'],
}

随机推荐

  1. Linux学习笔记:【001】Linux内核分析

    Linux内核 Linux内核是Linux系统构成中最核心的一个部分,是由5个子系统组成. 进程调度: 进程调度(SCHED)控制进程对CPU的访问.当需要选择下一个进程运行时,由调度程序选择最值得运 ...

  2. IT术语

    目录: 心跳检测 故障切换 主从配置 负载均衡 集群LVS 多集群横向扩容 纵向扩容 CDN DOS DDOS 会话跟踪 CSRF

  3. HDU 1026(迷宫 BFS+打印)

    题意是要穿过一个迷宫并且将每一步打印出来. 用宽搜的方法找到路径,在 vis 中存一下方向,只是这题被看到的一种不太对的运算符重载坑了很久...... 代码如下: #include <bits/ ...

  4. github下载更新代码到本地

    git remote -v git fetch origin master git log -p  master.. origin/master 如果本地已修改需要 git stash git mer ...

  5. C# web IIS服务器 DateTime 带中文解决

    C# Web应用在某些电脑IIS上部署运行,读取当前时间带有中文,比如2018-5-1 星期一 上午 12:00:00,虽然使用Format转换可以解决,但代码量较大难免遗漏,会引发问题,为了解决该问 ...

  6. 【八】虚拟机工具 01 jps命令详解

    JPS 名称: jps - Java Virtual Machine Process Status Tool 命令用法: jps [options] [hostid] options:命令选项,用来对 ...

  7. linux下有名管道进程通信

    一.任务 1.学习mkfifo等函数: 2.了解有名管道的特点.阻塞打开与非阻塞打开等: 3.编写一个关于有名管道进程通信的程序,并运行. 二.相关概念 1.相关函数 创建有名管道的函数是mkfifo ...

  8. 【bzoj 4764】弹飞大爷

    Description 自从WC退役以来,大爷是越来越懒惰了.为了帮助他活动筋骨,也是受到了弹飞绵羊一题的启发,机房的小伙伴们决定齐心合力构造一个下面这样的序列.这个序列共有N项,每项都代表了一个小伙 ...

  9. 利用PHP实现登录与注册功能以及使用PHP读取mysql数据库——以表格形式显示数据

    登录界面 <body><form action="login1.php" method="post"><div>用户名:&l ...

  10. 手动写Entity Framework 数据库上下文和Model实体

    1.引用EF对应的程序集 使用命令安装EntityFramework包Install-Package EntityFramework Entity Framework简单目录: 1.context数据 ...