Java教程

轻量级Web框架Flask(二)

本文主要是介绍轻量级Web框架Flask(二),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Flask-SQLAlchemy

MySQL是免费开源软件,大家可以自行搜索其官网(https://www.MySQL.com/downloads/)

测试MySQL是否安装成功

在所有程序中,找到MySQL→MySQL Server 5.6下面的命令行工具,然后单击输入密码后回车,就可以知道MySQL数据库是否链接成功。

右击桌面上的“计算机”,在弹出的快捷键菜单中选择“属性”|“高级系统设置”|“环境变量”,在path里面添加MySQL bin目录的路径。选择环境变量,在环境变量中的path路径下输入你的MySQL路径就行了。默认安装的路径是C:\MySQL\MySQL Server 5.6\bin

安装flask-sqlalchemy,安装不了就更换豆瓣源

pip install flask-sqlalchemy

 对象-关系映射实质

class  Lib_card(db.Model):
    __tablename__ = 'lib_card'
    id = db.Column(db.Integer, primary_key=True, comment='id号')
    card_id = db.Column(db.Integer, nullable=False, comment = '借书证')
    book_id = db.Column(db.Integer, db.ForeignKey('book.id'))
    books = db.relationship('Book', backref=db.backref('cards'),uselist=False)

在Flask-SQLAlchemy中,插入、修改、删除操作均由数据库会话管理

需要一个配置config.py

USERNAME= 'root'                                        #设置登录账号
PASSWORD= '930103'                                        #设置登录密码
HOST= '127.0.0.1'                                        #设置主机地址
PORT= '3306'                                                #设置端口号
DATABASE= 'demo1'                                #设置访问的数据库
SQLALCHEMY_DATABASE_URI= f'mysql+pymysql://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DATABASE}'#创建数据库连接示例
#动态追踪修改设置,如未设置只会提示警告
SQLALCHEMY_TRACK_MODIFICATIONS=False
#查询时会显示原始SQL语句
SQLALCHEMY_ECHO= True

实例

from datetime import datetime

from flask import Flask                                                        #导入Flask模块
from flask_sqlalchemy import SQLAlchemy               #导入SQLAlchemy模块
import config                                                                 #导入配置文件
app= Flask(__name__)                                                        #Flask初始化
app.config.from_object(config)                                        #配置文件实例化
#初始化一个对象
db=SQLAlchemy(app)

class Book(db.Model):
    __tablename__ = 'book'
    id = db.Column(db.Integer, primary_key = True,comment='id号')
    title = db.Column(db.String(50), nullable=False,comment='书名')
    publishing_office = db.Column(db.String(100), nullable=False,comment='出版社')
    isbn = db.Column(db.String(100), nullable=False, comment='isbn号')
    storage_time = db.Column(db.DateTime, default=datetime.now(), comment='入库时间')

class  Lib_card(db.Model):
    __tablename__ = 'lib_card'
    id = db.Column(db.Integer, primary_key=True, comment='id号')
    card_id = db.Column(db.Integer, nullable=False, comment = '借书证')
    book_id = db.Column(db.Integer, db.ForeignKey('book.id'))
    books = db.relationship('Book', backref=db.backref('cards'),uselist=False)

with app.app_context():
#测试数据库连接是否成功
    db.create_all()     #创建数据库
    # book1= Book(id=9,title='智能导论', publishing_office='高等教育出版社',isbn='9787040479844')
    # db.session.add(book1)
    # db.session.commit()
    # result = Book.query.filter(Book.id == 9).first()
    # print(result.title)
    # agine = Book.query.filter(Book.title == result.title).all()
    # for i in agine:
    #     print(i.id)
    # db.session.delete(result)
    # db.session.commit()
    # card1=Lib_card(card_id='18001', book_id='8')
    # card2=Lib_card(card_id='18002', book_id='8')
    # db.session.add(card1)
    # db.session.add(card2)
    # db.session.commit()
    book_query = Book.query.filter(Book.id == 9).first()
    lib_card_query = book_query.cards
    for i in lib_card_query:
        print(i.card_id)

@app.route('/')
def index():
    return 'index'

# if __name__== '__main__':
#     app.run(debug=True)

注意:一个表(模型)的定义必须要定义一个主键,这个主键一般为id。在定义了Lib_card类后,申明了一个外键,并且在relationship方法中使用uselist=False来约束其关系。book_id =db.Column(db.Integer,db.ForeignKey('book.id'))表示创建一个外键,类型要跟主表一样,通过db.ForeignKey("user.id")与主表绑定books =db.relationship('Book',backref=db.backref('cards');uselist=False)表示Book可以根据Lib_card中的借书证查找到book表中的信息,backref="cards"表示book表可以直接通过cards查找到该书下的借书证号码。

框架实例

建一个apps文件夹,添加一个admin包,admin包下创建三个py文件

#__init__.py
#预加载模块内容
#其他地方调用的时候 可以直接from apps.admin import bp as admin_bp不用找到views
from .views import bp
#forms.py
from flask_wtf import FlaskForm
from wtforms import *
from wtforms.validators import *

class NameForm(FlaskForm):
    username = StringField('用户名',validators=[DataRequired()])
    password = PasswordField('密码',validators=[DataRequired()])
    submit = SubmitField('提交')
#models.py
from exts import db

class User(db.Model):
    __tablename__ = 'jq_user'
    uid = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), nullable=False, comment="用户名")
    password = db.Column(db.String(100), nullable=False,comment="密码")
    email = db.Column(db.String(50), nullable=False, unique=True, comment = "邮箱")
