Skip to content

Instantly share code, notes, and snippets.

@amcgregor
Last active July 15, 2019 12:36
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 amcgregor/df63872beda87d4b0765c28963d5cf40 to your computer and use it in GitHub Desktop.
Save amcgregor/df63872beda87d4b0765c28963d5cf40 to your computer and use it in GitHub Desktop.
A comparison of supplying default arguments to endpoints between Flask and WebCore.
from datetime import datetime
from flask import Flask
app = Flask(__name__)
@app.route('/api/time')
def time():
return jsonify(now=datetime.now().isoformat())
@app.route('/api/greet/<name>')
@app.route('/api/greet-stranger/', defaults={'name': 'mysterious person'})
def greeting(name):
return jsonify(greeting=f"Welcome, {name}")
# Question this poses:
# Can you POST name=Bob+Dole to /api/greet-stranger/ and have it use the submitted form variable?
# Basically, is this unintentionally duplicating the possible API endpoints for this purpose?
# (Zen: There should be one, and preferably only one right way to do something...)
#
# Ansewer to the above: no. Flask does not automatically apply any request-sourced data beyond
# matching the path elements to arguments.
#
# Admittedly, object dispatch can't replicate a "greet-stranger" endpoint declaratively, as Python
# literals can not be broken up by hyphens.
from datetime import datetime
class Root:
class api:
def time(self):
return {"now": datetime.now().isoformat()}
def greet(self, name="mysterious person"):
"""Greet someone.
With nobody specified, defaults to a stranger. Allows:
GET /api/greet
GET /api/greet/<name>
GET /api/greet?name=<name>
POST /api/greet name=<name>
"""
return {"greeting": f"Welcome, {name}"}
def __getattr__(self, name): # Handle the special case of the hyphenated endpoint name.
if name != 'greet-stranger':
raise AttributeError()
return self.greet
# Notable distinction: the above API definition is entirely usable outside the context of web requests.
# There is absolutely no awareness of the web context in any of this.
#
# Additionally, by returning dictionaries, the serialization will be RESTfully negotiated using the Accept header.
# While preserving native Python API use. Your endpoints could also be returning actual model objects to be even
# more useful.
#
# Ref: https://github.com/marrow/WebCore/blob/develop/web/ext/serialize.py?ts=4#L54
# Ref: https://github.com/marrow/WebCore/blob/develop/web/core/view.py?ts=4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment