• Flask 简单GET/POST请求处理


    通过使用Python中 Flask 框架实现一个简单的API接口程序,用户可发送JSON格式的请求,服务器响应相应的JSON格式给客户。

    简单的登录接口调用: 最简单的Flask接收数据请求并处理的案例如下。

    from flask import Flask, render_template, request, redirect
    import json
    
    app = Flask(__name__, template_folder="templates")
    
    @app.route('/login', methods=['GET', 'POST'])
    def login():
        return_dict = {'status': '0', 'key': 'none'}
    
        if request.method == 'GET':
            # 判断参数不为0
            if len(request.args) != 0:
                get_data = request.args.to_dict()
                username = get_data.get("username")
                password = get_data.get("password")
                print("GET => username = {} password = {}".format(username,password))
    
            return json.dumps(return_dict, ensure_ascii=False)
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                username = request.values.get("username")
                password = request.values.get("password")
    
                print("username = {} => password = {}".format(username,password))
    
                if(username=="lyshark" and password == "123456"):
                    return_dict["status"] = "1"
                    return_dict["key"] = "1f3dsgf9834r98ugdf98gjd"
                    return json.dumps(return_dict, ensure_ascii=False)
    
        return json.dumps(return_dict, ensure_ascii=False)
    
    @app.route('/lat',methods=['GET', 'POST'])
    def lat():
        return_dict = {'status': '0','x': 'none', 'y':'none'}
    
        if request.method == 'GET':
            return json.dumps(return_dict, ensure_ascii=False)
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                key = request.values.get("key")
                tel = request.values.get("tel")
    
                print("key = {} => tel = {}".format(key,tel))
    
                if(key=="1f3dsgf9834r98ugdf98gjd"):
                    return_dict["status"] = "1"
                    return_dict['x'] = '12.5'
                    return_dict['y'] = '22.4'
    
                    return json.dumps(return_dict, ensure_ascii=False)
    
        return json.dumps(return_dict, ensure_ascii=False)
    
    if __name__ == '__main__':
        app.run(port=80,debug=False)
    

    实现简单的接口请求,首先创建数据库,增加两张表,一张用户表,一张计费表,初始化写入测试数据。

    import sqlite3
    
    # 增加用户表
    def UserDB():
        conn = sqlite3.connect("database.db")
        cursor = conn.cursor()
        create = "create table UserDB(" \
                 "id int auto_increment primary key," \
                 "username char(32) not null," \
                 "password char(32) not null," \
                 "key char(128) not null" \
                 ")"
    
        cursor.execute(create)
    
        insert = "insert into UserDB(id,username,password,key) values(1,'lyshark','123456','1f3dsgf9834r98ug');"
        cursor.execute(insert)
    
        insert = "insert into UserDB(id,username,password,key) values(2,'admin','1233','cef45f9f8480gfi5');"
        cursor.execute(insert)
    
        conn.commit()
        cursor.close()
        conn.close()
    
    # 增加计数表
    def CountDB():
        conn = sqlite3.connect("database.db")
        cursor = conn.cursor()
        create = "create table CountDB(" \
                 "id int auto_increment primary key," \
                 "username char(32) not null," \
                 "key char(128) not null," \
                 "lat_count int not null" \
                 ")"
    
        cursor.execute(create)
    
        insert = "insert into CountDB(id,username,key,lat_count) values(1,'lyshark','1f3dsgf9834r98ug',0);"
        cursor.execute(insert)
    
        insert = "insert into CountDB(id,username,key,lat_count) values(2,'admin','cef45f9f8480gfi5',0);"
        cursor.execute(insert)
    
        conn.commit()
        cursor.close()
        conn.close()
    
    UserDB()
    CountDB()
    
    '''
    创建用户验证表
    UserDB(id,username,password,key)
    
    创建计数表
    CountDB(id,key,lat_count,,,,,)
    '''
    

    增加测试接口: 定义并实现一些基本的功能,这些功能如下:

    • login 用户登录接口
    • is_login 判断用户是否登录
    • get_lat 模拟返回经纬度
    • get_count 获取调用次数
    from flask import Flask, render_template, request, redirect
    import json,sqlite3
    
    # 手机号规则
    TelList = ["130", "131", "132", "145", "155", "156", "175", "176", "185", "186", "166", "146", "10646"]
    
    app = Flask(__name__, template_folder="templates")
    
    def run_sql(sql):
        conn = sqlite3.connect("database.db")
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
        return cursor.fetchall()
    
    # 用户登录
    @app.route('/login', methods=['POST'])
    def login():
        return_dict = {'status': '0', 'key': 'none'}
    
        if request.method == 'GET':
            return json.dumps(return_dict, ensure_ascii=False)
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                username = request.values.get("username")
                password = request.values.get("password")
    
                # 验证账号密码是否正确
                ref_data = run_sql("select * from UserDB;")
                for data in ref_data:
                    # 正确返回key
                    if (data[1] == username) and (data[2] == password):
                        return_dict["status"] = "1"
                        return_dict["key"] = data[3]
                        return json.dumps(return_dict, ensure_ascii=False)
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 判断是否登录
    @app.route('/is_login',methods=['POST'])
    def is_login():
        return_dict = {'status': '0','user': 'none'}
    
        if request.method == 'GET':
            return json.dumps(return_dict, ensure_ascii=False)
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                key = request.values.get("key")
    
                # 验证是否登录
                ref_data = run_sql("select * from UserDB;")
                for data in ref_data:
                    if(data[3] == key):
                        return_dict['status'] = "1"
                        return_dict['user'] = data[1]
                        return json.dumps(return_dict, ensure_ascii=False)
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 模拟返回经纬度
    @app.route('/get_lat',methods=['POST'])
    def get_lat():
        return_dict = {'status': '0','mobile': 'none', 'longitude': 'none','latitude': 'none'}
    
        if request.method == 'GET':
            return json.dumps(return_dict, ensure_ascii=False)
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                key = request.values.get("key")
                mobile = request.values.get("mobile")
    
                # 通过说明是联通的手机号
                if mobile.strip()[0:3] in TelList or mobile.strip()[0:5] in TelList:
                    # 验证是否登录
                    ref_data = run_sql("select * from UserDB;")
                    for data in ref_data:
                        if(data[3] == key):
                            return_dict['status'] = '1'
                            return_dict['mobile'] = mobile
                            return_dict['longitude'] = '172.43'
                            return_dict['latitude'] = '22.56'
    
                            # 定位次数+1
                            ref_data = run_sql("select lat_count from CountDB where key='{}';".format(key))
                            new_count = int(ref_data[0][0]) + 1
                            run_sql("update CountDB set lat_count={} where key='{}'".format(new_count,key))
    
                            return json.dumps(return_dict, ensure_ascii=False)
    
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 获取计数
    @app.route('/get_count',methods=['POST'])
    def get_count():
        return_dict = {'status': '0','lat_count': '0'}
    
        if request.method == 'GET':
            return json.dumps(return_dict, ensure_ascii=False)
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                key = request.values.get("key")
    
                # 查询统计次数
                ref_data = run_sql("select * from CountDB where key='{}';".format(key))
                return_dict['status'] = '1'
                return_dict['lat_count'] = str(ref_data[0][3])
    
        return json.dumps(return_dict, ensure_ascii=False)
    
    if __name__ == '__main__':
        app.run(port=80,debug=False)
    

    完善动态登录功能: 上方登录时Key是固定的,我们再次调整,实现每次用户登录Key都会自动变化一次,当用户不使用的时候直接登出处理。

    首先创建数据库

    import sqlite3
    
    # 增加用户表
    def UserDB():
        conn = sqlite3.connect("database.db")
        cursor = conn.cursor()
        create = "create table UserDB(" \
                 "id int auto_increment primary key," \
                 "username char(32) not null," \
                 "password char(32) not null," \
                 "user_key char(128) not null," \
                 "company char(256) not null," \
                 "lat_count int not null" \
                 ")"
    
        cursor.execute(create)
    
        insert = "insert into UserDB(id,username,password,user_key,company,lat_count) values(1,'lyshark','123456','1f3dsgf9834r98ug','联通数科',0);"
        cursor.execute(insert)
    
        insert = "insert into UserDB(id,username,password,user_key,company,lat_count) values(2,'admin','1233','cef45f9f8480gfi5','联通数科',0);"
        cursor.execute(insert)
    
        conn.commit()
        cursor.close()
        conn.close()
    
    UserDB()
    

    Flask框架完善登录登出功能,代码如下:

    from flask import Flask, render_template, request, redirect
    import json,sqlite3
    import random,string
    
    # 手机号规则
    TelList = ["130", "131", "132", "145", "155", "156", "175", "176", "185", "186", "166", "146", "10646"]
    
    app = Flask(__name__, template_folder="templates")
    
    # 查询SQL
    def select_sql(sql):
        try:
            conn = sqlite3.connect("database.db")
            cursor = conn.cursor()
            cursor.execute(sql)
            conn.commit()
            return cursor.fetchall()
        except Exception:
            return False
    
    # 写出SQL
    def update_sql(sql):
        try:
            conn = sqlite3.connect("database.db")
            cursor = conn.cursor()
            cursor.execute(sql)
            conn.commit()
            conn.close()
            return True
        except Exception:
            return False
    
    # 生成一个指定长度的随机字符串
    def generate_random_str(randomlength=32):
        """
        string.digits=0123456789
        string.ascii_letters=abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
        """
        str_list = [random.choice(string.digits + string.ascii_letters) for i in range(randomlength)]
        random_str = ''.join(str_list)
        return random_str
    
    # ----------------------------------------------------------------------------------------------------------------------
    # 登录 + 验证 + 登出
    # ----------------------------------------------------------------------------------------------------------------------
    # 用户登录
    @app.route('/login', methods=['GET','POST','PUT','HEAD','DELETE'])
    def login():
        return_dict = {'status': '0', 'key': 'none'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                try:
                    username = request.values.get("username")
                    password = request.values.get("password")
    
                    # 验证账号密码是否正确
                    ref_data = select_sql("select * from UserDB;")
                    print(ref_data)
    
                    # 当查询不为假则执行
                    if ref_data != False:
                        for data in ref_data:
                            # 正确返回key
                            if (data[1] == username) and (data[2] == password):
                                # 生成并写入随机数
                                uuid = generate_random_str(32)
                                if update_sql("update UserDB set user_key='{}' where username='{}'".format(uuid, data[1])) != False:
                                    return_dict["status"] = "1"
                                    return_dict["key"] = uuid
                                    return json.dumps(return_dict, ensure_ascii=False)
                                else:
                                    return_dict["status"] = "0"
                                    return_dict["key"] = "密钥更新失败"
                                    return json.dumps(return_dict, ensure_ascii=False)
                    else:
                        return_dict["status"] = "0"
                        return_dict["key"] = "查询记录失败"
                        return json.dumps(return_dict, ensure_ascii=False)
    
                except Exception:
                    return_dict["status"] = "0"
                    return_dict["key"] = "接口异常"
                    return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict["status"] = "0"
                return_dict["key"] = "传入参数不能为空"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["key"] = "用户名或密码错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 判断是否登录
    @app.route('/is_login',methods=['GET','POST','PUT','HEAD','DELETE'])
    def is_login():
        return_dict = {'status': '0','user': 'none'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                try:
                    key = request.values.get("key")
                    # 验证是否登录
                    ref_data = select_sql("select * from UserDB;")
                    if ref_data != False:
                        for data in ref_data:
                            if(data[3] == key):
                                return_dict['status'] = "1"
                                return_dict['user'] = data[1]
                                return json.dumps(return_dict, ensure_ascii=False)
                    else:
                        return_dict["status"] = "0"
                        return_dict["key"] = "查询记录失败"
                        return json.dumps(return_dict, ensure_ascii=False)
    
                except Exception:
                    return_dict["status"] = "0"
                    return_dict["user"] = "接口异常"
                    return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict['status'] = "0"
                return_dict['user'] = "传入参数不能为空"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["user"] = "密钥失效,请重新登录"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 用户登出
    @app.route('/logout',methods=['GET','POST','PUT','HEAD','DELETE'])
    def logout():
        return_dict = {'status': '0','message': 'none'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                try:
                    key = request.values.get("key")
                    uuid = generate_random_str(32)
    
                    # 用户登出
                    if update_sql("update UserDB set user_key='{}' where user_key='{}'".format(uuid, key)) != False:
                        return_dict["status"] = "1"
                        return_dict["message"] = "已登出"
                        return json.dumps(return_dict, ensure_ascii=False)
    
                except Exception:
                    return_dict["status"] = "0"
                    return_dict["message"] = "接口异常"
                    return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict['status'] = "1"
                return_dict['message'] = "传入参数不能为空"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["message"] = "未登录,请登陆"
        return json.dumps(return_dict, ensure_ascii=False)
    
    if __name__ == '__main__':
        app.run(port=80,debug=False)
    

    增加针对定位对象组操作: 将多个表关联起来,并实现,创建,查询,删除,定位对象功能。

    SQL建库建表

    import sqlite3
    
    # 增加用户表
    def UserDB():
        conn = sqlite3.connect("database.db")
        cursor = conn.cursor()
        create = "create table UserDB(" \
                 "username char(32) not null," \
                 "password char(32) not null," \
                 "user_key char(128) not null," \
                 "company char(256) not null," \
                 "lat_count int not null" \
                 ")"
    
        cursor.execute(create)
    
        insert = "insert into UserDB(username,password,user_key,company,lat_count) values('lyshark','123456','1f3dsgf9834r98ug','联通数字科技有限公司',0);"
        cursor.execute(insert)
    
        insert = "insert into UserDB(username,password,user_key,company,lat_count) values('admin','1233','cef45f9f8480gfi5','联通数字科技有限公司',0);"
        cursor.execute(insert)
    
        conn.commit()
        cursor.close()
        conn.close()
    
    # 登录创建定位对象表
    def ObjectDB():
        conn = sqlite3.connect("database.db")
        cursor = conn.cursor()
        create = "create table ObjectDB(" \
                 "user_key char(128) not null," \
                 "uname char(32) not null," \
                 "mobile char(32) not null," \
                 "ugroup char(32) not null," \
                 "service_mobile char(32) not null," \
                 "message_name char(512) not null," \
                 "lat_count int not null," \
                 "is_auth char(32) not null" \
                 ")"
    
        cursor.execute(create)
    
        insert = "insert into ObjectDB(user_key,uname,mobile,ugroup,service_mobile,message_name,lat_count,is_auth) " \
                 "values('1f3dsgf9834r98ug','王瑞','15646596977','系统技术部','67882255','你好世界,这是一段测试文档',0,'未授权用户');"
        cursor.execute(insert)
    
        insert = "insert into ObjectDB(user_key,uname,mobile,ugroup,service_mobile,message_name,lat_count,is_auth) " \
                 "values('cef45f9f8480gfi5','郑凯','15646585548','系统技术部','67882255','你好世界,这是一段测试文档',0,'未授权用户');"
        cursor.execute(insert)
    
        conn.commit()
        cursor.close()
        conn.close()
    
    if __name__ == "__main__":
        UserDB()
        ObjectDB()
    

    Flask代码如下:

    from flask import Flask, request
    import json,sqlite3
    import random,string
    
    # 手机号规则
    TelList = ["130", "131", "132", "145", "155", "156", "175", "176", "185", "186", "166", "146", "10646"]
    
    # 数据库文件
    sql_file = "database.db"
    
    app = Flask(__name__, template_folder="templates")
    
    # 查询SQL
    def select_sql(sql):
        try:
            conn = sqlite3.connect(sql_file)
            cursor = conn.cursor()
            cursor.execute(sql)
            conn.commit()
            return cursor.fetchall()
        except Exception:
            return False
    
    # 插入新记录SQL
    def insert_sql(sql):
        try:
            conn = sqlite3.connect(sql_file)
            cursor = conn.cursor()
            cursor.execute(sql)
            conn.commit()
            conn.close()
            return True
        except Exception:
            return False
    
    # 更新SQL
    def update_sql(sql):
        try:
            conn = sqlite3.connect(sql_file)
            cursor = conn.cursor()
            cursor.execute(sql)
            conn.commit()
            conn.close()
            return True
        except Exception:
            return False
    
    # 删除记录SQL
    def delete_sql(sql):
        try:
            conn = sqlite3.connect(sql_file)
            cursor = conn.cursor()
            cursor.execute(sql)
            conn.commit()
            conn.close()
            return True
        except Exception:
            return False
    
    # 生成一个指定长度的随机字符串
    def generate_random_str(randomlength=32):
        """
        string.digits=0123456789
        string.ascii_letters=abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
        """
        str_list = [random.choice(string.digits + string.ascii_letters) for i in range(randomlength)]
        random_str = ''.join(str_list)
        return random_str
    
    # ----------------------------------------------------------------------------------------------------------------------
    # 登录 + 验证 + 登出
    # ----------------------------------------------------------------------------------------------------------------------
    # 用户登录
    @app.route('/login', methods=['POST'])
    def login():
        return_dict = {'status': '0', 'token': 'none'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                try:
                    username = request.values.get("username")
                    password = request.values.get("password")
    
                    # 验证账号密码是否正确
                    ref_data = select_sql("select * from UserDB;")
    
                    # 当查询不为假则执行
                    if ref_data != False:
                        for data in ref_data:
                            # 正确返回key
                            if (data[0] == username) and (data[1] == password):
                                return_dict["status"] = "1"
                                return_dict["token"] = data[2]
                                return json.dumps(return_dict, ensure_ascii=False)
                    else:
                        return_dict["status"] = "0"
                        return_dict["token"] = "查询记录失败"
                        return json.dumps(return_dict, ensure_ascii=False)
    
                except Exception:
                    return_dict["status"] = "0"
                    return_dict["token"] = "接口异常"
                    return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict["status"] = "0"
                return_dict["token"] = "传入参数不能为空"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["token"] = "用户名或密码错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 判断是否登录
    @app.route('/is_login',methods=['POST'])
    def is_login():
        return_dict = {'status': '0','user': 'none'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                try:
                    key = request.values.get("token")
                    # 验证是否登录
                    ref_data = select_sql("select * from UserDB;")
                    if ref_data != False:
                        for data in ref_data:
                            if(data[2] == key):
                                return_dict['status'] = "1"
                                return_dict['user'] = data[0]
                                return json.dumps(return_dict, ensure_ascii=False)
                    else:
                        return_dict["status"] = "0"
                        return_dict["user"] = "查询记录失败"
                        return json.dumps(return_dict, ensure_ascii=False)
    
                except Exception:
                    return_dict["status"] = "0"
                    return_dict["user"] = "接口异常"
                    return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict['status'] = "0"
                return_dict['user'] = "传入参数不能为空"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["user"] = "密钥失效,请重新登录"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 刷新用户Token
    @app.route('/flush_token',methods=['POST'])
    def flush_token():
        return_dict = {'status': '0','message': 'none'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                try:
                    key = request.values.get("token")
                    uuid = generate_random_str(32)
    
                    # 用户登出 更新第一张表中的Key
                    if update_sql("update UserDB set user_key='{}' where user_key='{}'".format(uuid, key)) != False:
                        # 更新第二张表中的Key
                        if update_sql("update ObjectDB set user_key='{}' where user_key='{}'".format(uuid, key)) != False:
                            return_dict["status"] = "1"
                            return_dict["message"] = "已刷新"
                            return json.dumps(return_dict, ensure_ascii=False)
                except Exception:
                    return_dict["status"] = "0"
                    return_dict["message"] = "接口异常"
                    return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict['status'] = "0"
                return_dict['message'] = "传入参数不能为空"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["message"] = "未知错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    
    # ----------------------------------------------------------------------------------------------------------------------
    # 定位对象相关接口
    # ----------------------------------------------------------------------------------------------------------------------
    
    # 创建定位对象
    @app.route('/create_object',methods=['POST'])
    def create_object():
        return_dict = {'status': '0','message': 'none'}
        if request.method == "POST":
            # 验证参数是否一致
            if len(request.get_data()) != 0 and len(request.values) == 6:
                key = request.values.get("token")
                uname = request.values.get("uname")
                mobile = request.values.get("mobile")
                ugroup = request.values.get("ugroup")
                service_mobile = request.values.get("service_mobile")
                message_name = request.values.get("message_name")
    
                # 验证是否是联通手机号
                if mobile.strip()[0:3] in TelList or mobile.strip()[0:5] in TelList:
    
                    # 查询UserDB表内是否存在用户传入的key
                    ref_data = select_sql("select user_key from UserDB where user_key='{}';".format(key))
                    if len(ref_data) != 0 and ref_data != False:
    
                        # 检查表内是否存在手机号
                        ref_mobile_data = select_sql("select count(mobile) from ObjectDB where mobile='{}'".format(mobile))
                        if int(ref_mobile_data[0][0]) == 0:
    
                            # 开始构建插入数据库语句
                            insert_ref = "insert into ObjectDB(user_key,uname,mobile,ugroup,service_mobile,message_name,lat_count,is_auth) " \
                 "values('{}','{}','{}','{}','{}','{}',0,'未授权用户');".format(key,uname,mobile,ugroup,service_mobile,message_name)
                            insert_ref_flag = insert_sql(insert_ref)
    
                            if insert_ref_flag == True:
                                return_dict["status"] = "1"
                                return_dict["message"] = "已新增定位对象"
                                return json.dumps(return_dict, ensure_ascii=False)
                            else:
                                return_dict["status"] = "0"
                                return_dict["message"] = "新增定位对象失败"
                                return json.dumps(return_dict, ensure_ascii=False)
    
                        else:
                            return_dict["status"] = "0"
                            return_dict["message"] = "手机号已存在,无法继续创建"
                            return json.dumps(return_dict, ensure_ascii=False)
                    else:
                        return_dict["status"] = "0"
                        return_dict["message"] = "传入Key密钥对错误"
                        return json.dumps(return_dict, ensure_ascii=False)
                else:
                    return_dict["status"] = "0"
                    return_dict["message"] = "请输入联通手机号"
                    return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict["status"] = "0"
                return_dict["message"] = "传入参数错误"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["message"] = "未知错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 查询所有定位对象
    @app.route('/select_all_object',methods=['POST'])
    def select_all_object():
        return_dict = {'status': '0','count': '0', 'message': 'none'}
        if request.method == "POST":
            # 验证参数是否一致
            if len(request.get_data()) != 0 and len(request.values) == 1:
                key = request.values.get("token")
                # 查询UserDB表内是否存在用户传入的key
                ref_data = select_sql("select user_key from UserDB where user_key='{}';".format(key))
                if len(ref_data) != 0 and ref_data != False:
                    # 定义组合模板
                    object_list = []
    
                    ref_data_object = select_sql("select * from ObjectDB;")
                    if ref_data_object != False:
    
                        # 循环组合成JSON
                        for item in ref_data_object:
                            li = [item[1],item[2],item[3],item[4],item[5]]
                            object_list.append(li)
    
                        return_dict["status"] = "1"
                        return_dict["count"] = len(object_list)
                        return_dict["message"] = object_list
                        return json.dumps(return_dict, ensure_ascii=False)
    
                else:
                    return_dict["status"] = "0"
                    return_dict["count"] = "0"
                    return_dict["message"] = "查询异常"
                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict["status"] = "0"
                return_dict["count"] = "0"
                return_dict["message"] = "传入参数错误"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["count"] = "0"
        return_dict["message"] = "未知错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 删除定位对象
    @app.route('/delete_object',methods=['POST'])
    def delete_object():
        return_dict = {'status': '0','message': 'none'}
        if request.method == "POST":
            # 验证参数是否一致
            if len(request.get_data()) != 0 and len(request.values) == 2:
                key = request.values.get("token")
                mobile = request.values.get("mobile")
    
                # 验证是否是联通手机号
                if mobile.strip()[0:3] in TelList or mobile.strip()[0:5] in TelList:
                    # 查询UserDB表内是否存在用户传入的key
                    ref_data = select_sql("select user_key from UserDB where user_key='{}';".format(key))
                    if len(ref_data) != 0 and ref_data != False:
                        ref = delete_sql("delete from ObjectDB where mobile = '{}'".format(mobile))
                        if ref == True:
                            return_dict["status"] = "1"
                            return_dict["message"] = "定位对象已删除"
                            return json.dumps(return_dict, ensure_ascii=False)
                else:
                    return_dict["status"] = "0"
                    return_dict["message"] = "请输入联通手机号"
                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict["status"] = "0"
                return_dict["message"] = "传入参数错误"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["message"] = "未知错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # ----------------------------------------------------------------------------------------------------------------------
    # 用户组相关接口
    # ----------------------------------------------------------------------------------------------------------------------
    
    # 查询所有用户组
    @app.route('/select_all_group',methods=['POST'])
    def select_all_group():
        return_dict = {'status': '0','count': 'none', 'message': 'none'}
        if request.method == "POST":
            # 验证参数是否一致
            if len(request.get_data()) != 0 and len(request.values) == 1:
                key = request.values.get("token")
                # 查询UserDB表内是否存在用户传入的key
                ref_data = select_sql("select user_key from UserDB where user_key='{}';".format(key))
                if len(ref_data) != 0 and ref_data != False:
                    # 定义组合模板
                    object_list = []
    
                    # 查询组并去重后放入ref
                    ref_select_data = select_sql("select ugroup from ObjectDB;")
                    if ref_select_data != False:
                        for each in ref_select_data:
                            object_list.append(each[0])
    
                        ref = list( set(object_list) )
                        ref_count = len(set(object_list))
    
                        # 返回系统部门
                        return_dict["status"] = "1"
                        return_dict["count"] = ref_count
                        return_dict["message"] = ref
                        return json.dumps(return_dict, ensure_ascii=False)
    
                    else:
                        return_dict["status"] = "0"
                        return_dict["message"] = "查询异常"
                        return json.dumps(return_dict, ensure_ascii=False)
    
                else:
                    return_dict["status"] = "0"
                    return_dict["count"] = "0"
                    return_dict["message"] = "查询异常"
                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict["status"] = "0"
                return_dict["message"] = "传入参数错误"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["message"] = "未知错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 查询用户组成员
    @app.route('/select_user_group',methods=['POST'])
    def select_user_group():
        return_dict = {'status': '0','count': 'none', 'group':'none', 'message': 'none'}
        if request.method == "POST":
            # 验证参数是否一致
            if len(request.get_data()) != 0 and len(request.values) == 2:
                key = request.values.get("token")
                ugroup = request.values.get("group")
                # 查询UserDB表内是否存在用户传入的key
                ref_data = select_sql("select user_key from UserDB where user_key='{}';".format(key))
                if len(ref_data) != 0 and ref_data != False:
                    # 定义组合模板
                    object_list = []
    
                    # 查询组并去重后放入ref
                    ref_select_data = select_sql("select uname,mobile,is_auth from ObjectDB where ugroup='{}';".format(ugroup))
                    if ref_select_data != False:
                        for each in ref_select_data:
                            object_list.append(each)
    
                        # 返回系统部门
                        return_dict["status"] = "1"
                        return_dict["count"] = len(object_list)
    
                        if len(object_list)==0:
                            return_dict["group"] = "none"
                        else:
                            return_dict["group"] = ugroup
    
                        return_dict["message"] = object_list
                        return json.dumps(return_dict, ensure_ascii=False)
    
                    else:
                        return_dict["status"] = "0"
                        return_dict["group"] = "none"
                        return_dict["count"] = "0"
                        return_dict["message"] = "查询异常"
                        return json.dumps(return_dict, ensure_ascii=False)
    
                else:
                    return_dict["status"] = "0"
                    return_dict["group"] = "none"
                    return_dict["count"] = "0"
                    return_dict["message"] = "查询异常"
                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict["status"] = "0"
                return_dict["group"] = "none"
                return_dict["count"] = "0"
                return_dict["message"] = "传入参数错误"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["group"] = "none"
        return_dict["count"] = "0"
        return_dict["message"] = "未知错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 修改用户组
    @app.route('/update_user_group',methods=['POST'])
    def update_user_group():
        return_dict = {'status': '0','message': 'none'}
        if request.method == "POST":
            # 验证参数是否一致
            if len(request.get_data()) != 0 and len(request.values) == 3:
                key = request.values.get("token")
                mobile = request.values.get("mobile")
                ugroup = request.values.get("group")
                # 查询UserDB表内是否存在用户传入的key
                ref_data = select_sql("select user_key from UserDB where user_key='{}';".format(key))
                if len(ref_data) != 0 and ref_data != False:
                    # 更新用户组
                    if update_sql("update ObjectDB set ugroup='{}' where user_key='{}' and mobile='{}'".format(ugroup,key,mobile)) != False:
                        # 返回系统部门
                        return_dict["status"] = "1"
                        return_dict["message"] = "已更新"
                        return json.dumps(return_dict, ensure_ascii=False)
                    else:
                        return_dict["status"] = "0"
                        return_dict["message"] = "查询异常"
                        return json.dumps(return_dict, ensure_ascii=False)
                else:
                    return_dict["status"] = "0"
                    return_dict["message"] = "查询异常"
                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict["status"] = "0"
                return_dict["message"] = "传入参数错误"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["message"] = "未知错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # ----------------------------------------------------------------------------------------------------------------------
    # 经纬度返回相关接口
    # ----------------------------------------------------------------------------------------------------------------------
    
    # 模拟返回经纬度
    @app.route('/get_lat',methods=['POST'])
    def get_lat():
        return_dict = {'status': '0','mobile': 'none', 'longitude': 'none','latitude': 'none'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0 and len(request.values) == 2:
                key = request.values.get("token")
                mobile = request.values.get("mobile")
    
                # 通过说明是联通的手机号
                if mobile.strip()[0:3] in TelList or mobile.strip()[0:5] in TelList:
                    # 验证是否登录
                    ref_UserDB_data = select_sql("select user_key from UserDB;")
                    for each in ref_UserDB_data:
                        if(each[0] == key):
    
                            # 判断是否为授权用户
                            select_auth = select_sql("select is_auth from ObjectDB where mobile='{}'".format(mobile))
                            if select_auth[0][0] != "已授权用户":
                                return_dict = {'status': '0', 'message': '未授权用户,请授权'}
                                return json.dumps(return_dict, ensure_ascii=False)
                            else:
                                # 如果授权了,直接定位返回结果
                                return_dict['status'] = '1'
                                return_dict['mobile'] = mobile
                                return_dict['longitude'] = '172.43'
                                return_dict['latitude'] = '22.56'
    
                                # UserDB 中的定位次数递增一次
                                ref_UserDB_Count = select_sql("select lat_count from UserDB where user_key='{}';".format(key))
                                if ref_UserDB_Count != False:
                                    new_count = int(ref_UserDB_Count[0][0]) + 1
                                    update_sql("update UserDB set lat_count={} where user_key='{}'".format(new_count,key))
    
                                # ObjectDB 中的定位次数递增一次
                                ref_Object_Count = select_sql("select lat_count from ObjectDB where mobile='{}'".format(mobile))
                                if ref_Object_Count != False:
                                    new_count = int(ref_Object_Count[0][0]) + 1
                                    update_sql("update ObjectDB set lat_count={} where mobile='{}'".format(new_count,mobile))
    
                                return json.dumps(return_dict, ensure_ascii=False)
    
                else:
                    return_dict = {'status': '0', 'message': '请输入联通手机号'}
                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict = {'status': '0','message': '传入参数错误'}
                return json.dumps(return_dict, ensure_ascii=False)
    
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 查询总调用定位次数
    @app.route('/select_all_count',methods=['POST'])
    def select_all_count():
        return_dict = {'status': '0','lat_count': '0'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0 and len(request.values) == 1:
                key = request.values.get("token")
                # 验证是否登录
                ref_UserDB_data = select_sql("select user_key from UserDB;")
                for each in ref_UserDB_data:
                    if (each[0] == key):
    
                        # 查询统计次数
                        ref_data = select_sql("select lat_count from UserDB where user_key='{}';".format(key))
                        return_dict['status'] = '1'
                        return_dict['lat_count'] = str(ref_data[0][0])
                        return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict = {'status': '0','message': '传入参数错误'}
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict = {'status': '0', 'message': '未知错误'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 查询某手机号调用次数
    @app.route('/select_mobile_count',methods=['POST'])
    def select_mobile_count():
        return_dict = {'status': '0','mobile': 'none', 'lat_count': '0'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0 and len(request.values) == 2:
                key = request.values.get("token")
                mobile = request.values.get("mobile")
    
                # 通过说明是联通的手机号
                if mobile.strip()[0:3] in TelList or mobile.strip()[0:5] in TelList:
                    # 验证是否登录
                    ref_UserDB_data = select_sql("select user_key from UserDB;")
                    for each in ref_UserDB_data:
                        if (each[0] == key):
                            # 查询统计次数
                            ref_data = select_sql("select lat_count from ObjectDB where mobile='{}';".format(mobile))
                            return_dict['status'] = '1'
                            return_dict['mobile'] = mobile
                            return_dict['lat_count'] = str(ref_data[0][0])
                            return json.dumps(return_dict, ensure_ascii=False)
    
                else:
                    return_dict = {'status': '0', 'message': '请输入联通手机号'}
                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict = {'status': '0', 'message': '传入参数错误'}
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict = {'status': '0', 'message': '未知错误'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 查询某个组调用总次数
    @app.route('/select_group_count',methods=['POST'])
    def select_group_count():
        return_dict = {'status': '0','group': 'none', 'lat_count': '0'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0 and len(request.values) == 2:
                key = request.values.get("token")
                ugroup = request.values.get("group")
    
                # 验证是否登录
                ref_UserDB_data = select_sql("select user_key from UserDB;")
                for each in ref_UserDB_data:
                    if (each[0] == key):
                        # 查询统计次数
                        ref_data = select_sql("select lat_count from ObjectDB where ugroup='{}';".format(ugroup))
                        group_count = 0
                        for count in ref_data:
                            group_count = group_count + int(count[0])
    
                        return_dict['status'] = '1'
                        return_dict['group'] = ugroup
                        return_dict['lat_count'] = group_count
                        return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict = {'status': '0', 'message': '传入参数错误'}
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict = {'status': '0', 'message': '未知错误'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    # ----------------------------------------------------------------------------------------------------------------------
    # 鉴权接口 相关接口
    # ----------------------------------------------------------------------------------------------------------------------
    
    # 查询用户权限状态
    @app.route('/select_auth_table',methods=['POST'])
    def select_auth_table():
        return_dict = {'status': '0','unauthorized': [],'authorized': []}
    
        if request.method == "POST":
            if len(request.get_data()) != 0 and len(request.values) == 1:
                key = request.values.get("token")
    
                # 验证是否登录
                ref_UserDB_data = select_sql("select user_key from UserDB;")
                for each in ref_UserDB_data:
                    if (each[0] == key):
                        # 查询统计次数
                        ref_data = select_sql("select mobile,is_auth from ObjectDB;")
    
                        not_auth = []
                        success_auth = []
    
                        for each in ref_data:
                            if each[1] == "未授权用户":
                                not_auth.append(each[0])
                            elif each[1] == "已授权用户":
                                success_auth.append(each[0])
    
                        return_dict['status'] = '1'
                        return_dict['unauthorized'] = not_auth
                        return_dict['authorized'] = success_auth
                        return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict = {'status': '0', 'message': '传入参数错误'}
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict = {'status': '0', 'message': '未知错误'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    # ----------------------------------------------------------------------------------------------------------------------
    # 其他 相关接口
    # ----------------------------------------------------------------------------------------------------------------------
    
    @app.route('/get_version',methods=['POST'])
    def get_version():
        return_dict = {'status': '1','version': '1.0.0', 'build': '2021-12-15 9:57'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    @app.errorhandler(404)
    def not_found(error):
        return_dict = {'status': '1', 'message': '页面没有找到'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    @app.errorhandler(405)
    def not_found(error):
        return_dict = {'status': '1', 'message': '服务器不提供请求类型'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    @app.errorhandler(500)
    def not_found(error):
        return_dict = {'status': '1', 'message': '错误接口'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    if __name__ == '__main__':
        app.run(port=80,debug=True)
    

    增加验证码功能: 对程序增加验证码验证功能,代码如下:

    SQL语句

    import sqlite3
    
    db = "database.db"
    
    def DropDB():
        conn = sqlite3.connect(db)
        cursor = conn.cursor()
    
        drops = "drop table UserDB;"
        cursor.execute(drops)
    
        drops = "drop table ObjectDB;"
        cursor.execute(drops)
    
        drops = "drop table LocationCountDB;"
        cursor.execute(drops)
    
        drops = "drop table VerificationCodeDB;"
        cursor.execute(drops)
    
        conn.commit()
        cursor.close()
        conn.close()
    
    # 用户表
    def UserDB():
        conn = sqlite3.connect(db)
        cursor = conn.cursor()
        create = "create table UserDB(" \
                 "username char(32) not null," \
                 "password char(32) not null," \
                 "user_key char(128) not null" \
                 ")"
    
        cursor.execute(create)
    
        insert = "insert into UserDB(username,password,user_key) values('lyshark','123456','1f3dsgf9834r98ug');"
        cursor.execute(insert)
    
        insert = "insert into UserDB(username,password,user_key) values('admin','1233','cef45f9f8480gfi5');"
        cursor.execute(insert)
    
        conn.commit()
        cursor.close()
        conn.close()
    
    # 定位对象表
    def ObjectDB():
        conn = sqlite3.connect(db)
        cursor = conn.cursor()
        create = "create table ObjectDB(" \
                 "user_key char(128) not null," \
                 "uname char(32) not null," \
                 "mobile char(32) not null," \
                 "ugroup char(32) not null," \
                 "service_mobile char(32) not null," \
                 "message_name char(512) not null," \
                 "is_auth char(32) not null" \
                 ")"
    
        cursor.execute(create)
    
        insert = "insert into ObjectDB(user_key,uname,mobile,ugroup,service_mobile,message_name,is_auth) " \
                 "values('1f3dsgf9834r98ug','王瑞','15646596977','系统技术部','67882255','你好世界,这是一段测试文档','未授权用户');"
        cursor.execute(insert)
    
        insert = "insert into ObjectDB(user_key,uname,mobile,ugroup,service_mobile,message_name,is_auth) " \
                 "values('cef45f9f8480gfi5','郑凯','15646585548','系统技术部','67882255','你好世界,这是一段测试文档','已授权用户');"
        cursor.execute(insert)
    
        conn.commit()
        cursor.close()
        conn.close()
    
    # 定位次数费率表
    def LocationCountDB():
        conn = sqlite3.connect(db)
        cursor = conn.cursor()
        create = "create table LocationCountDB(" \
                 "uname char(32) not null," \
                 "mobile char(32) not null unique," \
                 "lat_count int not null," \
                 "lat_rate float not null," \
                 "trajectory_count int not null," \
                 "trajectory_rate float not null," \
                 "enclosure_count int not null," \
                 "enclosure_rate int not null" \
                 ")"
    
        cursor.execute(create)
    
        insert = "insert into LocationCountDB(uname,mobile,lat_count,lat_rate,trajectory_count,trajectory_rate,enclosure_count,enclosure_rate) " \
                 "values('王瑞','15646596977',0,0,0,0,0,0);"
        cursor.execute(insert)
    
        insert = "insert into LocationCountDB(uname,mobile,lat_count,lat_rate,trajectory_count,trajectory_rate,enclosure_count,enclosure_rate) " \
                 "values('郑凯','15646585548',0,0,0,0,0,0);"
        cursor.execute(insert)
    
        conn.commit()
        cursor.close()
        conn.close()
    
    # 验证码验证表
    def VerificationCodeDB():
        conn = sqlite3.connect(db)
        cursor = conn.cursor()
        create = "create table VerificationCodeDB(" \
                 "mobile char(32) not null unique," \
                 "code char(16) not null unique," \
                 "time_stamp int not null" \
                 ")"
    
        cursor.execute(create)
    
        conn.commit()
        cursor.close()
        conn.close()
    
    if __name__ == "__main__":
        UserDB()
        ObjectDB()
        LocationCountDB()
        VerificationCodeDB()
    

    Python代码

    from flask import Flask, request
    import json,sqlite3
    import random,string
    import time,datetime
    
    # 手机号规则
    TelList = ["130", "131", "132", "145", "155", "156", "175", "176", "185", "186", "166", "146", "10646"]
    
    # 数据库文件
    sql_file = "database.db"
    
    app = Flask(__name__, template_folder="templates")
    
    # 查询SQL
    def select_sql(sql):
        try:
            conn = sqlite3.connect(sql_file)
            cursor = conn.cursor()
            cursor.execute(sql)
            conn.commit()
            return cursor.fetchall()
        except Exception:
            return False
    
    # 插入新记录SQL
    def insert_sql(sql):
        try:
            conn = sqlite3.connect(sql_file)
            cursor = conn.cursor()
            cursor.execute(sql)
            conn.commit()
            conn.close()
            return True
        except Exception:
            return False
    
    # 更新SQL
    def update_sql(sql):
        try:
            conn = sqlite3.connect(sql_file)
            cursor = conn.cursor()
            cursor.execute(sql)
            conn.commit()
            conn.close()
            return True
        except Exception:
            return False
    
    # 删除记录SQL
    def delete_sql(sql):
        try:
            conn = sqlite3.connect(sql_file)
            cursor = conn.cursor()
            cursor.execute(sql)
            conn.commit()
            conn.close()
            return True
        except Exception:
            return False
    
    
    # 生成一个指定长度的随机字符串
    def generate_random_str(randomlength=32):
        str_list = [random.choice(string.digits + string.ascii_letters) for i in range(randomlength)]
        random_str = ''.join(str_list)
        return random_str
    
    # ----------------------------------------------------------------------------------------------------------------------
    # 登录 + 验证 + 登出
    # ----------------------------------------------------------------------------------------------------------------------
    # 用户登录
    @app.route('/login', methods=['POST'])
    def login():
        return_dict = {'status': '0', 'token': 'none'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                try:
                    username = request.values.get("username")
                    password = request.values.get("password")
    
                    # 验证账号密码是否正确
                    ref_data = select_sql("select * from UserDB;")
    
                    # 当查询不为假则执行
                    if ref_data != False:
                        for data in ref_data:
                            # 正确返回key
                            if (data[0] == username) and (data[1] == password):
                                return_dict["status"] = "1"
                                return_dict["token"] = data[2]
                                return json.dumps(return_dict, ensure_ascii=False)
                    else:
                        return_dict["status"] = "0"
                        return_dict["token"] = "查询记录失败"
                        return json.dumps(return_dict, ensure_ascii=False)
    
                except Exception:
                    return_dict["status"] = "0"
                    return_dict["token"] = "接口异常"
                    return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict["status"] = "0"
                return_dict["token"] = "传入参数不能为空"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["token"] = "用户名或密码错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 判断是否登录
    @app.route('/is_login',methods=['POST'])
    def is_login():
        return_dict = {'status': '0','user': 'none'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                try:
                    key = request.values.get("token")
                    # 验证是否登录
                    ref_data = select_sql("select * from UserDB;")
                    if ref_data != False:
                        for data in ref_data:
                            if(data[2] == key):
                                return_dict['status'] = "1"
                                return_dict['user'] = data[0]
                                return json.dumps(return_dict, ensure_ascii=False)
                    else:
                        return_dict["status"] = "0"
                        return_dict["user"] = "查询记录失败"
                        return json.dumps(return_dict, ensure_ascii=False)
    
                except Exception:
                    return_dict["status"] = "0"
                    return_dict["user"] = "接口异常"
                    return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict['status'] = "0"
                return_dict['user'] = "传入参数不能为空"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["user"] = "密钥失效,请重新登录"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 刷新用户Token
    @app.route('/flush_token',methods=['POST'])
    def flush_token():
        return_dict = {'status': '0','message': 'none'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0:
                try:
                    key = request.values.get("token")
                    uuid = generate_random_str(32)
    
                    # 用户登出 更新第一张表中的Key
                    if update_sql("update UserDB set user_key='{}' where user_key='{}'".format(uuid, key)) != False:
                        # 更新第二张表中的Key
                        if update_sql("update ObjectDB set user_key='{}' where user_key='{}'".format(uuid, key)) != False:
                            return_dict["status"] = "1"
                            return_dict["message"] = "已刷新"
                            return json.dumps(return_dict, ensure_ascii=False)
                except Exception:
                    return_dict["status"] = "0"
                    return_dict["message"] = "接口异常"
                    return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict['status'] = "0"
                return_dict['message'] = "传入参数不能为空"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["message"] = "未知错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    
    # ----------------------------------------------------------------------------------------------------------------------
    # 定位对象相关接口
    # ----------------------------------------------------------------------------------------------------------------------
    
    # 创建定位对象
    @app.route('/create_object',methods=['POST'])
    def create_object():
        return_dict = {'status': '0','message': 'none'}
        if request.method == "POST":
            # 验证参数是否一致
            if len(request.get_data()) != 0 and len(request.values) == 6:
                key = request.values.get("token")
                uname = request.values.get("uname")
                mobile = request.values.get("mobile")
                ugroup = request.values.get("ugroup")
                service_mobile = request.values.get("service_mobile")
                message_name = request.values.get("message_name")
    
                # 验证是否是联通手机号
                if mobile.strip()[0:3] in TelList or mobile.strip()[0:5] in TelList:
    
                    # 查询UserDB表内是否存在用户传入的key
                    ref_data = select_sql("select user_key from UserDB where user_key='{}';".format(key))
                    if len(ref_data) != 0 and ref_data != False:
    
                        # 检查表内是否存在手机号
                        ref_mobile_data = select_sql("select count(mobile) from ObjectDB where mobile='{}'".format(mobile))
                        if int(ref_mobile_data[0][0]) == 0:
    
                            # 开始构建插入数据库语句
                            insert_ref = "insert into ObjectDB(user_key,uname,mobile,ugroup,service_mobile,message_name,is_auth) " \
                 "values('{}','{}','{}','{}','{}','{}','未授权用户');".format(key,uname,mobile,ugroup,service_mobile,message_name)
                            insert_ref_flag = insert_sql(insert_ref)
    
                            if insert_ref_flag == True:
    
                                # 同步插入计数计费表
                                insert_sql("insert into LocationCountDB(uname,mobile,lat_count,lat_rate,trajectory_count,trajectory_rate,enclosure_count,enclosure_rate) " \
                                         "values('{}','{}',0,0,0,0,0,0);".format(uname,mobile))
    
                                return_dict["status"] = "1"
                                return_dict["message"] = "已新增定位对象"
                                return json.dumps(return_dict, ensure_ascii=False)
                            else:
                                return_dict["status"] = "0"
                                return_dict["message"] = "新增定位对象失败"
                                return json.dumps(return_dict, ensure_ascii=False)
    
                        else:
                            return_dict["status"] = "0"
                            return_dict["message"] = "手机号已存在,无法继续创建"
                            return json.dumps(return_dict, ensure_ascii=False)
                    else:
                        return_dict["status"] = "0"
                        return_dict["message"] = "传入Key密钥对错误"
                        return json.dumps(return_dict, ensure_ascii=False)
                else:
                    return_dict["status"] = "0"
                    return_dict["message"] = "请输入联通手机号"
                    return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict["status"] = "0"
                return_dict["message"] = "传入参数错误"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["message"] = "未知错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 查询所有定位对象
    @app.route('/select_all_object',methods=['POST'])
    def select_all_object():
        return_dict = {'status': '0','count': '0', 'message': 'none'}
        if request.method == "POST":
            # 验证参数是否一致
            if len(request.get_data()) != 0 and len(request.values) == 1:
                key = request.values.get("token")
                # 查询UserDB表内是否存在用户传入的key
                ref_data = select_sql("select user_key from UserDB where user_key='{}';".format(key))
                if len(ref_data) != 0 and ref_data != False:
                    # 定义组合模板
                    object_list = []
    
                    ref_data_object = select_sql("select * from ObjectDB;")
                    if ref_data_object != False:
    
                        # 循环组合成JSON
                        for item in ref_data_object:
                            li = [item[1],item[2],item[3],item[4],item[5]]
                            object_list.append(li)
    
                        return_dict["status"] = "1"
                        return_dict["count"] = len(object_list)
                        return_dict["message"] = object_list
                        return json.dumps(return_dict, ensure_ascii=False)
    
                else:
                    return_dict["status"] = "0"
                    return_dict["count"] = "0"
                    return_dict["message"] = "查询异常"
                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict["status"] = "0"
                return_dict["count"] = "0"
                return_dict["message"] = "传入参数错误"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["count"] = "0"
        return_dict["message"] = "未知错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 删除定位对象
    @app.route('/delete_object',methods=['POST'])
    def delete_object():
        return_dict = {'status': '0','message': 'none'}
        if request.method == "POST":
            # 验证参数是否一致
            if len(request.get_data()) != 0 and len(request.values) == 2:
                key = request.values.get("token")
                mobile = request.values.get("mobile")
    
                # 验证是否是联通手机号
                if mobile.strip()[0:3] in TelList or mobile.strip()[0:5] in TelList:
                    # 查询UserDB表内是否存在用户传入的key
                    ref_data = select_sql("select user_key from UserDB where user_key='{}';".format(key))
                    if len(ref_data) != 0 and ref_data != False:
                        ref = delete_sql("delete from ObjectDB where mobile = '{}'".format(mobile))
                        if ref == True:
                            return_dict["status"] = "1"
                            return_dict["message"] = "定位对象已删除"
                            return json.dumps(return_dict, ensure_ascii=False)
                else:
                    return_dict["status"] = "0"
                    return_dict["message"] = "请输入联通手机号"
                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict["status"] = "0"
                return_dict["message"] = "传入参数错误"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["message"] = "未知错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # ----------------------------------------------------------------------------------------------------------------------
    # 用户组相关接口
    # ----------------------------------------------------------------------------------------------------------------------
    
    # 查询所有用户组
    @app.route('/select_all_group',methods=['POST'])
    def select_all_group():
        return_dict = {'status': '0','count': 'none', 'message': 'none'}
        if request.method == "POST":
            # 验证参数是否一致
            if len(request.get_data()) != 0 and len(request.values) == 1:
                key = request.values.get("token")
                # 查询UserDB表内是否存在用户传入的key
                ref_data = select_sql("select user_key from UserDB where user_key='{}';".format(key))
                if len(ref_data) != 0 and ref_data != False:
                    # 定义组合模板
                    object_list = []
    
                    # 查询组并去重后放入ref
                    ref_select_data = select_sql("select ugroup from ObjectDB;")
                    if ref_select_data != False:
                        for each in ref_select_data:
                            object_list.append(each[0])
    
                        ref = list( set(object_list) )
                        ref_count = len(set(object_list))
    
                        # 返回系统部门
                        return_dict["status"] = "1"
                        return_dict["count"] = ref_count
                        return_dict["message"] = ref
                        return json.dumps(return_dict, ensure_ascii=False)
    
                    else:
                        return_dict["status"] = "0"
                        return_dict["message"] = "查询异常"
                        return json.dumps(return_dict, ensure_ascii=False)
    
                else:
                    return_dict["status"] = "0"
                    return_dict["count"] = "0"
                    return_dict["message"] = "查询异常"
                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict["status"] = "0"
                return_dict["message"] = "传入参数错误"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["message"] = "未知错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 查询用户组成员
    @app.route('/select_user_group',methods=['POST'])
    def select_user_group():
        return_dict = {'status': '0','count': 'none', 'group':'none', 'message': 'none'}
        if request.method == "POST":
            # 验证参数是否一致
            if len(request.get_data()) != 0 and len(request.values) == 2:
                key = request.values.get("token")
                ugroup = request.values.get("group")
                # 查询UserDB表内是否存在用户传入的key
                ref_data = select_sql("select user_key from UserDB where user_key='{}';".format(key))
                if len(ref_data) != 0 and ref_data != False:
                    # 定义组合模板
                    object_list = []
    
                    # 查询组并去重后放入ref
                    ref_select_data = select_sql("select uname,mobile,is_auth from ObjectDB where ugroup='{}';".format(ugroup))
                    if ref_select_data != False:
                        for each in ref_select_data:
                            object_list.append(each)
    
                        # 返回系统部门
                        return_dict["status"] = "1"
                        return_dict["count"] = len(object_list)
    
                        if len(object_list)==0:
                            return_dict["group"] = "none"
                        else:
                            return_dict["group"] = ugroup
    
                        return_dict["message"] = object_list
                        return json.dumps(return_dict, ensure_ascii=False)
    
                    else:
                        return_dict["status"] = "0"
                        return_dict["group"] = "none"
                        return_dict["count"] = "0"
                        return_dict["message"] = "查询异常"
                        return json.dumps(return_dict, ensure_ascii=False)
    
                else:
                    return_dict["status"] = "0"
                    return_dict["group"] = "none"
                    return_dict["count"] = "0"
                    return_dict["message"] = "查询异常"
                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict["status"] = "0"
                return_dict["group"] = "none"
                return_dict["count"] = "0"
                return_dict["message"] = "传入参数错误"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["group"] = "none"
        return_dict["count"] = "0"
        return_dict["message"] = "未知错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 修改用户组
    @app.route('/update_user_group',methods=['POST'])
    def update_user_group():
        return_dict = {'status': '0','message': 'none'}
        if request.method == "POST":
            # 验证参数是否一致
            if len(request.get_data()) != 0 and len(request.values) == 3:
                key = request.values.get("token")
                mobile = request.values.get("mobile")
                ugroup = request.values.get("group")
                # 查询UserDB表内是否存在用户传入的key
                ref_data = select_sql("select user_key from UserDB where user_key='{}';".format(key))
                if len(ref_data) != 0 and ref_data != False:
                    # 更新用户组
                    if update_sql("update ObjectDB set ugroup='{}' where user_key='{}' and mobile='{}'".format(ugroup,key,mobile)) != False:
                        # 返回系统部门
                        return_dict["status"] = "1"
                        return_dict["message"] = "已更新"
                        return json.dumps(return_dict, ensure_ascii=False)
                    else:
                        return_dict["status"] = "0"
                        return_dict["message"] = "查询异常"
                        return json.dumps(return_dict, ensure_ascii=False)
                else:
                    return_dict["status"] = "0"
                    return_dict["message"] = "查询异常"
                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict["status"] = "0"
                return_dict["message"] = "传入参数错误"
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict["status"] = "0"
        return_dict["message"] = "未知错误"
        return json.dumps(return_dict, ensure_ascii=False)
    
    # ----------------------------------------------------------------------------------------------------------------------
    # 经纬度返回相关接口
    # ----------------------------------------------------------------------------------------------------------------------
    
    # 返回经纬度
    @app.route('/select_lat',methods=['POST'])
    def select_lat():
        return_dict = {'status': '0','mobile': 'none', 'longitude': 'none','latitude': 'none'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0 and len(request.values) == 2:
                key = request.values.get("token")
                mobile = request.values.get("mobile")
    
                # 通过说明是联通的手机号
                if mobile.strip()[0:3] in TelList or mobile.strip()[0:5] in TelList:
                    # 验证是否登录
                    ref_UserDB_data = select_sql("select user_key from UserDB;")
                    for each in ref_UserDB_data:
                        if(each[0] == key):
    
                            # 判断是否为授权用户
                            select_auth = select_sql("select is_auth,uname from ObjectDB where mobile='{}'".format(mobile))
                            if select_auth[0][0] != "已授权用户":
                                return_dict = {'status': '0', 'message': '未授权用户,请授权'}
                                return json.dumps(return_dict, ensure_ascii=False)
                            else:
                                # 如果授权了,直接定位返回结果
                                return_dict['status'] = '1'
                                return_dict['mobile'] = mobile
                                return_dict['longitude'] = '172.43'
                                return_dict['latitude'] = '22.56'
    
                                # LocationCountDB 中的定位次数递增一次
                                ref_LocationCount = select_sql("select lat_count from LocationCountDB where mobile='{}';".format(mobile))
                                if ref_LocationCount != False:
                                    new_count = int(ref_LocationCount[0][0]) + 1
                                    update_sql("update LocationCountDB set lat_count={} where mobile='{}'".format(new_count,mobile))
    
                                return json.dumps(return_dict, ensure_ascii=False)
    
                else:
                    return_dict = {'status': '0', 'message': '请输入联通手机号'}
                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict = {'status': '0','message': '传入参数错误'}
                return json.dumps(return_dict, ensure_ascii=False)
    
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 查询总计调用次数与费率信息
    @app.route('/select_all_count',methods=['POST'])
    def select_all_count():
        return_dict = {'status': '0', 'lat_count': '0', 'lat_rate':'0.00', 'trajectory_count': '0', 'trajectory_rate':'0.00', 'enclosure_count':'0', 'enclosure_rate':'0.0'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0 and len(request.values) == 1:
                key = request.values.get("token")
    
                # 验证是否登录
                ref_UserDB_data = select_sql("select user_key from UserDB;")
                for each in ref_UserDB_data:
                    if (each[0] == key):
    
                        # 查询统计次数
                        ref_data = select_sql("select lat_count,lat_rate,trajectory_count,trajectory_rate,enclosure_count,enclosure_rate"
                                              " from LocationCountDB;")
    
                        lat_count = 0
                        trajectory_count = 0
                        enclosure_count = 0
    
                        # 累加计数器
                        for item in ref_data:
                            lat_count = lat_count + int(item[0])
                            trajectory_count = trajectory_count + int(item[2])
                            enclosure_count = enclosure_count + int(item[4])
    
                        return_dict['status'] = '1'
                        return_dict['lat_count'] = lat_count
                        return_dict['lat_rate'] = item[1]
                        return_dict['trajectory_count'] = trajectory_count
                        return_dict['trajectory_rate'] = item[3]
                        return_dict['enclosure_count'] = enclosure_count
                        return_dict['enclosure_rate'] = item[5]
                        return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict = {'status': '0','message': '传入参数错误'}
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict = {'status': '0', 'message': '未知错误'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 查询某手机号调用次数与费率
    @app.route('/select_mobile_count',methods=['POST'])
    def select_mobile_count():
        return_dict = {'status': '0', 'mobile': 'none', 'lat_count': '0', 'lat_rate':'0.00', 'trajectory_count': '0', 'trajectory_rate':'0.00', 'enclosure_count':'0', 'enclosure_rate':'0.0'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0 and len(request.values) == 2:
                key = request.values.get("token")
                mobile = request.values.get("mobile")
    
                # 通过说明是联通的手机号
                if mobile.strip()[0:3] in TelList or mobile.strip()[0:5] in TelList:
                    # 验证是否登录
                    ref_UserDB_data = select_sql("select user_key from UserDB;")
                    for each in ref_UserDB_data:
                        if (each[0] == key):
    
                            # 查询统计次数
                            ref_data = select_sql(
                                "select mobile,lat_count,lat_rate,trajectory_count,trajectory_rate,enclosure_count,enclosure_rate"
                                " from LocationCountDB where mobile='{}';".format(mobile))
    
                            return_dict['status'] = '1'
                            return_dict['mobile'] = ref_data[0][0]
                            return_dict['lat_count'] = ref_data[0][1]
                            return_dict['lat_rate'] = ref_data[0][2]
                            return_dict['trajectory_count'] = ref_data[0][3]
                            return_dict['trajectory_rate'] = ref_data[0][4]
                            return_dict['enclosure_count'] = ref_data[0][5]
                            return_dict['enclosure_rate'] = ref_data[0][6]
    
                            return json.dumps(return_dict, ensure_ascii=False)
    
                else:
                    return_dict = {'status': '0', 'message': '请输入联通手机号'}
                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict = {'status': '0', 'message': '传入参数错误'}
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict = {'status': '0', 'message': '未知错误'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    # ----------------------------------------------------------------------------------------------------------------------
    # 鉴权接口 相关接口
    # ----------------------------------------------------------------------------------------------------------------------
    
    # 查询用户权限状态
    @app.route('/select_auth_table',methods=['POST'])
    def select_auth_table():
        return_dict = {'status': '0','unauthorized': [],'authorized': []}
    
        if request.method == "POST":
            if len(request.get_data()) != 0 and len(request.values) == 1:
                key = request.values.get("token")
    
                # 验证是否登录
                ref_UserDB_data = select_sql("select user_key from UserDB;")
                for each in ref_UserDB_data:
                    if (each[0] == key):
                        # 查询统计次数
                        ref_data = select_sql("select mobile,is_auth from ObjectDB;")
    
                        not_auth = []
                        success_auth = []
    
                        for each in ref_data:
                            if each[1] == "未授权用户":
                                not_auth.append(each[0])
                            elif each[1] == "已授权用户":
                                success_auth.append(each[0])
    
                        return_dict['status'] = '1'
                        return_dict['unauthorized'] = not_auth
                        return_dict['authorized'] = success_auth
                        return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict = {'status': '0', 'message': '传入参数错误'}
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict = {'status': '0', 'message': '未知错误'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 发送验证码
    @app.route('/send_message',methods=['POST'])
    def send_message():
        return_dict = {'status': '0' ,'message':'none'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0 and len(request.values) == 2:
                key = request.values.get("token")
                mobile = request.values.get("mobile")
    
                # 验证是否登录
                ref_UserDB_data = select_sql("select user_key from UserDB;")
                for each in ref_UserDB_data:
                    if (each[0] == key):
    
                        # 查询是否授权
                        ref_data = select_sql("select mobile,is_auth from ObjectDB;")
                        for each in ref_data:
    
                            # 如果是未授权则提供验证
                            if each[1] == "未授权用户" and each[0] == mobile:
    
                                msg_code = "1234"
    
                                # 设置五分钟时间戳
                                timeStamp = int(time.time()) + 300
                                dateArray = datetime.datetime.fromtimestamp(timeStamp)
                                otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
    
                                message_code = "您本次登录的验证码是:{},有效时间:5分钟。验证码有效期至:{}".format(str(msg_code), otherStyleTime)
                                print(message_code)
    
                                insert_sql("insert into VerificationCodeDB(mobile,code,time_stamp) values('{}','{}',{})".format(mobile,msg_code,timeStamp))
    
                                return_dict = {'status': '1', 'message': '验证码已发送,请注意查收'}
                                return json.dumps(return_dict, ensure_ascii=False)
    
                            else:
                                return_dict = {'status': '0', 'message': '用户已授权过,无需重复授权'}
                                return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict = {'status': '0', 'message': '传入参数错误'}
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict = {'status': '0', 'message': '未知错误'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 授权接口
    @app.route('/set_auth',methods=['POST'])
    def set_auth():
        return_dict = {'status': '0','mobile':'none','message':'none'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0 and len(request.values) == 4:
                key = request.values.get("token")
                mobile = request.values.get("mobile")
                vf_code = request.values.get("code")
                flag = request.values.get("flag")
    
                if flag == "False":
                    return_dict = {'status': '0', 'message': '如需授权,请接受许可协议'}
                    return json.dumps(return_dict, ensure_ascii=False)
    
                elif flag == "True":
                    # 验证是否登录
                    ref_UserDB_data = select_sql("select user_key from UserDB;")
                    for each in ref_UserDB_data:
                        if (each[0] == key):
    
                            # 查询授权记录
                            ref_data = select_sql("select is_auth from ObjectDB where mobile='{}';".format(mobile))
    
                            # 如果是未授权则继续
                            if ref_data[0][0] == "未授权用户":
                                LocaltimeStamp = int(time.time())
                                try:
                                    # 查询当前用户验证码与时间戳
                                    ref_vfa = select_sql("select mobile,time_stamp from VerificationCodeDB where mobile='{}';".format(mobile))
                                    if ref_vfa != False:
    
                                        # 验证时间戳是否有效
                                        if LocaltimeStamp <= ref_vfa[0][1]:
    
                                            # 检查用户输入验证码是否有效,如果有效则将该用户设置为已授权用户.
                                            ref_vf_code = select_sql("select code from VerificationCodeDB where mobile='{}'".format(mobile))
    
                                            # 验证码正确
                                            if ref_vf_code[0][0] == vf_code:
    
                                                update_sql("update ObjectDB set is_auth='{}' where mobile='{}'".format("已授权用户",mobile))
    
                                                return_dict = {'status': '1', 'message': '授权完成'}
                                                return json.dumps(return_dict, ensure_ascii=False)
    
                                            # 验证码错误
                                            else:
                                                return_dict = {'status': '1', 'message': '验证码错误,授权失败'}
                                                return json.dumps(return_dict, ensure_ascii=False)
    
    
                                        elif LocaltimeStamp > ref_vfa[0][1]:
                                            delete_sql("delete from VerificationCodeDB where mobile='{}'".format(mobile))
                                            return_dict = {'status': '0', 'message': '验证码已过期,请重新获取验证码'}
                                            return json.dumps(return_dict, ensure_ascii=False)
    
                                except Exception:
                                    return_dict = {'status': '0', 'message': '请先发送验证码,然后在调用该接口,完成授权'}
                                    return json.dumps(return_dict, ensure_ascii=False)
                            else:
                                # 如果已授权过,删除表中的验证码字段
                                delete_sql("delete from VerificationCodeDB where mobile='{}'".format(mobile))
                                return_dict = {'status': '0', 'message': '用户已授权,无需继续授权'}
                                return json.dumps(return_dict, ensure_ascii=False)
            else:
                return_dict = {'status': '0', 'message': '传入参数错误'}
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict = {'status': '0', 'message': '未知错误'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    # 取消授权接口
    @app.route('/unset_auth',methods=['POST'])
    def unset_auth():
    
        return_dict = {'status': '0','mobile':'none','message':'none'}
    
        if request.method == "POST":
            if len(request.get_data()) != 0 and len(request.values) == 2:
                key = request.values.get("token")
                mobile = request.values.get("mobile")
    
                # 验证是否登录
                ref_UserDB_data = select_sql("select user_key from UserDB;")
    
                if ref_UserDB_data != False:
                    for each in ref_UserDB_data:
                        if (each[0] == key):
                            # 查询授权记录
                            ref_data = select_sql("select is_auth from ObjectDB where mobile='{}';".format(mobile))
    
                            # 未授权直接返回
                            if ref_data[0][0] == "未授权用户":
                                return_dict['status'] = '0'
                                return_dict['mobile'] = mobile
                                return_dict['message'] = '未授权用户,无需取消授权'
                                return json.dumps(return_dict, ensure_ascii=False)
    
                            # 已授权直接改为未授权
                            else:
                                if update_sql("update ObjectDB set is_auth='{}' where mobile='{}'".format("未授权用户",mobile)) != False:
                                    return_dict['status'] = '1'
                                    return_dict['mobile'] = mobile
                                    return_dict['message'] = '取消授权成功'
                                    return json.dumps(return_dict, ensure_ascii=False)
    
            else:
                return_dict = {'status': '0', 'message': '传入参数错误'}
                return json.dumps(return_dict, ensure_ascii=False)
    
        return_dict = {'status': '0', 'message': '未知错误'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    # ----------------------------------------------------------------------------------------------------------------------
    # 其他功能
    # ----------------------------------------------------------------------------------------------------------------------
    
    @app.route('/get_version',methods=['POST'])
    def get_version():
        return_dict = {'status': '1','version': '1.0.0', 'build': '2021-12-15 9:57'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    @app.errorhandler(404)
    def not_found(error):
        return_dict = {'status': '404', 'message': '页面没有找到'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    @app.errorhandler(405)
    def not_found(error):
        return_dict = {'status': '405', 'message': '服务器不提供请求类型'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    @app.errorhandler(500)
    def not_found(error):
        return_dict = {'status': '500', 'message': '传入参数有误,或存在不规范输入'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    @app.errorhandler(400)
    def not_found(error):
        return_dict = {'status': '400', 'message': 'Bad Request'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    @app.errorhandler(409)
    def not_found(error):
        return_dict = {'status': '409', 'message': 'Conflict'}
        return json.dumps(return_dict, ensure_ascii=False)
    
    if __name__ == '__main__':
        app.run(port=80,debug=False)
    
  • 相关阅读:
    c++多继承布局
    copy constructor
    default construction
    对象模型如何影响程序
    c++对象模型-对象模型
    在网站中引入特殊字体
    数组基础相关
    CSS3 transform3D
    即时效果--元素出现在页面特定区域时加载
    svg动态绘制饼状图
  • 原文地址:https://www.cnblogs.com/LyShark/p/15670617.html
Copyright © 2020-2023  润新知