2025年3月27日 星期四 甲辰(龙)年 月廿六 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

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

时间:03-21来源:作者:点击数:6
第一步:封装使用方法

在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
  • }
  • })

顺带截图分享一下我的目录结构:

在这里插入图片描述
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