1.结构图css
ps: app:应用文件html
app/staic: 静态文件python
app/templates : 模板文件mysql
app/views : 视图文件sql
app/__init__: 启动后执行的文件数据库
auth : 扩展文件flask
manage.py : 启动文件session
setting : 配置文件app
建立数据库表:ide
import datetime from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime, UniqueConstraint, Index Base = declarative_base() class Users(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(32), index=True, nullable=False) pwd = Column(String(32)) def init_db(): """ 根据类建立数据库表 :return: """ engine = create_engine( "mysql+pymysql://root:@localhost:3306/sqlalchemy?charset=utf8", max_overflow=0, # 超过链接池大小外最多建立的链接 pool_size=5, # 链接池大小 pool_timeout=30, # 池中没有线程最多等待的时间,不然报错 pool_recycle=-1 # 多久以后对线程池中的线程进行一次链接的回收(重置) ) Base.metadata.create_all(engine) def drop_db(): """ 根据类删除数据库表 :return: """ engine = create_engine( "mysql+pymysql://root:@localhost:3306/sqlalchemy?charset=utf8", max_overflow=0, # 超过链接池大小外最多建立的链接 pool_size=5, # 链接池大小 pool_timeout=30, # 池中没有线程最多等待的时间,不然报错 pool_recycle=-1 # 多久以后对线程池中的线程进行一次链接的回收(重置) ) Base.metadata.drop_all(engine) if __name__ == '__main__': drop_db() init_db()
#!/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: conn = db_pool.POOL.connection() cursor = conn.cursor()
cursor.execute('select * from users where name=%s and pwd = %s',[request.form.get('user'),request.form.get('pwd'),]) result = cursor.fetchone()
cursor.close() conn.close() if result: current_app.auth_manager.login(result['name']) return redirect('/index') return render_template('login.html')
优化一下这部操做: 作个 上下文处理。
上面分三部:请求 处理 关闭, 请求进来,和最后 关闭 其实能够不须要重复写, 主要写处理。 咱们能够写个模块(专门作:SQLhelper)
SQLhelp: 作数据库操做的。
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() # with SQLHelper() as obj: # # print(obj) # print('正在执行')
优势 : 如要执行 fetchone/fetchall 直接调用它里面的方法便可。 如要本身执行 fetchmany, 不关系,能够本身写 open 方法里的 请求和执行方法。
优化以后的代码;
# 方式一 # 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')
class Foo(object): def __enter__(self): print('进入') return self def __exit__(self, exc_type, exc_val, exc_tb): print('退出') with Foo() as obj: print(obj) print('正在执行')
打印以下:
<!-- <link rel="stylesheet" href="/static/css/commons.css" /> --> <link rel="stylesheet" href="{{ url_for('static',filename='css/commons.css') }}" />