Flask的使用

ppt

Flask的使用

flask 的参考文档

Flask的安装

pip install flask

http的方法

HTTP请求方法大全 - 常用参考表对照表 - 脚本之家在线工具 (jb51.net)
常用的方法有 get、post、put、delete

请求参数的处理

# 导入 Flask 的模块
from flask import Flask, request

# 创建一个 Flask 应用的程序实例
app = Flask(__name__)


# get 请求数据
@app.route("/courses", methods=["get"])
def get_course():
    name = request.args.get("name")
    print(name)
    return {"code": 0, "msg": f"get {name} success"}


# json 参数
@app.route("/add_courses", methods=["post"])
def add_course():
    print(request.json)
    return {"code": 0, "msg": "post success"}


# 表单请求
@app.route("/login", methods=["post"])
def user_login():
    name = request.form.get("name")
    psw = request.form.get("password")
    print(f"收到前端的登录参数 name 为 {name}, password 为 {psw}")
    if name == "root" and psw == "123456":
        return {"code": 0, "msg": "login success"}
    else:
        return {"code": 401, "msg": "login fail"}


user_list = [
    {"username": "zhangsan", "password": "123456"},
    {"username": "lisi", "password": "12345"},
    {"username": "wangwu", "password": "12346"},
    {"username": "zhaoliu", "password": "12456"},
    {"username": "niuqi", "password": "123476"},
]


@app.route("/new_login", methods=["post"])
def user_login_new():
    username = request.form.get("username")
    psw = request.form.get("password")
    print(f"收到前端的登录参数 username 为 {username}, password 为 {psw}")
    for user_obj in user_list:
        print(f'当前查询的用户是{user_obj.get("username")},密码是{user_obj.get("username")}')
        if username == user_obj.get("username") and psw == user_obj.get("password"):
            return {"code": 0, "msg": "success", "data": {"name": username, "password": psw}}
    return {"code": 401, "msg": "login fail"}


# 处理文件请求
@app.route("/file_req", methods=["post"])
def file_req():
    file_obj = request.files.get("file")
    print(file_obj)
    if file_obj is None:
        # 表示没有发送文件
        return {"code": 40001, "msg": "file not upload"}
    file_obj.save("test_file.png")
    return {"code": 0, "msg": "file upload success"}

使用蓝图注册

server.py

# # 导入 Flask 的模块
from flask import Flask

from user_route import user_bp

# 创建一个 Flask 应用的程序实例
app = Flask(__name__)

# 注册蓝图

app.register_blueprint(user_bp)

# 启动app程序

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True)

user_route.py


from flask import Blueprint

user_bp = Blueprint("用户管理", __name__, url_prefix="/user")


@user_bp.route("/")
def user():
    return "用户列表"


@user_bp.route("/login")
def user_login():
    return "登录成功"


@user_bp.route("/register")
def user_register():
    return "注册成功"


@user_bp.route("/delete")
def delete_user():
    return "删除成功"

restful 风格的接口代码

from flask import Flask, request

from data.data import courses

app = Flask(__name__)



@app.route("/courses", methods=["get"])
def get_course():
    # 获取课程
    course_id = request.args.get("course_id")
    print(course_id)
    datas = []
    if course_id:
        # 如果不为空,则返回对应的课程
        for course in courses:
            if int(course_id) == course.get("course_id"):
                datas.append(course)
    else:
        # 返回所有数据
        datas = courses
    return {"code": 0, "msg": "success", "data": datas}


@app.route("/courses", methods=["post"])
def post_course():
    # 添加课程
    course_data = request.json
    print(f"接收到的参数<====== {course_data}")
    course_id = int(course_data.get("course_id"))
    course_name = course_data.get("course_name")
    course_desc = course_data.get("course_desc")
    new_course = {
        "course_id": course_id,
        "course_name": course_name,
        "course_desc": course_desc,
    }
    # 判断是否有课程
    for course in courses:
        if course.get("course_id") == course_id:
            return {"code": 40001, "msg": "course id is exists"}

    courses.append(new_course)
    print(f"当前所有课程:{courses}")
    return {"code": 0, "msg": "success", "data": new_course}


@app.route("/courses", methods=["put"])
def put_course():
    # 修改课程
    course_data = request.json
    print(f"接收到的参数<====== {course_data}")
    course_id = int(course_data.get("course_id"))
    course_name = course_data.get("course_name")
    course_desc = course_data.get("course_desc")
    update_course = {
        "course_id": course_id,
        "course_name": course_name,
        "course_desc": course_desc,
    }
    for course in courses:
        if course.get("course_id") == course_id:
            # 先删除,再添加
            print(f"需要更新的课程:{course}")
            courses.remove(course)
            courses.append(update_course)
            print(f"当前所有课程:{courses}")
            return {"code": 0, "msg": "success", "data": update_course}
    return {"code": 40001, "msg": "course is not exists"}


@app.route("/courses", methods=["delete"])
def del_course():
    # 删除课程
    course_id = int(request.json.get("course_id"))
    for course in courses:
        if course.get("course_id") == course_id:
            print(f"删除课程:{course}")
            courses.remove(course)
            print(f"当前所有课程:{courses}")
            return {"code": 0, "msg": "success"}
    return {"code": 40001, "msg": "course is not exists"}


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5008, debug=True)

202041412102甘胜华
server.py:

from flask import Flask

from demo2 import usecase
from user_route import user

app = Flask(__name__)


if __name__ == "__main__":
    app.register_blueprint(usecase)
    app.register_blueprint(user)

    app.run(host="0.0.0.0", debug=True)

user_route.py:

from flask import Blueprint, request

user = Blueprint("用户管理", __name__, url_prefix="/user")

