面试题答案
一键面试设计思路
- URL 路径与业务函数映射:创建一个字典,将不同的 URL 路径模式映射到对应的业务处理函数。
- 参数类型校验:在业务处理函数内部或者单独创建校验函数,对传入的参数进行类型检查。
- 错误处理:使用
try - except
块捕获可能出现的异常,如参数类型错误、函数未找到等,并返回合适的错误信息。 - 性能优化:
- 减少不必要的重复计算,例如对于相同的参数校验结果可以缓存。
- 使用高效的数据结构,如字典用于快速查找业务函数。
关键代码实现
# 业务处理函数示例
def handle_user_info(name: str, age: int):
if not isinstance(name, str) or not isinstance(age, int):
raise TypeError("name must be str and age must be int")
return f"User {name} is {age} years old"
def handle_product_info(product_id: int, price: float):
if not isinstance(product_id, int) or not isinstance(price, float):
raise TypeError("product_id must be int and price must be float")
return f"Product {product_id} has price {price}"
# URL 路径与业务函数的映射
route_map = {
"user": handle_user_info,
"product": handle_product_info
}
def route_handler(*args):
try:
if len(args) < 1:
raise ValueError("At least one argument (route key) is required")
route_key = args[0]
if route_key not in route_map:
raise KeyError(f"Route {route_key} not found")
handler = route_map[route_key]
# 传递除第一个参数(路由键)之外的其他参数给业务处理函数
return handler(*args[1:])
except (TypeError, ValueError, KeyError) as e:
return f"Error: {str(e)}"
你可以这样调用这个函数:
print(route_handler("user", "Alice", 30))
print(route_handler("product", 1001, 99.9))
print(route_handler("unknown", 1))