Python Flask SQLAlchemy 未提交对数据库的更改

Python Flask SQLAlchemy not commiting changes to the database

我有一个 class 供用户使用,然后有一种方法可以将数据保存到数据库中。

class User(db.Model, ExtraMixin):
    first_name = db.Column(db.String(50), nullable=False)
    last_name = db.Column(db.String(50), nullable=False)
    other_names = db.Column(db.String(100), nullable=True)
    phone_number = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), index=True, unique=True, nullable=False)
    password = db.Column(db.String(200), nullable=False)
    user_type_id = db.Column(db.Integer, db.ForeignKey('user_type.id'))
    vendor_id = db.Column(db.Integer, db.ForeignKey('vendor.id'), nullable=True)
    
    vendor = db.relationship('Vendor', primaryjoin="and_(User.vendor_id==Vendor.id)", lazy=True) 
    

  def save_to_db(self):
      db.session.add(self)
      db.session.commit()

出于某种原因,这不起作用。不知道是不是我做错了

这是调用 save_to_db 方法的地方

def post(self):
        data = self.parser.parse_args()
        new_user = User(
            first_name =data['first_name'],
            last_name =data['last_name'],
            other_names =data['other_names'],
            phone_number =data['phone_number'],
            email =data['email'],
            password =User.generate_hash(data['password']),
            user_type_id =data['user_type_id'],
            vendor_id =data['vendor_id'],
            created_by =get_jwt_claims()['id']
            )
        try:
            new_user.save_to_db()
            return {'message': 'New User {} added'.format(data['first_name'])}
        except:
            return {'message': 'Internal sever error. Please contact the person responsible'}, 500

提供您的数据库模型:

class User(db.Model, ExtraMixin):
    first_name = db.Column(db.String(50), nullable=False)
    last_name = db.Column(db.String(50), nullable=False)
    other_names = db.Column(db.String(100), nullable=True)
    phone_number = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), index=True, unique=True, nullable=False)
    password = db.Column(db.String(200), nullable=False)
    user_type_id = db.Column(db.Integer, db.ForeignKey('user_type.id'))
    vendor_id = db.Column(db.Integer, db.ForeignKey('vendor.id'), nullable=True)
    
    vendor = db.relationship('Vendor', primaryjoin="and_(User.vendor_id==Vendor.id)", lazy=True) 

根据您获取数据库信息的方式,您可以通过两种方式将数据写入数据库。

如果您正在构建 API 并从专用前端向 register 端点发出 POST 请求,您将从该请求中获取写入数据库的数据:

class SignUp(Resource):
    def post(self):
            data = request.get_json()
            user = User(**data)
            db.session.add(user)
            db.session.commit()
            return {'Success': 'Success '}
        return 400, {'error': 'Error creating user'}

api.add_resource(SignUp, "/register")

如果您正在构建 Flask SPA 而无需将数据发送到前端框架,您可以这样做并拥有一个 register 页面 RegistrationForm:

@app.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(first_name=form.first_name.data,
                    last_name=form.last_name.data, 
                    other_names=form.other_names.data
                    # the rest of the fields go here
                    )
        db.session.add(user)
        db.session.commit()
        flash(f'Created user {form.username.data}.')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)

通过执行这些建议之一,您将不需要模型 class 中的方法,因为它会在您到达路线或发出 POST 请求时执行。

您的 POST 请求应该是这样的:

def post(self):
        data = self.parser.parse_args()
        new_user = User(
            first_name =data['first_name'],
            last_name =data['last_name'],
            other_names =data['other_names'],
            phone_number =data['phone_number'],
            email =data['email'],
            password =User.generate_hash(data['password']),
            user_type_id =data['user_type_id'],
            vendor_id =data['vendor_id'],
            created_by =get_jwt_claims()['id']
            )
        try:
            db.session.add(new_user)
            db.session.commit()
            return {'message': 'New User {} added'.format(data['first_name'])}
        except:
            return {'message': 'Internal sever error. Please contact the person responsible'}, 500

或者,如果您真的想使用该方法,请将 new_user.save_to_db() 替换为 user.save_to_db(new_user)