Flask學習記錄之Flask-SQLAlchemy

Flask-SQLAlchemy庫讓flask更方便的使用SQLALchemy,是一個強大的關系形數據庫框架,既可以使用orm方式操作數據庫,也可以使用原始的SQL命令.

Flask-Migrate 是一個數據遷移框架,需要通過Flask-script庫來操作.

?

一.配置Flask-SQLAlchemy

程序使用的數據庫地址需要配置在SQLALCHEMY_DATABASE_URI中,SQLALchemy支持多種數據庫,配置格式如下:

  Postgres:

  postgresql://scott:tiger@localhost/mydatabase

  MySQL:

mysql_url ='mysql+mysqlconnector://root:liuwang@127.0.0.1:3306/mydb3'
  mysql://scott:tiger@localhost/mydatabase

  Oracle:

  oracle://scott:tiger@127.0.0.1:1521/sidname

  SQLite:

  sqlite:absolute/path/to/foo.db

db是SQLALchemy類的實例,表示程序使用的數據庫,為用戶提供Flask-SQLALchemy的所有功能

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemyapp = Flask(__name__)
#配置數據庫地址
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:tmp/test.db'
#該配置為True,則每次請求結束都會自動commit數據庫的變動
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
db = SQLAlchemy(app)
#也可以db = SQLAlchemy()        db.init_app(app)

二.定義模型

Flask-SQLALchemy使用繼承至db.Model的類來定義模型,如:

class User(db.Model, UserMixin):#UserMixin是Flask-Login庫中所需要的__tablename__ = 'users'#每個屬性定義一個字段id = db.Column(db.Integer,primary_key=True)username = db.Column(db.String(64),unique=True)password = db.Column(db.String(64))def __repr__(self):return '<User %r>' % self.username

定義完需要在Python Shell中導入db,調用db.create_all()來創建數據庫

(1)常用字段選項:

  primary_key 設置主鍵

  unique 是否唯一

  index 是否創建索引

  nullable 是否允許為空

  default 設置默認值,可以傳入函數的引用 如傳入 datetime.datetime.utcnow 則每次創建時時間都是最新時間

三.增刪查改

(1) 插入數據:

from app.models import User
from app import db#創建一個新用戶
u = User()
u.username = 'abc'
u.password = 'abc'#將用戶添加到數據庫會話中
db.session.add(u)#將數據庫會話中的變動提交到數據庫中,如果不Commit,數據庫中是沒有改動的
db.commit()

(2)查找數據:

#返回所有用戶保存到list中
user_list = User.query.all()#查找username為abc的第一個用戶,返回用戶實例
u = User.query.filter_by(username='abc').first()#模糊查找用戶名以c結尾的所有用戶
user_list  = User.query.filter(username.endswith('c')).all()#查找用戶名不是abc的用戶
u = User.query.filter(username != 'abc').first()

(3)刪除數據:

user = User.query.first()
db.session.delete(user)
db.session.commit()

(4)修改數據:

u = User.query.first()
u.username = 'sb'
db.session.commit()

四.一對多關系

我的理解是:在多的一邊定義外鍵,而relathonship()函數是用來建立關系的,可以只在一邊定義,也可以兩邊都使用(只在一邊使用時加上了backref選項等同于兩邊都使用)

class Person(db.Model):id = db.Column(db.Integer, primary_key=True)name = db.Column(db.String(50))#backref將在Address表中創建個名為persons的Person引用,之后可以使用address.persons訪問這個地址的所有人addresses = db.relationship('Address', backref='persons',lazy='dynamic')class Address(db.Model):id = db.Column(db.Integer, primary_key=True)email = db.Column(db.String(50))#在多的一邊使用db.ForeignKey聲明外鍵person_id = db.Column(db.Integer, db.ForeignKey('person.id'))

五.多對多關系

多對多關系可以分解為原表和關聯表之間兩個多對一關系,如下代碼建立了學生與所選課程之間的關系:

