How to Make Static .html Pages Accessible with Flask in Python

Categories: Tech | Pubby Cash Received:  10 | Click to Award

The following code can easily start a development web server on your machine with the flask module: from flask import Flask app = Flask(__name__) if __name__ == '__main__':     app.run(debug=True) Now, you would like to make any .html static files accessible using URL routing. What should you do? Here are the steps you need to follow:
Step 1: The above code needs to be revised like this: from flask import Flask, render_template app = Flask(__name__) @app.route('/html/<string:page_name>/') def render_static(page_name):     return render_template('html/%s.html' % page_name) if __name__ == '__main__':     app.run(debug=True) Step 2: Now Flask will look for any .html files in the "templates/html" folder. Go ahead to create a folder named templates in the root, and then create a subfolder named "html" within the "templates" folder. Step 3. Transfer all your static .html files into this html folder. And then all these files are accessible by the URL http://xxx.com/html/file_name Note: You cannot directly create an html folder in the root. Otherwise, the web server cannot be started, but throw out an error "ModuleNotFoundError: No module named 'htmlentitydefs'". If you delete the folder named html in the root, the error will be gone. This is because the folder name tricked Flask. By default, Flask will look into the "templates" folder for html pages. If you try to place your .html pages into a folder named other than "templates", it won't work either. Make sure be aware of that! If you are still not satisfied with this method, because with this method, it still cannot show a URL ending with a physical .html page. As you can see in the link above, the .html file name extension is cut off in the URL. To save the .html file extension in the URL the "send_from_directory" module will do the trick. from flask import Flask, render_template, send_from_directory app = Flask(__name__, static_url_path='') @app.route('/html/<path:path>') def send_html(path):     return send_from_directory('html', path) if __name__ == '__main__':     app.run(debug=True) Create a folder named 'html' in the root, and place all static .html pages into that folder. Those files will be accessible and the full name with .html extension will also be displayed in the URL like this: http://xxx.com/html/file_name.html Now you can name a folder "html" in the root in this case. That's why I like the second solution better.


Published from: Pennsylvania US
Liked by: Andy Tang, Evan Tang, fnfOzvSR 

Daily Deals


MECHANICSBURG WEATHER