Last active
March 17, 2017 20:20
-
-
Save tuxpowered/e3ed71842de647f9664df474cae98d57 to your computer and use it in GitHub Desktop.
URL Path parser for Flask Apps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from flask import Flask | |
| from werkzeug.routing import BaseConverter | |
| app = Flask(__name__) | |
| class FooConverter(BaseConverter): | |
| regex = '[^/].*?' | |
| weight = 200 | |
| def to_python(self, value): | |
| spl = value.split("/") | |
| rtn = { | |
| "category": spl[0], | |
| "values": [] | |
| } | |
| if len(value.split("/")) > 1: | |
| rtn["values"] = spl[1:] | |
| return rtn | |
| def to_url(self, values): | |
| return '+'.join(BaseConverter.to_url(value) for value in values) | |
| app.url_map.converters['custom_converter'] = FooConverter | |
| @app.route("/<custom_converter:data>", methods=["GET", "POST"]) | |
| def blabla(data): | |
| if data["category"] == "bla": | |
| if data["values"] == "w0w": | |
| pass | |
| return "category: %s, values: [%s]" % (data["category"], ",".join(data["values"])) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment