flask框架
安装 Flask
pip install Flask
cookies
设置
@app.route('/cookie') def set_cookie(): response = make_response() response.set_cookie('username','jack') return response
获取
@app.route('/getcookie') def get_cookie(): return request.cookies.get('username')
session
设置session
@app.route('/cookie2') def set_cookie2(): session['password']=12345 return 'ok
获取
@app.route('/getcookie2') def get_cookie2(): print('password:' session['password']) return 'ok'
蓝图
使用
引入蓝图 Blueprint
创建蓝图 (user)
注册蓝图(app)
上下文处理
flask3上下文全局变量 session, g 和 current_app
current_app = app
#在应用上下文中使用current_app with app.app_context(): #配置DEBUG模式 app.config['DEBUG']= False #访问应用的配置 debug_mode = current_app.config['DEBUG'] print(f'DEBUG模式:{debug_mode}')
g对象的基本概念 在flask中,g是一个特殊的全局变量,用于存储在请求处理期间共享的数据。它允许您在不同的请求处理函数之间 共享状态和数据,而不需要使用全局变量或显式传递参数。
g对象的作用 g 的主要作用是在不同的请求处理函数之间传递数据,以便在同一请求处理期间的不同函数之间共享状态。这有助
g 设置
@app.before_request def set_name(): g.username ='老六
g 获取
@app.route('/list') def list(): print(g.get('username')) return'学生列表
模板
参数传递
@app.route("/list") def list(): tit1e='学生信息列表2' return render_template('student.html',title=title)
html 代码
<h1> {{ title }} </h1>
引入静态文件
<img src="{{ url_for('static',filename='images/nezha.png') }}" alt="">
模板继承
使用
{% extends "base.html" %}
{% block title %} 博客列表页面 {% endblock %}
模板引入
{% include 'header.html' %}
数据库
数据库连接池
安装插件 DButils
创建连接池
P00L = PooledDB ( creator=pymysql,# 使用链接数据库的模块 maxconnections=0,#连接池允许的最大连接数,0和None表示不限制连接数 mincached=2, # 初始化时,链接池中至少创建的空闲的链接,0表示不创建 maxcached=3, # 链接池中最多闲置的链接,0和None不限制 blocking=True, # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错 setsession=[], # 开始会话前执行的命令列表。如:["set datestyle to...","set time zone...”] ping=0, host='127.0.0.1, port=3306, user='root', passwd='root123', charset="utf8", db='day20' )
链接
def fetch_one(sql, params): # conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root123', charset="utf8", db='day20') conn =P00L.connection() cursor =conn.cursor() cursor.execute(sql,params) # 传入数据 result=cursor.fetchone() cursor.close() #不是关闭连接,将此连接交还给连接池conn.close() return result

浙公网安备 33010602011771号