前言
工作有个特殊需求,类似Android应用签名,但不能提供密钥给他人。
想来想去,只好通过网页前后端来处理。
几年前写过一个,前端 html, 后端php,再回首已恍如隔世。
网上溜达了半天,发现 python flask,这玩意方便很多。
安装
flask 只支持 python 3.8 及其以上版本
需要安装的python库
flask werkzeug re pycryptodomex
目录结构
| - server-start.py 服务启动文件,包含具体的编码实现
| - templates 网页文件目录
| - app.html 网页文件,由 server-start.py 调用
| - upload 文件上传目录
源码示例
app.html
提交页面,供使用者上传文件,给到后端处理。其中 /uploader-hex 视为与后端的接口,format 指定文件格式(固定参数,供后端处理,不在网页上显示),file 指定上传的文件,submit 执行提交操作。
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h2>文件转换</h2>
<form action="/uploader-hex" method="POST" enctype="multipart/form-data">
<input type="text" name="format" value="hex" hidden />
<input type="file" name="file" />
<input type="submit" value="转换" />
</form>
<HR align=left width=500 SIZE=2 >
</body>
</html>
server-start.py
大部分逻辑都在此文件中,为了方便观看,我把解说当注释写进去了。
#!/usr/local/bin/python3
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
import os
import time
import re
import hashlib
app = Flask(__name__)
# 指定文件上传的目录
app.config['UPLOAD_FOLDER'] = 'upload/'
###### index
# 生成web的索引页面, @app.route('/') 指明挂载点
# 网页地址为 http://xxx.xxx.xxx.xxx:10000
# 语句格式是 html5
@app.route('/')
def web_index():
info = ""
info += '<br />\n'
info += '<a href="http://xxx.xxx.xxx.xxx:10000/hex">hex 格式转换</a>\n'
info += '<br />\n'
return info
###### hex
# 网页地址为 http://xxx.xxx.xxx.xxx:10000/hex,实际调用 app.html
@app.route('/hex')
def upload_file():
return render_template('app.html')
# 后端处理部分,/uploader-hex 就是 app.html 中指明的接口
@app.route('/uploader-hex',methods=['GET','POST'])
def uploader():
# POST 在 app.html 中有指明
if request.method == 'POST':
# 获取上传的文件句柄
f = request.files['file']
_name = f.filename
# 获取 app.html 中指明的格式信息
_format = request.form.get('format')
print("------------------")
print(request.files)
print(_name)
print(_format)
# 实际情况需要处理两类文件
if "hex" in _format:
if not re.match(".*\.hex", _name):
return "转换失败,请确认上传文件是否以 .hex 结尾?"
elif "bin" in _format:
if not re.match(".*\.bin", _name):
return "转换失败,请确认上传文件是否以 .bin 结尾?"
else:
return "上传文件格式错误?"
# 创建用于存储文件的目录
if not os.path.exists("upload"):
os.makedirs("upload")
str_date = time.strftime('%Y%m%d-%H%M%S',time.localtime(time.time()))
# 存储文件到本地
f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(str_date + "." + _format)))
# 因涉及公司业务,以下省略处理逻辑
# 处理后的文件会传到某个可以通过html下载的目录
# 以下 _url 是下载的地址,语句格式参照 html5,网页上会显示一个链接
return '<a href="' + _url + '">转换成功,点击进入下载地址</a>'
else:
return render_template('upload.html')
######
if __name__ == '__main__':
# 启动服务,参数部分指定服务的IP地址,和端口
app.run(host="xxx.xxx.xxx.xxx", port=10000)
启动服务
nohup ./server-start.py &
总结
相比php,对环境依赖少了很多。我为了方便,全都揉到 server-start.py 里面了,按理应该一个需求一个py脚本,server-start.py 只是加载不同脚本,这个扩展更方便些。(作为一个标准的懒人,以后有新需求的时候再重构吧)

被折叠的 条评论
为什么被折叠?



