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)
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 @functionally 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.