users = [
    {"name": "xiaohua", "password": "123"},
    {"name": "xiaomei", "password": "321"},
    {"name": "xiaodong", "password": "abc"}
]

#获取所有用户
@user.route("/", methods=["get"])
def get_user():
    return {"code": 200, "msg": "success", "data": users}


#用户登录
@user.route("/login", methods=["get"])
def user_login():
    name = request.args.get("name")
    password = request.args.get("password")

    for user in users:
        if name == user.get("name") and password == user.get("password"):
            return {"code": 200, "msg": "login success", "data": user}

    return {"code": 404, "msg": "login fail", "data": {}}


#注册用户
@user.route("/register", methods=["post"])
def user_register():
    name = request.form.get("name")
    password = request.form.get("password")
    new_user = {"name": name, "password": password}

    for user in users:
        if name == user.get("name"):
            return {"code": 400, "msg": "register fail,用户已存在", "data": {}}

    users.append(new_user)
    return {"code": 200, "msg": "register success", "data": new_user}


#删除用户
@user.route("/delete", methods=["delete"])
def delete_user():
    name = request.json.get("name")
    index = -1

    for user in users:
        index += 1
        if name == user.get("name"):
            del_user = users.pop(index)
            return {"code": 200, "msg": "delete success", "data": del_user}

    return {"code": 400, "msg": "delete fail,用户不存在", "data": {}}

image
image
image
image

202041412208 蒋冠岳
server.py

from flask import Flask
from user_route import user_bp
from case_route import case_bp

app = Flask(__name__)

app.register_blueprint(user_bp)
app.register_blueprint(case_bp)

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)

user_route.py

from flask import Blueprint, request
from data import users

user_bp = Blueprint("用户管理", __name__, url_prefix="/user")
userList = users


@user_bp.route("/", methods=["get"])
def user():
    return {"code": 0, "msg": "success", "data": userList}


@user_bp.route("/login",methods=["post"])
def user_login():
    user_data = request.json
    print(f"接收到的参数<======{user_data}")
    _id = int(user_data.get("id"))
    name = user_data.get("name")
    for user in userList:
        if int(user.get("id")) == _id and user.get("name") == name:
            return {"code": 0, "msg": "login success"}
    return {"code": 40002, "msg": "login fail"}


@user_bp.route("/register", methods=["post"])
def user_register():
    user_data = request.json
    print(f"接收到的参数<======{user_data}")
    _id = int(user_data.get("id"))
    name = user_data.get("name")
    desc = user_data.get("desc")
    new_case = {"id": _id, "name": name, "desc": desc}

    for user in userList:
        if int(user.get("id")) == _id or user.get("name") == name:
            return {"code": 40002, "msg": "data is exist"}
    userList.append(new_case)
    return {"code": 0, "msg": "success", "data": user_data}


@user_bp.route("/delete", methods=["get"])
def delete_user():
    _id = int(request.args.get("id"))
    print(f"id={_id}")
    user_list = [user for user in userList if user["id"] != _id ]
    print(f"user_list:{user_list}")
    if user_list == userList:
        return {"code": 40002, "msg": "delete is fail"}
    else:
        return {"code": 0, "msg": "delete is success"}

test_route_user.py

import requests


class TestUserRoute:

    def setup_class(self):
        self.base_url = "http://127.0.0.1:5000"

    def test_all(self):
        res = requests.get(f"{self.base_url}/user")
        print(res.json())
        assert res.json().get("code") == 0

    def test_login(self):
        data = {
            "id": 1,
            "name": "zs"
        }
        res = requests.post(f"{self.base_url}/user/login", json=data)
        print(res.json())
        assert res.json().get("code") == 0

    def test_register(self):
        data = {
            "id": 5,
            "name": "zl",
            "desc": "hello"
        }
        res = requests.post(f"{self.base_url}/user/register", json=data)
        print(res.json())
        assert res.json().get("code") == 0

    def test_delete(self):
        param = {"id": 1}
        res = requests.get(f"{self.base_url}/user/delete", params=param)
        print(res.json())
        assert res.json().get("code") == 0

姓名:胡福生 学号:202041404204
server.py

from flask import Flask
from user_route import user_bp

app = Flask(__name__)
app.register_blueprint(user_bp)

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True)

user_route.py

from flask import Blueprint,request

user_bp = Blueprint("用户管理", __name__, url_prefix="/user")

users=[
    {"username":"张三","password":"123"},
    {"username":"李四","password":"456"},
    {"username":"王五","password":"789"}
]

@user_bp.route("/", methods=['GET'])
def user():
    return {'code': 0, 'msg': 'success', 'data': users}

@user_bp.route("/login", methods=['POST'])
def user_login():
    user_data = request.json
    usernames = user_data.get("username")
    passwords = user_data.get("password")
    for user in users:
        if usernames == user.get("username") and passwords == user.get("password"):
            return {'code': 0, 'msg': 'login success', 'data': {'name': usernames, 'password': passwords}}
    return {'code': 401, 'msg': 'login false'}


@user_bp.route("/register", methods=['POST'])
def user_register():
    user_data = request.json
    usernames = user_data.get("username")
    passwords = user_data.get("password")
    for user in users:
        if usernames == user.get("username"):
            return {'code': 401, 'msg': 'register false', 'data': '用户已存在'}
    userss={"username": usernames,"password": passwords,}
    users.append(userss)
    return {'code': 0, 'msg': 'register success', 'data': {'user': userss}}

@user_bp.route("/delete", methods=['DELETE'])
def delete_user():
    user_data = request.json
    usernames = user_data.get("username")
    if usernames:
        for user in users:
            if usernames == user.get("username"):
                users.remove(user)
                return {'code': 0, 'msg': 'delete success', 'data': '用户已删除'}
    return {'code': 401, 'msg': 'delete false', 'data': '用户不存在'}








