Using a function to route several pages in Flask

Question:
I doubt my title makes sense. What I would like to do is create one function which I can call to use for several pages in Python Flask. However, Flask will only let me use the sub functions once. Please just view the example code as I can’t figure out how to explain this.
Repl link: I have included a basic code snippet which reproduces the issue instead.

# This is a basic demo of what I want to work
from flask import Flask
app = Flask(__name__)
otherPageName = "fun"
@app.route("/")
def homePage():
  return f"<h1><a href='/{otherPageName}'>Other page</a></h1>"
def myFlask(URL_name):
  @app.route(f"/{URL_name}")
  def main():
    return "<h1>Hello world!</h1>"
myFlask(otherPageName) # This works
myFlask("lol") # By using "myFlask" twice, the program crashes
# because the function "main" has already been used once by Flask.
# Is there a way to somehow use a variable value as the function
# name so that I can mitigate this error?
app.run(host='0.0.0.0', port=81)

You were right it does make little sense. Here’s what I think you want(?):

from flask import Flask

app = Flask(__name__)

def main():
  return "Main"

def otherFunc():
  return "Other one"

ROUTES = {
  "main": main,
  "other": otherFunc,
}

@app.route("/")
def homePage():
  msg = ""
  for r in ROUTES:
    msg += f"<a href=/{r}>{r}</a><br />"
    
  return msg


@app.route("/<route>")
def main(route):
  return ROUTES[route]()

app.run(host='0.0.0.0', port=81)
from flask import Flask

app = Flask(__name__)
routes = ["test", "lol", "func"]


@app.route("/<_route>")
def main(_route):
    if _route in routes:
        return "<h1>Hello World!</h1>"
    return "<h1>Invalid Route!</h1>"


app.run(host="0.0.0.0", port=80, debug=True)

Both of you made it clear to me that what I wanted to do was either impractical or impossible. After some tweaking, I got what I wanted to do working. Evidently you can’t easily (or at all) make a variable value as a function name so I used more URL-based variables as @Sky suggested. I had been doing that before but had to use even more to make my site work.
View the code (implementing these changes here). I hate to mark my own post as the solution but you two only gave me ideas and I ultimately solved this myself.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.