Search code examples
pythonrestflaskvariadic-functions

Working around receiving a string containing slashes in flask


I'm a newbie to Flask so I'm trying to wrap my head around this problem.

I'm trying to make a simple request using the following URL:

@app.route("/home/components/<component_name>")
def get_component(component_name):
  #do something
  return component_data

Which would yield all the data related to a component used in my project.

Problem is, all component names use slashes (ie: "Process/Newday", "Exe/ADM1/polling") which makes it impossible to pass them through the url, so what I'd need is something akin to this:

@app.route("/<components>/*args")
def get_component(args):
  component_name = ""
  for arg in args:
    component_name += "/{}".format(arg)
  #do something
  return component_data

However despite searching here and there I can't find a feasible way to achieve this


Solution

  • Have you considered using query parameters instead?

    from flask import request
    
    @app.route("/home/components")
    def get_component():
        component_name = request.args.get('name')
    

    and then access that address like:

    yourdomain.com/home/components?name="Exe/ADM1/polling"
    

    Note that otherwise, unless the number of slashes is fixed, there is no proper way for slack to know which slash is a separator and which is a part of the parameter