server.py

# # 导入 Flask 的模块
from flask import Flask

# 创建一个 Flask 应用的程序实例
from user_manage import users_bp

app = Flask(__name__)

# 注册蓝图

app.register_blueprint(users_bp)

# 启动app程序

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True)

user_manage.py

from flask import Blueprint, request

from user import users

users_bp = Blueprint("用户管理", __name__, url_prefix="/users")

userList = users


@users_bp.route("/", methods=["GET"])
def get_users():
    return {"code": 0, "msg": "success"}


@users_bp.route("/reg_log", methods=["GET"])
def login_users():
    name = request.form.get("name")
    psw = request.form.get("password")
    for user in userList:
        if name == user.get("name") and psw == user.get("password"):
            return {"code": 0, "msg": "success"}
    return {"code": 401, "msg": "fail"}


@users_bp.route("/reg_log", methods=["POST"])
def register_users():
    name = request.form.get("name")
    psw = request.form.get("password")
    reg_user = {"name": name, "password": psw}
    for user in userList:
        if name == user.get("name"):
            return {"code": 401, "msg": "fail"}
    userList.append(reg_user)
    return {"code": 0, "msg": "success"}


user.py

users = [
    {"name": "aaa", "password": "123"},
    {"name": "bbb", "password": "1234"},
    {"name": "ccc", "password": "12345"},
    {"name": "ddd", "password": "123456"}
]




202041404121 阮达
user_route

from flask import Blueprint, request

user = Blueprint("用户管理", __name__, url_prefix="/user")

users = [
    {"name": "ruan", "password": "202041404121"},
    {"name": "chen", "password": "123456"},
    {"name": "xiaodong", "password": "abc"}
]

#获取所有用户
@user.route("/", methods=["get"])
def get_user():
    return {"code": 200, "msg": "success", "data": users}


#用户登录
@user.route("/login", methods=["get"])
def user_login():
    name = request.args.get("name")
    password = request.args.get("password")

    for user in users:
        if name == user.get("name") and password == user.get("password"):
            return {"code": 200, "msg": "login success", "data": user}

    return {"code": 404, "msg": "login fail", "data": {}}


#注册用户
@user.route("/register", methods=["post"])
def user_register():
    name = request.form.get("name")
    password = request.form.get("password")
    new_user = {"name": name, "password": password}

    for user in users:
        if name == user.get("name"):
            return {"code": 400, "msg": "register fail,用户已存在", "data": {}}

    users.append(new_user)
    return {"code": 200, "msg": "register success", "data": new_user}


#删除用户
@user.route("/delete", methods=["delete"])
def delete_user():
    name = request.json.get("name")
    index = -1

    for user in users:
        index += 1
        if name == user.get("name"):
            del_user = users.pop(index)
            return {"code": 200, "msg": "delete success", "data": del_user}

    return {"code": 400, "msg": "delete fail,用户不存在", "data": {}}

server.py

from flask import Flask
from user_route import users

app = Flask(__name__)
app.register_blueprint(users)

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5001, debug=True)



姓名:李升升
学号:202041404115



image

学号:202041404110 姓名:胡鑫

server.py

from flask import Flask

from user_route import user_bp
from cases_route import cases_bp

app = Flask(__name__)

# 注册蓝图
app.register_blueprint(user_bp)

app.register_blueprint(cases_bp)

if __name__ == '__main__':
    app.run()

user_route.py

from flask import Blueprint,request
from data import users

user_bp = Blueprint("用户管理", __name__, url_prefix="/user")


@user_bp.route("/", methods=['get'])
def user():
    return {"code": 200, "msg": "success", "data": users}


@user_bp.route("/login", methods=['post'])
def user_login():
    username = request.json.get("username")
    password = request.json.get("password")
    for data in users:
        if username == data.get("name") and password == data.get("password"):
            return {"code": 200, "msg": "login success", "data": {data}}
    return {"code": 401, "msg": "not this user"}


@user_bp.route("/register", methods=['post'])
def user_register():
    username = request.json.get("username")
    password = request.json.get("password")
    for data in users:
        if username == data.get("name"):
            return {"code": 401, "msg": "username is exist"}
    user_data = {"username": username, "password": password}
    users.append(user_data)
    return {"code": 200, "msg": "register success"}


@user_bp.route("/delete", methods=['delete'])
def delete_user():
    username = request.json.get("username")
    for data in users:
        if username == data.get("name"):
            users.remove(data)
            return {"code": 200, "msg": "delete success"}
    return {"code": 401, "msg": "not this user"}


cases_route.py

from flask import Blueprint, request
from data import cases

cases_bp = Blueprint("参数管理", "__name__", url_prefix='/cases')


# 用例查询接口(GET请求)
@cases_bp.route('', methods=['GET'])
def get_test_cases():
    args = request.args
    _id = args.get("id")
    print(_id)
    datas = []
    for case in cases:
        print(case.get("id"))
        if int(_id) == int(case.get("id")):
            datas.append(case)
            return {"code": 200, "msg": "success", "data": datas}
    return {"code": 4001, "msg": "no this case"}


# 用例添加接口(POST请求)
@cases_bp.route('', methods=['POST'])
def add_test_case():
    data = request.json  # 获取POST请求中的JSON数据
    print(f"这是{data}")
    _id = int(data.get("id"))
    name = data.get("name")
    desc = data.get("desc")
    new_case = {"id": _id, "name": name, "desc": desc}
    for case in cases:
        if case.get("id") == _id or case.get("name") == name:
            return {"code": 40002, "msg": "case is exit"}
        cases.append(new_case)  # 将新用例添加到数据中
        return {"code": 200, "msg": "Test case added successfully", "data": new_case}


