python 新版本flask建立介面方式

深海里的星星i發表於2024-03-10
import pymysql
from pymysql.cursors import DictCursor
from flask import Flask, request
from flask.json.provider import DefaultJSONProvider
from flask_cors import CORS
from datetime import datetime, date

sqlconnect = pymysql.connect(
    user="root",
    password="yyjeiq",
    host="127.0.0.1",
    database="fmg",
    charset="utf8"
)
cursor = sqlconnect.cursor(DictCursor)


class CustomJSONEncoder(DefaultJSONProvider):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return DefaultJSONProvider.default(obj)


app = Flask(__name__)
app.json = CustomJSONEncoder(app)
app.json.ensure_ascii = False
CORS(app)


@app.route('/')
def get_user():
    uid = request.args.get('id_user')
    sql = "select * from tb_user"
    keys = ["id = %s"]
    vals = [uid]

    if len(keys):
        sql += ' where '
        sql += " ".join(keys)

    print(sql)
    cursor.execute(sql, vals)
    result = cursor.fetchone()
    print(result)
    return {
        "data": [result]
    }


if __name__ == '__main__':
    app.run(debug=True)

相關文章