Flask学习笔记

Flask学习笔记

官方教程:https://flask.palletsprojects.com/en/2.3.x/
W3CSchool: https://www.w3cschool.cn/flask_1/
知乎资料:https://www.zhihu.com/people/im-greyli
flask中文网:http://flask123.sinaapp.com/
python相关论坛:https://learnku.com/python

待解决的问题

  1. 虚拟环境的安装与配置
#1. 创建虚拟环境
#macOS/Linux系统:
$ mkdir myproject
$ cd myproject
$ python3 -m venv venv
#Windows系统:
> mkdir myproject
> cd myproject
> py -3 -m venv venv
#2.激活虚拟环境
#macOS/Linux系统:
$ . venv/bin/activate
#Windows系统
venv\Scripts\activate
#3.安装Flask
pip install Flask
  1. pycharm中调试模式的开启
    参考:https://blog.csdn.net/u011870022/article/details/109192121
  2. 自定义过滤器
    参考:https://blog.csdn.net/qq_40132294/article/details/123559365
#单次注册
@app.template_filter('format_time') # 模板渲染中格式话时间戳
def format_str_time(timestamp):
return datetime.fromtimestamp(timestamp)
#使用
#创建日期:{{ project["time"] | format_time }}</div>
#批次注册
app.add_template_filter(format_str_time,'format_time')
  1. Response()
  2. 上下文的使用
    参考: https://blog.csdn.net/qq_43621629/article/details/106008229
  3. sqlAlchemy的使用
    参考:https://blog.csdn.net/qq_41341757/article/details/109462158
    参考:https://blog.csdn.net/weixin_47906106/article/details/123774620
    建立关系
    参考:https://blog.csdn.net/mr_hui_/article/details/83217566
    查询结果转换为字典:https://blog.csdn.net/luanxiyuan/article/details/80434767
    练习:
#db.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def init_app(app,db):
# 连接数据库
app.config['SQLALCHEMY_DATABASE_URI'] = \
"mysql+pymysql://root:******@127.0.0.1:3306/briefing"
# 关闭数据库修改跟踪操作[提高性能]:
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 开启输出底层执行的sql语句
app.config['SQLALCHEMY_ECHO'] = True
db.init_app(app)
#构建模型类
class User(db.Model):
# 指定表名:默认使用类名小写
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64))
email = db.Column(db.String(64))
age = db.Column(db.Integer)
def __repr__(self):
return "(%s, %s, %s, %s)"%(self.id, self.name, self.email, self.age)
#main.py
from flask import Flask,render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
from db import db,init_app,User
app = Flask(__name__,template_folder='templates')
init_app(app,db)
@app.route('/')
def index():
# 查询所有用户
users = User.query.all()
return 'ok'
  1. 装饰器原理
    参考:https://blog.csdn.net/duyun0/article/details/118087073
  2. flask加载配置方式
    参考:https://blog.csdn.net/C_Redemption/article/details/125028823
    参考:https://blog.csdn.net/lingyingdon/article/details/108073302
    参考:https://blog.csdn.net/yannanxiu/article/details/88354184
  3. 钩子函数原理
    参考:https://www.jianshu.com/p/03ee563b4231
#练习
#hooks.py
class MyHook(object):
def __init__(self,bpp):
@bpp.before_request
def before_request():
print('how are u')
@bpp.after_request
def after_request(res):
print('bye!')
return res
#main.py
from hooks import MyHook
app = Flask(__name__)
MyHook(app)
  1. 蓝图BluePrint
    参考:https://blog.csdn.net/weixin_41973615/article/details/82252501
    参考:https://www.cnblogs.com/nq31/p/14326361.html
    蓝图路径问题:https://blog.csdn.net/fresh_nam/article/details/124343905