@cases_bp.route('', methods=['put'])
def put_test_cases():
    data = request.json
    _id = int(data.get("id"))
    name = data.get("name")
    desc = data.get("desc")
    for case in cases:
        if _id == case["id"]:
            case["name"] = name
            case["desc"] = desc
            return {"code": 200, "msg": "success", "data": case}
    return {"code": 4001, "msg": "no this case"}


# 用例删除接口(delete请求)
@cases_bp.route('', methods=['delete'])
def delete_test_cases():
    args = request.args
    _id = int(args.get("id"))
    print(_id)
    for case in cases:
        if int(_id) == case.get("id"):
            cases.remove(case)
            return {"code": 200, "msg": "success", "data": _id}
    return {"code": 4001, "msg": "no this case"}


data.py

cases = [
    {"id": 1, "name": "用例1", "desc": "用例描述1"},
    {"id": 2, "name": "用例2", "desc": "用例描述2"},
    {"id": 3, "name": "用例3", "desc": "用例描述3"}]

users = [
    {"username": "hxin1", "password": "123456"},
    {"username": "hxin2", "password": "1234567"},
    {"username": "hxin3", "password": "12345678"}
]


test_server.py

import requests


class TestServer:

    def setup_class(self):
        self.base_url = "http://127.0.0.1:5000"

    def test_cases_get(self):
        arg = {
            "id": 2
        }
        url = f"{self.base_url}/cases"
        res = requests.get(url, params=arg)
        print(res.json())

    def test_cases_post(self):
        case = {"id": 4, "name": "用例4", "desc": "用例描述4"}
        url = f"{self.base_url}/cases"
        res = requests.post(url, json=case)
        print(res.json())

    def test_cases_put(self):
        case = {"id": 2, "name": "用例4", "desc": "用例描述4"}
        url = f"{self.base_url}/cases"
        res = requests.post(url, json=case)
        print(res.json())

    def test_cases_delete(self):
        arg = {
            "id": 2
        }
        url = f"{self.base_url}/cases"
        res = requests.delete(url, params=arg)
        print(res.json())

    def test_users_get(self):
        url = f"{self.base_url}/user"
        res = requests.get(url)
        print(res.json())

    def test_user_login(self):
        url = f"{self.base_url}/user/login"
        user_data = {
            "username": "hxin1",
            "password": "123456"
        }
        res = requests.post(url, json=user_data)
        print(res.json())

    def test_user_register(self):
        url = f"{self.base_url}/user/register"
        user_data = {
            "username": "hxin4",
            "password": "123456789"
        }
        res = requests.post(url, json=user_data)
        print(res.json())

    def test_delete_user(self):
        url = f"{self.base_url}/user/delete"
        user_data = {
            "username": "hxin2",
        }
        res = requests.delete(url, json=user_data)
        print(res.json())


测试结果

202041404129 詹佳润
python
user_route.py
from flask import Blueprint, request

user = Blueprint("user", __name__, url_prefix="/users")

users = [
    {"name": "xiaohua", "password": "123"},
    {"name": "xiaomei", "password": "321"},
    {"name": "xiaodong", "password": "abc"}
]

# Get all users
@user.route("/", methods=["GET"])
def get_users():
    return {"code": 200, "msg": "success", "data": users}

# User login
@user.route("/login", methods=["POST"])
def login():
    data = request.get_json()
    name = data.get("name")
    password = data.get("password")

    for user in users:
        if name == user.get("name") and password == user.get("password"):
            return {"code": 200, "msg": "login success", "data": user}

    return {"code": 404, "msg": "login fail", "data": {}}

# Register a new user
@user.route("/", methods=["POST"])
def register_user():
    data = request.get_json()
    name = data.get("name")
    password = data.get("password")
    new_user = {"name": name, "password": password}

    for existing_user in users:
        if name == existing_user.get("name"):
            return {"code": 400, "msg": "register fail, user already exists", "data": {}}

    users.append(new_user)
    return {"code": 200, "msg": "register success", "data": new_user}

# Delete a user
@user.route("/", methods=["DELETE"])
def delete_user():
    data = request.get_json()
    name = data.get("name")

    for user in users:
        if name == user.get("name"):
            users.remove(user)
            return {"code": 200, "msg": "delete success", "data": user}

    return {"code": 400, "msg": "delete fail, user does not exist", "data": {}}

server.py
# # 导入 Flask 的模块
from flask import Flask

from blueprint.user_route import user

# 创建一个 Flask 应用的程序实例
app = Flask(__name__)

# 注册蓝图

app.register_blueprint(user)

# 启动app程序

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5066, debug=True)

79e5d17edbbd27d52db6b6f49cf5e84
2d38dc43b95d2d407e1c5990fe10a72



202041404214刘均豪
server.py

# 导入 Flask 的模块

from flask import Flask
from fifthday.cases_route import cases_bp
from user_route import user_bp

创建一个 Flask 应用的程序实例

app = Flask(name)

注册蓝图

app.register_blueprint(user_bp)
app.register_blueprint(cases_bp)

启动app程序

if name == ‘main’:
app.run(host=“0.0.0.0”, debug=True)

user_route.py
from flask import Blueprint,request
from data import users

user_bp = Blueprint(“用户管理”, name, url_prefix=“/user”)

@user_bp.route(“/”, methods=[‘get’])
def user():
return {“code”: 200, “msg”: “success”, “data”: users}

@user_bp.route(“/login”, methods=[‘post’])
def user_login():
username = request.json.get(“username”)
password = request.json.get(“password”)
for data in users:
if username == data.get(“name”) and password == data.get(“password”):
return {“code”: 200, “msg”: “login success”, “data”: {data}}
return {“code”: 401, “msg”: “not this user”}

