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

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

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

安裝模組
  1. pip install flask
  2. pip install pymysql
  3. pip install mariadb
  4. pip install json
複製代碼

建立資料庫flask_tw
建立資料表
Id, FristName, LastName, Addr, City


程式碼
  1. import pymysql
  2. from flask import Flask
  3. pymysql.install_as_MySQLdb()  # Install MySQL driver
  4. import json
  5. import mariadb
  6. config = {
  7.     'host': '127.0.0.1',
  8.     'port': 3306,
  9.     'user': 'flask_tw',
  10.     'password': 'password',
  11.     'database': 'flask_tw'
  12. }

  13. app = Flask(__name__)

  14. @app.route("/")
  15. def index():
  16.     return "connect success!!"

  17. @app.route('/api/people', methods=['GET'])
  18. def dbtest():
  19.    # connection for MariaDB
  20.    conn = mariadb.connect(**config)
  21.    # create a connection cursor
  22.    cur = conn.cursor()
  23.    # execute a SQL statement
  24.    cur.execute("select * from people")

  25.    # serialize results into JSON
  26.    row_headers=[x[0] for x in cur.description]
  27.    rv = cur.fetchall()
  28.    json_data=[]
  29.    for result in rv:
  30.         json_data.append(dict(zip(row_headers,result)))

  31.    # return the results!
  32.    return json.dumps(json_data)

  33. if __name__ == '__main__':
  34.     app.run()
複製代碼

新增資料 加入
  1. @app.route("/insert")
  2. def insert():
  3.     insertStatement = "INSERT INTO people (id, LastName, FirstName,Address,City) VALUES (5,'woff2','lin2','hsinchu2','city2')";
  4.     conn = mariadb.connect(**config)
  5.     # create a connection cursor
  6.     cur = conn.cursor()
  7.     cur.execute(insertStatement)
  8.     return ("Successfully added entry to database")
複製代碼





測試網址
http://flask.netyea.com/test/api/people

flask mysql 資料庫

flask mysql 資料庫


文章出處: NetYea 網頁設計

https://hackernoon.com/getting-s ... -and-flask-pa1i3ya3
 
您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則

Archiver|手機版|小黑屋|TShopping

GMT+8, 2025-3-15 17:38 , Processed in 0.025272 second(s), 23 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

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