直接进入主题吧
项目结构:
|—app
| | —init.py
| | —settings.py
| | —view.py
init.py:
from apis.settings import config
def create_app(config_name=None):
app = Flask(__name__, template_folder=template_folder)
app.config.from_object(config[config_name])
register_errors(app)
return app
def register_errors(app):
# 当上传文件超出大小限制时,会报413错误,现在捕获413错误处理。
@app.errorhandler(413)
def forbidden(e):
response = MockerResponse().error(message='上传文件大小超出限制,文件最大为3MB')
response.status_code = 403
return response
settings.py
class BaseConfig:
# 限制上传文件大小#######################################
MAX_CONTENT_LENGTH = 3 * 1024 * 1024 # 3MB
# 限制上传录制脚本格式是jmx格式
RECORD_ALLOWED_EXTENSIONS = {"jmx"}
class DevelopmentConfig(BaseConfig):
# 设置上传文件存放路径
UPLOAD_FOLDER = os.path.abspath(os.path.dirname(os.getcwd()))
class ProductionConfig(BaseConfig):
pass
class TestingConfig(BaseConfig):
pass
config = {
'development': DevelopmentConfig,
'production': ProductionConfig,
'testing': TestingConfig
}
view.py
interface_info_bp 是注册的蓝图
import datetime
from flask import current_app
# 判断文件格式是否规范
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in current_app.config['RECORD_ALLOWED_EXTENSIONS']
@interface_info_bp.route('/update-file', methods=['POST'])
def update_file():
# 判断是否有文件上传
if request.files:
f = request.files['file']
if allowed_file(f.filename):
# 处理文件名,防止文件名重复
# 获取系统时间
ftime = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
# 拼成字符串
file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], ftime + f.filename)
f.save(file_path)
return jsonify(msg="上传成功")
else:
return jsonify(msg='文件类型错误,文件类型仅支持:%s'%current_app.config['RECORD_ALLOWED_EXTENSIONS'])
else:
return jsonify(msg="文件不能为空")
完毕