#創建關聯表,兩個字段的外鍵是另兩個表,一個學生對應多個關聯表,一個關聯表對應多個課程
registrations = db.Table('registrations',db.Column('student_id',db.Integer,db.ForeignKey('students.id')),db.Column('class_id',db.Integer,db.ForeignKey('classes.id')))class Student(db.Model):__tablename__ = 'students'id = db.Column(db.Integer,primary_key=True,)name = db.Column(db.String)classes = db.relationship('Class',secondary = registrations, #關聯表,只需要在一個表建立關系,sqlalchemy會負責處理好另一個表backref = db.backref('students',lazy='dynamic'),lazy = 'dynamic')class Class(db.Model):__tablename__ = 'classes'id = db.Column(db.Integer, primary_key=True)name = db.Column(db.String)

多對多的使用:

#學生1增加一門選課
student1.classes.append(class1)
#學生1退選class1
student1.classes.remove(class1)
#學生1所選課程,由于指定了lazy='dynamic'所以沒有直接返回列表,而需要使用.all()
student1.classes.all()

?

六.分頁導航

Flask-SQLALchemy的Pagination對象可以方便的進行分頁,

對一個查詢對象調用pagenate(page, per_page=20, error_out=True)函數可以得到pagination對象,第一個參數表示當前頁,第二個參數代表每頁顯示的數量,error_out=True的情況下如果指定頁沒有內容將出現404錯誤,否則返回空的列表

#從get方法中取得頁碼
page = request.args.get('page', 1, type = int)
#獲取pagination對象pagination = Post.query.order_by(Post.timestamp.desc()).paginate(page, per_page=10, error_out = False)#pagination對象的items方法返回當前頁的內容列表posts = pagination.items

pagination對象常用方法:

has_next :是否還有下一頁

has_prev :是否還有上一頁

items : 返回當前頁的所有內容

next(error_out=False) : 返回下一頁的Pagination對象

prev(error_out=False) :?返回上一頁的Pagination對象

page : 當前頁的頁碼(從1開始)

pages : 總頁數

per_page : 每頁顯示的數量

prev_num : 上一頁頁碼數

next_num :下一頁頁碼數

query :返回 創建這個Pagination對象的查詢對象

total :查詢返回的記錄總數

iter_pages(left_edge=2, left_current=2, right_current=5, right_edge=2)

在模版中使用

{% macro render_pagination(pagination, endpoint) %}<div class=pagination>{%- for page in pagination.iter_pages() %}{% if page %}{% if page != pagination.page %}<a href="{{ url_for(endpoint, page=page) }}">{{ page }}</a>{% else %}<strong>{{ page }}</strong>{% endif %}{% else %}<span class=ellipsis>…</span>{% endif %}{%- endfor %}</div>
{% endmacro %}

?七.事件監聽

Flask-SQLALchemy不但提供了方便的數據庫操作,還提供了事件的監聽,如下

from sqlalchemy import eventdef my_append_listener(target, value, initiator):print "received append event for target: %s" % targetevent.listen(MyClass.collection, 'append', my_append_listener)

Listeners have the option to return a possibly modified version of the value, when the?retval=Trueflag is passed to?listen():

def validate_phone(target, value, oldvalue, initiator):"Strip non-numeric characters from a phone number"return re.sub(r'(?![0-9])', '', value)# setup listener on UserContact.phone attribute, instructing
# it to use the return value
listen(UserContact.phone, 'set', validate_phone, retval=True)

A validation function like the above can also raise an exception such as?ValueError?to halt the operation.

Several modifiers are available to the?listen()?function.

Parameters:
  • active_history=False?– When True, indicates that the “set” event would like to receive the “old” value being replaced unconditionally, even if this requires firing off database loads. Note that?active_history?can also be set directly viacolumn_property()?and?relationship().
  • propagate=False?– When True, the listener function will be established not just for the class attribute given, but for attributes of the same name on all current subclasses of that class, as well as all future subclasses of that class, using an additional listener that listens for instrumentation events.
  • raw=False?– When True, the “target” argument to the event will be theInstanceState?management object, rather than the mapped instance itself.
  • retval=False?– when True, the user-defined event listening must return the “value” argument from the function. This gives the listening function the opportunity to change the value that is ultimately used for a “set” or “append” event.

append(target,?value,?initiator)

Receive a collection append event.

Parameters:
  • target?– the object instance receiving the event. If the listener is registered with?raw=True, this will be the?InstanceState?object.
  • value?– the value being appended. If this listener is registered withretval=True, the listener function must return this value, or a new value which replaces it.
  • initiator?– the attribute implementation object which initiated this event.
Returns:

if the event was registered with?retval=True, the given value, or a new effective value, should be returned.

remove(target,?value,?initiator)

Receive a collection remove event.

Parameters:
  • target?– the object instance receiving the event. If the listener is registered with?raw=True, this will be the?InstanceState?object.
  • value?– the value being removed.
  • initiator?– the attribute implementation object which initiated this event.
Returns:

No return value is defined for this event.

set(target,?value,?oldvalue,?initiator)

Receive a scalar set event.

Parameters:
  • target?– the object instance receiving the event. If the listener is registered with?raw=True, this will be the?InstanceState?object.
  • value?– the value being set. If this listener is registered with?retval=True, the listener function must return this value, or a new value which replaces it.
  • oldvalue?– the previous value being replaced. This may also be the symbol?NEVER_SET?or?NO_VALUE. If the listener is registered withactive_history=True, the previous value of the attribute will be loaded from the database if the existing value is currently unloaded or expired.
  • initiator?– the attribute implementation object which initiated this event.
Returns:

if the event was registered with?retval=True, the given value, or a new effective value, should be returned.

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/456290.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/456290.shtml
英文地址,請注明出處:http://en.pswp.cn/news/456290.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Postico —— OS X 上的免費 PostgreSQL 客戶端

Postico 是 OS X 下的一個 PostgreSQL 客戶端管理工具。要求 OS X 10.8 或者更新版本。 文章轉載自 開源中國社區 [http://www.oschina.net]

hdu 1760 A New Tetris Game(搜索博弈)

題目鏈接&#xff1a;hdu 1760 A New Tetris Game 題意&#xff1a; 給你一個矩陣&#xff0c;0表示可以放格子&#xff0c;現在給你2*2的格子&#xff0c;lele先放&#xff0c;問是否能贏。 題解&#xff1a; 爆搜。具體看代碼 1 #include<bits/stdc.h>2 #define F(i,a,…

flask-restful接口

同flask一樣&#xff0c;flask-restful同樣支持返回任一迭代器&#xff0c;它將會被轉換成一個包含原始 Flask 響應對象的響應&#xff1a; class ArticleApi(Resource):def get(self):return {"hello":"world"},201&#xff0c;{"course":&quo…

如約而至 Nexus 6 的 Android 7.1.1 已經上線

經過近一個月的等待&#xff0c;Google 已正式為 Nexus 6 推送 Android 7.1.1 更新&#xff0c;本次更新版本號為 N6F26Q&#xff0c;可以點擊這里下載完整系統鏡像或者下載 OTA 升級包。 相比其他 Nexus 和 Pixel 設備&#xff0c;Nexus 6 已經發布了超過兩年之久&#xff0c;…

關于jedis2.4以上版本的連接池配置,及工具類

jedis.propertise 注意以前版本的maxAcitve和maxWait有所改變&#xff0c;JVM根據系統環境變量ServerType中的值 取不同的配置&#xff0c;實現多環境&#xff08;測試環境、生產環境&#xff09;集成。 redis.pool.maxTotalredis.pool.maxActive.${ServerType} redis.pool.max…

關于response格式轉換

調用圖靈機器人api實例&#xff1a; class RobotHandler(WebSocketHandler):def open(self):# print("WebSocket opened",self.request.remote_ip)robot_set.add(self)# 獲取websocket的發過來的信息def on_message(self, message):urlhttp://openapi.tuling123.com/…

微軟老兵 Antoine LeBlond 將正式離職

Antoine LeBlond (安東勒布朗)是微軟眾高管之一,他在微軟工作將近25年之久,然而他將在下周一,也就是他在微軟的第9000天正式離職. 在發給微軟眾同事的郵件中,勒布朗表示他希望"探索微軟之外的世界". 勒布朗在微軟Office部門度過了他在微軟的前20年時光,并與前微軟高管…

轉載——java synchronized詳解

文章來源&#xff1a;http://www.cnblogs.com/GnagWang/archive/2011/02/27/1966606.html轉載于:https://www.cnblogs.com/insist8089/p/6515885.html

Django中的F對象和Q對象

F對象 可以獲取到自己的屬性值實現自己的屬性自己的屬性關聯的復雜條件支持運算 Q對象 Q對象實際上是對條件的一個封裝封裝后支持邏輯運算與或非 &|~ 支持嵌套 例子 from django.db.models import Max, Avg, F, Q from django.http import HttpResponse from django.s…

總鏈接

字符集修改、Linux時間同步、調整文件描述符http://11815879.blog.51cto.com/11805879/1915276正則表達式&#xff1a;http://11815879.blog.51cto.com/11805879/1919777 文件系統inode與blockhttp://11815879.blog.51cto.com/11805879/1917068 文件類型與軟硬鏈接&#xff1a;…

Django模型關系

模型關系 1:1 一對一 &#xff08;一個身份證對應一個駕照&#xff09; 是使用外鍵唯一約束實現的對應最多只能有一個我們通常會在從表中聲明關系 主表&#xff0c;從表 主表數據刪除&#xff0c;從表數據級聯刪除從表數據刪除&#xff0c;主表不受影響誰聲明關系&#xff0c…

Android常用開源項目

Android常用開源項目 Android 2014-05-23 16:39:43 發布您的評價: 4.3 收藏 24收藏Android開源項目第一篇——個性化控件(View)篇包括ListView、ActionBar、Menu、ViewPager、Gallery、GridView、ImageView、ProgressBar、TextView、其他Android開源項目第二篇——工具庫…

Django中數據知識點歸納

Django對象的增刪改查 我們為了對django對象的增刪改查進行總結&#xff0c;先在model.py文件中創建類便于舉例 定義學生&#xff1a; class Students(models.Model):snamemodels.CharField(max_length20)sgendermodels.BooleanField(defaultTrue)sagemodels.IntegerField()…

面 試 細 節 一 點 通

面談的禮節是社會新人及求職者踏人社會工作前最重要且最需學習的課題&#xff0c;因為這關系到是否能順利踏入社會且尋找到一份合適滿意的工作。 一個社會新人除了應注意的面試禮節外&#xff0c;在開始進行面談之前及面談結束之后&#xff0c;還有不少必須注意的禮儀。 面談時…

寬帶與流量的關系

流量&#xff0c;一般指的是每秒鐘流經某設備的數據的多少。也就是Byte/Second( 字節每秒)。 比方說1M&#xff0c;這個概念的單位叫bPS(bit Per Second)比特每秒。而事實上經常用另外一個詞來代替描述&#xff0c;也就是帶寬。 而帶寬和流量的換算關系是&#xff1a; 1 By…

PHP函數處理方法總結

call_user_func_array (PHP 4 > 4.0.4, PHP 5, PHP 7) call_user_func_array — 調用回調函數&#xff0c;并把一個數組參數作為回調函數的參數 說明 mixed call_user_func_array ( callable $callback , array $param_arr ) 把第一個參數作為回調函數&#xff08;callback&…

Django刪除多對多表關系 :

刪除多對多表關系 &#xff1a; # 刪除子表與母表關聯關系,讓小虎不喜歡任何顏色 # 寫法1: child_obj Child.objects.get(name"apollo") colors_obj Colors.objects.all() child_obj.favor child_obj.save() # 寫法2: child_obj Child.objects.get(name"apo…

git push/pull時總需要輸入用戶名密碼的解決方案

在提交項目代碼或者拉代碼的時候&#xff0c;git會讓你輸入用戶名密碼&#xff0c;解決方案&#xff1a;&#xff08;我們公司用的是gitlab&#xff09;執行git config --global credential.helper store命令然后git push origin your-branch會讓你輸入用戶名和密碼&#xff0c…

Django源代碼寫DetailView與ListView

基于類的通用視圖 - 展平索引 通用顯示視圖 以下兩個通用的基于類的視圖旨在顯示數據。在許多項目中&#xff0c;它們通常是最常用的視圖。 一、DetailView django.views.generic.detail.DetailView 在執行此視圖時&#xff0c;self.object將包含視圖正在操作的對象。 此視圖…

開源商務智能軟件Pentaho

1 簡介Pentaho是世界上最流行的開源商務智能軟件,以工作流為核心的&#xff0c;強調面向解決方案而非工具組件的&#xff0c;基于java平臺的商業智能(Business Intelligence,BI)套件BI&#xff0c;之所以說是套件是因為它包括一個web server平臺和幾個工具軟件&#xff1a;報表…