Flask-数据库-SQLAlchemy

SQLAlchemy是flask的扩展,是一个功能强大的OR映射器,支持多种数据库后台,可以将类的对象映射至数据库表。

使用这个工具,可以创建数据库,创建表,并为数据库添加数据,进行查询操作等。

参考:Flask SQLAlchemy - Flask 教程 | BootWiki.com

创建实例 

 app=Flask(__name__)  #创建Flask实例

 app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'#设置数据库URL

app.config[]可以为Flask实例添加一些配置。

这个配置指明当前文件夹下students.sqlite3数据库文件作为数据库访问的URL,这个数据库文件当前可以不存在,在程序运行时create。

在Flask-SQLAlchemy中,数据库使用URL指定。几种最流行的数据库引擎使用的URL格式

 

app.config['SECRET_KEY'] = "random string"

 这个配置设置了secret_key,用于session,在学习session的时候已经知道,服务器加密会话数据时需要一个secret_key,至于这里为什么要用到session,在后面会说到。

db=SQLAlchemy(app) 创建一个SQLAlchemy类的对象。 该对象包含ORM操作的辅助函数。 它还提供了一个使用其声明用户定义模型的父级模型类。

类和模型 

模型这个术语表示应用使用的持久化实体。在ORM中,模型一般是一个Python类,类中的属性对应于数据库表中的列。

定义一个类(students模型),继承Model模型。这个类和数据库的表对应,类的属性分别对应表的字段。

class students(db.Model):
    id = db.Column('student_id', db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    city = db.Column(db.String(50))
    addr = db.Column(db.String(200))
    pin = db.Column(db.String(10))
    def __init__(self,name,city,addr,pin):


        self.name=name
        self.city=city
        self.addr=addr
        self.pin=pin

db.Column类构造函数的第一个参数是数据库列和模型属性的类型 

常用的类型

 

db.Column的其余参数指定属性的配置选项

常用的SQLAlchemy配置选项 

通过属性定义,也为表添加了字段。id为主键。

db.create_all()

使用这个语句,执行创建数据库操作。

CRUD操作 

 SQLAlchemy的Session对象管理ORM对象的所有持久性操作。

db.session.add(模型对象) - 将一条记录插入到映射表中   准备把对象写入数据库之前,要先将其添加到会话中
db.session.delete(模型对象) - 从表中删除记录
模型.query.all() - 从表中检索所有记录(对应于SELECT查询)。

db.session.commit()提交修改  为了把对象写入数据库,我们要调用commit()方法提交会话

可以使用filter属性将筛选器应用于检索到的记录集。例如,要在students表中检索city ='Haikou'的记录,请使用以下语句 

Students.query.filter_by(city = 'Haikou').all()

 

 

数据库会话db.session和Flask的session对象没有关系。数据库会话也称为事务, 能保证数据库的一致性。提交操作使用原子方式把会话中的对象全部写入数据库。如果在写入会话的过程中发生了错误,那么整个会话都会失效。如果你始终把相关改动放在会话中提交,就能避免因部分更新导致的数据库不一致。

实战

实现一个添加学生信息并展示信息的小应用。

点击添加学生,打开添加学生页面,提交信息后,展示所有学生信息列表。

http://localhost:5000/

http://localhost:5000/new

 

http://localhost:5000/ 

这个应用,一共有两个页面,一个展示所有信息show_all.html,一个添加学生信息new.html。

在展示所有信息页面,首先显示闪现消息flash,当没有闪现消息的时候不显示。添加学生链接至new页面,最下方读取数据库数据并显示,数据库无数据时不显示数据。

show_all.html如下

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask示例</title>
</head>
   <body>

      <h1>
         Flask
            SQLAlchemy示例
      </h1>

      <hr/>
      {%- for message in get_flashed_messages() %}
         {
   
   { message }}
      {%- endfor %}

      <h1>(<a href = "{
   
   { url_for('new') }}">添加学生
         </a>)</h1>

      <table>
         <thead>
            <tr>
               <th>姓名</th>
               <th>城市</th>
               <th>地址</th>
               <th>Pin</th>
            </tr>
         </thead>

         <tbody>
            {% for student in students %}
               <tr>
                  <td>{
   
   { student.name }}</td>
                  <td>{
   
   { student.city }}</td>
                  <td>{
   
   { student.addr }}</td>
                  <td>{
   
   { student.pin }}</td>
               </tr>
            {% endfor %}
         </tbody>
      </table>

   </body>
