|
環境 python 3.9
安裝模組
- pip install flask
- conda install sqlalchemy
- pip install flask_sqlalchemy
- pip install psycopg2
複製代碼
安裝postgresql,到 https://www.postgresql.org/download/ 下載
設定帳號 admin 密碼 123456
程式碼
- from flask import Flask
- from flask_sqlalchemy import SQLAlchemy
- db = SQLAlchemy()
- # creates a Flask application
- app = Flask(__name__)
- app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://admin:123456@127.0.0.1:5432/testdb'
- db = SQLAlchemy(app)
- class students(db.Model):
- __tablename__ = 'students'
- sid = db.Column(db.Integer, primary_key = True)
- name = db.Column(db.String(50), nullable = False)
- tel = db.Column(db.String(50))
- addr = db.Column(db.String(200))
- email = db.Column(db.String(200))
- def __init__(self,name,tel,addr ,email):
- self.name =name
- sel,rel=tel
- self.addr = addr
- self.email = email
- @app.route("/")
- def index():
- db.create_all()
- return "connect success!!"
- # Press the green button in the gutter to run the script.
- if __name__ == '__main__':
- app.run()
複製代碼
最後到 pgAdmin 4 檢查是否成功
flask postgresql 資料庫
文章出處: NetYea 網頁設計
|
|