从0开始python学习-54.python中flask创建MD5和base64加密校验的接口

MD5加密接口

import hashlib
from flask import Flask, request, jsonify

# 初始化一个flask的对象
app = Flask(__name__)

# MD5加密校验数据请求
# 定义用户数据
user_data = [
    {"username": "admin1", "password": "E10ADC3949BA59ABBE56E057F20F883E"}, # 123456
    {"username": "admin2", "password": "C33367701511B4F6020EC61DED352059"} # 654321
]

# 请求接口-form
@app.route("/post_md5",methods=['post'])
def post_MD5():
    username = request.form.get('username')
    password = request.form.get('password')

    if not username or not password:
        return jsonify({'error': '用户名和密码是必填项'})

    # 计算密码的MD5哈希值--注意user_data中的password是大写,所以这里需要转成大写
    hash_pwd = hashlib.md5(password.encode()).hexdigest().upper()

    # 遍历用户数据,匹配用户名和密码进行校验
    for user in user_data:
        if user['username'] == username and user['password'] == hash_pwd:
            return jsonify({'message': '登录成功'})

    return jsonify({'error': '用户名或密码不正确'})

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

base64加密接口

# 初始化一个flask的对象
app = Flask(__name__)

# 定义用户数据
user_data2 = [
    {"username": "admin1", "password": "MTIzNDU2"}, # 123456
    {"username": "admin2", "password": "NjU0MzIx"} # 654321
]
@app.route('/post_base64', methods=['POST'])
def post_base64():
    username = request.json.get('username')
    password = request.json.get('password')

    if not username or not password:
        return jsonify({'error': '用户名和密码是必填项'})


    # 进行 base64 编码
    encoded_password = base64.b64encode(password.encode()).decode()

    # 遍历用户数据,查找匹配的用户名和密码
    for user in user_data2:
        if user['username'] == username and user['password'] == encoded_password:
            return jsonify({'message': '登录成功'})

    return jsonify({'error': '用户名或密码不正确'})

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

 

 

你可能感兴趣的:(python,python,学习,flask,测试工具,开发语言,后端)