Flask操作数据库

姓名:王冠毅 学号:202041412222

orm_connect.py

from mysqlx import Session
from sqlalchemy import *
from sqlalchemy.orm import declarative_base, sessionmaker

Base = declarative_base()
# 创建引擎,通过这个引擎,可以创建数据库连接,比如:mysql,sqlite...
# engine = create_engine("sqlite:///test.db")
# ## windows 时,有可能会报错,需要加上这个参数
engine =create_engine('sqlite:///test.db',connect_args={'check_same_thread': False})
DBSession = sessionmaker(bind=engine)
db_session: Session = DBSession()
class User(Base):
    __tablename__ = "user"
    # 属性 -- 对应 -- 表的列属性
    id = Column(Integer, primary_key=True)
    username = Column(String(80), nullable=False, unique=False)
    password = Column(String(120))

    def __repr__(self):
        return '<User %r>' % self.username


class TestCase(Base):
    __tablename__ = "testcase"
    id = Column(Integer, primary_key=True)
    name = Column(String(100), nullable=False)
    desc = Column(String(100))


if __name__ == '__main__':
    # 创建表,创建存储在元素数据中所有的表
    # Base.metadata.create_all(engine)
    # 删除表
    # Base.metadata.drop_all(engine)
    instance = User(username="yuki", password=1234)
    db_session.add(instance)
    # id = instance.id
    res = db_session.query(User).all()
    # 遍历数据,得到想要的字段
    for rs in res:
        print(rs.username, rs.password)
    db_session.commit()
    db_session.close()

user_route.py

from flask import Blueprint, request
from orm_connect import db_session,User

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



@user_bp.route("/", methods=["get"])
def user():
    users=db_session.query(User).all()
    if users:
        return {
            "code": 200,
            "msg": "success",
            "data": [{
                "id": user.id,
                "username": user.username,
                "password": user.password,

            }
                for user in users
            ]
        }

    return {"code": 404, "msg": "users is not exist", "data": {}}


@user_bp.route("/login",methods=["get"])
def user_login():
    user_data = request.json
    data = request.json
    # 使用请求的数据构建用户的对象
    user = User(**data)

    user_result_data = db_session.query(User).filter_by(username=user.username).first()

    if not user_result_data:
        # 没查到用户
        return {"code": 405, "msg": "用户不存在"}
    if user_result_data.password!=user.password:
        return {"code": 401, "msg": "用户名或密码错误"}
    return {"code": 0, "msg": "登录成功"}


@user_bp.route("/register", methods=["post"])
def user_register():
    user_data = request.json
    user = User(**user_data)

    if db_session.query(User).filter_by(username=user.username).first():
        return {"code": 400, "msg": "用户名已存在"}

    db_session.add(user)
    db_session.commit()
    user_id = user.id
    db_session.close()
    if user_id:
        return {"code": 200, "msg": "注册成功"}
    else:
        return {"code": 400, "msg": "注册失败"}

@user_bp.route("/delete", methods=["post"])
def delete_user():
    user_id = request.json.get("id")
    user = db_session.query(User).filter_by(id=user_id).first()

    if user:
        db_session.delete(user)
        db_session.commit()
        db_session.close()
        return {"code": 200, "msg": "删除成功", "data": user_id}

    return {"code": 404, "msg": "用户不存在", "data": {}}


202041404217 万晋江
user_route.py

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

# from data.data import cases
from orm_connect import db_session, TestCase, User

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

@user.route("/register", methods = ["POST"])
def user_register():
    register_data = request.json
    username = register_data.get("username")
    password = register_data.get("password")
    create_time = datetime.datetime.now()
    instance = User(username=username,password=password,create_time=create_time)

    if db_session.query(User).filter_by(username = username).first():
        return {"code": 40002, "msg": "user is exists"}
    db_session.add(instance)
    db_session.commit()
    _id = instance.id
    db_session.close()
    if _id:
        return {"code": 0, "msg": "add success"}
    else:
        return {"code": 40001, "msg": "add failed"}