</html>


对于的视图函数如下

@app.route('/')
def show_all():
    return render_template('show_all.html',students=students.query.all())

添加学生信息页面new.html,也会显示flash,下放展示一个表单,点击提交按钮后,表单数据以post方式提交给服务器,并使用视图函数new接收表单数据进行处理。对表单数据进行校验,不满足校验显示flash,满足校验,则向数据库添加数据,并重定向至展示信息页面。

new.html页面如下:


<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask示例</title>
</head>

    <h3>添加学生信息</h3>
      <hr/>

      {%- for category, message in get_flashed_messages(with_categories = true) %}
         <div class = "alert alert-danger">
            {
   
   { message }}
         </div>
      {%- endfor %}

      <form action = "/new" method = "post">
         <label for = "name">姓名</label><br>
         <input type = "text" name = "name" placeholder = "Name" /><br>
         <label for = "email">城市</label><br>
         <input type = "text" name = "city" placeholder = "city" /><br>
         <label for = "addr">地址</label><br>
          <textarea name = "addr" placeholder = "addr"></textarea><br>
         <label for = "PIN">邮编</label><br>
         <input type = "text" name = "pin" placeholder = "pin" /><br>
         <input type = "submit" value = "提交" />
      </form>

   </body>
</html>



 对于视图函数如下

@app.route('/new',methods=['GET','POST'])
def new():

    if request.method=='POST':
        if not request.form['name']or not request.form['city']or not request.form['addr']:
            flash('Please enter all the fields','error') #如果有一个没填写,闪现消息
        else:
            student = students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin'])
            print(student)
            db.session.add(student)#把数据添加到数据库
            db.session.commit()#提交数据
            flash('Record was successfully added')#闪现消息添加成功
            return  redirect(url_for('show_all')) #一个函数可以有两个return
    return render_template('new.html') #点击添加按钮,渲染new.html页面

最后附上程序入口,运行程序,即可访问。

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

完整代码:

from flask_sqlalchemy import SQLAlchemy
from flask import Flask,render_template,request,flash,redirect,url_for
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'#设置数据库URL
#创建一个SQLAlchemy类的对象。 该对象包含ORM操作的辅助函数。 它还提供了一个使用其声明用户定义模型的父级模型类。
app.config['SECRET_KEY'] = "random string"




db=SQLAlchemy(app)
class students(db.Model):
    id = db.Column('student_id', db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    city = db.Column(db.String(50))
    addr = db.Column(db.String(200))
    pin = db.Column(db.String(10))
    def __init__(self,name,city,addr,pin):


        self.name=name
        self.city=city
        self.addr=addr
        self.pin=pin



@app.route('/')
def show_all():
    db.create_all()
    return render_template('show_all.html',students=students.query.all())


@app.route('/new',methods=['GET','POST'])
def new():

    if request.method=='POST':
        if not request.form['name']or not request.form['city']or not request.form['addr']:
            flash('Please enter all the fields','error') #如果有一个没填写,闪现消息
        else:
            student = students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin'])
            print(student)
            db.session.add(student)#把数据添加到数据库
            db.session.commit()#提交数据
            flash('Record was successfully added')#闪现消息添加成功
            return  redirect(url_for('show_all')) #一个函数可以有两个return
    return render_template('new.html') #点击添加按钮,渲染new.html页面

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

 总结:文本学习了Flask数据库相关扩展SQLAlchemy的使用,并实现了一个添加并展示学生信息的应用。


 

猜你喜欢

转载自blog.csdn.net/seanyang_/article/details/125824848
今日推荐