formations/python-avancé/examples/decorator-flask.py

40 lines
768 B
Python

from urllib.parse import parse_qsl
class Application:
def __init__(self):
self.routes = {}
def route(self, path):
def deco(fct):
self.routes[path] = fct
return fct
return deco
def get(self, path):
try:
path, qs = path.split("?", maxsplit=1)
except ValueError:
qs = {}
return self.routes[path](**dict(parse_qsl(qs)))
app = Application()
@app.route("/")
def home():
return "<a href='/api'>/api</a>"
@app.route("/api")
def api():
return {"version": "1"}
@app.route("/auth/")
def auth(username, password):
return f"Wrong password for {username}"
print(app.get("/"))
print(app.get("/api"))
print(app.get("/auth/?username=mdk&password=test"))