@user.route("/login", methods = ["POST"])
def user_login():
    """
    登录功能,获取用户提交的数据,进行校验,校验成功则返回登录成功
    :return:
    """
    # return "登录成功"
    # 获取请求体
    data = request.json
    # 使用请求的数据构建用户的对象
    user = User(**data)  # 等价于 User(username=data.get("username"),password=data.get("password"))
    # 查询用户是否存在,存在则进行后续的步骤
    user_result_data = db_session.query(User).filter_by(username=user.username).first()
    # user_result = User()
    if not user_result_data:
        # 没查到用户
        return {"code": 405, "msg": "user is not register"}
    if not user_result_data.check_hash_password(data.get("password")):
        return {"code": 401, "msg": "user or password is wrong"}
    return {"code": 0, "msg": "user login success"}

@user.route("/list", methods = ["GET"])
def user_list():
    users = db_session.query(User).all()
    if users:
        return {"code":0, "msg":"get all message success",
                "data":[{"id":user.id, "username":user.username, "password":user.password, "create_time":user.create_time} for user in users]
                }
    return {"code":200, "msg":"user massage not found"}

test_user_route.py

import requests


class TestUserRoute:

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

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

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

    def test_register(self):
        data = {
            "username": "asfgfg6",
            "password": "123456"
        }
        res = requests.post(f"{self.base_url}/register", json=data)
        print(res.json())
        assert res.json().get("code") == 0

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

谢世龙 202041412121

from flask import Blueprint, request

from orm_study.orm_connect import User, db_session

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

#登录功能,获取用户提交的数据,进行密码校验,校验成功则返回登录成功
@user_bp.route(“/login”, methods=[“post”])
def user_login():
# 获取请求体
data = request.json
# 使用请求的数据构建用户的对象
user = User(**data) # 等价于 User(username=data.get(“username”),password=data.get(“password”))
# 查询用户是否存在,存在则进行后续的步骤
user_result_data = db_session.query(User).filter_by(username=user.username).first()

if not user_result_data:
    # 没查到用户
    return {"code": 405, "msg": "user is not register"}
if not user_result_data.check_hash_password(data.get("password")):
    return {"code": 401, "msg": "user or password is wrong"}
return {"code": 0, "msg": "user login success"}

#注册用户,对密码进行加密
@user_bp.route(“/register”, methods=[“post”])
def user_register():
user_data = request.json
# username = user_data.get(“username”)
# password = user_data.get(“password”)
# user = User(name=name, password=password)
user = User(**user_data)

if db_session.query(User).filter_by(username=user.username).first():
    return {"code": 400, "msg": "user is exist"}

db_session.add(user)
db_session.commit()
user_id = user.id
db_session.close()
if user_id:
    return {"code": 200, "msg": "register success"}
else:
    return {"code": 400, "msg": "register fail"}

#获取所有用户
@user_bp.route(“/”, methods=[“get”])
def get_all_user():
users = db_session.query(User).all()
if users:
return {
“code”: 200,
“msg”: “success”,
“data”: [{
“id”: user.id,
“username”: user.username,
“password”: user.password,
“create_time”: user.create_time
}
for user in users
]
}

return {"code": 404, "msg": "users is not exist", "data": {}}

#删除用户
@user_bp.route(“/delete”, methods=[“delete”])
def delete_user():
user_id = request.json.get(“id”)
user = db_session.query(User).filter_by(id=user_id).first()

if user:
    db_session.delete(user)
    db_session.commit()
    db_session.close()
    return {"code": 200, "msg": "delete success", "data": user.as_dict()}

return {"code": 404, "msg": "user is not exist", "data": {}}

202041413221 叶磊
case_route.py

from flask import Blueprint, request

from orm_study.orm_connect import User, db_session

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


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


@user_bp.route("/login", methods=["POST"])
def user_login():
    """
    登录功能,获取用户提交的数据,进行校验,校验成功则返回登录成功
    :return:
    """
    # return "登录成功"
    # 获取请求体
    data = request.json
    # 使用请求的数据构建用户的对象
    user = User(**data)  # 等价于 User(username=data.get("username"),password=data.get("password"))
    # 查询用户是否存在,存在则进行后续的步骤
    user_result_data = db_session.query(User).filter_by(username=user.username).first()
    # user_result = User()
    if not user_result_data:
        # 没查到用户
        return {"code": 405, "msg": "user is not register"}
    if not user_result_data.check_hash_password(data.get("password")):
        return {"code": 401, "msg": "user or password is wrong"}
    return {"code": 0, "msg": "user login success"}


