This is the 26th day of my participation in Gwen Challenge

preface

The previous article covered the encapsulation of query/view/delete methods

This article continues with detailed explanations of other approaches

Began to encapsulate

Flask before we start today’s package, we’ll explain that the most commonly used flask returns json:

from flask import jsonify

def api() :
    return jsonify(result)
Copy the code

The jsonify function provided by Flask is used for processing

Paging query

In a real business scenario, we often encounter paging queries

Flask-sqlalchemy has a very mature paging query: paginate

However, the result returned by this method cannot be directly converted to JSON format, so a degree of processing is required:

@classmethod
def page(cls, parameters: dict = None) :
    """ paging query :param parameters:
    if parameters is None:
        parameters = {}
    pageable = parameters.get("pageable") or Pageable(1.50)
    result = cls.query.filter(**parameters).paginate(pageable.page, pageable.size, error_out=False).__dict__
    del result['query']
    return result
Copy the code

Convert paging result objects into dictionaries using Python’s built-in __dict__ method

Then delete the non-essential Query attributes, and then return and transform the content

new

Having just finished converting to JSON, the challenge now is how do you convert JSON to objects

After some bad attempts at handwriting initializing methods/adding from_dict methods, etc

The author solves this problem by using parametric structure, namely **

Therefore, there is no solution in the encounter, must first calm thinking or consulting others, do not study at random, will take too many detours

The code:

@classmethod
def add(cls, data: dict) :
    "" new :return: none """
    result = cls(**data)
    db.session.add(result)
    db.session.commit()
    return result
Copy the code

Structure the JSON format data (that is, the dictionary) passed by the front end to realize the object construction

Modify the

Unlike additions, modifications may change only some fields but not all of them

So, we take advantage of hasattr and setattr:

@classmethod
def update(cls, id, data) :
    "" update :return: none """
    old = cls.get(id)
    if old is None:
        raise BusinessException('Resource does not exist')
    for key, value in data.items():
        if hasattr(old, key):
            setattr(old, key, value)
    db.session.commit()
Copy the code

conclusion

The basic CRUD encapsulation is complete at this point

But there seems to be some inelegance, and tomorrow’s final post will be refined