6 后端开发 - 简单代码

简单的后端代码

import json
import hashlib
import config
from flask import Flask, request, jsonify
from flask_jwt_extended import JWTManager,create_access_token,get_jwt_identity,jwt_required
from test_sqlite import SqliteUtil



'''
初始化
'''
app = Flask(__name__)
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = 30 # 过期时间,单位秒
app.config['JWT_SECRET_KEY'] = '123456'  # 自定义
app.config["JWT_TOKEN_LOCATION"] = ['headers']  # 设置从前端请求的json数据中获取 token
app.config.from_object(config)
jwt = JWTManager(app)


# 链接数据库
su = SqliteUtil("token_test.s3db")
# 返回数据
respone_json_data = {
    'code': 1,
    'data': '',
    'msg': ''
}

'''
请求
'''
# 首页
@app.route('/')
def hello_lizi():
    return 'Hello Lizi!'


# 注册
@app.route(rule='/user/register', methods=['POST'])
def user_register():
    # 获取请求数据
    req_json_data = json.loads(request.get_data())
    # 根据key拿出value
    username = req_json_data['username']
    password = req_json_data['password']
    # md5 密码加密
    md5_password = hashlib.md5(password.encode()).hexdigest()
    # 入库
    result = su.exec_sql("insert into user (username, password, is_active) values('{}','{}','{}')"
                    .format(username, md5_password, 1))
    su.commit()
    print(result)
    # 返回信息
    respone_json_data['code'] = 1
    respone_json_data['data'] = result
    respone_json_data['msg'] = 'register user success'
    return json.dumps(respone_json_data)


# 登录
@app.route(rule='/user/login', methods=['POST'])
def login():
    # 获取请求数据
    req_json_data = json.loads(request.get_data())
    username = req_json_data['username']
    password = req_json_data['password']
    # 验证用户名密码
    if username is None or password is None:
        respone_json_data['code'] = 1001
        respone_json_data['data'] = []
        respone_json_data['msg'] = 'username or password is None'
    else:
        # md5 密码加密
        md5_password = hashlib.md5(password.encode()).hexdigest()
        user = su.exec_sql("select * from user where username='{}' and password='{}'".format(username, md5_password))
        print(user)
        # 表中有user
        if len(user) != 0:
            # token = create_access_token(identity={"username": username})
            token = create_access_token(identity={"user": user})
            # 返回信息
            respone_json_data['code'] = 1
            respone_json_data['data'] = [{"token": token}]
            respone_json_data['msg'] = 'login success'
        else:
            respone_json_data['code'] = 1002
            respone_json_data['data'] = []
            respone_json_data['msg'] = 'login fail'
    return json.dumps(respone_json_data)


# 博客列表
@app.route(rule='/blog/list', methods=['GET'])
@jwt_required()
def blog_list():
    # 这个是为了理解
    current_user = get_jwt_identity()
    print(current_user)
    # print(type(current_user))
    # 表查询
    blogs = su.exec_sql("select * from blog")
    # print(blogs)
    # 返回信息
    respone_json_data['code'] = 1
    respone_json_data['data'] = blogs
    respone_json_data['msg'] = 'get blogs success'
    return json.dumps(respone_json_data)


# 新增博客
@app.route(rule='/blog/add', methods=['POST'])
@jwt_required()
def blog_add():
    # 获取请求数据
    req_json_data = json.loads(request.get_data())
    title = req_json_data['title']
    content = req_json_data['content']
    # 新增博客
    result = su.exec_sql("insert into blog (title, content) values('{}','{}')"
                    .format(title, content))
    su.commit()
    # 返回信息
    respone_json_data['code'] = 1
    respone_json_data['data'] = result
    respone_json_data['msg'] = 'add blog success'

    return json.dumps(respone_json_data)

# 修改博客
@app.route(rule='/blog/update', methods=['POST'])
@jwt_required()
def blog_update():
    # 获取请求数据
    req_json_data = json.loads(request.get_data())
    id = req_json_data['id']
    title = req_json_data['title']
    content = req_json_data['content']
    # 更新博客
    result = su.exec_sql("update blog set title='{}',content='{}' where id='{}'"
                    .format(title, content, id))
    su.commit()
    print(result)
    # 返回信息
    respone_json_data['code'] = 1
    respone_json_data['data'] = result
    respone_json_data['msg'] = 'update blog success'
    return json.dumps(respone_json_data)


# 删除博客
@app.route(rule='/blog/del', methods=['POST'])
@jwt_required()
def blog_del():
    # 获取请求数据
    req_json_data = json.loads(request.get_data())
    id = req_json_data['id']
    # 删除博客
    result = su.exec_sql("delete from blog where id='{}'".format(id))
    su.commit()
    print(result)
    # 返回信息
    respone_json_data['code'] = 1
    respone_json_data['data'] = result
    respone_json_data['msg'] = 'delete blog success'
    return json.dumps(respone_json_data)


'''
运行项目
'''
if __name__ == '__main__':
    app.run()

 

posted @ 2021-03-16 22:52  栗子测试开发  阅读(248)  评论(0)    收藏  举报