当前位置:网站首页>Mini web framework: adding routes in decorator mode | dark horse programmer
Mini web framework: adding routes in decorator mode | dark horse programmer
2022-06-24 04:43:00 【Dark horse programmer official】
Learning goals
- You can know how to add routes in decorator mode
1. Add a route using a decorator with parameters
We have already implemented the routing list , But every time you add a route, you need to add it manually , Next, we want to complete the automatic addition of routes , It can be realized by decorator , When decorating a processing function with a decorator, we need to know that the decorated function is associated with the request path , That is to say, the decorator needs to receive one url Parameters , So the decorator we define is a decorator with parameters .
Sample code :
"""miniweb frame , Responsible for processing dynamic resource requests """
import time
# Define routing list
route_list = []
# Decorator with parameters
def route(path):
# Decorator
def decorator(func):
# When executing the decorator to decorate the specified function , Add paths and functions to the routing list
route_list.append((path, func))
def inner():
# Execute the specified function
return func()
return inner
# Return to the decorator
return decorator
# Get home page data
@route("/index.html")
def index():
# Response state
status = "200 OK";
# Response head
response_header = [("Server", "PWS2.0")]
# Open template file , Reading data
with open("template/index.html", "r") as file:
file_data = file.read()
# Processed data , Query from database
data = time.ctime()
# Replace the template in the template file
result = file_data.replace("{%content%}", data)
return status, response_header, result
# Get personal center data
@route("/center.html")
def center():
# Response state
status = "200 OK";
# Response head
response_header = [("Server", "PWS2.0")]
# Open template file , Reading data
with open("template/center.html", "r") as file:
file_data = file.read()
# Processed data , Query from database
data = time.ctime()
# Replace the template in the template file
result = file_data.replace("{%content%}", data)
return status, response_header, result
# Dynamic resource not found
def not_found():
# Response state
status = "404 Not Found";
# Response head
response_header = [("Server", "PWS2.0")]
# Processed data
data = "not found"
return status, response_header, data
# Handle dynamic resource requests
def handle_request(env):
# Get the dynamic request resource path
request_path = env["request_path"]
print(" Dynamic resource request received :", request_path)
# Traverse the routing list , Select the function to execute
for path, func in route_list:
if request_path == path:
result = func()
return result
else:
# Dynamic resource not found
result = not_found()
return result
2. Summary
- Decorate the handler with a decorator with parameters , And complete the function of adding routes .
More details are welcome Python special column , Continue to update more good learning content for everyone ↑ ↑ ↑
边栏推荐
- Activity recommendation | cloud native community meetup phase VII Shenzhen station begins to sign up!
- Advanced authentication of uni app [Day12]
- What does VPS server mean? What is the difference between a VPS server and an ECS?
- What are the advantages of ECS? Is ECS better than VM?
- Advantages of fixed assets management system
- SAP MTS/ATO/MTO/ETO专题之七:ATO模式1 M+M模式策略用82(6892)
- Web technology sharing | [map] to realize customized track playback
- Integration of Alibaba cloud SMS services and reasons for illegal message signing
- 事件
- How to add a domain name to ECS? What are the advantages of ECS?
猜你喜欢

阿里云新一代云计算体系架构 CIPU 到底是啥?

Weibo International Edition changed its name to Weibo light sharing Edition

Detailed explanation of tcpip protocol

『渗透基础』Cobalt Strike基础使用入门_Cobalt Strike联动msfconsole

一款支持内网脱机分享文档的接口测试软件

Recognize workplus again, not only im but also enterprise mobile application management expert

博士申请 | 香港科技大学(广州)刘浩老师招收数据挖掘方向全奖博士/硕士

SAP MTS/ATO/MTO/ETO专题之八:ATO模式2 D+空模式策略用85

External network access SVN server (external network access SVN server deployed on the cloud)

Multi task video recommendation scheme, baidu engineers' actual combat experience sharing
随机推荐
What is etcd and its application scenarios
Doctor application | Hong Kong University of science and Technology (Guangzhou) Mr. Liu Hao recruits the full award doctor / Master in data mining
What is the difference between arm architecture, ARM7, ARM9, STM32, cortex m3 M4, 51 and AVR
SAP mts/ato/mto/eto topic 7: ATO mode 1 m+m mode strategy 82 (6892)
Application and related research of Worthington elastase
集成阿里云短信服务以及报签名不合法的原因
An interface testing software that supports offline document sharing in the Intranet
数据库解答建标,按要求回答
2020年Android面试题汇总(中级)
ServiceStack. Source code analysis of redis (connection and connection pool)
How to add a domain name to ECS? What are the advantages of ECS?
Introduction to C language custom types (structure, enumeration, union, bit segment)
web渗透测试----5、暴力破解漏洞--(8)PostgreSQL密码破解
『应急响应实践』LogParser日志分析实践
Spirit breath development log (16)
Brief introduction: how much do you know about supply chain attacks
Training course of mixed accuracy from simple to deep
uni-app进阶之认证【day12】
Web penetration test - 5. Brute force cracking vulnerability - (5) SMB password cracking
External network access SVN server (external network access SVN server deployed on the cloud)