Skip to content

Instantly share code, notes, and snippets.

@tuxpowered
Last active March 17, 2017 20:20
Show Gist options
  • Select an option

  • Save tuxpowered/e3ed71842de647f9664df474cae98d57 to your computer and use it in GitHub Desktop.

Select an option

Save tuxpowered/e3ed71842de647f9664df474cae98d57 to your computer and use it in GitHub Desktop.
URL Path parser for Flask Apps
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