当前位置:   article > 正文

python+web框架Flask接口小demo案例,适合有一定其他编程基础的、想学python,但不适合小白_flask的小demo

flask的小demo
准备工作

安装python准备工作链接

app.js(入口文件)
# 第一种方式使用服务的方式
# 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()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
连接数据库
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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
路由
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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
转换data为JSON格式
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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
'
运行
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/812509
推荐阅读
相关标签
  

闽ICP备14008679号