The Seven Year Itch.

MENU

如何实现一个精简实用性强的图片接口(第一次修改)

July 13, 2018 • Read: 389 • 环境,Flask

**记录的乱。慢慢的调优!


第一次微调 code

@api.route('', methods=['POST'])
@auth.login_required
def uploads():
    """图片上传"""
    form = UploadForm()
    form.validate_for_api()
    re_name = change_filename(form.files.data['files'].filename)
    filename = files.save(form.files.data['files'], name=re_name)
    if re_name is None:
        return ImagesError(message="文件上传失败!")
    return jsonify({'code': 0, 'filename': filename, 'file_url': files.url(filename)})

form

class UploadForm(BaseForm):
    """上传文件"""
    files = FileField(validators=[FileAllowed(files, message="文件格式不正确!")])

重写Form

from flask import request
from wtforms import Form

from app.libs.error_code import ParameterException


class BaseForm(Form):
    """
    重写Form,实现是指验证api参数
    """

    def __init__(self):
        # 静默模式接受json参数
        data = request.get_json(silent=True)
        args = request.args.to_dict()
        files = request.files
        super(BaseForm, self).__init__(data=data, files=files, **args)

    def validate_for_api(self):
        valid = super(BaseForm, self).validate()
        if not valid:
            raise ParameterException(message=self.errors)
        return self

配置文件(笨方法)

files = UploadSet('files', DOCUMENTS)

def create_app():
    """
    初始化项目
    :return:
    """
    app = Flask(__name__)
    app.config.from_object('app.config.setting')
    app.config.from_object('app.config.securecrt')
    app.config['UPLOADED_FILES_DEST'] = os.getcwd() + '/vendor/uploads'
    configure_uploads(app, files)
    patch_request_class(app)
    apply_cors(app)
    register_blueprints(app)
    register_database(app)
    register_swagger(app)
    return app

重写DOCUMENTS

DOCUMENTS = tuple('jpg jpe jpeg png gif svg bmp doc docx xls xlsx'.split())  # 允许上传的文件类型

code

@api.route('/upload', methods=['POST'])
@auth.login_required
def uploads():
    form = UploadForm()
    form.validate_for_api()
    re_name = change_filename(form.files.data.filename)
    filename = files.save(form.files.data, name=re_name)
    if re_name is None:
        return ImagesError(message="文件上传失败!")
    return jsonify({'code': 0, 'filename': filename, 'file_url': files.url(filename)})

form

class UploadForm(BaseForm):
    """上传文件"""
    files = FileField(validators=[FileAllowed(files, message="文件格式不正确!")])

重写Form

from flask import request
from wtforms import Form

from app.libs.error_code import ParameterException


class BaseForm(Form):
    """
    重写Form,实现是指验证api参数
    """

    def __init__(self):
        # 静默模式接受json参数
        data = request.get_json(silent=True)
        args = request.args.to_dict()
        files = request.files['files']
        super(BaseForm, self).__init__(data=data, files=files, **args)

    def validate_for_api(self):
        valid = super(BaseForm, self).validate()
        if not valid:
            raise ParameterException(message=self.errors)
        return self

配置文件(笨方法)

files = UploadSet('files', DOCUMENTS)

def create_app():
    """
    初始化项目
    :return:
    """
    app = Flask(__name__)
    app.config.from_object('app.config.setting')
    app.config.from_object('app.config.securecrt')
    app.config['UPLOADED_FILES_DEST'] = os.getcwd() + '/vendor/uploads'
    configure_uploads(app, files)
    patch_request_class(app)
    apply_cors(app)
    register_blueprints(app)
    register_database(app)
    register_swagger(app)
    return app

重写DOCUMENTS

DOCUMENTS = tuple('jpg jpe jpeg png gif svg bmp doc docx xls xlsx'.split())  # 允许上传的文件类型

类似网上一些教程的

# @api.route('/upload', methods=['POST'])
# @auth.login_required
# def uploads():
#     if request.method == 'POST':
#         if 'photo' not in request.files:
#             return ImagesError()
#         file = request.files['photo']
#         re_name = change_filename(file.filename)
#         if file.filename == '':
#             return ImagesError(message="没有找到这个文件!")
#         else:
#             try:
#                 filename = photos.save(file, name=re_name)
#                 return jsonify({'code': 0, 'filename': filename, 'image_url': photos.url(filename)})
#             except Exception as e:
#                 return ImagesError(message="上传的文件格式不支持!")
#     else:
#         return ImagesError(message="错误的请求方式!")
Tags: None
Archives QR Code
QR Code for this page
Tipping QR Code
Leave a Comment

已有 1 条评论
  1. @(滑稽) 简洁≠简陋