Create First Flask web app
from flask import Flask
app = Flask(__name__)
app.config["DEBUG"] = True
@app.route('/')
def home():
return "<h1>Hello Flask!</h1>"
if __name__ == '__main__':
app.run()
Database Configure
安裝PostgreSQL套件psycopg2-binary
pip install psycopg2-binary
安裝套件flask-sqlalchemy
pip install flask-sqlalchemy
在檔案目錄中創建一檔案,名為config.py並加入連線內容
SQLALCHEMY_DATABASE_URI = "postgresql://[user_name]:[password]@[ip]:[port]/[db_name]"
SQLALCHEMY_TRACK_MODIFICATIONS = False
加入資料庫連線
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["DEBUG"] = True
app.config.from_object('config')
db = SQLAlchemy(app)
@app.route('/')
def home():
return "<h1>Hello Flask!</h1>"
if __name__ == '__main__':
app.run()
運行python app.py,如果沒有錯誤,就表是資料庫連結成功。