Flask ==> SQLhelper

Flask ==>   SQLhelper

1.结构图

ps:   app:应用文件

  app/staic: 静态文件

  app/templates : 模板文件

  app/views : 视图文件

  app/__init__: 启动后执行的文件

  auth : 扩展文件

  manage.py : 启动文件

  setting : 配置文件

创建数据库表:

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('正在执行')
SQLhelper

 优点 :  如要执行 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')

Flask ==>  上下文管理

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('正在执行')

打印如下:

template   == 》  模板渲染的两种方式导入

    <!-- <link rel="stylesheet" href="/static/css/commons.css" /> -->
    <link rel="stylesheet" href="{{ url_for('static',filename='css/commons.css') }}" />
原文地址:https://www.cnblogs.com/zhongbokun/p/8276786.html