@@ -99,11 +99,66 @@ the folder and then create a file named `app.py` with the following
9999code.
100100
101101``` python
102+ import re
103+ from flask import Flask, render_template
104+ from werkzeug.exceptions import NotFound
102105
106+
107+ app = Flask(__name__ )
108+
109+ MIN_PAGE_NAME_LENGTH = 2
110+
111+
112+ @app.route (" /<string:page>/" )
113+ def show_page (page ):
114+ valid_length = len (page) >= MIN_PAGE_NAME_LENGTH
115+ valid_name = re.match(' ^[a-z]+$' , page.lower()) is not None
116+ if valid_length and valid_name:
117+ return render_template(" {} .html" .format(page))
118+ else :
119+ msg = " Sorry, couldn't find page with name {} " .format(page)
120+ raise NotFound(msg)
121+
122+
123+ if __name__ == " __main__" :
124+ app.run(debug = True )
103125```
104126
127+ The above application code has some standard Flask imports so we can
128+ create a Flask web app and render template files. We have a single
129+ function named ` show_page ` to serve a single Flask route. ` show_page `
130+ checks if the URL path contains only lowercase alpha characters for a
131+ potential page name. If the page name can be found in the ` templates `
132+ folder then the page is rendered, otherwise an exception is thrown
133+ that the page could not be found. We need to create at least one template
134+ file if our function is ever going to return a non-error reponse.
135+
136+ Save ` app.py ` and make a new subdirectory named ` templates ` under your
137+ project directory. Create a new file named ` battlegrounds.html ` and put
138+ the following [ Jinja2] ( /jinja2.html ) template markup into it.
139+
140+ ``` jinja2
141+ <!DOCTYPE html>
142+ <html>
143+ <head>
144+ <title>You found the Battlegrounds GIF!</title>
145+ </head>
146+ <body>
147+ <h1>PUBG so good.</h1>
148+ <img src="https://media.giphy.com/media/3ohzdLMlhId2rJuLUQ/giphy.gif">
149+ </body>
150+ </html>
151+ ```
152+
153+ ** The above template does...**
154+
155+ Time to run and test our code. Change into the base directory of your
156+ project where ` app.py ` is located. Execute ` app.py ` using the ` python `
157+ command as follows:
105158
106- Test it out.
159+ ``` bash
160+ python app.py
161+ ```
107162
108163We can see the error because we are testing our application locally,
109164but what happens when our application is deployed and a user gets the
0 commit comments