赞
踩
# 第一种方式使用服务的方式 # from wsgiref.simple_server import make_server # 第二种方式使用服务的方式 from gevent import pywsgi # web框架flask from flask import Flask # 自定义的模块类 from mysql.DB import DB # 路由 from router.index import setRoute # 连接数据库 db = DB() # 创建应用 app = Flask(__name__) # 初始化路由 initRoute = setRoute(app, db) if __name__ == '__main__': # 第一种方式 # server = make_server('192.168.55.26', 8899, app) # 第二种方式 server = pywsgi.WSGIServer(('192.168.155.26', 8899), app) print('Running on http://192.168.155.26:8899/') server.serve_forever()
import pymysql # 连接数据库 class DB(): def __init__(self): self.__connectDb() def __connectDb(self): db = pymysql.connect(host='127.0.0.1', user='root', password='root', database='my-build-party') return db def query(self, sql): # 获取游标对象 cursor = self.__connectDb().cursor() # 查找数据 'select * from sys_user ' sql_select = sql # 执行sql cursor.execute(sql_select) results = cursor.fetchall() # 关闭数据库 self.__connectDb().close() return results
from mysql.jsonData import get_data import json class setRoute(): def __init__(self, app, db): self.app = app self.db = db self.initRoute() def initRoute(self): self.__setHomeRoute() # __(双下划线)+方法名静态方法定义命名 self.setHomeUserList() def __setHomeRoute(self): @self.app.route('/') def hello_world(): return 'hello world!' def setHomeUserList(self): @self.app.route("/user/<int:id>") def api(id): request_id = int(id) global real_json # 打开数据库,读取内容 try: file = get_data(self.db.query('select * from sys_user')) print(file) j1 = json.loads(file) real_json = "未找到该数据" for i in j1: # 索引ID id = i['userId'] if request_id == id: print(i) real_json = json.dumps(i, ensure_ascii=False) except file.DoesNotExist: print("连接数据库失败") body = real_json response = body print("\nresponse data:", response) return response
import json
# 获取data
def get_data(results):
json_data = []
for i in results:
# 查找指定字段
result = {"userId": i[0], "userName": i[2], "deptId": i[1]}
json_data.append(result)
jsondatar = json.dumps(json_data, ensure_ascii=False)
return jsondatar
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。