@user_bp.route(“/register”, methods=[‘post’])
def user_register():
username = request.json.get(“username”)
password = request.json.get(“password”)
for data in users:
if username == data.get(“name”):
return {“code”: 401, “msg”: “username is exist”}
user_data = {“username”: username, “password”: password}
users.append(user_data)
return {“code”: 200, “msg”: “register success”}

@user_bp.route(“/delete”, methods=[‘delete’])
def delete_user():
username = request.json.get(“username”)
for data in users:
if username == data.get(“name”):
users.remove(data)
return {“code”: 200, “msg”: “delete success”}
return {“code”: 401, “msg”: “not this user”}

cases_route.py
from flask import Blueprint, request
from data import cases

cases_bp = Blueprint(“参数管理”, “name”, url_prefix=‘/cases’)

用例查询接口(GET请求)

@cases_bp.route(‘’, methods=[‘GET’])
def get_test_cases():
args = request.args
_id = args.get(“id”)
print(_id)
datas =
for case in cases:
print(case.get(“id”))
if int(_id) == int(case.get(“id”)):
datas.append(case)
return {“code”: 200, “msg”: “success”, “data”: datas}
return {“code”: 4001, “msg”: “no this case”}

用例添加接口(POST请求)

@cases_bp.route(‘’, methods=[‘POST’])
def add_test_case():
data = request.json # 获取POST请求中的JSON数据
print(f"这是{data}")
_id = int(data.get(“id”))
name = data.get(“name”)
desc = data.get(“desc”)
new_case = {“id”: _id, “name”: name, “desc”: desc}
for case in cases:
if case.get(“id”) == _id or case.get(“name”) == name:
return {“code”: 40002, “msg”: “case is exit”}
cases.append(new_case) # 将新用例添加到数据中
return {“code”: 200, “msg”: “Test case added successfully”, “data”: new_case}

@cases_bp.route(‘’, methods=[‘put’])
def put_test_cases():
data = request.json
_id = int(data.get(“id”))
name = data.get(“name”)
desc = data.get(“desc”)
for case in cases:
if _id == case[“id”]:
case[“name”] = name
case[“desc”] = desc
return {“code”: 200, “msg”: “success”, “data”: case}
return {“code”: 4001, “msg”: “no this case”}

用例删除接口(delete请求)

@cases_bp.route(‘’, methods=[‘delete’])
def delete_test_cases():
args = request.args
_id = int(args.get(“id”))
print(_id)
for case in cases:
if int(_id) == case.get(“id”):
cases.remove(case)
return {“code”: 200, “msg”: “success”, “data”: _id}
return {“code”: 4001, “msg”: “no this case”}

data.py
cases = [
{ “id”: 1,
“name”: “用例1”,
“desc”: “用例描述1”
},
{ “id”: 2,
“name”: “用例2”,
“desc”: “用例描述2”
},
{ “id”: 3,
“name”: “用例3”,
“desc”: “用例描述3”
}
]

test_data.py
import requests

class TestServer:

def setup_class(self):
    self.base_url = "http://127.0.0.1:5000"

def test_cases_get(self):
    arg = {
        "id": 2
    }
    url = f"{self.base_url}/cases"
    res = requests.get(url, params=arg)
    print(res.json())

def test_cases_post(self):
    case = {"id": 4, "name": "用例4", "desc": "用例描述4"}
    url = f"{self.base_url}/cases"
    res = requests.post(url, json=case)
    print(res.json())

def test_cases_put(self):
    case = {"id": 2, "name": "用例4", "desc": "用例描述4"}
    url = f"{self.base_url}/cases"
    res = requests.post(url, json=case)
    print(res.json())

def test_cases_delete(self):
    arg = {
        "id": 2
    }
    url = f"{self.base_url}/cases"
    res = requests.delete(url, params=arg)
    print(res.json())

def test_users_get(self):
    url = f"{self.base_url}/user"
    res = requests.get(url)
    print(res.json())

def test_user_login(self):
    url = f"{self.base_url}/user/login"
    user_data = {
        "username": "ljh",
        "password": "123456"
    }
    res = requests.post(url, json=user_data)
    print(res.json())

def test_user_register(self):
    url = f"{self.base_url}/user/register"
    user_data = {
        "username": "ljh",
        "password": "123456789"
    }
    res = requests.post(url, json=user_data)
    print(res.json())

def test_delete_user(self):
    url = f"{self.base_url}/user/delete"
    user_data = {
        "username": "ljh",
    }
    res = requests.delete(url, json=user_data)
    print(res.json())

202041412221 阮凯林

app_server.py

from flask import Flask
from case_server import case_server
from user_server import user_server


app_server = Flask(__name__)


if __name__ == '__main__':
    app_server.register_blueprint(case_server)
    app_server.register_blueprint(user_server)
    app_server.run()

case_server.py

from flask import Blueprint, request


case_server = Blueprint("Case", __name__, url_prefix="/case")

case_list = [
    {"id": 1, "name": "用例1", "desc": "用例描述1"},
    {"id": 2, "name": "用例2", "desc": "用例描述2"},
    {"id": 3, "name": "用例3", "desc": "用例描述3"}
]


@case_server.route("/get", methods=["get"])
def get():
    case_id = request.args.get("id")
    if case_id is None:
        return {"code": 200, "msg": "success", "data": case_list}
    else:
        case_id = int(case_id)
        for case in case_list:
            if case_id == case.get("id"):
                return {"code": 200, "msg": "success", "data": case}
        return {"code": 404, "msg": "not found", "data": None}


