在本教程中,我们将了解 CRUD,然后创建我们的 Flask CRUD 应用程序。所以让我们开始吧!
什么是 CRUD 应用程序?
处理创建/检索/更新或删除操作的 Web 应用程序称为 CRUD 应用程序。CRUD 应用程序的典型示例是博客网站。
- 我们可以创建一个新的博客:创建
- 查看已发布的博客:检索
- 更新博客:更新
- 删除博客: 删除
CRUD的定义总结如下:
手术 | 功能 |
---|---|
创造 | 创建新数据并将其添加到数据库中 |
取回 | 从数据库中检索数据 |
更新 | 将现有数据更新到数据库中 |
删除 | 删除现有数据到数据库中 |
CRUD
创建 Flask CRUD 应用程序
我们将创建一个简单的 Flask CRUD 应用程序,它可以创建/检索/更新/删除员工信息。项目目录结构如下:
因此,在此应用程序中,您可以:
- 新建员工信息
- 查看员工名单。
- 查看特定员工的信息。
- 更新员工信息
- 删除员工信息
1. 编写 Models.py
在这里,我们将使用 Flask_SQLAlchemy 和 SQLite DB。
首先安装 Flask_SQLAlchemy
pip install flask_sqlalchemy
|
现在创建一个models.py文件并添加以下代码:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class EmployeeModel(db.Model):
__tablename__ = "table"
id = db.Column(db.Integer, primary_key = True )
employee_id = db.Column(db.Integer(),unique = True )
name = db.Column(db.String())
age = db.Column(db.Integer())
position = db.Column(db.String( 80 ))
def __init__( self , employee_id,name,age,position):
self .employee_id = employee_id
self .name = name
self .age = age
self .position = position
def __repr__( self ):
return f "{self.name}:{self.employee_id}"
|
在这里,我们只是创建了EmployeeModel。如果您在理解语法方面有任何困难,请查看SQLAlchemy教程
2.编写主应用程序
现在,让我们编写我们的主要Flask 应用程序文件。我们将首先导入 Flask,初始化 Flask 应用程序,并设置应用程序运行时详细信息。
from flask import Flask
app = Flask(__name__)
app.run(host = 'localhost' , port = 5000 )
|
现在我们需要将 SQLite DB 与 SQLAlchemy 连接起来。所以添加以下代码片段:
from flask import Flask
app = Flask(__name__)
app.config[ 'SQLALCHEMY_DATABASE_URI' ] = 'sqlite:///<db_name>.db'
app.config[ 'SQLALCHEMY_TRACK_MODIFICATIONS' ] = False
app.run(host = 'localhost' , port = 5000 )
|
将<db_name>替换为您想要的 DB 文件名称。
此外,我们需要在用户访问服务器之前链接数据库实例(来自models.py)并创建数据库文件。所以为此:
from flask import Flask
app = Flask(__name__)
app.config[ 'SQLALCHEMY_DATABASE_URI' ] = 'sqlite:///<db_name>.db'
app.config[ 'SQLALCHEMY_TRACK_MODIFICATIONS' ] = False
db.init_app(app)
@app .before_first_request
def create_table():
db.create_all()
app.run(host = 'localhost' , port = 5000 )
|
好的,现在 DB 和模型已经就位,让我们编写我们的 CRUD 视图。
3. 编写创建视图
Create 视图应该能够执行以下操作:
- 当客户端进入这个页面时(GET 方法),它应该显示一个表单来获取客户端的数据。
- 在提交(POST 方法)时,它应该将客户的数据保存在 EmployeeModel 数据库中。
所以创建视图将是:
@app .route( '/data/create' , methods = [ 'GET' , 'POST' ])
def create():
if request.method = = 'GET' :
return render_template( 'createpage.html' )
if request.method = = 'POST' :
employee_id = request.form[ 'employee_id' ]
name = request.form[ 'name' ]
age = request.form[ 'age' ]
position = request.form[ 'position' ]
employee = EmployeeModel(employee_id = employee_id, name = name, age = age, position = position)
db.session.add(employee)
db.session.commit()
return redirect( '/data' )
|
该createpage.html将包含HTML表格:
< form action = '' method = "POST" >
< p >employee ID < input type = "integer" name = "employee_id" /></ p >
< p >name < input type = "text" name = "name" /></ p >
< p >age < input type = "integer" name = "age" /></ p >
< p >position < input type = "text" name = "position" /></ p >
< p >< input type = "submit" value = "Submit" /></ p >
</ form >
|
4. 编码检索视图
在这里,我们将有 2 个视图:
- 显示员工列表。
- 显示单个员工的信息。
所以第一个RetrieveDataList视图将是:
@app .route( '/data' )
def RetrieveDataList():
employees = EmployeeModel.query. all ()
return render_template( 'datalist.html' ,employees = employees)
|
该datalist.html文件将显示员工列表:
{ % for employee in employees % }
<h3>{{employee}}< / h3><hr>
{ % endfor % }
|
请查看我们的Flask 模板以了解有关模板语言的更多信息。
第二个RetrieveSingleEmployee视图将是:
@app .route( '/data/<int:id>' )
def RetrieveSingleEmployee( id ):
employee = EmployeeModel.query.filter_by(employee_id = id ).first()
if employee:
return render_template( 'data.html' , employee = employee)
return f "Employee with id ={id} Doenst exist"
|
EmployeeModel.query.filter_by(employee_id = id).first()将返回数据库中第一个 Employee ID = id的 Employee或者如果具有该 id 的 Employee 不存在则返回None。
该data.html显示该员工的信息:
< h3 >Id</ h3 >
< p >{{employee.employee_id}}</ p >< hr >
< h3 >Name</ h3 >
< p >{{employee.name}}</ p >< hr >
< h3 >Age</ h3 >
< p >{{employee.age}}</ p >< hr >
< h3 >Position</ h3 >
< p >{{employee.position}}</ p >< hr >
|
5. 编写更新视图
更新视图将使用用户提交的新员工详细信息更新数据库中的员工详细信息。
因此更新视图将是:
@app .route( '/data/<int:id>/update' ,methods = [ 'GET' , 'POST' ])
def update( id ):
employee = EmployeeModel.query.filter_by(employee_id = id ).first()
if request.method = = 'POST' :
if employee:
db.session.delete(employee)
db.session.commit()
name = request.form[ 'name' ]
age = request.form[ 'age' ]
position = request.form[ 'position' ]
employee = EmployeeModel(employee_id = id , name = name, age = age, position = position)
db.session.add(employee)
db.session.commit()
return redirect(f '/data/{id}' )
return f "Employee with id = {id} Does nit exist"
return render_template( 'update.html' , employee = employee)
|
用户将通过表单提交新的详细信息。这里我们首先删除数据库中存在的旧信息,然后添加新信息
该update.html显示表格提交的新的细节:
< form action = '' method = "POST" >
< p >name < input type = "text" name = "name" value = "{{employee.name}}" /></ p >
< p >age < input type = "integer" name = "age" value = "{{employee.age}}" /></ p >
< p >position < input type = "text" name = "position" value = "{{employee.position}}" /></ p >
< p >< input type = "submit" value = "Submit" /></ p >
</ form >
|
6. 编码删除视图
删除视图只会从数据库文件中删除员工信息。
删除视图将是:
@app .route( '/data/<int:id>/delete' , methods = [ 'GET' , 'POST' ])
def delete( id ):
employee = EmployeeModel.query.filter_by(employee_id = id ).first()
if request.method = = 'POST' :
if employee:
db.session.delete(employee)
db.session.commit()
return redirect( '/data' )
abort( 404 )
return render_template( 'delete.html' )
|
该delete.html只是重新确认删除:
< form action = '' method = "post" >
Click YES to confirm
< input type = "submit" value = "YES" >
< a href = '/data' >Cancel</ a >
</ form >
|
如果用户按是,则员工将被删除。否则他会被带回去。
CRUD 应用程序的完整代码
模型.py:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class EmployeeModel(db.Model):
__tablename__ = "table"
id = db.Column(db.Integer, primary_key = True )
employee_id = db.Column(db.Integer(),unique = True )
name = db.Column(db.String())
age = db.Column(db.Integer())
position = db.Column(db.String( 80 ))
def __init__( self , employee_id,name,age,position):
self .employee_id = employee_id
self .name = name
self .age = age
self .position = position
def __repr__( self ):
return f "{self.name}:{self.employee_id}"
|
的主要应用烧瓶:
from flask import Flask,render_template,request,redirect
from models import db,EmployeeModel
app = Flask(__name__)
app.config[ 'SQLALCHEMY_DATABASE_URI' ] = 'sqlite:///data.db'
app.config[ 'SQLALCHEMY_TRACK_MODIFICATIONS' ] = False
db.init_app(app)
@app .before_first_request
def create_table():
db.create_all()
@app .route( '/data/create' , methods = [ 'GET' , 'POST' ])
def create():
if request.method = = 'GET' :
return render_template( 'createpage.html' )
if request.method = = 'POST' :
employee_id = request.form[ 'employee_id' ]
name = request.form[ 'name' ]
age = request.form[ 'age' ]
position = request.form[ 'position' ]
employee = EmployeeModel(employee_id = employee_id, name = name, age = age, position = position)
db.session.add(employee)
db.session.commit()
return redirect( '/data' )
@app .route( '/data' )
def RetrieveList():
employees = EmployeeModel.query. all ()
return render_template( 'datalist.html' ,employees = employees)
@app .route( '/data/<int:id>' )
def RetrieveEmployee( id ):
employee = EmployeeModel.query.filter_by(employee_id = id ).first()
if employee:
return render_template( 'data.html' , employee = employee)
return f "Employee with id ={id} Doenst exist"
@app .route( '/data/<int:id>/update' ,methods = [ 'GET' , 'POST' ])
def update( id ):
employee = EmployeeModel.query.filter_by(employee_id = id ).first()
if request.method = = 'POST' :
if employee:
db.session.delete(employee)
db.session.commit()
name = request.form[ 'name' ]
age = request.form[ 'age' ]
position = request.form[ 'position' ]
employee = EmployeeModel(employee_id = id , name = name, age = age, position = position)
db.session.add(employee)
db.session.commit()
return redirect(f '/data/{id}' )
return f "Employee with id = {id} Does nit exist"
return render_template( 'update.html' , employee = employee)
@app .route( '/data/<int:id>/delete' , methods = [ 'GET' , 'POST' ])
def delete( id ):
employee = EmployeeModel.query.filter_by(employee_id = id ).first()
if request.method = = 'POST' :
if employee:
db.session.delete(employee)
db.session.commit()
return redirect( '/data' )
abort( 404 )
return render_template( 'delete.html' )
app.run(host = 'localhost' , port = 5000 )
|
实施该瓶CRUD应用
运行服务器并转到“ /data/create ”
创造
现在输入详细信息并按Submit。同样,我又添加了一些。转到“ /数据”
数据列表
让我们检查第一个。转到“ /data/1 ”
数据
现在让我们去“ /data/1/update ”并更新一些细节
更新
详细信息现已更新。现在让我们删除这个员工。转到“ /data/1/delete ”
删除
点击是,瞧!员工被删除
结论
就是这样,伙计们!!这完全是关于 Flask 中的 CRUD 操作。请查看我们的Flask REST API 教程,它是 Flask REST Framework 中的 CRUD 应用程序。
下篇文章见!!