找回密碼
 註冊
搜索
查看: 267|回復: 0

[教學] 如何在 flask 使用 postgresql 資料庫

[複製鏈接]
發表於 2025-2-16 17:30:26 | 顯示全部樓層 |閱讀模式
Push to Facebook
環境 python 3.9


安裝模組
  1. pip install flask
  2. conda install sqlalchemy
  3. pip install flask_sqlalchemy
  4. pip install psycopg2
複製代碼


安裝postgresql,到 https://www.postgresql.org/download/ 下載
設定帳號 admin 密碼 123456

程式碼
  1. from flask import Flask
  2. from flask_sqlalchemy import SQLAlchemy
  3. db = SQLAlchemy()
  4. # creates a Flask application
  5. app = Flask(__name__)

  6. app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://admin:123456@127.0.0.1:5432/testdb'
  7. db = SQLAlchemy(app)

  8. class students(db.Model):
  9.     __tablename__ = 'students'
  10.     sid = db.Column(db.Integer, primary_key = True)
  11.     name = db.Column(db.String(50), nullable = False)
  12.     tel = db.Column(db.String(50))
  13.     addr = db.Column(db.String(200))
  14.     email = db.Column(db.String(200))

  15.     def __init__(self,name,tel,addr ,email):
  16.         self.name =name
  17.         sel,rel=tel
  18.         self.addr = addr
  19.         self.email = email

  20. @app.route("/")
  21. def index():
  22.     db.create_all()
  23.     return "connect success!!"

  24. # Press the green button in the gutter to run the script.
  25. if __name__ == '__main__':
  26.     app.run()
複製代碼


最後到 pgAdmin 4 檢查是否成功

flask postgresql 資料庫

flask   postgresql 資料庫


文章出處: NetYea 網頁設計

您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則

Archiver|手機版|小黑屋|TShopping

GMT+8, 2025-4-30 15:16 , Processed in 0.025129 second(s), 24 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回復 返回頂部 返回列表