TAGS :Viewed: 3 - Published at: a few seconds ago

[ Web Hosting Using Python Part 2 ]

In the previous part of this tutorial we saw how to run a basic web page on a server using Flask. The tutorial can be found here. Now we can take a look at how to render an already present HTML page which can also include CSS in itself. Creating the HTML File Below is a basic HTML file that also contains CSS (between the Style Tags) and some JavaScript (between the script tag). This is a dynamic page as its output changes on button click. The output of the above code is as shown below Output Before Button Click Output After Button Click This HTML file runs smoothly on the machine (without any server), but to run this on a Flask server we will need to add the entire HTML code for the file in the return statement, which is not really feasible. Let’s see an easier way to do it in Flask. File Structure of a Flask Server All the HTML files are stored in a folder named templates which can be in the same directory as the Flask application. Hence, to include the HTML file in the application, we create a folder in the same directory as our Flask application and name it as templates. Now we need to add our Flask file to this templates folder. File Structure The HTML file is included in the templates folder. Changes to the Flask Application Making changes to the Flask application is fairly simple. We just need to specify the name of the HTML file from which we want to render the HTML code. Flask by default looks at the templates folder to search for HTML templates. Code For Flask Application The only changes made in this Flask application is on lines 1 and line 6. On line 1 we import the render template module and on line 6 we include it in the return statement, by passing the name of the HTML file. The process to run the application on the local server remains the same as discussed in the first tutorial. Lets see the output of the application on the local server. Output Before Button Click Output After Button Click As we can see, our Flask application runs perfectly fine now on the server. Thanks for Reading In the upcoming Publications we will see how to render CSS and JavaScript that are present as separate files and not included in the same HTML document. Please comment your views about the publication in the comment box.