This article example describes the Sanic framework routing usage. Shared for your reference, as follows:
The previous article, "TheSanic Framework Installation and Getting StartedA brief introduction to the installation and basic usage of the Sanic framework, here to learn more about the routing of the Sanic framework.
synopsis
Sanic is a Flask-like Python 3.5+ web server that writes very fast. In addition to Flask, Sanic supports asynchronous request handlers. This means you can use the shiny new asynchronous/wait syntax in Python 3.5 to make your code non-blocking and fast.
Preface:Sanic supports Python 3.5 as a minimum.If you need to learn Sanic, please download it first.Python packages with version no less than 3.5
routing (in computer networks)
Routing allows the user to specify different handler functions for different URL endpoints, and we took out the previous article,Sanic Framework Installation and Getting StartedThe routing of "The
from import json @("/") async def hello_sanic(request): data = json({"code":0}) return data
When we typehttp://localhost:5000/When it matches to the handler function according to the routehello_sanic
The Sanic handler function must use the syntaxasync def
to be defined because they are isoparametric numbers.
Request Parameters
The Sanic handler function comes with a parameter that supports the request, i.e. the aboverequest
Parameters. If we need to formulate a parameter, we can enclose it in sharp brackets as follows:
from import json @("/hello/<name>") async def hello(request,name): return json({"name":name})
At this point we enter it again in the browser:http://localhost:5000/hello/laowangWhen you do this, Sanic will match the processing function against the route and return the data. At this point, we need to specify the type of the parameter, which can be done by appending the:type
, assuming that you pass in aageparameter for theinttype, routes can be written this way:/hello/<age:int>
. The code is as follows:
from import json @("/hello/<age:int>") async def hello_age(request,age): return json({"age":age})
At this point it is possible to specify that the user passes in a parameter of the specified type. If the type is not correct, a 404 error will be reported.
Type of request
There are quite a few examples of Sanic handling web requests, but these are all GET requests, so how do we define a POST request? Same as Flask.@
Supports an optional parametermethods
,methods
A list type can be passed in so that it will allow the handler function to use any HTTP method in the list.
from import json @("/post/json_data",methods=["POST"]) async def post_json(request): """ POST request json data """ return json() @("/post/form_data",methods=["POST"]) async def post_form(request): """ POST request form form data """ return json() @("/get/data",methods=["GET"]) async def get_data(request): """ GET request """ return json()
on account ofGETrequest by default, so if you need to define aGETrequest, then the methods parameter may not be passed.@
Another optional parameter is also supportedhost, which restricts a route to the provided host or hosts.
from import text @("/hello/host",host="") async def hello_host(request): return text("hello host")
Access this route in a browser if the host headers do not matchIf you do, then a 404 error will be reported.
The decorator writing style for routing can be abbreviated in addition to the kind described above, as follows:
from import json @("/short/get") async def short_get(request): return json() @("/short/post") async def short_post(request): return json()
add_route method
Typically we specify a route via the@
decorator, however, this decorator is really just thisadd_route
A wrapper around the method, used as follows:
async def add_get_route(request): """ Adding a GET request """ return json() async def add_get_type_route(request,age): """ Adding a GET request with a parameter of the specified type """ return json({"age":age}) async def add_post_route(request): """ Adding a POST request """ return json() app.add_route(add_get_route,"/add_get_route") app.add_route(add_get_type_route,"/add_get_type_route/<age:int>") app.add_route(add_post_route,"/add_post_route",methods=["POST"])
redirects
Sanic provides a method for url_for to generate URLs based on handler method names. This is useful if you want to avoid hard-coding URL paths into your application. For example:
from import text,redirect @("/url_info") async def url_info(request): url = app.url_for('post_handler',name="laozhang",arg_one="one",arg_two="two") print(url) return redirect(url) @("/post_handler/<name>") async def post_handler(request,name): print() return text("name:{}".format(name))
Note on the use of url_for: the first parameter is the route name of the redirected URL (default is the function name), not the URL name. Also we can assign some request parameters to the url_for method, the above example redirected url will be:
/post_handler/laozhang?arg_one=one&arg_two=two
It is also possible to pass multi-valued parameters:
app.url_for("post_handler",favorite=["football","bastketball"]) # /post_handler?favorite=football&favorite=bastketball
Unique URL
In Flask, we top one by one.URL
because of/get
At this point, we will be able to access /get successfully if we type/get/
will return a 404 error, which is the unique URL. this feature is also available in Sanic, which we can configure with thestrict_slashes
parameter to realize it:
from import text @("/get",strict_slashes=True) async def get(request): return text("it is ok!")
take note of:strict_slashes
The default value is None, and if it is not set, accessing the/get
maybe/get/
All will be accessible successfully, then this is not a unique URL. In the example above, we set this value to True, at which point we type/get/
, which will return a 404 error, thus completing the implementation of a unique URL.
If we need to set all URLs as unique URLs, we can do this:
from sanic import Sanic from import text app = Sanic(strict_slashes=True) @("/hello") async def hello(request): return text("it is ok!") @("/world") async def world(request): return text("it is ok!")
/hello
cap (a poem)world
are turned into unique URLs.
If we only need part of the URL to be set to a unique URL, we can set it in the@
The decorator passes in thestrict_slashes
, and set to Flase, then this URL will not be a unique URL. or we can define a blueprint as follows:
from sanic import Blueprint ss_bp = Blueprint("aaa",strict_slashes=False) @ss_bp.route("/world") async def world(request): return text("it is ok!") (ss_bp)
Even if you pass parameters in the appstrict_slashes=True
, then it's no use, all URLs defined through this blueprint will not be unique URLs.
Customized Route Names
Usually the name of a route is the name of the program's processing method, theFunctions. __name__
generated for a decorator that can be passed a name parameter to modify its name as follows:
from import text @("/get",name="get_info") async def get(request): return text("it is ok!")
this timeurl_for
Instead of the function name, the value of name will be passed:
print(app.url_for("get_info")) # /get
The same applies to blueprints:
from sanic import Blueprint ss_bp = Blueprint("test_bp") @ss_bp.route("/get",name="get_info") async def get(request): return text("it is ok!") (ss_bp) print(app.url_for("test_bp.get_info"))
URL of the static file
We need to construct a specific URL to access the HTML we need, at this point we can do this:
from sanic import Sanic,Blueprint app = Sanic() ("/home","./static/")
At this point we are accessing the/home
It will be able to link to the HTML we specified. This method also applies to blueprints.
CompositionView
In addition to the above methods for defining routes, Sanic also provides theCompositionView
to dynamically add routes:
from import CompositionView from import text async def post_handler(request): print() return text('it is ok!') view = CompositionView() (["POST"],post_handler) app.add_route(view,"/post_info")
In this way, an interface for POST requests is constructed
processor decorator
Since Sanic handlers are simple Python functions, modifiers similar to Flask can be applied to them. A typical use case is when some code wants to be executed before the handler's code is executed:
from import text def is_authorized(): return True def authorized(func): async def wrapper(request,*args,**kwargs): is_auth = is_authorized() if is_auth: response = await func(request,*args,**kwargs) return response else: return text("it is not authorized") return wrapper @("/get_user_info") @authorized async def get_user_info(request): return text("get_user_info")
More about Python related content can be viewed on this site's topic: thePython introductory and advanced classic tutorials》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand theSummary of Python file and directory manipulation techniques》
I hope that what I have said in this article will help you in Python programming.