#练习
#admin.py
from flask import Blueprint
admin = Blueprint('admin', __name__)
@admin.route('/admin')
def login():
return 'hello,admin'
@admin.route('/admin/register')
def register():
return 'register'
#main.py
from admin import admin
app.register_blueprint(admin)
  1. 生成路由 url_for
#视图函数前要加蓝图名称
#url_for(blueprint.view)
url_for('admin.register')
  1. flask 设置cookie和session
    参考:https://blog.csdn.net/wei18791957243/article/details/85172653
    参考:https://www.cnblogs.com/big-handsome-guy/p/8550310.html

  2. flask 重定向
    参考:https://blog.csdn.net/qq_40132294/article/details/123544818
    参考:https://blog.csdn.net/qq_38866586/article/details/100945646

  3. 错误处理
    参考:http://t.zoukankan.com/zhongyehai-p-11874509.html

  4. 消息闪现 Flash()
    参考:https://blog.csdn.net/weixin_44491423/article/details/123224986
    参考:https://dormousehole.readthedocs.io/en/latest/patterns/flashing.html
    参考:http://www.javashuo.com/article/p-snjpqdpd-dg.html

  5. 文件上传
    参考:https://zhuanlan.zhihu.com/p/24423891
    参考:https://www.likecs.com/show-305515056.html
    参考:https://pythonhosted.org/Flask-Uploads/
    参考:https://blog.csdn.net/pzl_pzl/article/details/80861231
    文件名冲突:https://vimsky.com/examples/detail/python-ex-flaskext.uploads-UploadSet-resolve_conflict-method.html
    flask_uploads.UploadNotAllowed:IMAGES.update(".jfif")