@case_server.route("/add", methods=["post"])
def add():
    request_body = request.json
    add_case = {
        "id": request_body.get("id"),
        "name": request_body.get("name"),
        "desc": request_body.get("desc")
    }
    if add_case.get("id") is None or add_case.get("name") is None or add_case.get("desc") is None:
        return {"code": 403, "msg": "param is error", "data": None}
    else:
        for case in case_list:
            if add_case.get("id") == case.get("id") or add_case.get("name") == case.get("name"):
                return {"code": 403, "msg": "case is exist", "data": None}
        case_list.append(add_case)
        return {"code": 200, "msg": "success", "data": None}

user_server.py

from flask import Blueprint, request


user_server = Blueprint("User", __name__, url_prefix="/user")

user_list = [
    {"username": "zhangsan", "password": "123"},
    {"username": "lisi", "password": "456"},
    {"username": "wangwu", "password": "789"},
]


@user_server.route("/login", methods=["post"])
def login():
    request_body = request.json
    login_user = {
        "username": request_body.get("username"),
        "password": request_body.get("password")
    }
    for user in user_list:
        if login_user.get("username") == user.get("username") and login_user.get("password") == user.get("password"):
            return {"code": 200, "msg": "login success"}
    return {"code": 401, "msg": "account or password error"}


@user_server.route("/register", methods=["post"])
def register():
    request_body = request.json
    register_user = {
        "username": request_body.get("username"),
        "password": request_body.get("password")
    }
    for user in user_list:
        if register_user.get("username") == user.get("username"):
            return {"code": 401, "msg": "username is exist"}
    user_list.append(register_user)
    return {"code": 200, "msg": "register success"}

from flask import Flask
from case_server import case_server
from user_server import user_server

app_server = Flask(name)

if name == ‘main’:
app_server.register_blueprint(case_server)
app_server.register_blueprint(user_server)
app_server.run()
case_server.py

from flask import Blueprint, request

case_server = Blueprint(“Case”, name, url_prefix=“/case”)

case_list = [
{“id”: 1, “name”: “用例1”, “desc”: “用例描述1”},
{“id”: 2, “name”: “用例2”, “desc”: “用例描述2”},
{“id”: 3, “name”: “用例3”, “desc”: “用例描述3”}
]
@case_server.route(“/get”, methods=[“get”])
def get():
case_id = request.args.get(“id”)
if case_id is None:
return {“code”: 200, “msg”: “success”, “data”: case_list}
else:
case_id = int(case_id)
for case in case_list:
if case_id == case.get(“id”):
return {“code”: 200, “msg”: “success”, “data”: case}
return {“code”: 404, “msg”: “not found”, “data”: None}
@case_server.route(“/add”, methods=[“post”])
def add():
request_body = request.json
add_case = {
“id”: request_body.get(“id”),
“name”: request_body.get(“name”),
“desc”: request_body.get(“desc”)
}
if add_case.get(“id”) is None or add_case.get(“name”) is None or add_case.get(“desc”) is None:
return {“code”: 403, “msg”: “param is error”, “data”: None}
else:
for case in case_list:
if add_case.get(“id”) == case.get(“id”) or add_case.get(“name”) == case.get(“name”):
return {“code”: 403, “msg”: “case is exist”, “data”: None}
case_list.append(add_case)
return {“code”: 200, “msg”: “success”, “data”: None

user_server.py

from flask import Blueprint, request
user_server = Blueprint(“User”, name, url_prefix=“/user”)

user_list = [
{“username”: “zhangsan”, “password”: “123”},
{“username”: “lisi”, “password”: “456”},
{“username”: “wangwu”, “password”: “789”},
]
@user_server.route(“/login”, methods=[“post”])
def login():
request_body = request.json
login_user = {
“username”: request_body.get(“username”),
“password”: request_body.get(“password”)
}
for user in user_list:
if login_user.get(“username”) == user.get(“username”) and login_user.get(“password”) == user.get(“password”):
return {“code”: 200, “msg”: “login success”}
return {“code”: 401, “msg”: “account or password error”}
@user_server.route(“/register”, methods=[“post”])
def register():
request_body = request.json
register_user = {
“username”: request_body.get(“username”),
“password”: request_body.get(“password”)
}
for user in user_list:
if register_user.get(“username”) == user.get(“username”):
return {“code”: 401, “msg”: “username is exist”}
user_list.append(register_user)
return {“code”: 200, “msg”: “register success”}

202041404101
曹岚

202041404213 刘建升



聂振枫 202041404216

mini_web_server.py
from flask import Flask, render_template
from flask import request

app = Flask(name)

login_form = [{“username”:“admin”,“password”:“123456”},
{“username”:“admin1”,“password”:“1234567”},
{“username”:“admin2”,“password”:“12345678”}]

@app.route(“/”)
def hello_world():
return “

hello world

@app.route(“/list”)
def list_case():
return “

返回列表

@app.route(“/html”)
def get_html():
return render_template(“upload.html”)

@app.route(“/login”,methods=[“POST”])
def login():
username = request.form.get(“username”)
password = request.form.get(“password”)
print(username)
print(password)
for login_forms in login_form:
if username == login_forms.get(“username”):
if password == login_forms.get(“password”):
return {“code”:0,“msg”:“login success”,“data”:{“username”:username,“password”:password}}
return {“code”:1,“msg”:“the password is wrong”}

return {"code":1, "msg":"user not found"}

@app.route(“/register”,methods=[“POST”])
def register():
username = request.form.get(“username”)
password = request.form.get(“password”)
print(username)
print(password)
for loginf in login_form:
if username == loginf.get(“username”):
return {“code”:1, “msg”:“user exist”}
login_form.append({“username”:username, “password”:password})
return {“code”:0, “msg”:“register success”}

@app.route(“/list1”,methods=[“GET”])
def list():
return {“code”:1, “msg”:login_form}

if name == ‘main’:
app.run()

结果:





姓名:翁开锋,学号:202041412223
server.py

# # 导入 Flask 的模块
from flask import Flask

from user_route import user_bp

# 创建一个 Flask 应用的程序实例
app = Flask(__name__)

# 注册蓝图

app.register_blueprint(user_bp)

# 启动app程序

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True)

