1安装虚拟环境
跳转到安装路径:
安装虚拟环境:
跳转到虚拟环境:
安装flask:
2.调试模式
1)app.run方法
app.run()
修改启动的ip和端口
app.run(host='0.0.0.0',port=8080)
修改启动的ip和端口,debug模式
app.run(host='0.0.0.0',port=8080,debug=True)
2)manager.run方法
导入包 pip install flask_script
ip和端口没有在原代码中写死
添加:from flask_script import Manager
添加:manager=Manager(app=app)
manager.run()
修改启动的ip和端口,debug模式
在terminal中输入:python xxx.py runserver -h 0.0.0.0 -p 8080 -d 启动xxx.py
3.匹配路由规则
1)<id>:默认结束的类型为str
2)<string:id(‘id’可以用任意字符串表示)>,指定id的类型为str
3)<int:id>,指定id的类型为int
4)<float:id>,指定id的类型为浮点数
5)<path:paht>,指定接收的paht为URL中的路径
@app.route('/get_id/<id>/')
def get_id(id):
# 匹配str类型的id值
return 'id: %s' % id
@ app.route('/get_int_id/<int:id>/')
def get_int_id(id):
# 匹配int类型的id值
return 'id: %d' % id\
@ app.route('/get_float/<float:uid>/')
def get_float(uid):
# 匹配float类型的id值
return 'id: %.2f' % uid
@app.route('/get_path/<path:upath>')
def get_path(upath):
#匹配URL路径
return 'path:%s' % upath
4.运行中的调试器
Debugger PIN: 165-343-513
点击右边的小黑屏幕
输入:在PIN中输入Debugger PIN的值
5.蓝图
- 什么是蓝图
在Flask项目中可以用Blueprint(蓝图)实现模块化的应用,使用蓝图可以让应用层次更清晰,开发者更容易去维护和开发项目。蓝图将作用于相同的URL前缀的请求地址,将具有相同前缀的请求都放在一个模块中,这样查找问题,一看路由就很快的可以找到对应的视图,并解决问题了。
- 使用蓝图
2.1 安装
pip install flask_blueprint
2.2 实例化蓝图应用
blue = Blueprint(‘first’,\_\_name\_\_)
注意:Blueprint中传入了两个参数,第一个是蓝图的名称,第二个是蓝图所在的包或模块,name代表当前模块名或者包名
2.3 注册
app = Flask(\_\_name\_\_)
app.register_blueprint(blue, url_prefix='/user')
#设置secret_key
app.config['SECRET_KEY']='123'
注意:第一个参数即我们定义初始化定义的蓝图对象,第二个参数url_prefix表示该蓝图下,所有的url请求必须以/user开始。这样对一个模块的url可以很好的进行统一管理
3 使用蓝图
修改视图上的装饰器,修改为@blue.router(‘/’)
@blue.route('/', methods=['GET', 'POST'])
def hello():
# 视图函数
return 'Hello World'
注意:该方法对应的url为127.0.0.1:5000/user/
4 url_for反向解析
语法:
url_for('蓝图中定义的第一个参数.函数名', 参数名=value)
定义跳转:
from flask import url_for, redirect
@blue.route('/redirect/')
def make_redirect():
# 第一种方法
return redirect('/hello/index/')
# 第二种方法
return redirect(url_for('first.index'))
6.跳转
@blue.route('/redirect/')
def redirect_hello():
# 实现跳转
# 1.硬编码URL(将路径写死)
# return redirect('/app/')
# 2.反向解析redirect(url_for('蓝图别名.跳转的函数名称'))
# return redirect(url_for('app.hello_world'))
return redirect(url_for('app.get_id',id=3))
7.请求
@blue.route('/request/',methods=['GET','POST','PUT'])
def get_request():
# 请求上下文
# 获取GET请求的传递的参数,request.args.get(key)/request.args.getlist(key)
# 获取POST、PUT、PATCH、DELETE请求的传递的参数,request.form.get(key)/request.form.getlist(key)
# 判断HTTP请求方式:request.method
pass
8.响应
@blue.route('/response/',methods=['GET'])
def get_response():
# 200是状态码
# res=make_response('人身苦短,我也python',200)
# 响应绑定cookie,set_cookie(key,value,max_age.expires)
# 删除cookie,delete_cookie(key)
# set_cookie('key', value, max_ages='', expires='')
res_index=render_template('index.html')
res=make_response(res_index,200)
return res
9.异常处理
···
@blue.route('/index/',methods=['GET'])
def index():
a=int(request.args.get('a'))
b=int(request.args.get('b'))
try:
a/b
except Exception as e:
print(e)
abort(500)
return render_template('index.html')
@blue.errorhandler(500)
def error500(exception):
return '捕捉异常,错误信息为:%s' % exception
···
manage.py
from flask import Flask
from flask_script import Manager
from app.views import blue
app=Flask(__name__)
# 第二步:绑定蓝图blue和app的关系
app.register_blueprint(blueprint=blue,url_prefix='/app')
# 设置secret_key
app.config['SECRET_KEY']='123'
# 将flask对象交给Manager管理,并且启动方式修改为manager
manager=Manager(app=app)
# 路由copy到views中,在manage.py中不用写路由,
# @app.route('/')
# def hello_world():
# 1/0
# return 'Hello World'
#
# # 路由匹配规则
# # 1.<id>:默认结束的类型为str
# # 2.<string:id(‘id’可以用任意字符串表示)>,指定id的类型为str
# # 3.<int:id>,指定id的类型为int
# # 4.<float:id>,指定id的类型为浮点数
# # 5.<path:paht>,指定接收的paht为URL中的路径
#
#
# @app.route('/get_id/<id>/')
# def get_id(id):
# # 匹配str类型的id值
# return 'id: %s' % id
#
#
# @ app.route('/get_int_id/<int:id>/')
# def get_int_id(id):
# # 匹配int类型的id值
# return 'id: %d' % id\
#
#
# @ app.route('/get_float/<float:uid>/')
# def get_float(uid):
# # 匹配float类型的id值
# return 'id: %.2f' % uid
#
#
# @app.route('/get_path/<path:upath>')
# def get_path(upath):
# #匹配URL路径
# return 'path:%s' % upath
if __name__=='__main__':
# 使用app
# app.run()
# 修改启动的ip和端口
# app.run(host='0.0.0.0',port=8080)
# 修改启动的ip和端口,debug模式
# app.run(host='0.0.0.0',port=8080,debug=True)
#使用manager
manager.run()
# 修改启动的ip和端口,debug模式
#python xxx.py runserver -h 0.0.0.0 -p 8080 -d
views.py
from flask import Blueprint, redirect, \
url_for, make_response, render_template, \
request, abort, session
from utils.functions import is_login
# 第一步:获取蓝图对象,指定蓝图别名为app
blue=Blueprint('app',__name__)
@blue.route('/')
@is_login
def hello_world():
# 1/0
return 'Hello World'
# 路由匹配规则
# 1.<id>:默认结束的类型为str
# 2.<string:id(‘id’可以用任意字符串表示)>,指定id的类型为str
# 3.<int:id>,指定id的类型为int
# 4.<float:id>,指定id的类型为浮点数
# 5.<path:paht>,指定接收的paht为URL中的路径
@blue.route('/get_id/<id>/')
def get_id(id):
# 匹配str类型的id值
return 'id: %s' % id
@ blue.route('/get_int_id/<int:id>/')
def get_int_id(id):
# 匹配int类型的id值
return 'id: %d' % id\
@ blue.route('/get_float/<float:uid>/')
def get_float(uid):
# 匹配float类型的id值
return 'id: %.2f' % uid
@blue.route('/get_path/<path:upath>')
def get_path(upath):
#匹配URL路径
return 'path:%s' % upath
@blue.route('/redirect/')
def redirect_hello():
# 实现跳转
# 1.硬编码URL(将路径写死)
# return redirect('/app/')
# 2.反向解析redirect(url_for('蓝图别名.跳转的函数名称'))
# return redirect(url_for('app.hello_world'))
return redirect(url_for('app.get_id',id=3))
@blue.route('/request/',methods=['GET','POST','PUT'])
def get_request():
# 请求上下文
# 获取GET请求的传递的参数,request.args.get(key)/request.args.getlist(key)
# 获取POST、PUT、PATCH、DELETE请求的传递的参数,request.form.get(key)/request.form.getlist(key)
# 判断HTTP请求方式:request.method
pass
@blue.route('/response/',methods=['GET'])
def get_response():
# 200是状态码
# res=make_response('人身苦短,我也python',200)
# 响应绑定cookie,set_cookie(key,value,max_age.expires)
# 删除cookie,delete_cookie(key)
# set_cookie('key', value, max_ages='', expires='')
res_index=render_template('index.html')
res=make_response(res_index,200)
return res
@blue.route('/index/',methods=['GET'])
def index():
a=int(request.args.get('a'))
b=int(request.args.get('b'))
try:
a/b
except Exception as e:
print(e)
abort(500)
return render_template('index.html')
@blue.errorhandler(500)
def error500(exception):
return '捕捉异常,错误信息为:%s' % exception
@blue.route('/login/',methods=['GET','POST'])
def login():
if request.method=='GET':
return render_template('login.html')
if request.method=='POST':
username=request.form.get('username')
password=request.form.get('password')
# 验证用户名和密码是否正确
if username=='coco' and password=='123456':
# 验证通过,登录成功向session中存入登录成功的标识符
session['login_status']=1
return redirect(url_for('app.get_response'))
else:
return render_template('login.html')
pass