Building off of where we left at in Building a modular web application with python flask, Angular, and AWS : Part 1 we created a simple page that served very static content from within the page itself. Now let’s make this Python Flask code look a little more like a web application and be sure to follow me if you want to updated on when the next post is released.
To start off lets add an index.html inside of the templates folder and give it the following content:
And inside theme.css lets add a simple background color change on the body to see that Flask is indeed serving our static assets.
Now we need to modify our previous application a little. We will go back to app/__init__.py and change our Flask object declaration to this:
app = Flask(__name__, static_path=’/static’)
The main takeaways are we added the from flask import line, this will give us access to use flask’s provided Jinja2 templating engine which you can use this to drive all of your views if you wish but as stated in part 1, driving the UI client side will give us a few added benefits such as saving server load and presenting realtime data updates without having to reload the page by building dynamic backend routes.
We also replaced return “hello world” with the method call render_template(‘index.html’) which flask will automatically look for an index.html in our templates folder to render back to the client.
Our new web page as an actual html file:
As you can see we are getting the title and content as set from the html as well as the background from our style sheet. The page still looks like it was made by a third grader but we are getting closer to doing something cool at least.
As an exercise in Jinja2’s templating and a little more about Python routes lets add another page with a conditional. Copy the following into the bottom of our views.py file:
return render_template(‘hello.html’, user=user)
What we are doing is adding the new hello route enabling us to type http://127.0.0.1:5000/hello/ or http://127.0.0.1:5000/hello/yourname into the browser. Flask will determine if the optional user was provided and flask will do it’s fancy magic before serving the page back to the client.
In the next part of this tutorial we will bring in a free bootstrap theme to make our UI look a little better and create a simple angular page to start doing some client side logic and expose data from our flask back-end into our angular ui.
Thanks for stopping by and hope to see you next time, if you like the content please help me out by sharing and enabling me to continue bringing more technical content!