Files
DelLevin-Home f1b9f6a1d0 222
2026-01-30 22:43:35 +08:00

70 lines
2.2 KiB
Python

from flask import Flask, render_template, request, jsonify
import base64
import proj_utils.utils as utils # 导入你的工具模块
app = Flask(__name__)
@app.route('/')
def index():
"""渲染主页模板"""
return render_template('index.html')
@app.route('/en-de-code')
def index():
"""渲染主页模板"""
return render_template('en-de-code-index.html')
@app.route('/decode', methods=['POST'])
def decode_endpoint():
"""处理解码请求的 API 端点"""
data = request.get_json()
base64_input = data.get('input_text', '').strip()
if not base64_input:
return jsonify({'success': False, 'error': '输入不能为空。'})
try:
# 1. Base64 解码
decoded_bytes = base64.b64decode(base64_input)
except Exception as e:
return jsonify({'success': False, 'error': f'Base64 解码失败: {str(e)}'})
# 2. 使用 utils 模块中的 detect_and_decode 函数进行编码检测和解码
decoded_result = utils.detect_and_decode(decoded_bytes)
# 返回成功的 JSON 响应
return jsonify({
'success': True,
'result': decoded_result,
})
@app.route('/encode', methods=['POST'])
def encode_endpoint():
"""处理编码请求的 API 端点"""
data = request.get_json()
text_to_encode = data.get('text_to_encode', '')
encoding = data.get('encoding', 'utf-8') # 默认使用 UTF-8
if text_to_encode is None:
return jsonify({'success': False, 'error': '输入不能为空。'})
try:
# 1. 根据指定编码格式将文本转换为字节数组
encoded_bytes = text_to_encode.encode(encoding)
except LookupError:
return jsonify({'success': False, 'error': f'未知的编码格式: {encoding}'})
except UnicodeEncodeError as e:
return jsonify({'success': False, 'error': f'编码失败: {str(e)}'})
# 2. 将字节数组进行 Base64 编码
encoded_string = base64.b64encode(encoded_bytes).decode('ascii')
# 返回成功的 JSON 响应
return jsonify({
'success': True,
'result': encoded_string
})
# pip install pipreqs
# pipreqs D:\UserData\Desktop\demo\python_script\base64-de-in-code
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)