代码:
# Developer:CT # encoding = utf-8 # Project: businessSystem # Creator:Administrator # Create time:2021-07-27 11:18 # IDE:PyCharm # Introduction: """ """ import MySQLdb # 一、封装成无参数传入的接口 from flask import Flask, jsonify, request db = MySQLdb.connect("127.0.0.1", "root", "root", "huwenlong", charset='utf8') # 打开数据库连接 cursor = db.cursor() # 使用cursor()方法获取操作游标 sql = "SELECT * FROM huwenlong.cmdb_userinfo;" # SQL 查询语句 try: cursor.execute(sql) # 执行SQL语句 results = cursor.fetchall() # 获取所有记录列表 login_system = [] c = login_system.append(results) except: print(70014, "system", "Error: unable to fetch data") db.close() user_list_info = results data = user_list_info app = Flask(__name__) # 创建一个服务,赋值给APP @app.route('/get_user', methods=['post']) # 指定接口访问的路径,支持什么请求方式get,post # 讲的是封装成一种静态的接口,无任何参数传入 def get_user(): # -----这里的函数名称可以任意取 return jsonify(data) # 把字典转成json串返回 if __name__ == '__main__': app.run(host='127.0.0.1', port=8802, debug=True) # #这个host:windows就一个网卡,可以不写,而liux有多个网卡,写成0:0:0可以接受任意网卡信息, # 通过访问127.0.0.1:8802/get_user,可返回data信息 # #debug:调试的时候,可以指定debug=true;如果是提供接口给他人使用的时候,debug要去掉
使用psotmen 调接口
127.0.0.1:8802/get_user
返回 json
[ [ "1", "13324681397", "6", "章程", "1", "1", "2912", "荣超金贸中心", "Fri, 16 Jul 2021 10:54:20 GMT", "Fri, 16 Jul 2021 10:54:24 GMT", "15215" ], [ "2", "13128721811", "a123456", "赵田毅", "2", "22", "2910", "牛牛商社", "Fri, 16 Jul 2021 15:37:46 GMT", "Fri, 16 Jul 2021 15:37:51 GMT", "155221" ], [ "3", "13631589252", "123456", "闫大全", "2", "15", "2911", "深圳大墙", "Fri, 16 Jul 2021 16:06:22 GMT", "Fri, 16 Jul 2021 16:06:26 GMT", "155421" ] ]