Skip to content

Base.py superclass

Sihan Tawsik edited this page Jun 14, 2020 · 8 revisions

Base.py

Description

Base.py is a superclass for creating views easily.

File path

The Base.py file is located at src/views/base directory of the project folder.

Methods

Currently there are three methods in this class:

  • get()
  • post()
  • put()
  • object_to_dict()

1. get()

Parameters

  • Class: Model class to query objects
  • attributes: A tuple containing the Class attributes of the query objects that are sent on the get request
  • status_kwargs: A dictionary containing success_code, fail_code and fail_msg for sending response
  • query_kwargs: A dictionary containing query parameters

Returns

A json response and status code

2. post()

Parameters

  • Class: Model class to create new instance
  • attributes: A tuple containing the attributes to check the post_data
  • process_func: A function to process the post_data for creating new Class object
  • status_kwargs: A dictionary containing success_code, fail_code and fail_msg for sending response

Returns

A json response and status code

3. put()

Parameters

  • Class: Model class to create new instance
  • attributes: A tuple containing the attributes to check the post_data
  • process_func: A function to process the post_data for updating Class object
  • status_kwargs: A dictionary containing success_code, fail_code and fail_msg for sending response

Returns

A json response and status code

4. object_to_dict()

Parameters

  • class_object: An instance of Class
  • attributes: A tuple containing the Class attributes of the query objects that are sent on the get request

Returns

A dictionary containing the attributes of the class_object

Usage

  1. To use Base.py for creating custom views, first a model class is needed. Let's add a model class in the src/models.py file like this:
class Mymodel(db.Model):

    __tablename__ = "my_model"

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(20), unique=True, nullable=False)
    description = db.Column(db.Text, nullable=False)
  1. Next we need to make a subclass inheriting the superclass Base.py. Let's make a subclass src/views/custom/custom.py and put some codes like this below:
from flask import request

from src.views.base.Base import BaseAPI
from src.models import MyModel
from src.defs.decorators import login_required


class CustomAPI(BaseAPI):
    def get(self):
        return super().get()

    def post(self):
        return super().post()
  1. Now we need to fill in the parameters for completing the request. Let's suppose we want to send the attributes id and name of the MyModel objects which have id equal to 2. So, we do something like this:
class CustomAPI(BaseAPI):
    def get(self):
        query_kwargs = {"id": 2}
        return super().get()

    def post(self):
        return super().post()
  1. Now adding the attributes and fail_msg:
class CustomAPI(BaseAPI):
    def get(self):
        query_kwargs = {"id": 2}
        attributes = ("id", "name")
        status_kwargs = {
            "success_code": 200,
            "fail_code": 404,
            "fail_msg": "No objects found."
        }
        return super().get(MyModel, attributes, status_kwargs, query_kwargs)

    def post(self):
        return super().post()
  1. Now for completing the post() method, we need a process function that processes the post data. Let's complete the method like this:
class CustomAPI(BaseAPI):
    def get(self):
        query_kwargs = {"id": 2}
        attributes = ("id", "name")
        status_kwargs = {
            "success_code": 200,
            "fail_code": 404,
            "fail_msg": "No objects found."
        }
        return super().get(MyModel, attributes, status_kwargs, query_kwargs)

    def post(self):
        def process_func():
            post_data = request.get_json()
            if not post_data:
                return ("500", "No data provided")
            return post_data

        attributes = ("id", "name", "description")
        status_kwargs = {
            "success_code": 201,
            "fail_code": 500,
            "fail_msg": "Internal Server Error."
        }
        return super().post(Class, attributes, process_func, status_kwargs)
  1. After completing the custom.py file, path is needed to be added on src/routers.py:
from flask import Blueprint

from src.views.custom.custom import CustomAPI

auth_blueprint = Blueprint("auth", __name__)

custom_view = CustomAPI.as_view("custom_api")

auth_blueprint.add_url_rule("/custom", view_func=custom_view, methods=["GET", "POST"])
  1. After running the project and going http://127.0.0.1:5000/custom, there should be some responses like this:
{
  "data": [
    {
      "id": 2,
      "name": "something"
    }
  ], 
  "status": "success"
}

If there is no object in the database that matches the query, you'll get something like this:

{
  "data": [], 
  "message": "No objects found.", 
  "status": "fail"
}