|
環境 python 3.9
安裝模組
- pip install flask
- pip install pymysql
- pip install mariadb
- pip install json
複製代碼
建立資料庫flask_tw
建立資料表
Id, FristName, LastName, Addr, City
程式碼
- import pymysql
- from flask import Flask
- pymysql.install_as_MySQLdb() # Install MySQL driver
- import json
- import mariadb
- config = {
- 'host': '127.0.0.1',
- 'port': 3306,
- 'user': 'flask_tw',
- 'password': 'password',
- 'database': 'flask_tw'
- }
- app = Flask(__name__)
- @app.route("/")
- def index():
- return "connect success!!"
- @app.route('/api/people', methods=['GET'])
- def dbtest():
- # connection for MariaDB
- conn = mariadb.connect(**config)
- # create a connection cursor
- cur = conn.cursor()
- # execute a SQL statement
- cur.execute("select * from people")
- # serialize results into JSON
- row_headers=[x[0] for x in cur.description]
- rv = cur.fetchall()
- json_data=[]
- for result in rv:
- json_data.append(dict(zip(row_headers,result)))
- # return the results!
- return json.dumps(json_data)
- if __name__ == '__main__':
- app.run()
複製代碼
新增資料 加入
- @app.route("/insert")
- def insert():
- insertStatement = "INSERT INTO people (id, LastName, FirstName,Address,City) VALUES (5,'woff2','lin2','hsinchu2','city2')";
- conn = mariadb.connect(**config)
- # create a connection cursor
- cur = conn.cursor()
- cur.execute(insertStatement)
- return ("Successfully added entry to database")
複製代碼
測試網址
http://flask.netyea.com/test/api/people
flask mysql 資料庫
文章出處: NetYea 網頁設計
https://hackernoon.com/getting-s ... -and-flask-pa1i3ya3
|
|