1

我将棉花糖和 Flask Restplus 用于我的 API 代码之一,其中我有几列的表,我想使用 POST 方法将数据发布到表中。在表中,我有一列作为 BLOB,它接受 JPEG 或 PDF 文件并将其存储到数据库中。

我能够使用常规烧瓶表单将记录保存到数据库中,现在我想使用 API 启用此功能。

为此,我有以下代码

费用模型.py

from flask_sqlalchemy  import SQLAlchemy
from app import db,ma
from datetime import datetime
from flask import url_for, current_app
from app.utils.exceptions import ValidationError
from sqlalchemy.dialects.mysql import LONGBLOB
from marshmallow import  fields, pre_load, validate
from app.models.Person_model import PersonSchema
from app.models.ExpType_model import ExpTypeSchema

#This is model defination for the Expnese Table and its api calls with get post put all covered in here.
class Expenses(db.Model):
    __tablename__ = 'Expesnes'
    __table_args__ = {'extend_existing': True}
    id = db.Column(db.Integer, primary_key=True)
    per_id = db.Column(db.Integer, db.ForeignKey('Persons.id'), nullable=False)
    U_id = db.Column(db.Integer, db.ForeignKey('Users.id'), nullable=False, index=True)
    Exp_per_name = db.Column(db.String(64), index=True)
    Exp_type_name = db.Column(db.String(100),index=True)
    Exp_amt = db.Column(db.Float)
    Exp_img = db.Column(db.LargeBinary)
    Exp_FileName = db.Column(db.String(300))
    Exp_date = db.Column(db.DateTime,index=True)
    Exp_comm = db.Column(db.String(200))

    def __init__(self,Exp_per_name,Exp_type_name,Exp_amt,Exp_img,Exp_FileName,Exp_date,Exp_comm):
        self.Exp_per_name = Exp_per_name,
        self.Exp_type_name = Exp_type_name,
        self.Exp_amt = Exp_amt,
        self.Exp_img = Exp_img,
        self.Exp_FileName = Exp_FileName,
        self.Exp_date = Exp_date,
        self.Exp_comm = Exp_comm
# Custom validator
def must_not_be_blank(data):
    if not data:
        raise ValidationError('Data not provided.')

class ExpensesSchema(ma.Schema):
    class Meta:
        model = Expenses
    id = fields.Integer(dump_only=True)
    u_id = fields.Integer(dump_only=True)
    Exp_per_name = fields.Nested(PersonSchema, validate=must_not_be_blank)
    ExpType_name = fields.Nested(ExpTypeSchema,validate=must_not_be_blank)
    Exp_amt =fields.Float(required=True)
    Exp_img = fields.Raw()
    Exp_FileName = fields.Str(allow_none=None)
    Exp_comm = fields.Str(allow_none=None)

Expense_Resource.py 文件

from flask_restplus  import  Resource
import json
from flask import request
from flask_login import current_user, login_required
from app.models.Expense_model import Expenses, ExpensesSchema
from datetime import datetime
from app import db

expenses_schema = ExpensesSchema(many=True)
expense_schema = ExpensesSchema()


class ExpenseRes(Resource):
    # This is  method for all ExpTypes
    @classmethod
    @login_required
    def get(cls):
        exptypes = Expenses.query.filter_by(u_id=current_user.id)
        invtypes = expenses_schema.dump(exptypes).data
        return {'status': 'success', 'data': exptypes}, 200

    # This is new records creation Persons
    @classmethod
    @login_required
    def post(cls):
        json_data = request.get_json(force=True)
        if not json_data:
            return {'message': 'No input data provided'}, 400
        # Validate and deserialize input
        data, errors = expense_schema.load(json_data)
        print data
        if errors:
            return errors, 422
        expensetype = Expenses.query.filter_by(u_id=current_user.id,
                                               Exp_per_name=data['Exp_per_name'],
                                               Exp_type_name = data['Exp_type_name'],
                                               Exp_amt=data['Exp_amt'],
                                               Exp_date=data['Exp_date']
                                               ).first()
        if expensetype:
            return {'message': 'Expense name already exists'}, 400
        newexpensetype = Expenses(u_id=current_user.id,
                             Exp_per_name=data['Exp_per_name'],
                             Exp_type_name=data['Exp_type_name'],
                             Exp_img = request.json['binary'],
                             Exp_FileName= request.json['file_name'],
                             Exp_amt=data['Exp_amt'],
                             Exp_date=data['Exp_date'],
                             Exp_comm= data['Exp_comm']
                             )

        try:
            db.session.add(newexpensetype)
            db.session.commit()
            result = expense_schema.dump(newexpensetype).data
            return {"status": 'success', 'data': result}, 201
        except:
            return {'message': 'An error occurred while creating Investment Type'}, 500

如何将文件保存到数据库以及如何将文件负载传递给我的 API。有没有办法只允许大小小于 15 MB 的 JPEG 和 PDF 文件

感谢您的宝贵时间并感谢您的反馈。

4

0 回答 0