Is there a way of recreating Sinatra's URL routing in Python? And are there any reasons why this might not be desirable?
From Sinatra:
get '/' do
'Hello world!'
end
From Flask (using decorators for routing):
@app.route("/")
def hello():
return "Hello World!"
Sinatra achieves this succinctness through Ruby blocks:
def get(path, opts={}, &block)
conditions = @conditions.dup
route('GET', path, opts, &block)
@conditions = conditions
route('HEAD', path,开发者_如何学JAVA opts, &block)
end
I gather that Python does not have an exact equivalent of Ruby blocks, but that there are ways of recreating the functionality. How might this be done?
As you said, Python doesn't have something like ruby blocks. Decorators are the commonly used solution for routing. The other way would be creating a list/dict containing the routes but since you seem to want the route definitions next to the underlying code, the decorator way is what you'll want to use.
Another way would be using metaclasses, as it is done in webpy's web.autoapplication, source code for that.
So, to your second question of 'And are there any reasons why this might not be desirable?'.
- Having named functions makes it possible to do things
url_for(some_function)
, which makes it easy to restructure the site. - named functions allow for testing, docstrings, etc.
精彩评论