初遇Flask 蓝图

初遇Flask 蓝图

Flask 是一个微型的 Python 开发的 Web 框架,基于Werkzeug WSGI工具箱和Jinja2 模板引擎。 Flask使用BSD授权。 Flask也被称为“microframework”,因为它使用简单的核心,用extension增加其他功能。Flask没有默认使用的数据库、窗体验证工具。然而,Flask保留了扩增的弹性,可以用Flask-extension加入这些功能:ORM、窗体验证工具、文件上传、各种开放式身份验证技术。

​ 关于flask的基础知识可以直接网页百度然后打开第一个链接。

蓝图 针对flask程序进行模块化处理,简单的来说,蓝图是一个存储视图的地方,这些操作在这个Blueprint 被注册到一个应用之后就可以被调用,Flask 可以通过Blueprint来组织URL以及处理请求。但是一个Blueprint并不是一个完整的应用,它不能独立于应用运行,而必须要注册到某一个应用中。

​ 我会(继续)尽量用简单的话来说明的。

1 使用到的工具

pycharm #这个就不断解释了吧
mysql + Navicat #数据库和数据库管理工具
postman #用来模仿远端发送文件

2 实验目标

​ 其实就是熟悉一下flask和蓝图的应用,做一下flask简单的增删改查。

3 实验目录和数据库表结构

初遇Flask 蓝图_第1张图片

​ 简单说一下八,author是创建app的,为什么取这个名字,我也不知道(取名鬼才上线),database是数据库连接,methods_face中存放着我们的蓝图,manager是我们的启动文件。

初遇Flask 蓝图_第2张图片

4 蓝图

​ 导入flask,蓝图以及数据库连接,并创建一个蓝图

from flask import Blueprint
from flask import request
import json
import logging
import time
from database import connection

ss = Blueprint("s_update", __name__, static_folder="static")#static_folder指定静态文件地址
db, cursor = connection()	

def commit(db):
    db.commit()

​ 下面是蓝图的增删改查,需要注意的是,收到的请求一般为json文件,我们在获取request时要注意发送的文件类型。

​ 增:

#设置methods为“GET”
@ss.route('/user_add', methods = ["GET"])
def user_add():
    data = request.json
    print(data)
    try:
        id = data['id']
        author = data['author']
        age = data['age']
        current_address = data['current_address']
        times_awards = data['times_awards']
        sql_insert = "INSERT INTO author (id,author,age,current_address,times_awards) VALUES (%s,%s, %s, %s, %s)"
        cursor.execute(sql_insert, (id, author, age, current_address, times_awards))
        commit(db)
        return "OK"
    except Exception as e:
        print("输入格式错误")
        logger_error('添加失败', exc_info=True)
        return "失败"

删:

#设置methods为“DELETE”
@ss.route('/user_delete', methods = ["DELETE"])
def user_delete():
    data = request.json
    try:
        id = data['id']
        author = data['author']
        sql_drop = "DELETE FROM author WHERE author = %s and id = %s"
        cursor.execute(sql_drop, (author, id))
        commit(db)
        return "删除成功"
    except:
        logger_error('删除失败', exc_info=True)
        return "删除失败"

改:

#设置methods为“PUT”
@ss.route('/user_update', methods = ["PUT"])
def user_update():
    data = request.json
    try:
        id = data['id']
        author = data['author']
        age = data['age']
        current_address = data['current_address']
        times_awards = data['times_awards']
        sql_update = "UPDATE author SET age=%s,current_address=%s,times_awards=%s  WHERE author=%s and id = %s"
        cursor.execute(sql_update, (age, current_address, times_awards, author, id))
        info = cursor.fetchall()
        print(info)
        commit(db)
        return "更新成功"
    except:
        pass
        logger_error('更新失败', exc_info=True)
        return "无此人"

查:

#设置methods为“GET”
@ss.route('/user_info', methods = ["GET"])
def user_info():
    data = request.json
    try:
        id = data['id']
        author = data['author']
        sql_select = "select * from author where author = %s and id = %s"
        if cursor.execute(sql_select, (author, id)):
            info = cursor.fetchall()
            jsondata = []
            for row in info:
                result = {}
                result["id"] = row[0]
                result["author"] = row[1]
                result["age"] = row[2]
                result["current_address"] = row[3]
                result["time_awards"] = row[4]
                jsondata.append(result)
            jsondatar = json.dumps(jsondata, ensure_ascii=False)#把列表转换成json文件,返回json文件
            return jsondatar
        else:
            return("用户不匹配")
    except:
        logger_error('获取信息失败', exc_info=True)
        return "查询失败"

5 各个模块

database.py

#这一个部分很简单数据库连接
import pymysql
def connection():
    db = pymysql.connect("localhost", "root", "mysql123456789", "BASEONE")
    cursor = db.cursor()
    return db, cursor

author.py

from flask import Flask
from methods_move import methods_face
def create_app():
    app = Flask(__name__)
    app.register_blueprint(methods_face.ss)# type:# Flask
    return app

​ 这一步其实就是在简单的flask建立的基础上,把Blueprint 注册到app(应用)中,其中ss是我创建的蓝图对象的名称。

