SHARE
TWEET

Untitled

a guest Jul 21st, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from flask import Flask, request
  2. from flask_restplus import Api, Resource, fields
  3. from flask_sqlalchemy import SQLAlchemy
  4. from marshmallow import Schema, fields as FM
  5. from sqlalchemy import (Text)  # you can add another table column type if you need
  6. from flask_migrate import Migrate
  7.  
  8. app = Flask(__name__)
  9. # we can access swagger documentation at localhost:5000/docs
  10. api = Api(app, doc='/docs')
  11. # our base API path will be {BASE_URL}/my_api
  12. name_space = api.namespace('my_api', description='API Project')
  13.  
  14. # configure SQLAlchemy
  15. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  16. # my MySQL user is root with password root and my database is my_project
  17. app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:root@localhost/my_project'
  18. db = SQLAlchemy(app)
  19.  
  20.  
  21. # model to table Log
  22. class Log(db.Model):
  23.     id = db.Column(db.Integer, primary_key=True)
  24.     detail = db.Column(Text)
  25.  
  26.  
  27. # will be used to serialize model Log into JSON for API result
  28. class LogSchema(Schema):
  29.     id = FM.Int()
  30.     detail = FM.Str()
  31.  
  32.  
  33. # this will be used to add parameter in swagger for inserting/updating record
  34. logSwagger = api.model('Log', {
  35.     'detail': fields.String(required=True, description='Log detail content')
  36. })
  37.  
  38. schema = LogSchema()
  39.  
  40.  
  41. @name_space.route("/")
  42. class LogList(Resource):
  43.     def get(self):  # will be used to fetch all record from log later
  44.         return {
  45.             "status": "List all log"
  46.         }
  47.  
  48.     @name_space.expect(logSwagger)
  49.     def post(self):
  50.         payload = request.get_json()
  51.         log = Log()
  52.         log.detail = payload['detail']
  53.         db.session.add(log)
  54.         db.session.commit()
  55.  
  56.         return {
  57.             "data": schema.dump(log)
  58.         }
  59.  
  60.  
  61. @name_space.route("/<int:id>")
  62. class LogDetail(Resource):
  63.     def get(self, id):  # will be used to see one particular log detail
  64.         return {
  65.             "status": "See detail for log with id " + str(id)
  66.         }
  67.  
  68.     def put(self, id):  # will be used to update particular log
  69.         return {
  70.             "status": "Updated log with id " + str(id)
  71.         }
  72.  
  73.     def delete(self, id):  # will be used to delete particular log
  74.         return {
  75.             "status": "Deleted log with id " + str(id)
  76.         }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top