Skip to content

Instantly share code, notes, and snippets.

@aaronchall
Last active March 23, 2016 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronchall/bcf6fdea61cb561a5b4d to your computer and use it in GitHub Desktop.
Save aaronchall/bcf6fdea61cb561a5b4d to your computer and use it in GitHub Desktop.
"""Remove redundancy and give function names meaning when using the route decorator.
@route
def home():
return 'hello'
@route
def profile(username):
return 'your name is ' + username
@route
def post(post_num: int):
return '<h1>Post ID is %s </h1>' % post_num
Actual code with explanation below
"""
from flask import Flask
app = Flask(__name__)
def route(fn):
fn_name = fn.__name__
if fn_name == 'home':
return app.route('/')(fn)
annotations = fn.__annotations__
if annotations:
if len(annotations) == 1:
key, value = list(annotations.items())[0]
if isinstance(value, type):
value = value.__name__
else:
raise RuntimeError('type annotation must be a type?')
return app.route('/{}/<{}:{}>'.format(fn_name, value, key))(fn)
else:
raise RuntimeError('I do not know what I am doing.')
else:
code_obj = fn.__code__
if code_obj.co_argcount == 1:
return app.route('/{}/<{}>'.format(fn_name, code_obj.co_varnames[0]))(fn)
@route
def home(): # home mapped to /
return 'hello'
@route
def profile(username): # will be /profile/<username>
return 'your name is ' + username
@route
def post(post_num: int): # will be /post/<int:post_num>
return '<h1>Post ID is %s </h1>' % post_num
# above now same as below
'''
@app.route('/')
def home():
return 'hello'
@app.route('/profile/<username>')
def profile(username):
return 'your name is ' + username
@app.route('/post/<int:post_num>')
def post(post_num):
return '<h1>Post ID is %s </h1>' % post_num
'''
if __name__ == '__main__':
app.debug = True
app.run('0.0.0.0', debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment