Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from flask import Flask, request
- from flask_restplus import Api, Resource, fields
- from flask_sqlalchemy import SQLAlchemy
- from marshmallow import Schema, fields as FM
- from sqlalchemy import (Text) # you can add another table column type if you need
- from flask_migrate import Migrate
- app = Flask(__name__)
- # we can access swagger documentation at localhost:5000/docs
- api = Api(app, doc='/docs')
- # our base API path will be {BASE_URL}/my_api
- name_space = api.namespace('my_api', description='API Project')
- # configure SQLAlchemy
- app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
- # my MySQL user is root with password root and my database is my_project
- app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:root@localhost/my_project'
- db = SQLAlchemy(app)
- # model to table Log
- class Log(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- detail = db.Column(Text)
- # will be used to serialize model Log into JSON for API result
- class LogSchema(Schema):
- id = FM.Int()
- detail = FM.Str()
- # this will be used to add parameter in swagger for inserting/updating record
- logSwagger = api.model('Log', {
- 'detail': fields.String(required=True, description='Log detail content')
- })
- schema = LogSchema()
- @name_space.route("/")
- class LogList(Resource):
- def get(self): # will be used to fetch all record from log later
- return {
- "status": "List all log"
- }
- #implement parameter we have created at line 34
- @name_space.expect(logSwagger)
- def post(self):
- payload = request.get_json()
- log = Log()
- log.detail = payload['detail']
- db.session.add(log)
- db.session.commit()
- return {
- "data": schema.dump(log)
- }
- @name_space.route("/<int:id>")
- class LogDetail(Resource):
- def get(self, id): # will be used to see one particular log detail
- return {
- "status": "See detail for log with id " + str(id)
- }
- def put(self, id): # will be used to update particular log
- return {
- "status": "Updated log with id " + str(id)
- }
- def delete(self, id): # will be used to delete particular log
- return {
- "status": "Deleted log with id " + str(id)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement