📅  最后修改于: 2021-01-02 04:36:14             🧑  作者: Mango
Flask SQLAlchemy是一个ORM工具,用于建立对象与关系数据库表之间的关系。
两者之间的映射很重要,因为Python能够以对象的形式存储数据,而数据库则以关系表(即行和列的集合)的形式存储数据。
对象关系映射是一种将Python对象存储到数据库表中而无需编写原始SQL查询的技术。
在本教程的这一部分中,我们将使用flask-sqlalchemy ORM技术创建一个小型Web应用程序。
要使用flask ORM技术创建Web应用程序,我们必须使用pip安装程序安装flask-sqlalchemy。
$ pip install flask-sqlalchemy
要确认安装,请尝试在Python shell上导入模块。如果成功导入,则安装成功。
$ import flask_sqlalchemy
在本教程的这一部分中,我们将使用ORM SQLAlchemy在Python创建一个CRUD应用程序。
add.html
Add new Employee
{%- for category, message in get_flashed_messages(with_categories = true) %}
{{ message }}
{%- endfor %}
list_employees.html
Home
Employee Management System
{%- for message in get_flashed_messages() %}
{{ message }}
{%- endfor %}
Employees List
Name
Salary
Age
Pin
{% for employee in Employees %}
{{ employee.name }}
{{ employee.salary }}
{{ employee.age }}
{{ employee.pin }}
{% endfor %}
Add New Employee
app.py
from flask import Flask, request, flash, url_for, redirect, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///employees.sqlite3'
app.config['SECRET_KEY'] = "secret key"
db = SQLAlchemy(app)
class Employees(db.Model):
id = db.Column('employee_id', db.Integer, primary_key = True)
name = db.Column(db.String(100))
salary = db.Column(db.Float(50))
age = db.Column(db.String(200))
pin = db.Column(db.String(10))
def __init__(self, name, salary, age,pin):
self.name = name
self.salary = salary
self.age = age
self.pin = pin
@app.route('/')
def list_employees():
return render_template('list_employees.html', Employees = Employees.query.all() )
@app.route('/add', methods = ['GET', 'POST'])
def addEmployee():
if request.method == 'POST':
if not request.form['name'] or not request.form['salary'] or not request.form['age']:
flash('Please enter all the fields', 'error')
else:
employee = Employees(request.form['name'], request.form['salary'],
request.form['age'], request.form['pin'])
db.session.add(employee)
db.session.commit()
flash('Record was successfully added')
return redirect(url_for('list_employees'))
return render_template('add.html')
if __name__ == '__main__':
db.create_all()
app.run(debug = True)
输出:
单击链接“添加新员工”以将新员工添加到数据库。
单击提交,我们将在主页列表中看到新添加的员工。