flask CURD
manage.py file
from config import create_app,db # In profile
from flask_script import Manager # Expand db Instructions
from flask_migrate import Migrate,MigrateCommand # Database migration database
app = create_app()
manager = Manager(app) # Command management class
migrate = Migrate(app,db=db) # Create a migration object
manager.add_command('db',MigrateCommand) # Extend new database operation instructions db
if __name__ == '__main__':
manager.run() # start-up
The configuration file
'''
config.py Save project configuration
'''
from flask import Flask # Import Flask modular
from flask_sqlalchemy import SQLAlchemy # Additional installation : Database operation module
from flask_wtf import CSRFProtect # Extra import , csrf protective
# from apps.models import Users,Books
#
# api_user = Namespace('user', description='user related operations')
# Database objects
db = SQLAlchemy()
class Config(object): # Configuration class definition Flask Project configuration
''' Project configuration information '''
DEBUG=True # Turn on debugging mode
# database
SQLALCHEMY_DATABASE_URI= 'mysql://root:[email protected]:3306/1907curd'
SQLALCHEMY_TRACK_MODIFICATIONS= True
SQLALCHEMY_ECHO= True
SECRET_KEY = "sdfdfdfdxfddesfdgb^$" # Encrypted string csrf Need to use session Also need to use
def create_app():
''' establish app object '''
app =Flask(__name__)
# 2. Use csrf Protect applications
CSRFProtect(app)
app.config.from_object(Config) # Load the configuration information through the configuration class
# Initialize database configuration
db.init_app(app)
# Import blueprint
from apps.users import users
from apps.book import book
app.register_blueprint(users, url_prefix="/users") # User blueprint / modular
app.register_blueprint(book, url_prefix="/book")# Book module
return app
models
#1.'''
If it's team development :
The fastest solution : The project manager put models finish writing sth. ! Individuals fine tune according to their own needs !!!
'''
from config import db # Import database objects
from datetime import datetime
# The user model (id,name,pwd,phone,email,addr, Creation time )
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) # Not empty , Indexing speeds up access , The name is unique
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)) # Address
create_time = db.Column(db.DATE,default=datetime.now()) # The default time is the current system date
def __str__(self):
return f' name :{self.name}, Telephone :{self.phone}'
# author
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) # Not empty , Indexing speeds up access , The name is unique
# 1 Side configuration relationship , Configure the name of the reverse reference
books = db.relationship('Books',backref='author')
# Books (id, name , Price , author id, Publication date )
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) # Not empty , Indexing speeds up access , The name is unique
# Multiple foreign keys : Books .author. Author's name
author_id = db.Column(db.Integer,db.ForeignKey('author.id'))# or Author.id
Add books
# Back end
@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'))
# front end
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title> Add books </title>
</head>
<body>
<h1> Add books </h1>
<form action="/book/add_book" method="post" >
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
name :<input type="text" name="name"/> <br/>
author id:<input type="text" name="author_id"/> <br/>
<input type="submit" value=" increase "/>
</form>
</body>
</html>
Delete books
# Back end
@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'))
Revise the book
# Back end
@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'))
# front end
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title> Revise the book </title>
</head>
<body>
<h1> Revise a book </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/>
name :<input type="text" name="name" value="{{books.name}}"/><br/>
author :<input type="text" name="author_id" value="{{books.author.name}}"/><br/>
<input type="submit" value=" modify "/>
</form>
</body>
</html>
# Back end
from .models import Books,Users
@book.route('/list',methods=["POST","GET"]) # Route definition !
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(' Fuzzy query ')
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)
# front end
<ul class="pg">
{% if paginate.has_prev%}
<li><a href="/book/list?page={{paginate.prev_num}}"> The previous page </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}}"> The next page </a></li>
{%endif %}
</ul>