Question:
How do I create a separate URL for each item in a list in Flask?
I’m trying to archive some of the fun things PikaBot2005 said and I was hoping to not have to manually create a URL for each document. Basically, the goal is to take a list I made of file names and create a separate URL for each file, sending its content to a webpage.
Currently only the first file listed on the main page works. I don’t even know why it works because there are spaces in the URL. I’m learning Flask but have a pretty good understanding of Python as a whole; please help me.
All static files in flask will be served if they are under the static directory, although you can configure this. A flask structure usually looks like this:
What I want is the URL to be the name of the files in /static/pikaDocs. I also want the data in render_template to be the contents of that file. I know how to do this manually but I really want a for loop or something so that it’s easier to add to.
EDIT: More specifically, the URL of the HTML page needs to be the name of the text file.
@app.route('/docs/<string:docTitle>')
def docs(docTitle):
for docTitle in pikaDocs:
with open(f"static/pikaDocs/{docTitle}") as document:
document = document.readlines()
return render_template("document.html", title=docTitle, document=document)
Was right, except for the for loop, remove that. It is unnecessary, I also recommend not putting the docs in static, as then they can be shown publicly without the html.
Really I was that close? That’s kinda sad. It works now. I’ll move the folder once I get the rest of this figured out (I don’t find it urgent). I have two questions though.
How do the parameters work in the Flask @app.route() functions?
How do I fix the spaces in the URLs? I’m fine replacing them with underscores. I might just have to rename the files. I could even have the program do that.
I seriously have no idea why it works now. How does it know what docTitle is? I have no idea where that gets assigned, just where it gets used.
@app.route('/docs/<string:docTitle>')
def docs(docTitle):
with open(f"static/pikaDocs/{docTitle}") as document:
document = document.readlines()
return render_template("document.html", title=docTitle, document=document)
Okay I figured it out. The URL is supplying the file name. I’m going to do something to fix the spaces in the URL (probably rename the files). Thanks for the help!