webapp2的实际提供这种开箱 - 的WSGIApplication
类实例在其router
属性提供Router
实例可用于集中URL马平as shown in the documentation。
烧瓶没有,但这实际上是以其最基本的形式记录在Patterns for Flask: Lazy Loading中。使用LazyView
类,它定义您可以构建一个系统来提供中央URL映射 - 既可以是每个模块中的预定义符号,也可以是模块中的特定函数或类实例。
我最近发布了一个包(HipPocket),它提供了包装来简化这种模式的入门。它为此提供了两类LateLoader
和Mapper
。使用HipPocket,你的中心路由配置文件可能看起来像这样(这里假定包的布局类似于discussed here):
app。PY
from flask import Flask
app = Flask("yourapp")
# ... snip ...
urls.py
from .app import app
from hip_pocket import Mapper
mapper = Mapper(app)
mapper.add_url_rule("/", "index.index")
mapper.add_url_rule("/test", "index.test_endpoint", methods=["POST"])
mapper.add_url_rule("/say-hello/<name>",
"say_hello.greeter",
methods=["GET", "POST"])
index.py
def index():
return "Hello from yourapp.index.index!"
def test_endpoint():
return "Got a post request at yourapp.index.test_endpoint"
say_hello.py
def say_hello(name=None):
name = name if name is not None else "World"
return "Greetings {name}!".format(name=name)
run_app.py
from yourapp.app import app
from yourapp.urls import mapper
# We need to import the mapper to cause the URLs to be mapped.
if __name__ == "__main__":
app.run()
Pull requests和issue reports的欢迎!
如何为一个方法使用多个端点? 例如方法“view.index”中的“/”和“/ index” – hayi
@hayi - 你应该可以添加另一行到'urls.py'映射'/ index'到'view.index' - e 。 G。 'mapper.add_url_rule(“/”,“view.index”)'后面跟着'mapper.add_url_rule(“/ index”,“view.index”)' –
@SeanVieira您的图书馆看起来令人印象深刻,正在我的项目中使用它。我面临的一个问题是,我需要添加一个动态通配符路由。像/ context//。如何在add_url_rule函数中做到这一点 –
madhairsilence