当前位置:网站首页>flask图书CURD小项目

flask图书CURD小项目

2020-11-09 16:31:30 ryy_love

flask CURD

manage.py文件

from config import  create_app,db  #配置文件中
from flask_script import Manager # 扩展db指令
from flask_migrate import  Migrate,MigrateCommand # 数据库迁移库
app = create_app()
manager = Manager(app) # 命令管理类
migrate = Migrate(app,db=db) #创建迁移对象
manager.add_command('db',MigrateCommand)  #扩展新的数据库操作指令db

if __name__ == '__main__':
    manager.run() #启动

配置文件

'''
config.py 保存项目配置
'''
from flask import  Flask  # 导入Flask模块
from flask_sqlalchemy import  SQLAlchemy  #额外安装: 数据库操作模块
from flask_wtf import  CSRFProtect  # 额外导入, csrf防护

# from apps.models import  Users,Books
#
# api_user = Namespace('user', description='user related operations')

# 数据库对象
db = SQLAlchemy()
class Config(object):  #配置类定义Flask项目配置
    '''项目配置信息'''
    DEBUG=True  # 开启调试模式
    # 数据库
    SQLALCHEMY_DATABASE_URI= 'mysql://root:root@62.234.3.175:3306/1907curd'
    SQLALCHEMY_TRACK_MODIFICATIONS= True
    SQLALCHEMY_ECHO= True
    SECRET_KEY = "sdfdfdfdxfddesfdgb^$" # 加密字符串 csrf需要用session也需要用
def create_app():
    '''创建app对象'''
    app =Flask(__name__)
    # 2. 使用csrf保护应用程序
    CSRFProtect(app)
    app.config.from_object(Config) # 通过配置类加载配置信息
    # 初始化数据库配置
    db.init_app(app)


    #导入蓝图
    from apps.users import users
    from apps.book import book
    app.register_blueprint(users, url_prefix="/users") #用户蓝图/模块
    app.register_blueprint(book, url_prefix="/book")# 书籍模块
    return app



models

#1.'''
如果是团队开发:
最快方案: 项目经理把models写完!个人按照自己需求微调!!!
'''
from config import  db # 导入数据库对象
from datetime import datetime

# 用户模型(id,name,pwd,phone,email,addr,创建时间)
class Users(db.Model):
    __tablename="users"
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(50),nullable=False,unique=True) #不为空,索引加快访问速度,名字唯一
    pwd = db.Column(db.String(20),nullable=False)
    email = db.Column(db.String(20))
    phone = db.Column(db.String(20))
    addr = db.Column(db.String(20)) #地址
    create_time = db.Column(db.DATE,default=datetime.now())  # 时间默认为系统当前日期

    def __str__(self):
        return f'名字:{self.name},电话:{self.phone}'


# 作者
class Author(db.Model):
    __tablename = "author"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50), nullable=False, unique=True)  # 不为空,索引加快访问速度,名字唯一

    # 1方配置关系,配置反向引用的名字
    books = db.relationship('Books',backref='author')



# 书籍(id,名字,价格,作者id,出版日期)
class Books(db.Model):
    __tablename = "books"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50), nullable=False, unique=True)  # 不为空,索引加快访问速度,名字唯一

    # 多方外键:  书籍.author.作者名字
    author_id = db.Column(db.Integer,db.ForeignKey('author.id'))#或Author.id

增加图书

#后端
@book.route('/add_book',methods=["POST","GET"])
def add_book():
    if request.method == 'GET':
        return render_template('add.html')
    else:
        name = request.form.get('name')
        author_id = request.form.get('author_id')
        book = Books(name=name,author_id=author_id)
        db.session.add(book)
        db.session.commit()
        return redirect(url_for('book.index'))


#前端
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>增加图书</title>
</head>
<body>

 <h1>增加书籍</h1>
    <form action="/book/add_book" method="post" >
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
        名字:<input type="text" name="name"/> <br/>
        作者id:<input type="text" name="author_id"/> <br/>
        <input type="submit" value="增加"/>

    </form>

</body>
</html>

删除图书

#后端
@book.route('/book_delete/<int:id>')
def book_delete(id):
    book = Books.query.get(id)
    db.session.delete(book)
    db.session.commit()
    return redirect(url_for('book.index'))

修改图书

#后端
@book.route('/book_update/<int:id>',methods=['POST','GET'])
def book_update(id):
    if request.method=='GET':
        books = Books.query.get(id)
        return render_template('update.html',books=books)
    else:
        book = Books.query.get(id)
        name = request.form.get('name')
        book.name = name
        print(1)
        db.session.commit()

    return redirect(url_for('book.index'))

#前端
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>修改图书</title>
</head>
<body>

 <h1>修改书籍</h1>
    <form action="/book/book_update/{{ books.id }}" method="post" >
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
        id:<input type="text" name="id" value="{{books.id}}"/><br/>
        名字:<input type="text" name="name" value="{{books.name}}"/><br/>
        作者:<input type="text" name="author_id" value="{{books.author.name}}"/><br/>

        <input type="submit" value="修改"/>

    </form>

</body>
</html>

查找图书+分页

#后端
from .models import  Books,Users
@book.route('/list',methods=["POST","GET"])     # 路由定义!
def index():
    if request.method =='GET':
        paginate = Books.query.paginate(1,3)
        page = int(request.args.get('page',1))
        if page < 0:
            page = 1
        if page >= paginate.pages:
            page = paginate.pages
        paginate = Books.query.paginate(page,3)
        books = paginate.items
        return render_template('/books.html',books=books,paginate=paginate)
    else:
        print('模糊查询')
        name = request.form.get('name')
        paginate = Books.query.filter(Books.name.like("%"+name+"%")).paginate(1,3)
        books = paginate.items
        return render_template('/books.html',books=books,paginate=paginate,name=name)

#前端
<ul class="pg">
    {% if paginate.has_prev%}
        <li><a href="/book/list?page={{paginate.prev_num}}">上一页</a></li>
    {%endif%}
    {%for i in paginate.iter_pages()%}
        {%if paginate.page == i %}
            <li><a href="/book/list?page={{i}}" class="current">{{i}}</a></li>
        {%else%}
            <li><a href="/book/list?page={{i}}">{{i}}</a></li>
        {%endif%}

    {%endfor%}
    {% if paginate.has_next%}
        <li><a href="/book/list?page={{paginate.next_num}}">下一页</a></li>
    {%endif %}

</ul>

版权声明
本文为[ryy_love]所创,转载请带上原文链接,感谢
https://www.cnblogs.com/renyiyang/p/13949106.html