This is the 27th day of my participation in Gwen Challenge
preface
The above completes the encapsulation of the CRUD method
Conversion between JSON and flask-SQLalchemy query result objects is also briefly introduced
But there are a few small problems:
- How do I return json results
- How to unify the date format
- Paging queries return inelegant results
This article will answer these three questions in detail
plan
How do I return json results
In Flask, we are provided with a function called jsonify that converts the data content into A JSON string
So our interface can be written roughly like this:
from flask import request, jsonify
from flask_restx import Namespace, Resource
from .model import User
auth = Namespace('auth'.'Authentication Management')
@auth.route('/login')
class Login(Resource) :
def post(self) :
params = request.get_json()
user = User.get_by_username(params['username'])
if not check_password_hash(user.password, data['password') :raise BusinessException('Password error')
return jsonify(user)
Copy the code
How to unify the date format
In general, we convert the date from the background to a timestamp and pass it to the front end. There are two simple solutions:
- Save as a timestamp
- Manual conversion process
The first one is obviously not displayed and provides a date field in the database, saving it as a timestamp is a bit of an overkill
The second is obviously correct in theory, but manual is not required
We obviously want the code to automatically handle date formatting, such as some annotations in Java, every time we transform JSON
Flask actually provides support for custom JSON encoders:
from flask import Flask
from .encoders import MyJSONEncoder
app = Flask(__name__)
app.json_encoder = MyJSONEncoder
Copy the code
After replacing the JSON encoder, let’s take a look at how our encoder handles time:
from datetime import datetime
from flask.json import JSONEncoder
class MyJSONEncoder(JSONEncoder) :
def default(self, o) :
if isinstance(o, datetime):
return str(round(o.timestamp()))
else:
return super().default(o)
Copy the code
Did the guys have a lot of ideas all of a sudden?
Paging queries return inelegant results
Json encoders can be customized, this problem will not be us?
In paging, the tricky part is how do you convert the resulting object into a dictionary and get rid of query attributes that can’t be serialized
Now that we know how to modify it, we can continue to adjust the JSON encoder:
from datetime import datetime
from flask.json import JSONEncoder
from flask_sqlalchemy import Pagination
class KoalaJSONEncoder(JSONEncoder) :
def default(self, o) :
if isinstance(o, datetime):
return str(round(o.timestamp()))
if isinstance(o, Pagination):
temp = o.__dict__
del temp['query']
temp['pages'] = o.pages
return temp
else:
return super().default(o)
Copy the code
conclusion
At this point, the encapsulation of Flask-SQLAlchemy is almost complete
Of course, the author also carried out more in-depth encapsulation of these in the follow-up, and then there will be time for more detailed explanation for the new brothers