@user_bp.route("/register", methods=["POST"])
def user_register():
    # 获取请求体
    data = request.json
    # 构建用户对象
    user = User(**data)
    print(user.password)

    if user:
        # 查询用户是否存在,存在则进行后续的步骤
        user_result_data = db_session.query(User).filter_by(username=user.username).first()
        if user_result_data:
            return {"code": 40003, "msg": "user is exist"}
        db_session.add(user)
        db_session.commit()
        user_id = user.id
        if user_id:
            # 存在id,则证明新增成功了
            return {"code": 0, "msg": f"register success"}
        else:
            return {"code": 40001, "msg": "register fail"}
    return {"code": 40001, "msg": "register fail"}

@user_bp.route("/get", methods = ["GET"])
def user_list():
    users = db_session.query(User).all()
    if users:
        return {"code":200, "msg":"success",
                "data":[{"id":user.id, "username":user.username, "password":user.password, "create_time":user.create_time} for user in users]
                }
    return {"code":401, "msg":"fail"}

@user_bp.route("/delete",methods=["DELETE"])
def delete_user():
    _id = request.args.get("id")
    user_d = db_session.query(User).filter_by(id=_id).first()
    if user_d:
        db_session.query(User).filter_by(id=_id).delete()
        db_session.commit()
        db_session.close()
        return {"code": 200, "msg": "success"}
    return {"code": 401, "msg": "no this user"}

image
image
image
image

201941412218 魏峰
from flask import Blueprint, request
from study6.orm_mysql import db_session, User

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

@user_bp.route(“/”, methods=[“GET”])
def user():
user_list = db_session.query(User).all()
for user in user_list:
print(user)
print(f"userList:{user_list}")
if user_list:
return {“code”: 0, “msg”: “select success”}
else:
return {“code”: 4003, “msg”: “select fail”}

@user_bp.route(“/login”, methods=[“POST”])
def user_login():
data = request.json
user = User(**data)
password=data.get(“password”))
user_result_data = db_session.query(User).filter_by(username=user.username).first()
# user_result = User()
if not user_result_data:
return {“code”: 4005, “msg”: “user is not register”}
if not user_result_data.check_hash_password(data.get(“password”)):
return {“code”: 4001, “msg”: “user or password is wrong”}
return {“code”: 0, “msg”: “user login success”}

@user_bp.route(“/register”, methods=[“POST”])
def user_register():
data = request.json
user = User(**data)
user_result_data = db_session.query(User).filter_by(username=user.username).first()
if user_result_data:
return {“code”: 4005, “msg”: “user is register”}
else:
db_session.add(user)
db_session.commit()
user_id = user.id
# db_session.close()
if user_id:
return {“code”: 0, “msg”: “user register success”}

    else:
        return {"code": 0, "msg": "user register fail"}