user_route.py

from flask import Blueprint, request

user_bp = Blueprint("用户管理", __name__, url_prefix="/user")

list_login = [
    {
        "name": "admin",
        "password": "12345"
    }, {
        "name": "me",
        "password": "123456"
    }, {
        "name": "username",
        "password": "56789"
    }]


@user_bp.route("/")
def user():
    return {
        "code": 0,
        "msg": "success",
        "data": list_login
    }


@user_bp.route("/login", methods=["post"])
def user_login():
    name = request.form.get("name")
    password = request.form.get("password")
    print(f"{name},{password}")
    for list1 in list_login:
        if list1["name"] == name and list1["password"] == password:
            return {
                "code": 0,
                "msg": "登录成功",
            }

    return {
        "code": 201,
        "msg": "登录失败",
    }


@user_bp.route("/register", methods=["post"])
def user_register():
    name = request.form.get("name")
    password = request.form.get("password")
    for list1 in list_login:
        if list1["name"] == name and list1["password"] == password:
            return {
                "code": 201,
                "msg": "用户已经存在",
            }
    list_login.append({
        "name": name,
        "password": password
    })
    return {
        "code": 0,
        "msg": "注册成功",
    }


@user_bp.route("/delete", methods=["post"])
def delete_user():
    name = request.form.get("name")
    password = request.form.get("password")
    print(f"{name}and {password}")
    for list1 in list_login:
        if list1["name"] == name and list1["password"] == password:
            list_login.remove(list1)
            return {
                "code": 0,
                "msg": "删除成功",
            }
    return {
        "code": 201,
        "msg": "该用户不存在",
    }

test_user_route.py

import requests


class TestUserRoute:
    def setup_class(self):
        self.base_url = "http://127.0.0.1:5000"

    def test_all(self):
        res = requests.get(f"{self.base_url}/user")
        print(res.json())
        assert res.json().get("code") == 0

    def test_login(self):
        data = {
            "name": "admin",
            "password": "12345"
        }
        res = requests.post(f"{self.base_url}/user/login", data=data)
        print(res.json())
        assert res.json().get("code") == 0

    def test_register(self):
        data = {
            "name": "翁开锋",
            "password": "202041412223"
        }
        res = requests.post(f"{self.base_url}/user/register", json=data)
        print(res.json())
        assert res.json().get("code") == 0

    def test_delete(self):
        param = {
            "name": "username",
            "password": "56789"
        }
        res = requests.post(f"{self.base_url}/user/delete", data=param)
        print(res.json())
        assert res.json().get("code") == 0


image

server.py

# # 导入 Flask 的模块
from flask import Flask

from user_route import user_bp

# 创建一个 Flask 应用的程序实例
app = Flask(__name__)

# 注册蓝图

app.register_blueprint(user_bp)

# 启动app程序

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True,port=8848)

test_user_route.py

import requests


class TestUserRoute:
    def setup_class(self):
        self.base_url = "http://127.0.0.1:8848"

    def test_all(self):
        res = requests.get(f"{self.base_url}/user")
        assert res.json().get("code") == 200

    def test_login(self):
        data = {
            "name": "admin",
            "password": "admin"
        }
        res = requests.post(f"{self.base_url}/user/login", data=data)
        assert res.json().get("code") == 200

    def test_register(self):
        data = {
            "name": "刘尚杰",
            "password": "202041412216"
        }
        res = requests.post(f"{self.base_url}/user/register", json=data)
        assert res.json().get("code") == 200

    def test_delete(self):
        param = {
            "name": "test_user",
            "password": "test_password"
        }
        res = requests.post(f"{self.base_url}/user/delete", data=param)
        assert res.json().get("code") == 201

user_route.py

from flask import Blueprint, request

user_bp = Blueprint("用户管理", __name__, url_prefix="/")

list_login = [
    {
        "name": "admin",
        "password": "admin"
    }, {
        "name": "刘尚杰",
        "password": "202041412216"
    }, {
        "name": "test_name",
        "password": "test_password"
    }]


@user_bp.route("/user")
def user():
    return {
        "code": 200,
        "msg": "success",
        "data": list_login
    }


@user_bp.route("/user/login", methods=["post"])
def user_login():
    name = request.form.get("name")
    password = request.form.get("password")
    print(f"{name},{password}")
    for list1 in list_login:
        if list1["name"] == name and list1["password"] == password:
            return {
                "code": 200,
                "msg": "login success",
            }

    return {
        "code": 400,
        "msg": "login fail",
    }


@user_bp.route("/user/register", methods=["post"])
def user_register():
    name = request.form.get("name")
    password = request.form.get("password")
    for list1 in list_login:
        if list1["name"] == name:
            return {
                "code": 201,
                "msg": "user has existed",
            }
    list_login.append({
        "name": name,
        "password": password
    })
    return {
        "code": 200,
        "msg": "register success",
    }


@user_bp.route("/user/delete", methods=["post"])
def delete_user():
    name = request.form.get("name")
    password = request.form.get("password")
    print(f"{name}and {password}")
    for list1 in list_login:
        if list1["name"] == name:
            list_login.remove(list1)
            return {
                "code": 202,
                "msg": "delete success",
            }
    return {
        "code": 201,
        "msg": "user has not existed",
    }

202041412218 倪灿烽
server.py

# 导入Flask 的模块
from flask import Flask

from user_route import user_bp

