Untitled
unknown
plain_text
2 years ago
2.3 kB
1
Indexable
Never
from flask import Flask from flask_restful import Api, Resource, reqparse, abort, fields, marshal_with from flask_sqlalchemy import SQLAlchemy from datetime import datetime app = Flask(__name__) api = Api(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' db = SQLAlchemy(app) class DataModel(db.Model): id = db.Column(db.Integer, primary_key=True) content = db.Column(db.String(200), nullable=False) number = db.Column(db.Integer, nullable=False) def __repr__(self): return f"Video(content = {content}, number = {number})" data_put_args = reqparse.RequestParser() data_put_args.add_argument("name", type=str, help="Data is required", required=True) data_put_args.add_argument("number", type=int, help="Views of the video", required=True) data_update_args = reqparse.RequestParser() data_put_args.add_argument("name", type=str, help="Data is required") data_put_args.add_argument("number", type=int, help="Views of the video") resource_fields = { 'id': fields.Integer, 'content': fields.String, 'number': fields.Integer, } class Video(Resource): @marshal_with(resource_fields) def get(self, data_id): result = DataModel.query.filter_by(id=data_id).first() if not result: abort(404, message="Could not find data with that id") return result @marshal_with(resource_fields) def put(self, data_id): args = data_put_args.parse_args() result = DataModel.query.filter_by(id=data_id).first() if result: abort(409, message="Data id taken...") data = DataModel(id=data_id, content=args['content'], number=args['number']) db.session.add(data) db.session.commit() return data, 201 @marshal_with(resource_fields) def patch(self, data_id): args = data_update_args.parse_args() result = DataModel.query.filter_by(id=data_id).first() if not result: abort(404, message="Data doesn't exist, cannot update") if args['content']: result.name = args['content'] if args['number']: result.views = args['number'] db.session.commit() return result def delete(self, data_id): result = DataModel.query.filter_by(id=data_id).first() db.session.delete(result) return '', 204 api.add_resource("/data/<int:data_id>") if __name__ == "__main__": app.run(debug=True)