Python 如何封装工具类方法,以及使用md5加密

第一步:封装使用方法

在utils目录中,编写我的md5加密的方法,如下:

import re
import hashlib
from os import path
from typing import Callable
from flask import current_app

# 这里封装的是工具类的方法

def basename(filename: str):
    name, ext = path.splitext(filename)
    return name.rstrip(ext)


def md5(x: str) -> str:
    h1 = hashlib.md5() #创建一个md5对象
    h1.update(x.encode(encoding='utf-8')) # 使用utf-8编码数据
    return h1.hexdigest()  # 返回加密后的十六进制字符串


upper: Callable[[str], str] = lambda x: x.upper()

# 去除html标签
def filter_html_tag(html):
    pattern = re.compile('<[^>]+>', re.IGNORECASE)
    from typing import Match

    def repl_func(match: Match[str]) -> str:
        if match.group(0).startswith('<img'):
            return match.group(0)
        elif match.group(0).startswith('<br'):
            return match.group(0)
        else:
            return ''

    result = pattern.sub(repl_func, html)
    result = result.replace('&nbsp;', '') \
        .replace('&lt;', '') \
        .replace('\n', '<br/>')
    return result.strip()

# 封建常用的生成token的方法
def api_sign(user_id:str, project_id:str):
    import time
    timestamp = int(time.time()) #当前时间戳
    api_key = current_app.config.get('API_KEY') # 从配置文件获取key
    str_to_sign = "project_id{}timestamp{}user_id{}".format(
        project_id, timestamp, user_id)

    token = upper(md5(md5(str_to_sign) + api_key))
    return token, timestamp


第二步:使用方法

from project.utils import api_sign

blog_base_blueprint = Blueprint('blog', __name__, url_prefix='/api')

@blog_base_blueprint.route('/token', methods=['POST'])
def postToken():
    user_id = request.form.get('user_id')
    project_id = request.form.get('project_id')

    current_app.logger.info('生成token哟')

    (token, timestamp) = api_sign(user_id, project_id)

    return jsonify({
        'code': 1,
        'msg': '成功',
        'data': {
            'token' : token,
            'timestamp' : timestamp
        }
    })

顺带截图分享一下我的目录结构:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值