# 创建一个Flask 应用的程序实例
app = Flask(__name__)

# 注册蓝图
app.register_blueprint(user_bp)

# 启动app程序

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True)

user_route.py

from typing import List, Union, Dict

from flask import Blueprint, request

user_bp = Blueprint("用户管理", __name__, url_prefix="/user")

list_login = [
    {
        "name": "root",
        "password": "123456"
    },
    {
        "name": "b",
        "password": "1234"
    },
    {
        "name": "c",
        "password": "1235"
    }
]


@user_bp.route("/", methods=["get"])
def user():
    return {
        "code": 0,
        "msg": "success",
        "data": list_login
    }


@user_bp.route("/login", methods=["post"])
def user_login():
    name = request.form.get("name")
    password = request.form.get("password")
    print(f"{name},{password}")
    for lists in list_login:
        if name == lists["name"] and password == lists["password"]:
            return {"code": 0, "msg": "success", "data": {"name": name, "password": password}}
        else:
            return {"code": 401, "msg": "fail"}
    return "登录成功"


@user_bp.route("/register", methods=["put"])
def user_register():
    name = request.form.get("name")
    password = request.form.get("password")
    for list1 in list_login:
        if list1["name"] == name and list1["password"] == password:
            return {"code": 201, "msg": "user is in list"}
    list_login.append({"name": name, "password": password})
    return {"code": 0, "msg": "注册成功"}


@user_bp.route("/delete", methods=["delete"])
def delete_user():
    name = request.form.get("name")
    password = request.form.get("password")
    print(f"{name}and {password}")
    for list1 in list_login:
        if list1["name"] == name and list1["password"] == password:
            list_login.remove(list1)
            return {
                "code": 0,
                "msg": "删除成功",
            }
    return {
        "code": 201,
        "msg": "该用户不存在",
    }

test_user_route.py

import requests


class TestUserRoute:
    def setup_class(self):
        self.base_url = "http://127.0.0.1:5000"

    def test_all(self):
        res = requests.get(f"{self.base_url}/user")
        print(res.json())
        assert res.json().get("code") == 0

    def test_login(self):
        data = {
            "name": "root",
            "password": "123456"
        }
        res = requests.post(f"{self.base_url}/user/login", data=data)
        print(res.json())
        assert res.json().get("code") == 0

    def test_register(self):
        data = {
            "name": "ncf",
            "password": "202041412218"
        }
        res = requests.put(f"{self.base_url}/user/register", json=data)
        print(res.json())
        assert res.json().get("code") == 0

    def test_delete(self):
        param = {
            "name": "b",
            "password": "1234"
        }
        res = requests.delete(f"{self.base_url}/user/delete", data=param)
        print(res.json())
        assert res.json().get("code") == 0

202041404211 李范佑

server.py

from flask import Flask
from user_route import user_bp

app = Flask(__name__)
app.register_blueprint(user_bp)

if __name__ == '__main__':
    app.run(host="0.0.0.0", debug=True)

user_rpute

from flask import Blueprint,request

user_bp = Blueprint("用户管理", __name__, url_prefix="/user")

users=[
    {"username":"张三","password":"123"},
    {"username":"李四","password":"456"},
    {"username":"王五","password":"789"}
]

@user_bp.route("/", methods=['GET'])
def user():
    return {'code': 0, 'msg': 'success', 'data': users}

@user_bp.route("/login", methods=['POST'])
def user_login():
    user_data = request.json
    usernames = user_data.get("username")
    passwords = user_data.get("password")
    for user in users:
        if usernames == user.get("username") and passwords == user.get("password"):
            return {'code': 0, 'msg': 'login success', 'data': {'name': usernames, 'password': passwords}}
    return {'code': 401, 'msg': 'login false'}


@user_bp.route("/register", methods=['POST'])
def user_register():
    user_data = request.json
    usernames = user_data.get("username")
    passwords = user_data.get("password")
    for user in users:
        if usernames == user.get("username"):
            return {'code': 401, 'msg': 'register false', 'data': '用户已存在'}
    userss={"username": usernames,"password": passwords,}
    users.append(userss)
    return {'code': 0, 'msg': 'register success', 'data': {'user': userss}}

@user_bp.route("/delete", methods=['DELETE'])
def delete_user():
    user_data = request.json
    usernames = user_data.get("username")
    if usernames:
        for user in users:
            if usernames == user.get("username"):
                users.remove(user)
                return {'code': 0, 'msg': 'delete success', 'data': '用户已删除'}
    return {'code': 401, 'msg': 'delete false', 'data': '用户不存在'}

202041404203 段杰东
from flask import Blueprint, request

users_bp = Blueprint(“用户管理”, name, url_prefix=“/users”)
users = [
{“name”: “a”, “password”: “123”},
{“name”: “b”, “password”: “1234”},
{“name”: “c”, “password”: “12345”},
{“name”: “d”, “password”: “123456”}
]

userList = users

@users_bp.route(“/”, methods=[“GET”])
def get_users():
return {“code”: 0, “msg”: “success”}

@users_bp.route(“/login”, methods=[“GET”])
def login_users():
name = request.form.get(“name”)
psw = request.form.get(“password”)
for user in userList:
if name == user.get(“name”) and psw == user.get(“password”):
return {“code”: 0, “msg”: “success”}
return {“code”: 401, “msg”: “fail”}

@users_bp.route(“/zhuce”, methods=[“POST”])
def register_users():
name = request.form.get(“name”)
psw = request.form.get(“password”)
reg_user = {“name”: name, “password”: psw}
for user in userList:
if name == user.get(“name”):
return {“code”: 401, “msg”: “fail”}
userList.append(reg_user)
return {“code”: 0, “msg”: “success”}
image
image
image
image