#views.py
from flask import Blueprint, request, flash, render_template
from apps.admin.forms import NameForm
from apps.admin.models import User

bp = Blueprint("admin",__name__)

@bp.route("/admin",methods=['GET','POST'])
def index():
    form = NameForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            username = request.form.get('username')
            password = request.form.get('password')
            result = User.query.filter(User.username==username).first()
            if result and password == result.password:
                flash('登录成功')
            else:
                return render_template('login.html', form=form, errormsg="登陆失败")
    return render_template('login.html', form=form)

建一个文件夹templates,专门放login.html文件,通过render_template调用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <h1>用户注册登录</h1>
    <form method="post" action="/test/admin">
        {{ form.csrf_token()}}
        {{ form.username.label }}{{ form.username}}
        {{ form.password.label }}{{ form.password}}
        {{ form.submit }}{{errormsg}}

        {% for message in get_flashed_messages() %}
            {{ message }}
        {% endfor %}
    </form>
</head>
<body>

</body>
</html>

建一个app.py

from flask import Flask
from apps.admin import bp as admin_bp
from exts import db
from apps.common import bp as common_bp
from apps.front import bp as front_bp
from apps.admin.models import User
from apps.common.models import Book


def create_app():
    app = Flask(__name__)
    app.secret_key = '123321'
    #注册蓝图,注册时候可以设置前缀
    app.register_blueprint(admin_bp,url_prefix="/test")
    app.register_blueprint(common_bp)
    app.register_blueprint(front_bp)
    app.config.from_object('config')
    # db.app = app
    db.init_app(app)
    return app



if __name__ == '__main__':
    app = create_app()
    with app.app_context():
        db.create_all()
    app.run(host="127.0.0.1",port=1314,debug=True)

建一个config.py

DEBUG=True
USERNAME= 'root'                                        #设置登录账号
PASSWORD= '930103'                                        #设置登录密码
HOST= '127.0.0.1'                                        #设置主机地址
PORT= '3306'                                                #设置端口号
DATABASE= 'demo1'                                #设置访问的数据库
SQLALCHEMY_DATABASE_URI= f'mysql+pymysql://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DATABASE}'#创建数据库连接示例
#动态追踪修改设置,如未设置只会提示警告
SQLALCHEMY_TRACK_MODIFICATIONS=False
#查询时会显示原始SQL语句
SQLALCHEMY_ECHO= True

建一个exts.py

#encoding:utf-8
from flask_sqlalchemy import SQLAlchemy
db=SQLAlchemy()
这篇关于轻量级Web框架Flask(二)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!