flask那些事(一)
flask配置文件
flask路由系统
@app.route() 装饰器中的参数
如果不明白装饰器 点击这里
methods : 当前 url 地址,允许访问的请求方式
@app.route("/info", methods=["GET", "POST"])
def student_info():
stu_id = int(request.args["id"])
return f"Hello Old boy {stu_id}" # Python3.6的新特性 f"{变量名}"
endpoint : 反向url地址,默认为视图函数名 (url_for)
from flask import url_for
@app.route("/info", methods=["GET", "POST"], endpoint="r_info")
def student_info():
print(url_for("r_info")) # /info
stu_id = int(request.args["id"])
return f"Hello Old boy {stu_id}" # Python3.6的新特性 f"{变量名}"
defaults : 视图函数的参数默认值{"nid":1}
from flask import url_for
@app.route("/info", methods=["GET", "POST"], endpoint="r_info", defaults={"nid": 100})
def student_info(nid):
print(url_for("r_info")) # /info
# stu_id = int(request.args["id"])
print(nid) # 100
return f"Hello Old boy {nid}" # Python3.6的新特性 f"{变量名}"
strict_slashes : url地址结尾符"/"的控制 False : 无论结尾 "/" 是否存在均可以访问 , True : 结尾必须不能是 "/"
# 访问地址 : /info
@app.route("/info", strict_slashes=True)
def student_info():
return "Hello Old boy info"
# 访问地址 : /infos or /infos/
@app.route("/infos", strict_slashes=False)
def student_infos():
return "Hello Old boy infos"
redirect_to : url地址重定向
# 访问地址 : /info 浏览器跳转至 /infos
@app.route("/info", strict_slashes=True, redirect_to="/infos")
def student_info():
return "Hello Old boy info"
@app.route("/infos", strict_slashes=False)
def student_infos():
return "Hello Old boy infos"
subdomain : 子域名前缀 subdomian="DragonFire" 这样写可以得到 DragonFire.oldboyedu.com 前提是app.config["SERVER_NAME"] = "oldboyedu.com"
app.config["SERVER_NAME"] = "oldboy.com"
@app.route("/info",subdomain="DragonFire")
def student_info():
return "Hello Old boy info"
# 访问地址为: DragonFire.oldboy.com/info
关于路由目前就说这么多,之后的课程中会有关于Flask路由系统的源码剖析,再详细说明Flask路由系统的工作原理
动态参数路由:
from flask import url_for
# 访问地址 : http://127.0.0.1:5000/info/1
@app.route("/info/<int:nid>", methods=["GET", "POST"], endpoint="r_info")
def student_info(nid):
print(url_for("r_info",nid=2)) # /info/2
return f"Hello Old boy {nid}" # Python3.6的新特性 f"{变量名}"
int:nid 就是在url后定义一个参数接收
但是这种动态参数路由,在url_for的时候,一定要将动态参数名+参数值添加进去,否则会抛出参数错误的异常
路由正则:
一般不用,如果有特殊需求,不怕麻烦的话,这个东西还是挺好用的,前提是你的正则玩儿的很6
注意事项以及源码示例:
- flask的路由系统比较特殊,是通过装饰器实现的,但是究其本质,还是通过 app.add_url_rute 方法来实现的。
from flask import Flask, request, current_app
import importlib
app = Flask(__name__)
# 导入配置文件
app.config.from_object('settings.DevConfig')
# flask路由系统
@app.route('/')
def hello_world():
return 'Hello World!'
路由源码以及其分析
# 以 @app.route('/index', endpoint='index', methods=['GET']) 为例
# 函数本质是是个闭包函数
def route(self, rule, **options):
# self 表示的app对象的实例
# rule 表示路由 rule='/index'
# **options 是其他参数 这里 endpoint='index', methods=['GET']
def decorator(f):
# 这里是获取 endpoint的值,如果不存在则为None
endpoint = options.pop("endpoint", None)
# 本质上是 执行 app.add_url_rule('/index',....)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
"""
第一步 执行route 后返回 decorator
第二步 执行@decorator -->decorator(index)
"""
@app.route('/index', endpoint='index', methods=['GET'])
# 参数endpoint不写 默认为函数名,用户反向生成url
def index():
print(current_app.config['DB'])
return "xxx"
def login():
return 'login'
# 这是另外一种路由方式,类似于django中的path('',views.....)
app.add_url_rule('/login', 'n2',login,methods=['GET', 'POST'])
if __name__ == '__main__':
app.run()
def _endpoint_from_view_func(view_func):
"""
Internal helper that returns the default endpoint for a given
function. This always is the function name.
"""
assert view_func is not None, "expected view func if endpoint is not provided."
# 如果 endpoint=None的时候,返回的是 默认的endpoint view_func的名字
return view_func.__name__
CBV简单实现
from flask import Flask, request, current_app,views
import importlib
app = Flask(__name__)
app.config.from_object('settings.DevConfig')
# 装饰器
def auth(func):
def inner(*args,**kwargs):
result = func(*args,**kwargs)
return result
return inner
class IndexView(views.MethodView):
methods = ['GET','POST']
decorators =[auth,]
def get(self):
return 'index.get'
def post(self):
return 'index.post'
app.add_url_rule('/index',view_func=IndexView.as_view(name='index')) # name=endpoint
if __name__ == '__main__':
app.run()
源码分析
class MethodView(with_metaclass(MethodViewType, View)):
"""A class-based view that dispatches request methods to the corresponding
class methods. For example, if you implement a ``get`` method, it will be
used to handle ``GET`` requests. ::
class CounterAPI(MethodView):
def get(self):
return session.get('counter', 0)
def post(self):
session['counter'] = session.get('counter', 0) + 1
return 'OK'
app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))
"""
# 类似于django中的dispatch,视图类中分发不同请求说对应的方法
def dispatch_request(self, *args, **kwargs):
meth = getattr(self, request.method.lower(), None)
# If the request method is HEAD and we don't have a handler for it
# retry with GET.
if meth is None and request.method == "HEAD":
meth = getattr(self, "get", None)
assert meth is not None, "Unimplemented method %r" % request.method
return meth(*args, **kwargs)
# 如果是get请求,返回的是 get(*args,**kwargs)
host文件路径(修改本地DNS对应关系)
windows:C:\Windows\System32\drivers\etc\hosts
mac:/etc/hosts
flask那些事(一)的更多相关文章
- 一般人不知道的Flask框架SQLAlchemy的那些事
目录 SQLAlchemy 1.介绍 2.简单使用(能创建表,删除表,不能修改表) 3.一对多关系 4.多对多关系 5.操作数据表 6.基于scoped_session实现线程安全 7.基本增删查改 ...
- Flask —— 使用Python和OpenShift进行即时Web开发
最近Packtpub找到了我,让我给他们新出版的关于Flask的书写书评.Flask是一个很流行的Python框架.那本书是Ron DuPlain写的<Flask 即时Web开发>.我决定 ...
- 写给新手看的Flask+uwsgi+Nginx+Ubuntu部署教程
学习 Flask,写完一个 Flask 应用需要部署的时候,就想着折腾自己的服务器.根据搜索的教程照做,对于原理一知半解,磕磕碰碰,只要运行起来了,谢天谢地然后不再折腾了,到下一次还需要部署时,这样的 ...
- flask开发restful api系列(1)
在此之前,向大家说明的是,我们整个框架用的是flask + sqlalchemy + redis.如果没有开发过web,还是先去学习一下,这边只是介绍如果从开发web转换到开发移动端.如果flask还 ...
- Flask中endpoint的理解
在flask框架中,我们经常会遇到endpoint这个东西,最开始也没法理解这个到底是做什么的.最近正好在研究Flask的源码,也就顺带了解了一下这个endpoint 首先,我们看一个例子: @app ...
- flask tutorial => make a blog :) flask 搭建博客系统从零开始!
please follow the tutorial from the official site :) http://flask.pocoo.org/docs/ You could download ...
- 关于flask线程安全的简单研究
flask是python web开发比较主流的框架之一,也是我在工作中使用的主要开发框架.一直对其是如何保证线程安全的问题比较好奇,所以简单的探究了一番,由于只是简单查看了源码,并未深入细致研究,因此 ...
- flask + Python3 实现的的API自动化测试平台---- IAPTest接口测试平台(总结感悟篇)
前言: 在前进中去发现自己的不足,在学习中去丰富自己的能力,在放弃时想想自己最初的目的,在困难面前想想怎么踏过去.在不断成长中去磨炼自己. 正文: 时间轴 flask + Python3 实现的的AP ...
- 【Flask】 网站的用户管理
网站用户管理 不知道为什么很多学习Flask的人都是从搭博客开始的(大概是因为那本书的案例是博客,同时对bootstrap支持良好,bootstrap又是twitter开发的吧..)既然是搭建博客,就 ...
随机推荐
- Jmeter获取数据库查询结果某一字段的值
1.首先进行连接数据库 2.添加JDBC Request 3.添加BeanShell PostProcessor 4.注意点:如果获取的是INT数字类型的,结尾需要添加toString()
- 1.web2
听说聪明的人都能找到答案http://123.206.87.240:8002/web2/ 直接查看源码~~~
- c#数组没有Remove方法,转换为list,再使用Remove方法(例如数组 a,b,c 去除b 只剩a c)
c#数组没有Remove方法,转换为list再移除,因为list自带Remove方法 string aaa=a,b,c; var array=aaa.Split(',');// 数组 List ...
- Codeforces Round #554 (Div. 2) D 贪心 + 记忆化搜索
https://codeforces.com/contest/1152/problem/D 题意 给你一个n代表合法括号序列的长度一半,一颗有所有合法括号序列构成的字典树上,选择最大的边集,边集的边没 ...
- WordPress更改“固定链接”后 ,页面出现404的解决方法
一.Web服务器对应的是Nginx 解决方案:修改linux服务器下Nginx的配置文件,目录为:/usr/local/nginx/conf/nginx.conf, 也可以直接使用命令nginx -t ...
- FFmpeg 常用结构体
0.FFmpeg 中最关键的结构体之间的关系 FFmpeg 中结构体很多.最关键的结构体可以分成以下几类: 1)解协议(http, rtsp, rtmp, mms) AVIOContext,URLPr ...
- 在Anaconda中使用linux的命令
在Anaconda中使用linux的命令 1.在anaconda中执行以下命令即可(要先activation 想用的环境): conda install m2-base 2.安装git.添加环境变量即 ...
- LeetCode 94:二叉树的中序遍历 Binary Tree Inorder Traversal
题目: 给定一个二叉树,返回它的中序 遍历. Given a binary tree, return the inorder traversal of its nodes' values. 示例: 输 ...
- 修改centos服务器时区并同步最新时间
rm -rf /etc/localtime ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime ntpdate cn.pool.ntp.org ...
- Java & PHP RSA 互通密钥、签名、验签、加密、解密
RSA加密算法是一种非对称加密算法.在公开密钥加密和电子商业中RSA被广泛使用.RSA是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Le ...