@user_bp.route(“/delete”, methods=[“DELETE”])
def user_delete():
_id = request.args.get(“id”)
print(f"id={_id}“)
exist = db_session.query(User).filter_by(id=_id).first()
print(f"exist=====>{exist}”)
if exist:
db_session.query(User).filter_by(id=_id).delete()
db_session.commit()
# db_session.close()
return {“code”: 0, “msg”: “delete success”}
else:
return {“code”: 0, “msg”: “delete false”}

202041404202 陈杰选
user_route.py

from flask import Blueprint, request
from orm_connect import db_session, User

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


@user_bp.route("/", methods=['GET'])
def user():
    users = db_session.query(User).all()
    if users:
        return {
            "code": 0,
            "msg": "select success",
            "data":
                [{"id": user.id,"username": user.username,"password": user.password,"create_time": user.create_time} for user in users]
        }
    else:
        return {'code': 401, 'msg': 'fail', 'data': "list display fail"}


@user_bp.route("/login", methods=['POST'])
def user_login():
    """
    登录功能,获取用户提交的数据,进行校验,校验成功则返回登录成功
    :return:
    """
    # return "登录成功"
    # 获取请求体
    data = request.json
    # 使用请求的数据构建用户的对象
    user = User(**data)  # 等价于 User(username=data.get("username"),password=data.get("password"))
    # 查询用户是否存在,存在则进行后续的步骤
    user_result_data = db_session.query(User).filter_by(username=user.username).first()
    # user_result = User()
    if not user_result_data:
        # 没查到用户
        return {"code": 405, "msg": "user is not register"}
    if not user_result_data.check_hash_password(data.get("password")):
        return {"code": 401, "msg": "user or password is wrong"}
    return {"code": 0, "msg": "user login success"}


@user_bp.route("/register", methods=['POST'])
def user_register():
    # 获取请求体
    data = request.json
    # 使用请求的数据构建用户的对象
    user = User(**data)  # 等价于 User(username=data.get("username"),password=data.get("password"))
    # 查询用户是否存在,存在则进行后续的步骤
    user_result_data = db_session.query(User).filter_by(username=user.username).first()
    # user_result = User()
    if not user_result_data:
        # 没查到用户
        db_session.add(user)
        db_session.commit()
        db_session.close()
        return {"code": 0, "msg": "register success"}
    else:
        return {"code": 401, "msg": "register fail", 'data': '用户已存在'}


@user_bp.route("/delete", methods=['DELETE'])
def delete_user():
    _id = request.json.get("id")
    user_result_data = db_session.query(User).filter_by(id=_id).first()
    # user_result = User()
    if not user_result_data:
        # 没查到用户
        return {'code': 401, 'msg': 'delete fail', 'data': '用户不存在'}
    else:
        db_session.query(User).filter_by(id=_id).delete()
        db_session.commit()
        db_session.close()
        return {'code': 0, 'msg': 'delete success', 'data': '用户已删除'}

test_user_route.py

import requests


class TestUserRoute:

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

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

    def test_user_login(self):
        data = {
            "username": "cjx",
            "password": "202041404202"
        }
        res = requests.post(f"{self.base_url}/login", json=data)
        print(res.json())
        assert res.json().get("code") == 0

    def test_user_register(self):
        data = {
            "username": "cjx",
            "password": "123456"
        }
        res = requests.post(f"{self.base_url}/register", json=data)
        print(res.json())
        assert res.json().get("code") == 0

    def test_user_delete(self):
        data = {"id": 2}
        res = requests.delete(f"{self.base_url}/delete", json=data)
        print(res.json())
        assert res.json().get("code") == 0

202041404218 吴宏杰

from flask import Blueprint, request

from sql import User, session

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



@user_bp.route("/")
def user():
    user2 = session.query(User).all()
    users = []
    for rs in user2:
        data = {"id":rs.id, "username": rs.username, "password": rs.password}
        users.append(data)
    return {"code": 200, "msg": "success", "data": users}


@user_bp.route("/login")
def user_login():
    data = request.json
    user = User(**data)  # 等价于 User(username=data.get("username"),password=data.get("password"))
    user_result_data = session.query(User).filter_by(username=user.username).first()
    if not user_result_data:
        # 没查到用户
        return {"code": 405, "msg": "user is not register"}
    if not user_result_data.check_hash_password(data.get("password")):
        return {"code": 401, "msg": "user or password is wrong"}
    return {"code": 0, "msg": "user login success"}


@user_bp.route("/register")
def user_register():
    data = request.json
    user = User(**data)
    user_result = session.query(User).filter_by(username=user.username).first()
    if not user_result:
        username = data.get("username")
        password = data.get("password")
        session.add(User(username=f"{username}", password=f"{password}"))
        session.commit()
        return {"code": 200, "msg": "注册成功"}
    else:
        return {"code": 200, "msg": "已存在该用户名"}


@user_bp.route("/delete")
def delete_user():
    id = request.args.get("id")
    user_result = session.query(User).filter_by(id=id).first()
    if not user_result:
        return {"code": 401, "msg": "没有该用户"}
    session.query(User).filter_by(id=id).delete()
    session.commit()
    if session.query(User).filter_by(id=id).first():
        return {"code": 501, "msg": "delete fail"}
    return {"code": 200, "msg": "delete success"}

image
image
image