Python——Flask框架——數據庫


一、數據庫框架 Flask-SQLAlchemy

  (1)安裝: pip install flask-sqlalchemy

  (2)Flask-SQLAlchemy數據庫URL

數據庫引擎 URL
MySQL mysql://username:password@hostname/database
Postgres postgresql://username:password@hostname/database
SQLite(Unix) sqlite:////abslute/path/to/database
SQLite(Windows) sqlite:///c:/absolute/path/tp/database

二、配置數據庫

from flask.ext.sqlalchemy import SQLAlchemy
basedir = os.path.abspath(os.path.dirname(__file__)
app = Flask(__name__)
app.config['SQLACHEMY_DATABASE_URI'] = \'sqlite:///' + os.path.join(basedir,'data.sqlite')
app.config['SQLACHEMY_COMMIT_ON_TEARDOWN'] = True
db = SQLAlchemy(app)

三、定義模型

**roles表和user表定義模型Role和User

class Role(db.Model):
    #數據庫中使用的表名
    __tablenaame__ = 'roles'
    id = db.Column(db.Integer, primary_key =True)
    name = db.column(db.String(64),unique = True)
    def __repr__(self):
        return <Role %r>' % self.name
        
class User(db.Model):
    __tablenaame__ = 'users'
    id = db.Column(db.Integer, primary_key =True)
    username = db.column(db.String(64),unique = True,index = True)
    def __repr__(self):
        return <User %r>' % self.username

  (2)最常使用的SQLAlchemy列選項

選項名 說明
primary_key 主鍵,經常是ID
unique 不允許出現重復的值
index 創建索引,提升查詢效率
nullable 允許空值
default 定義默認值

四、關系

  (1)一對多關系

class Role(db.Model):
    #數據庫中使用的表名
    '''
    __tablenaame__ = 'roles'
    id = db.Column(db.Integer, primary_key =True)
    name = db.column(db.String(64),unique = True)
    '''
    users = db.relationship('User',backref = 'role')
    '''
    def __repr__(self):
        return <Role %r>' % self.name
    '''
class User(db.Model):
    '''
    __tablenaame__ = 'users'
    id = db.Column(db.Integer, primary_key =True)
    username = db.column(db.String(64),unique = True,index = True)
    '''
    role_id = db.Column(db.Integer,db.ForeignKey('role.id'))
    '''
    def __repr__(self):
        return <User %r>' % self.username
    '''

  (2)常用的關系項

選項 說明
backref 在關系的另一個模型中添加反向引用
primaryjoin 明確兩個模型中間的連接條件
lazy 指定加載相關記錄
uselist 設置Fales,不使用列表
order_by 指定關系中記錄的排序方式
secondary 指定多對多關系表的名字
secondaryjoin 無法自行決定時,指定多堆垛關系的耳機連接條件

**lazy可選值select(首次訪問時需要加載),immediate(源對象加載后就加載),joined(加載記錄,單使用連接),subquery(立即加載,單使用子查詢),noload(永不加載)和dynamic(不加載記錄,單提供加載記錄查詢)

**db.relationship(),把uselist設置為False,把“多”變成“一”

五、數據庫操作

   (1)創建表

from hello import db
db.create_all()

**創建一個名字為data.sqlite

  (2)插入行

db.session.all_all([admin_role,mod_role,user_role,user_john,user_susan,user_david])
#提交數據
db.session.commit()

**數據回滾 db.session.rollback()

  (3)修改行

#把"Admin" 角色重命名為"Administrator"
admin_role.name = 'Administrator'
db.session.add(admin_role)
db.session.commit()

  (4)刪除行

db.session.delete(mod_role)
db.session.commit()

  (5)查詢行

 

  5.2常用的查詢過濾器

過濾器 說明
filter 把過濾器添加到原查詢上,返回一個新查詢
filter_by 把等值過濾器添加到原查詢上,返回一個新查詢
limit 使用指定的值限制原查詢返回的結果數量,返回一個查詢
offset 偏移原查詢返回的結果,返回一個新查詢
order_by 根據指定條件對原查詢結果進行排序,返回一個新查詢
group_by 根據指定條件對原查詢結果進行分組,返回一個新查詢

  5.3常用查詢執行函數

方法 說明
all 以列表形式返回查詢的所有結果
first 返回查詢的第一個結果,沒有結果返回None
first_or_404 返回查詢的第一個結果,沒有結果,返回404錯誤
get 返回指定主鍵對應的行,沒有結果返回None
get_or_404 返回指定主鍵對應的行,沒有結果,返回404錯誤
count 返回查詢的結果的數量
paginate 返回Paginate對象,它包含指定范圍內容的結果

六、在視圖函數中操作數據庫

 

七、集成Python shell 

  為shell命令添加一個上下文

def make_shell_context():
    return dict(app=app,db=db,User=User,Role=Role)
manager.add_command("shell",Shell(make_context=make_shell_context)

**make_shell_context函數注冊了程序,數據庫實例以及模型,因此這些對象能直接導入shell

八、數據庫遷移(Flask-Migrate)

  (1)安裝 :  pip install flask-migrate

  (2)配置Flask-Migrate

form flask.ext.migrate import Migrate,MigrateCommand
#...
migrate = Migrate(app,db)
manager.add_command('db',MigrateCommand)

  (2)遷移腳本

    upgrade()函數把遷移中的改動應用到數據庫中

    downgrade()函數責將改動刪除

    自動遷移腳本: python hello.py db migrate -m "initial migration"

九、更新數據庫

  python hello.py db upgrade


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM