


Detailed explanation of python using decorator to automatically register Tornado routing
First version
In this version, the RouterConfig object is first created, and its constructor creates tornado.web.Application()
and assigns a value For self.Application
, add the @app.route
decorator on each Handler, which corresponds to the route object under RouterConfig, in which the Handler instance will be assigned to the handler parameter. Finally, the corresponding relationship between URL and Handler is added to the routing table, and the URL attribute is created in each Handler.
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # Created by 安生 on 2017/2/9 import tornado import tornado.web import tornado.ioloop class RouterConfig: def __init__(self): self.Application = tornado.web.Application() # 创建路由对象 def route(self, handler): self.Application.add_handlers('.*$', [(handler.URL, handler)]) # 路有关系映射添加到路由表中 app = RouterConfig() # 创建路由 @app.route class MainHandler(tornado.web.RequestHandler): URL = r'/' def get(self, *args, **kwargs): self.write('Hello, 安生') @app.route class MainHandler(tornado.web.RequestHandler): URL = r'/hi' def get(self, *args, **kwargs): self.write('hi, 安生') if __name__ == "__main__": app.Application.listen(8000) print("http://127.0.0.1:8000/") tornado.ioloop.IOLoop.instance().start()
Second version
Create a Route object, and then add a decorator to the Handler @route(r'/')
, and pass in the URL, which corresponds to the url parameter in the __call__
method, and then add the route correspondence to the list in the form of ancestors , after all routes have been added, create the Tornado route object, then put the routing table into it, and finally complete the registration.
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # Created by 安生 on 2017/2/9 import tornado.ioloop import tornado.web class Route(object): """ 把每个URL与Handler的关系保存到一个元组中,然后追加到列表内,列表内包含了所有的Handler """ def __init__(self): self.urls = list() # 路由列表 def __call__(self, url, *args, **kwargs): def register(cls): self.urls.append((url, cls)) # 把路由的对应关系表添加到路由列表中 return cls return register route = Route() # 创建路由表对象 @route(r'/') class MainHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): self.write('Hello, 安生') @route(r'/hi') class MainHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): self.write('hi, 安生') application = tornado.web.Application(route.urls) # 创建app,并且把路有关系放入到Application对象中 if __name__ == '__main__': application.listen(8000) print("http://127.0.0.1:%s/" % 8000) tornado.ioloop.IOLoop.instance().start()
The third version
This version is also the version I am using now, the principles are the same , the feature here is to inherit the Tornado routing object
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # Created by 安生 on 2017/2/9 import tornado.web import tornado.ioloop class RouterConfig(tornado.web.Application): """ 重置Tornado自带的路有对象 """ def route(self, url): """ :param url: URL地址 :return: 注册路由关系对应表的装饰器 """ def register(handler): """ :param handler: URL对应的Handler :return: Handler """ self.add_handlers(".*$", [(url, handler)]) # URL和Handler对应关系添加到路由表中 return handler return register app = RouterConfig(cookie_secret='ulb7bEIZmwpV545Z') # 创建Tornado路由对象,默认路由表为空 @app.route(r'/') class MainHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): self.write('Hello, 安生') @app.route(r'/hi') class MainHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): self.write('hi, 安生') if __name__ == "__main__": app.listen(8000) print("http://127.0.0.1:%s/" % 8000) tornado.ioloop.IOLoop.instance().start()
Test
In the above version, test The method and output are the same. You can use the requests module to simulate HTTP requests
>>> import requests >>> requests.get('http://127.0.0.1:8000/').text 'Hello, 安生' >>> requests.get('http://127.0.0.1:8000/hi').text 'hi, 安生'
More python uses decorators to automatically register Tornado routing related articles Please pay attention to PHP Chinese website!

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version
Useful JavaScript development tools
