A request parameter checking and parsing library
Hi, have you used sanic-pydantic? It is a pydantic extension plugin for sanic
Every time I process request parameters, I must use the get method to get them out at first, and then check the validity of each request parameter.
I always thinking is there any good way to do parameter type checking for me?
As predicted I found python-sanicargs
and sanic-pydantic
When I browsed the community and awsome-sanic projects.
All of them are request parameter check plugins and I used it in a long time.
But, are they really friendly and easy to use ? I don’t think so.
python-sanicargs
is very simple, but I must give all parameters as formal parameters for my function and tell it their types. It is enough for daily simple parameter type checking. But it has no way to complete more complex parameter checking.
@app.route("/me/<id>/birthdate", methods=['GET'])
@parse_query_args
async def test_datetime(req, id: str, birthdate: datetime.datetime):
return response.json({'id': id, 'birthdate': birthdate.isoformat()})
If you want check more complex paramters, you need use sanic-pydantic
. It supports custom pydantic classes and performs parameter checking.
At one time, I thought I had found the best parameter checking tool, But I found that I couldn’t install it with pipy !
What? What the fuck? all right, I can install by git. but when I installed it, I found that it doesn’t support class-based views ! oh~ dear, I worked hard, only to find that it can’t be used in class-based views.
Well, since none of them meet my requirements, I’ll have to make a tool myself.
So I created the sanic-dantic library, It is based on pydantic, which can facilitate developers to quickly check and obtain request parameters.
In here, you needn’t give all parameters as formal parameters and it supports class-based views. And the most important point is that it can quickly get the request parameters in different request methods from the same place.
Are you a little excited? please come and have a look at here
Finally, thanks to the author Eric Jolibois of pydantic and the author Ahmed Nafies of sanic-pydantic, Because of their open source, I have the inspiration to write sanic-dantic. Thank them very much
P.S. Send out a simple useage
from sanic import Sanic
from sanic.response import text
from sanic_dantic import BaseModel, parse_params
app = Sanic("SimpleExample")
class Person(BaseModel):
name: str
age: int
class Car(BaseModel):
speed: int
@app.route('/example')
@parse_params(query=Car, body=Person)
async def example(request, params):
return text(f"{params.name} is {params.age} years old, " +
f" his speed is {params.speed}")
if __name__ == '__main__':
app.run("0.0.0.0", port=8000)