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') }}" />