WEB DEVELOPMENT
Python provides a great platform for web development; it is a flexible programming language that interfaces with many other languages and frameworks such as SQL to control a database and django to control dynamic elements of web pages. Here we look at how to use some frameworks, starting with Flask.
WHAT IS FLASK
Flask is a Python add-on that helps bridge your Python code to your webpage, allowing Python to control backend operations and HTML, CSS and JavaScript create a neat user-friendly web based front end. Before you tackle this section, you should be familiar with HTML.
SECTION 1 | INSTALL FLASK
On a MAC go to the terminal, in Windows OS go to the command prompt and type:
pip3 install flask
pip3 install flask
SECTION 2 | HELLO WORLD WEBSITE
After you have installed Flask you are ready to build your first website with Python and Flask. Copy the code from below.
HELLO WORLD WITH PYTHON AND FLASK
When you run your code you should get a message in Python editor similar to below:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
After this message appears your website should be ready to open in your web-browser, note the number shown in the python editor ends in 5000. Type localhost: 5000 or http://127.0.0.1:5000/ into the browser URL and your website should appear. This references the app route so for example if your app route is @app.route('/home') Then to open this page in your browser you would need to type http://127.0.0.1:5000/home.
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
After this message appears your website should be ready to open in your web-browser, note the number shown in the python editor ends in 5000. Type localhost: 5000 or http://127.0.0.1:5000/ into the browser URL and your website should appear. This references the app route so for example if your app route is @app.route('/home') Then to open this page in your browser you would need to type http://127.0.0.1:5000/home.
SECTION 3 | FOLDER STRUCTURE
To practice the skills in this section you will need to have a couple of HTML webpages already set up and they should be in the correct folder structure. If you do not have this then create a couple of HTML pages, a CSS file and create the folder structure shown below to get you started with Flask and Python.
Having this folder structure will make it easy for various pages and elements of your website to link to each other.
Choose where you are going to save your work.
1: Create a folder to hold your work, call it anything you want - keep it meaningful (myWebsite). This is where your Python files should go.
2: Inside the folder you created, create a subfolder called 'templates'. This is where your HTML pages should go.
3a: Create another folder inside the first folder you created, call it 'static'
3b: Inside the folder called 'static' create another folder called 'css'. This is where your CSS file should go.
3c: Inside the folder called 'static' create another folder called ' images'. This is where your images should go.
Choose where you are going to save your work.
1: Create a folder to hold your work, call it anything you want - keep it meaningful (myWebsite). This is where your Python files should go.
2: Inside the folder you created, create a subfolder called 'templates'. This is where your HTML pages should go.
3a: Create another folder inside the first folder you created, call it 'static'
3b: Inside the folder called 'static' create another folder called 'css'. This is where your CSS file should go.
3c: Inside the folder called 'static' create another folder called ' images'. This is where your images should go.
SECTION 4 | FLASK BASIC PRINCIPLES
Flask is a micro web framework written in Python and is great for its:
Flask will allow you to send element from your Python code to your webpage and allow you to get elements from your webpage such as user inputs back into Python. Before we move on to including HTML it is important to understand some fundamentals of Python with Flask.
- Simplicity: Flask provides the essentials to get a web application up and running.
- Flexibility: While it comes with very little out of the box, Flask is highly extensible, allowing developers to add the components they need.
- Lightweight: Flask has a small and easy-to-understand codebase, making it accessible for beginners.
- Beginner-Friendly: Flask's simplicity makes it a great choice for those new to web development or Python.
- Rapid Development: With Flask, you can have a basic application running in minutes.
- Extensibility: There are numerous extensions available for Flask, making it easy to add functionality as needed.
- Versatility: Flask can be used for a wide range of applications, from simple web pages to complex RESTful web services.
- Community Support: Flask has a strong community, ensuring good documentation, tutorials, and support.
Flask will allow you to send element from your Python code to your webpage and allow you to get elements from your webpage such as user inputs back into Python. Before we move on to including HTML it is important to understand some fundamentals of Python with Flask.
Looking at the code above, here is what is happening:
LINE1 | from flask import Flask
LINE 2 | app = Flask(__name__)
LINE 3 | @app.route('/')
LINE 4 | def index():
LINE 5 | return("Hello World !")
LINE 6 | if __name__ == "__main__":
LINE 7 | app.run(debug=True)
Next we will look at connecting Python to your webpages.
LINE1 | from flask import Flask
- This line imports the Flask class from the flask module.
- The Flask class is the core of any Flask application. It's used to create an instance of the Flask web server.
LINE 2 | app = Flask(__name__)
- Here, an instance of the Flask class is created and assigned to the variable app.
- The __name__ argument determines the root path for the application so that Flask knows where to look for resources such as templates and static files. In this context, __name__ refers to the current module (i.e., the file this code is written in).
LINE 3 | @app.route('/')
- This is a decorator that tells Flask what URL should trigger the associated function.
- In this case, the '/' URL (the root URL) will trigger the index() function defined below it. Note the related function must be on the line directly below the app.route
LINE 4 | def index():
- This defines a function named index.
- When the root URL ('/') is accessed in the web-browser, this function will be executed. Note this function must be on the line directly under the app.route.
LINE 5 | return("Hello World !")
- Inside the index() function, this line returns the string "Hello World !".
- When a user accesses the root URL of the web application, they will see "Hello World !" displayed on the page.
- NOTE - Later we will return an entire webpage, 'hello world' is just for testing purpose.
LINE 6 | if __name__ == "__main__":
- This is a common Python idiom. It checks if the script is being run as the main program.
- If the script is being imported into another module, the code within this conditional will not be executed. This is useful if you have one Python file that runs another Python file the __main__ help identify which file is the main one being run.
LINE 7 | app.run(debug=True)
- This line starts the Flask web server.
- The debug=True argument enables debug mode for the Flask application. In debug mode, any changes you make to the code will automatically be reflected in the running application without needing to restart the server. Additionally, any errors will be displayed in a detailed manner in the browser.
Next we will look at connecting Python to your webpages.
SECTION 5 | YOUR HTML AND CSS FILES
Before we delve deeper into Python and Flask, ensure you have your HTML files prepared and stored in the correct location. At this stage, these files can be basic designs. If you haven't created any HTML files yet, click here to learn how to craft them. If you already possess your HTML files, ensure they are stored in the 'templates' folder, as discussed in Section 3. We will link to these files with Flask so they must be int he correct location.
SECTION 6 | IMPORTS NEEDED
For the following tasks you will need various imports. The line below contains all the imports needed for this section.
from flask import Flask, render_template, request, redirect, url_for, flash
Copy the imports from above before you begin.
from flask import Flask, render_template, request, redirect, url_for, flash
Copy the imports from above before you begin.
SECTION 7 | RENDER TEMPLATE
The render template method is used to simply load a html page. If you have a home page or are using the files provided, you can now tell python to load the page using render template by using the code below.
RENDER TEMPLATE
Make the changes to the code above to load your webpage and then when you run it you should get a message in Python editor similar to below:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
After this message appears your website should be ready to open in your web-browser, if your app route is @app.route('/home') Then to open this page in your browser you would need to type http://127.0.0.1:5000/home
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
After this message appears your website should be ready to open in your web-browser, if your app route is @app.route('/home') Then to open this page in your browser you would need to type http://127.0.0.1:5000/home
SECTION 7 | REDIRECT
The redirect method is used the redirect to another app route. Redirects are often used on button presses and other user interaction. In the example below the ' / ' route will always redirect to the 'user_login' route, the user login route will then load the login.html page.
REDIRECT
REDIRECT URL FOR
Use the redirect(url_for) command to redirect to the url for another app.route() as you have instructed in the holding function, in other words it is redirecting to the function not the app route. In the example below the route for ' / ' now redirects to the route ' login ' and then in login render temple is used to open the HTML page for login.
REDIRECT URL FOR
WORKING WITH BUTTONS
We look at creating buttons in the HTML section, here we address recognising in Python when the button has been pressed. Firstly this involves a few changes to the HTML code, there are a few ways of doing this, here will will use a form method. Treating the buttons as part of a form, this will be the same for handling user inputs.
<body>
<form action="/userpage" method="POST">
<input type="submit" name="login_button" value="LOGIN">
</form>
</body>
From the HTML code above:
Now moving on the receiving the button press within your Python script.
@app.route('/userpage', methods = ["POST","GET"])
def user_page():
if request.method == "POST":
print("The button worked")
From the Python code above:
If you have more than 1 button on the page then you will need to refer to the button by the name you gave the button in the HTML code and the value you gave it. For example:
@app.route('/userpage', methods = ["POST","GET"])
def user_page():
if request.method == "POST":
if request.form.get("login_button") == "LOGIN":
print("The login button worked")
You can use the same request.form.get method for multiple buttons and the same method for multiple user input boxes.
<body>
<form action="/userpage" method="POST">
<input type="submit" name="login_button" value="LOGIN">
</form>
</body>
From the HTML code above:
- The form action = '/userpage' is the way of assigning the form to a route within Python. /userpage is just an example, use the name of your route here.
- the method = 'POST' is is a bit like sending a message to the Python script, we will receive this in the Python part of the program.
- The input type = 'submit' is the part of HTML that create the button.
- The name = 'login_button' assigns a name to the button so we can reference it later, the same as a variable and you can call the button anything you want, just use the same naming conventions as you would with a variable.
- The value = 'LOGIN' is the text that the user will see on the button, again call it anything you want.
Now moving on the receiving the button press within your Python script.
@app.route('/userpage', methods = ["POST","GET"])
def user_page():
if request.method == "POST":
print("The button worked")
From the Python code above:
- The methods = ['POST','GET'] allows Python to uses these methods within the functions and the data within. For the purpose of this example the GET is not needed.
- The if request.method = 'POST' checks if there has been a post, in this case a button press because that is what was assigned to the post int he HTML page.
- The print is just to check it works, this is where your program would continue, for example by rendering a new page.
If you have more than 1 button on the page then you will need to refer to the button by the name you gave the button in the HTML code and the value you gave it. For example:
@app.route('/userpage', methods = ["POST","GET"])
def user_page():
if request.method == "POST":
if request.form.get("login_button") == "LOGIN":
print("The login button worked")
You can use the same request.form.get method for multiple buttons and the same method for multiple user input boxes.
USER INPUT FORMS
To give an example of a user input form, we are using the same code from creating a button above and adding a field for the user to type their email.
<body>
<form action="/userpage" method="POST">
<input type="submit" name="login_button" value="LOGIN">
<input type="text" name="user" placeholder="Email:">
</form>
</body>
From the HTML code above:
@app.route('/userpage', methods = ["POST","GET"])
def user_page():
if request.method == "POST":
users_email = request.form['user']
print(users_email)
In the example above the line users_email = request.form['user'] assigns a variable to hold the data from the form, requests the data contained in the form, this will happen when the button is pressed because it triggers the post method. The ['user'] tells Python which text box to get the user input from.
<body>
<form action="/userpage" method="POST">
<input type="submit" name="login_button" value="LOGIN">
<input type="text" name="user" placeholder="Email:">
</form>
</body>
From the HTML code above:
- The input type = 'text' is the part of HTML that creates the user input box
- The name = 'user' assigns a name to the button so we can reference it later, the same as a variable and you can call the button anything you want, just use the same naming conventions as you would with a variable.
- The value = 'Email' is the text that the user will see inside the text box as a prompt of what the box is for.
@app.route('/userpage', methods = ["POST","GET"])
def user_page():
if request.method == "POST":
users_email = request.form['user']
print(users_email)
In the example above the line users_email = request.form['user'] assigns a variable to hold the data from the form, requests the data contained in the form, this will happen when the button is pressed because it triggers the post method. The ['user'] tells Python which text box to get the user input from.
FLASH MESSAGES
If you want to create a pop-up message such as a message that say's 'Username or password not recognised' the the flash message is a good option to use. Flash messages are normally only used in some sort of conditional statement, such as an if statement, For example on a login page IF the username or password are incorrect the you could flash a message by using the code below.
flash("Sorry, the username or password you entered is not correct")
You will then need to receive the flash message in the HTML page that the app route is rendering, this can be done with the following code in your HTML page.
<p>{{message}}</p>
Note: If the above HTML does not work then you could try explicitly getting the flash message in the HTML page with the following code.
{% for message in get_flashed_messages()%}
<p>{{message}}</p>
{% endfor %}
flash("Sorry, the username or password you entered is not correct")
You will then need to receive the flash message in the HTML page that the app route is rendering, this can be done with the following code in your HTML page.
<p>{{message}}</p>
Note: If the above HTML does not work then you could try explicitly getting the flash message in the HTML page with the following code.
{% for message in get_flashed_messages()%}
<p>{{message}}</p>
{% endfor %}
JINJA2 - SENDING DATA TO THE WEBPAGE
This can be done using the flash method or sending in the data when rendering the HTML template. The flash method is normally used for simple and small amounts of data sure as an error message or basic personalisations. The method discussed here is a little more comprehensive and more frequently used for more data than a brief flash message.
return render_template('home.html', myValue = usersName)
And in the HTML
An example of this being used can be see below. After getting the users name from the post method, the template is rendered to welcome the user.
if request.method == "POST":
if request.form.get("submit") == "LOGIN":#submit from the name and LOGIN from the placeholder - from html page
userName = request.form['user'] #This will get the content from the user input box
password = request.form['login'] #This will get the content from the password input box
if usersName != None:#Check if returned value from checking the database contains user details
return render_template('home.html', myValue = usersName)# re-render the home page and send the users name to the hTML
Then you need to receive the variable holding the data/username in the HTML with the following code.
<p>Welcome {{myValue}}</p>
myValue is just a variable so you can call it anything appropriate and acceptable.
return render_template('home.html', myValue = usersName)
And in the HTML
An example of this being used can be see below. After getting the users name from the post method, the template is rendered to welcome the user.
if request.method == "POST":
if request.form.get("submit") == "LOGIN":#submit from the name and LOGIN from the placeholder - from html page
userName = request.form['user'] #This will get the content from the user input box
password = request.form['login'] #This will get the content from the password input box
if usersName != None:#Check if returned value from checking the database contains user details
return render_template('home.html', myValue = usersName)# re-render the home page and send the users name to the hTML
Then you need to receive the variable holding the data/username in the HTML with the following code.
<p>Welcome {{myValue}}</p>
myValue is just a variable so you can call it anything appropriate and acceptable.
DOWNLOAD PAGE AS PDF |
DYNAMIC TABLES
Using a similar method to that above you can also create tables and us Python to populate the tables. Creating tables this way mean you can create custom content and use the power of Python for data handling and the power of the web-browser interface to present a neat user interface and experience. For the purpose of this introduction we will use two arrays in python and populate the content of a HTML table, however it is just as easy to pull data from a database or even web-scrap data to populate your tables.
THE PYTHON
THE HTML
THE CSS
QUICK REFERENCE GUIDE
By this stage you should be confident with using Python, Flask, CSS and HTML. Use the quick reference guides for each to further develop your skills and build your project.
NEED MORE METHODS - CHECK OUT THESE FLASK PROJECTS