methods_face.py

from flask import Blueprint
from flask import request
import json
import logging
import time
from database import connection


ss = Blueprint("s_update", __name__, static_folder="static")
db, cursor = connection()

@ss.route('/user_add', methods = ["GET"])
def user_add():
    data = request.json
    print(data)
    try:
        id = data['id']
        author = data['author']
        age = data['age']
        current_address = data['current_address']
        times_awards = data['times_awards']
        sql_insert = "INSERT INTO author (id,author,age,current_address,times_awards) VALUES (%s,%s, %s, %s, %s)"
        cursor.execute(sql_insert, (id, author, age, current_address, times_awards))
        commit(db)
        return "OK"
    except Exception as e:
        print("输入格式错误")
        logger_error('添加失败', exc_info=True)
        return "失败"

@ss.route('/user_delete', methods = ["DELETE"])
def user_delete():
    data = request.json
    try:
        id = data['id']
        author = data['author']
        sql_drop = "DELETE FROM author WHERE author = %s and id = %s"
        cursor.execute(sql_drop, (author, id))
        commit(db)
        return "删除成功"
    except:
        logger_error('删除失败', exc_info=True)
        return "删除失败"

@ss.route('/user_info', methods = ["GET"])
def user_info():
    data = request.json
    try:
        id = data['id']
        author = data['author']
        sql_select = "select * from author where author = %s and id = %s"
        if cursor.execute(sql_select, (author, id)):
            info = cursor.fetchall()
            jsondata = []
            for row in info:
                result = {}
                result["id"] = row[0]
                result["author"] = row[1]
                result["age"] = row[2]
                result["current_address"] = row[3]
                result["time_awards"] = row[4]
                jsondata.append(result)
            jsondatar = json.dumps(jsondata, ensure_ascii=False)
            return jsondatar
        else:
            return("用户不匹配")
    except:
        logger_error('获取信息失败', exc_info=True)
        return "查询失败"

@ss.route('/user_update', methods = ["PUT"])
def user_update():
    data = request.json
    try:
        id = data['id']
        author = data['author']
        age = data['age']
        current_address = data['current_address']
        times_awards = data['times_awards']
        sql_update = "UPDATE author SET age=%s,current_address=%s,times_awards=%s  WHERE author=%s and id = %s"
        cursor.execute(sql_update, (age, current_address, times_awards, author, id))
        info = cursor.fetchall()
        print(info)
        commit(db)
        return "更新成功"
    except:
        pass
        logger_error('更新失败', exc_info=True)
        return "无此人"

def commit(db):
    db.commit()

def logger_error():
    # 创建一个logger
    global logger
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)  # Log等级总开关

    # 创建一个handler,用于写入日志文件
    rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
    log_path = 'C:/Users/BBD' + '/Logs/'
    log_name = log_path + rq + '.log'
    logfile = log_name
    fh = logging.FileHandler(logfile, mode='w')
    fh.setLevel(logging.DEBUG)  # 输出到file的log等级的开关

    # 定义handler的输出格式
    formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
    fh.setFormatter(formatter)
    logger.addHandler(fh)

manager.py

from author import create_app

flask_app = create_app()

if __name__ == '__main__':
    flask_app.run(host='0.0.0.0', debug=True)

​ 就是一个启动文件,host='0.0.0.0’表示所有的IP地址(就是不限制IP地址),debug = True代表进入调试模型,在你做测试的时候打开这个设置能让你更好的去发现和处理问题,但是在正式环境下一般都是关闭的。

6 测试模型

​ 直接运行manager.py文件

初遇Flask 蓝图_第3张图片

​ 这里有一个注意的是,我们访问时应该走网址http://127.0.0.1:5000/ 或者 http://localhost:5000/ ,其中127.0.0.1和localhost都表示本地主机。

​ 如果直接打开这个网站,你会发现:

初遇Flask 蓝图_第4张图片

​ 难道我们写错了嘛,其实也不是,我们没有给网站发送json文件,所以出错(这里我的日志函数好像有点问题,以后有机会再修改一下)。所有这里我们使用postman软件来模拟这个过程,虽然网上有教程,但也还是简单说一下这个软件吧。

初遇Flask 蓝图_第5张图片

​ 现’GET’的地方就是method类型,还有其他可以选择,其中经常使用的是’GET’,‘POST’,‘PUT’,‘DELETE’。

​ 简单测试一下,

​ 增加操作:

初遇Flask 蓝图_第6张图片

​ 数据库添加一条数据:

初遇Flask 蓝图_第7张图片

​ 查询操作:

初遇Flask 蓝图_第8张图片

​ 可以看到成功返回了一个json数据。删除,修改操作相似。

模型的不足

​ 这里有一个问题,在实际中我们是不会给别人或者前端展示id的id最好是自增,因此增删改查不应该让远端发送的json文件中包含id字段。
资源:https://download.csdn.net/download/weixin_43755907/12529067

​ 最后,在这里感谢我的“至爱亲朋”的友情客串(手动狗头)hhhh

https://www.jianshu.com/p/7c474ee9ffee

你可能感兴趣的:(python,数据库,flask)