1.模板继承
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> 盒子1 <!-- <link rel="stylesheet" href="/static/css/commons.css" /> --> 引入 css第一种方式 <link rel="stylesheet" href="{{ url_for('static',filename='css/commons.css') }}" /> 引入css第二种方式 {% block css %}{% endblock %} 盒子2 </head> <body> <div class="pg-header"></div> <div class="pg-body"> {% block body %}{% endblock %} 盒子3 </div> {% block js %}{% endblock %} 盒子4 </body> </html>
2.连接数据库
db_pool.py --------------------------------------------- 创建数据库连接池
import time import pymysql import threading from DBUtils.PooledDB import PooledDB, SharedDBConnection POOL = PooledDB( creator=pymysql, # 使用链接数据库的模块 maxconnections=6, # 连接池允许的最大连接数,0和None表示不限制连接数 mincached=2, # 初始化时,链接池中至少创建的空闲的链接,0表示不创建 maxcached=5, # 链接池中最多闲置的链接,0和None不限制 maxshared=3, # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。 blocking=True, # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错 maxusage=None, # 一个链接最多被重复使用的次数,None表示无限制 setsession=[], # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."] ping=0, # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always host='47.93.4.198', port=3306, user='root', password='123', database='s6', charset='utf8' )
sqlhelper.py ------------------------------------------------------- 因为每次操作都需要连接连接池,获取游标等,所以把这些操作封装起来
from utils.pool import db_pool import pymysql class SQLHelper(object): def __init__(self): self.conn = None self.cursor = None def open(self, cursor=pymysql.cursors.DictCursor): self.conn = db_pool.POOL.connection() self.cursor = self.conn.cursor(cursor=cursor) def close(self): self.cursor.close() self.conn.close() def fetchone(self, sql, params): cursor = self.cursor cursor.execute(sql, params) result = cursor.fetchone() return result def fetchall(self, sql, params): cursor = self.cursor cursor.execute(sql, params) result = cursor.fetchall() return result def __enter__(self): self.open() return self def __exit__(self, exc_type, exc_val, exc_tb): self.close()
login.py ---------------------------------------------
#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Blueprint, request, render_template, redirect, session,current_app from utils.pool import db_pool from utils.pool.sqlhelper import SQLHelper account = Blueprint('account', __name__) @account.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') else: # 方式一 # helper = SQLHelper() # helper.open() # result = helper.fetchone('select * from users where name=%s and pwd = %s',[request.form.get('user'),request.form.get('pwd'),]) # helper.close() # 方式二: with SQLHelper() as helper: result = helper.fetchone('select * from users where name=%s and pwd = %s',[request.form.get('user'),request.form.get('pwd'),]) if result: current_app.auth_manager.login(result['name']) return redirect('/index') return render_template('login.html')
3.应用flask-session
from flask_session import Session
#引入session后,注册app
app = Flask(__name__) Session(app)
settings.py 配置 --------------
#!/usr/bin/env python # -*- coding:utf-8 -*- import redis class BaseConfig(object): SESSION_TYPE = 'redis' # session类型为redis SESSION_KEY_PREFIX = 'session:' # 保存到session中的值的前缀 SESSION_PERMANENT = False # 如果设置为True,则关闭浏览器session就失效。 SESSION_USE_SIGNER = False # 是否对发送到浏览器上 session:cookie值进行加密 class ProductionConfig(BaseConfig): SESSION_REDIS = redis.Redis(host='47.93.4.195', port=6379, password='123123') # 用于连接redis的配置 class DevelopmentConfig(BaseConfig): SESSION_REDIS = redis.Redis(host='47.93.4.196', port=6379, password='123123') # 用于连接redis的配置 class TestingConfig(BaseConfig): SESSION_REDIS = redis.Redis(host='47.93.4.197', port=6379, password='123123') # 用于连接redis的配置
其他的正常操作就可以了