当前位置:网站首页>Routing decorator of tornado project
Routing decorator of tornado project
2022-07-04 07:15:00 【youhebuke225】
With The current project As an example , Code
- When we start the project , The first thing you need is to register routes , So we can define a method , This method is called
get_handlers, To get the route of the whole project - But how to represent a class as a route ? This is the time , We used decorators
open_handler, The class decorated by this decorator , Then he is a route , thereforeopen_handlerThere are at least two parameterspathrouteindexUsed for routing sorting
Decorator
We're in the catalog tornado project core\decorators\open_handler Write down a decorator , Class as decorator Click on
class HandlerDecorate:
""" Route decorator 1. In essence, the route decorator just adds __url_path__ Properties of 2. When we initialize, we pass __url_path__ This attribute determines whether the current class is the routing processor 3. __url_path_index__ Used to sort routes """
def __init__(self, path, index=None) -> None:
self.__url_path__ = path
self.__url_path_index__ = index
def __call__(self, cls):
cls.__url_path__ = self.__url_path__
cls.__url_path_index__ = self.__url_path_index__
return cls
We are __init__.py Expose this decorator
from core.decorators.open_handler.index import HandlerDecorate
open_handler = HandlerDecorate
Just go through @open_hander Modified class , Will contain __url_paht__ attribute , Such as
@open_handler(path="/api/(.*)", index=1)
class openApiHandlerService(RequestHandler):
def get(self, *args, **kwargs):
self.write("hello world")
self.finish()
that ,openApiHandlerService Will contain __url_paht__ The attribute is /api/(.*)
Collection of routes
Definition get_handlers Method , To get the class decorated by the decorator
Traverse the project file
We need to define a function to traverse the project file , The current function is used to find the items that are
open_handlerModified class
We are core\utils\module_utils.py Next , Create a new function , Used to traverse to get all the module
import importlib
import pkgutil
import os
def get_all_modules(path, file_name):
""" Get all under the path file_name Of module """
# Get the configuration of the directory ( The directory must be a package , Just can have __path__ attribute )
_app = importlib.import_module(path)
def get_all_moudules_name(package_path, prefix=""):
# For deep traversal of folders
for loader, name, is_package in pkgutil.iter_modules([package_path]):
if is_package:
# If it's still a bag , Then traverse again , And prefix it when traversing
for _name in get_all_moudules_name(os.path.join(package_path, name), prefix=f"{
name}."):
yield prefix + _name
else:
yield prefix + name
return [
importlib.import_module(f"{
path}.{
module_name}")
for module_name in get_all_moudules_name(_app.__path__[0])
if module_name.split(".")[-1][:len(file_name)] == file_name
]
- import_module Click on , Get the function in the module 、 Properties, etc
- iter_modules Click on , Get module
To regulate , All the classes defined by our route are handlers In the file of
Get all routes under the project
We are core\decorators\open_handler So let's make a new one OpenHandler Class , And define a get_handlers Method is used to get all routes
class OpenHandler:
""" Routing container 1. Get the container class and tool class of the route during initialization 2. return tornado The routing list """
def __init__(self, source_libs) -> None:
self.source_libs = source_libs # Pass the directory name , Used to get all classes using decorators in the directory
self.handler_libs = [] # Container for storing routes
def get_handlers(self):
self._handler_libs_ = []
_modules = [] # All the moudule Containers
for _path in self.source_libs:
_modules += get_all_modules(_path, "handler")
for _module in _modules:
self.handler_libs += [
dict(
path=_member.__url_path__,
handler=f"{
_member.__module__}.{
_member.__name__}",
index = _member.__url_path_index__
)
for _name,_member in inspect.getmembers(_module, inspect.isclass)
if hasattr(_member, "__url_path__")
]
# Sort
self.handler_libs.sort(key=lambda x: x['index'])
# Generate tornado The routing object of
_result = []
for _handler_lib in self.handler_libs:
# Traversal generation tornado The routing object of
_path = _handler_lib.get("path")
_result.append(
url(_path, import_object(_handler_lib.get("handler"))))
# All routing lists
return _result
Registered routing
Generally, we need to register the route when starting the project
obtain handler All routes under
For the purpose of project specification, we have registered all routes under the name
handlerUnder folder , When starting the environment , We usually callEnvironmentClass , We areEnvironmentNext , Write a get handler Routing method under
class Environment:
...
def get_all_handlers(self):
open_handler = OpenHandler(["core"])
return open_handler.get_handlers()
What he said is to get core All routes under the folder , Then we register the route
class Application(Application):
def __init__(self):
# Initialize database 、redis etc. , When the project starts , Do not introduce model classes
# Registered routing
handlers = environment.get_all_handlers()
# Add dynamic routing
super().__init__(handlers, **config.settings)
test
- Start project , We type in
http://localhost:8888/api/, We will find that we can access the registered route 
边栏推荐
- 电子协会 C语言 1级 34 、分段函数
- 2022年6月小结
- Recursive Fusion and Deformable Spatiotemporal Attention for Video Compression Artifact Reduction
- Node connection MySQL access denied for user 'root' @ 'localhost' (using password: yes
- Transition technology from IPv4 to IPv6
- Solution of running crash caused by node error
- What is industrial computer encryption and how to do it
- How notepad++ counts words
- 云Redis 有什么用? 云redis怎么用?
- 图的底部问题
猜你喜欢

the input device is not a TTY. If you are using mintty, try prefixing the command with ‘winpty‘

Experience installing VMware esxi 6.7 under VMware Workstation 16

CMS source code of multi wechat management system developed based on thinkphp6, with one click curd and other functions
![[GF (q) + LDPC] regular LDPC coding and decoding design and MATLAB simulation based on the GF (q) field of binary graph](/img/5e/7ce21dd544aacf23b4ceef1ec547fd.png)
[GF (q) + LDPC] regular LDPC coding and decoding design and MATLAB simulation based on the GF (q) field of binary graph

Valentine's Day is coming! Without 50W bride price, my girlfriend was forcibly dragged away...
![[Flink] temporal semantics and watermark](/img/4d/cf9c7e80ea416155cee62cdec8a5bb.jpg)
[Flink] temporal semantics and watermark

图的底部问题

NLP literature reading summary

The most effective futures trend strategy: futures reverse merchandising

A new understanding of how to encrypt industrial computers: host reinforcement application
随机推荐
socket inet_ pton() inet_ Ntop() function (a new network address translation function, which converts the expression format and numerical format to each other. The old ones are inet_aton(), INET_ ntoa
【Kubernetes系列】Kubernetes 上安装 KubeSphere
【FreeRTOS】FreeRTOS学习笔记(7)— 手写FreeRTOS双向链表/源码分析
[MySQL transaction]
2022-021ARTS:下半年開始
Introduction to rce in attack and defense world
Centos8 install mysql 7 unable to start up
Selenium driver ie common problem solving message: currently focused window has been closed
Check and display one column in the known table column
Experience installing VMware esxi 6.7 under VMware Workstation 16
Since DMS is upgraded to a new version, my previous SQL is in the old version of DMS. In this case, how can I retrieve my previous SQL?
CMS source code of multi wechat management system developed based on thinkphp6, with one click curd and other functions
Boast about Devops
Boosting the Performance of Video Compression Artifact Reduction with Reference Frame Proposals and
[FPGA tutorial case 8] design and implementation of frequency divider based on Verilog
Redis interview question set
由于dms升级为了新版,我之前的sql在老版本的dms中,这种情况下,如何找回我之前的sql呢?
MySQL 45 lecture learning notes (VII) line lock
Deep understanding of redis -- a new type of bitmap / hyperloglgo / Geo
云Redis 有什么用? 云redis怎么用?