1. 程式人生 > >Python中Flask的基礎入門(三)

Python中Flask的基礎入門(三)

如果我們想要在flask中用到資料庫,那麼我們需要配置。

下面我們有mysql為例來配置

首先你的電腦上要有一個mysql資料庫,然後才可以。

下面是我們配置的程式碼

from flask import Flask,render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://root:[email protected]/base'#配置資料庫的地址
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False#跟蹤資料庫的修改
db = SQLAlchemy(app)

@app.route('/',methods=['GET','POST'])
def login_html():
    return render_template('login.html')
if __name__ == '__main__':
    app.run(debug=True)

現在我們就已經和資料庫連線上了。

app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://root:[email protected]/base'

如果你用的是python3,那麼我們要使用pymysql來進行連線

還有要明確一點,你想要連線資料庫,首先你要有資料庫,這裡的資料庫是指你已經建立好的資料庫,沃恩要做的事在你已經建立好的資料庫中建立表。

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# app.config['SQLALCHEMY_DATABASE_URI']='mysql://root:
[email protected]
/3306'#配置資料庫的地址 app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://root:[email protected]/base' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False#跟蹤資料庫的修改 db = SQLAlchemy(app) #資料庫模型。需要繼承db.Model class Role(db.Model): #定義表名 _tablename_='role' #定義欄位 id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(64),unique=True,nullable=True) # users = db.relationship('users', backref='role') # def __repr__(self): # return '<Role %s>' % self.name class User(db.Model): # 定義表名 _tablename_ = 'users' # 定義欄位 id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) #ForeignKey表示是外來鍵 role_id = db.Column(db.Integer, db.ForeignKey('role.id')) # # def __repr__(self): # return '<User %s>' % self.name @app.route('/') def index(): return 'helloworld' if __name__ == '__main__': #刪除表 db.drop_all() #建立表 db.create_all() #資料新增 role = Role(name='admin') db.session.add(role) db.session.commit() user = User(name='ssl',role_id=role.id) db.session.add(user) db.session.commit() #修改資料 user.name = 'hxf' # #刪除資料 # db.session.delete(user) # db.session.commit() app.run(debug=True)

上面就是我們往資料庫中新增資料,更改資料,刪除資料。