Javascript

Flask 查询 MYSQL数据JSON序列化

本文主要是介绍Flask 查询 MYSQL数据JSON序列化,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.具体代码如下

from flask import Flask
from flask import request, Response
app = Flask(__name__)
import os
def getApolloconf(k):
    import requests
    env = os.environ.get("RUNTIME_ENV") or "dev"
    getApolloconfig = requests.get(
        'http://configserver-{env}.chj.cloud/configs/op-bmc-api/default/application'.format(env=env))
    data = getApolloconfig.json()["configurations"]
    return data.get(k)
#######获取配置插入数据库#########
def mysqlConfig(sql):
    import pymysql
    import json
    USERNAME = getApolloconf("USERNAME")
    PASSWORD = getApolloconf("PASSWORD")
    HOST = getApolloconf("HOST")
    DATABASE = getApolloconf("NGINXDATABASE")
    dbconfig = pymysql.connect(HOST, USERNAME, PASSWORD, DATABASE)
    try:
        cursor = dbconfig.cursor()
        try:
            cursor.execute(sql)
            results = cursor.fetchall()
            reultData=[]
            columnList=["run_type","upstreamname","front_listen","domain_name","backend_ip"]
            for row in results:
                reultData.append(dict(zip(columnList, list(row))))
                str1=(json.dumps(reultData,indent=4,ensure_ascii=False))   
            return str1 
        except Exception as e:
            pass
    except Exception as err:
        print(err)

def nginxtbale():
    try:
        sql = "select run_type,upstreamname,front_listen,domain_name,backend_ip from  nginxManager_dj_nginx_conf order by create_time"
        return mysqlConfig(sql)    
    except Exception as e:
        # 如果发生错误则回滚
        print(e)

@app.route('/')
def index():
    import json
    return Response(nginxtbale())
if __name__ == '__main__':
    app.run(
    host="192.168.54.12",
    port=8008,
    debug=True
   )
这篇关于Flask 查询 MYSQL数据JSON序列化的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!