Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update row (SQLAlchemy) with data from marshmallow

Tags:

People also ask

How do I update an item in SQLAlchemy?

Update a row entry in SQLAlchemyGet the books to table from the Metadata object initialized while connecting to the database. Pass the update query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results.

Is SQLAlchemy worth learning?

SQLAlchemy is great because it provides a good connection / pooling infrastructure; a good Pythonic query building infrastructure; and then a good ORM infrastructure that is capable of complex queries and mappings (as well as some pretty stone-simple ones).

Is flask-SQLAlchemy the same as SQLAlchemy?

Flask-SQLAlchemy¶Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. It simplifies using SQLAlchemy with Flask by setting up common objects and patterns for using those objects, such as a session tied to each web request, models, and engines.


I'm using Flask, Flask-SQLAlchemy, Flask-Marshmallow + marshmallow-sqlalchemy, trying to implement REST api PUT method. I haven't found any tutorial using SQLA and Marshmallow implementing update.

Here is the code:

class NodeSchema(ma.Schema):     # ...   class NodeAPI(MethodView):     decorators = [login_required, ]     model = Node      def get_queryset(self):         if g.user.is_admin:             return self.model.query         return self.model.query.filter(self.model.owner == g.user)      def put(self, node_id):         json_data = request.get_json()         if not json_data:             return jsonify({'message': 'Invalid request'}), 400          # Here is part which I can't make it work for me         data, errors = node_schema.load(json_data)         if errors:             return jsonify(errors), 422          queryset = self.get_queryset()           node = queryset.filter(Node.id == node_id).first_or_404()         # Here I need some way to update this object         node.update(data) #=> raises AttributeError: 'Node' object has no attribute 'update'          # Also tried:         # node = queryset.filter(Node.id == node_id)         # node.update(data) <-- It doesn't if know there is any object         # Wrote testcase, when user1 tries to modify node of user2. Node doesn't change (OK), but user1 gets status code 200 (NOT OK).          db.session.commit()         return jsonify(), 200