#一. 原生方法
#步骤一:在HTML中创建表单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">提交</button>
</form>
<img src="{{ url }}" alt="">
</body>
#步骤二:设定上传文件相关配置
#1.指定上传目录
app.config['UPLOAD_FOLDER'] = 'static/files'
#2.指定文件大小,例16M
app.config['MAX_CONTENT_LENGTH'] = 1024*1024*16
#3.设置文件类型
ALLOWED_EXTENSIONS = {'jpg', 'pdf', 'jpeg', 'png'}
#步骤三:定义相关函数和视图
#1.检验文件类型
def allow_file(filename):
return '.' in filename and '.'.split(filename,1)[1] in ALLOWED_EXTENSIONS
#2.生成文件路径url
@app.route('/static/files/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],filename)
#3.接收文件并保存
@app.route('/upload', methods=['POST', 'GET'])
def upload():
if request.method == "POST":
file = request.files['file']
if file:
# print(file.filename)
filename = secure_filename(file.filename)
# print(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
file_url = url_for('uploaded_file',filename=filename)
print(file_url)
return render_template('upload.html',url=file_url)
else:
return render_template('upload.html')
#二:使用扩展工具 flask_uploads
#可能出现的问题:
#1. cannot import name 'secure_filename' from 'werkzeug'
#解决:修改flask_uploads源代码中第26行
#参考: https://blog.csdn.net/m0_48669897/article/details/112096620
from werkzeug.utils import secure_filename
from werkzeug.datastructures import FileStorage
# 步骤一:创建表单
# 步骤二:相关配置
#1. 设置上传目录
#这里的字段名称和设置的文件集名称匹配,对应文件集名的大写
app.config['UPLOADED_IMAGE_DEST'] = 'static/files'
#2.创建文件集并初始化
photos = UploadSet('image', IMAGES)
configure_uploads(app, photos)
#3.设置文件大小限制,默认是16M
patch_request_class(app, 12 * 1024 * 1024)
#4.定义表单对应视图
#生成文件url使用扩展自带的url()方法
@app.route('/upload', methods=['POST', 'GET'])
def upload_file():
if request.method == 'POST' and 'file' in request.files:
filename = photos.save(request.files['file'])
file_url = photos.url(filename)
return render_template('upload.html',url=file_url)
else:
return render_template('upload.html')
#三、多文件上传
#步骤一:修改form表单file字段属性
<input type="file" name="files" multiple="multiple">
#步骤二:遍历request.files.getlist('files')文件列表
@app.route('/',methods=['POST','GET'])
def upload():
if request.method == 'POST' and 'files' in request.files:
print(request.files)
urls = []
for file in request.files.getlist('files'):
filename = photos.save(file)
url = photos.url(filename)
urls.append(url)
return render_template('upload.html',urls=urls)
else:
return render_template('upload.html')
#四.文件拖拽上传插件
#参考:https://zhuanlan.zhihu.com/p/24513281?refer=flask
  1. 文件下载
    参考:https://www.cnblogs.com/ExMan/p/14298905.html
    参考:https://blog.csdn.net/qq_44198436/article/details/106922355

  2. sijax扩展
    参考:https://blog.csdn.net/weixin_44491423/article/details/123247495

  3. flask处理ajax请求的一般方法
    参考:https://www.cnblogs.com/adamans/articles/9093711.html

  4. flask发送邮件 FLASK-MAIL
    参考:https://codingdict.com/article/4880
    参考:https://blog.csdn.net/qq_25861247/article/details/122564893

  5. flask信号机制
    参考:https://www.w3cschool.cn/flask_1/flask_1-1ovj3izw.html
    参考:https://blog.csdn.net/feit2417/article/details/80735643
    参考:http://flask123.sinaapp.com/article/53/

  6. flask即插视图
    参考:https://www.w3cschool.cn/flask_1/flask_1-1txq3j0n.html
    参考:https://zhuanlan.zhihu.com/p/465355642
    参考:https://blog.csdn.net/qq_39330486/article/details/122695388

  7. flask WTF扩展
    参考:https://blog.csdn.net/u014465934/article/details/80157058
    官方:https://flask-wtf.readthedocs.io/en/1.0.x/
    参考:https://blog.csdn.net/tscaxx/article/details/114193046
    参考:https://www.cnblogs.com/haiyan123/p/8254228.html

  8. flask Bootstrap扩展
    参考:https://blog.csdn.net/linshuhe1/article/details/51742474
    参考:https://blog.csdn.net/qq_41856814/article/details/101230159
    参考:https://www.csdn.net/tags/MtzaMg1sNDYxNC1ibG9n.html
    参考:https://blog.csdn.net/os373/article/details/79620450

  9. PyYAML
    参考:https://blog.csdn.net/qq_22034353/article/details/88591681

  10. Shell交互模式
    参考:https://dormousehole.readthedocs.io/en/latest/shell.html

  11. flask-admin扩展
    参考:https://blog.csdn.net/Gherbirthday0916/article/details/123292575
    官方:https://flask-admin.readthedocs.io/en/latest/
    参考:https://my.oschina.net/chenyangbo3?tab=newest&catalogId=6373620

  12. flask-login扩展
    官方:https://flask-login.readthedocs.io/en/latest/

  13. flask-security扩展
    官方:https://flask-security.readthedocs.io/en/latest/

  14. flask-script扩展
    参考:https://www.jianshu.com/p/a7fd176a3426
    参考:https://blog.csdn.net/weixin_43067754/article/details/88561565
    官方:https://flask-script.readthedocs.io/en/latest/
    参考:https://flask.palletsprojects.com/en/2.1.x/cli/

  15. flask-moment扩展
    参考:https://zhuanlan.zhihu.com/p/64438998

  16. flask-restful扩展
    官方:https://flask-restful.readthedocs.io/en/latest/

  17. flask token认证
    参考:https://www.zlkt.net/post/detail/60
    参考:https://flask-jwt-extended.readthedocs.io/en/stable/
    参考:https://blog.csdn.net/t8116189520/article/details/122673112

  18. flask-migrate
    参考:https://blog.csdn.net/qq_40127080/article/details/120396771

posted on   朝朝暮Mu  阅读(88)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示