Flask is a code library which makes life easier for the developer when building reliable, scalable, and maintainable web applications by providing a reusable code or extensions for common operations.
Setting up environment:
Open terminal/ command prompt and type:
For windows:~pip install virtualenv
For macOS:
For Linux:$sudo apt-get install python-virtualenv
Create a folder myProject and venv folder inside the folder. And type the following in command prompt/ terminal:~mkdir myProject
~cd myProject
~py –m virtualenv venv
Activate environment:
To start the project we first need to activate the corresponding environment.
~venv/bin/activate
On windows:
~venv\Scripts\activate
Shell prompt will show the name of the activated environment.
Install flask:
Open command prompt and type:~pip install flask
1
2
3
4
5
6
7
8
9
10
11
12
from flask
import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run()
#Activate the environment.\venv\ Scripts\ activate
#Run the python file
OUTPUT:(Terminal)
Press Ctrl+ returned link
127.0.0.1 - LOCAL HOST
:5000 - PORT
First we imported Flask class. This created an instance class Web Server Gateway Interface(WSGI) application.
The first argument is the name of the application’s module. This is needed so that flask can access templates, static files and so on. To learn more check out
Flask documentation.
Route () decorator in flask is used to bind the URL to the function.
The function is given a name which we want to display in the user’s browser.
When the application is in the development stage, it has to be restarted manually for every individual change in the code. To avoid this there is a feature called debug mode/ debug support in which the server will reload itself when the code is changed. It will also provide a debugger to track any errors in the code.
This is done by passing the parameter debug = true in app.run() method.
1
2
3
4
5
6
7
8
9
10
from flask
import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug = True)
Modern web application framework uses routing techniques to help the user to remember the application URL.
1
2
3
4
@app.route('/') # route() decorator uses to bind the URL
def hello_world(): #name of the
function
return 'Hello, World!'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from flask
import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "<h1> Home Page </h1>"
#we can also pass html scripts inside the
return method.
@app.route('/about')
def about():
return "<h1> About page </h1>"
if __name__ == '__main__':
app.run(debug = True)
#Activate the environment.\venv\ Scripts\ activate and run the python file.
What this code does?
The home() function makes the home page.
The about() redirects us to the about page.
The app.route(‘/about’) is used to navigate to the about page.
We can edit the URL and add at the end /about which will redirect us to the about page.
Templates can be used to return more complex HTML Code.
To use a template, we need to create a templates directory within the folder.
Inside the templates directory we create two files named home.html and about.html.
To view the template, we need to import render_template from Flask.
Inside the return method in home() and about()need to type render_template(‘home.html’) and render_template(‘about.html’)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#hello.py
from flask
import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
# This method is used to render the template.
@app.route('/about')
def about():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug = True)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<!----home.html --> <!DOCTYPE html> <html> <head> <title>My First Webpage</title> <meta charset="UTF-8"> <meta name="description" content="This is my first website. It includes lots of information about my life."> </head> <body> <h1>Welcome </h1> <p>Welcome to my brand new website.</p> <p>This site will be my new home on the web.</p> <a href="http://www.google.com">Google</a> </body> </html>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<!----about.html --> <!DOCTYPE html> <html> <head> <title>About</title> <meta charset="UTF-8"> <meta name="description" content= "This is my first website. It includes lots of information about my life."> </head> <body> <h1>About this page </h1> <p>This website was created for demonstration purpose</p> </body> </html>
Forms in flask are made using wtf forms.
To install wtf form:~pip install flask-wtf
Create a Python file in the project directory.(froms.py)
Import Flask Form from flask-wtf.
Import StringField, PasswordForm, SubmitField from wtforms.
Import DataRequired, Length, Email from wtforms.validators.
Create a registration form class which will inherit from FlaskForm.
The first field in the form will be username, which will be created using StringField class.
StringField class can also be constrained using DataRequired()
.
The second field is the Email field using the same steps as above. Emails can be validated using Email validators.
Create another field password and confirm password using the above steps.
Create a SubmitField for sign up.
Now, inside the layout.py
Create a new route()
, which will render a template of forms.
Inside the templates create a html file (register.html)
A few more features are added in the code including sidebar, posts error messages etc.
Add the about.html, layout.html, login.html, register.html, home.html in a templates folder.
For the source code refer to this GitHub Gist link .
PART 1 (FRONTEND): CREATING THE REGISTRATION / LOGIN FROM FIELDS.
I. CREATING THE USERNAME / EMAIL /PASSWORD AND REGISTRATION FIELDS.
Import the StringField class from wtforms, which helps to create text fields.
Inside the registration form we need to create attributes name, username, which is of type StringField.
Inside the StringField we need to pass various arguments such as the name of the text field.
We can also provide restrictions to the user such as limited number of characters, text field can’t be left null, which are passed as a list inside the validators method, which are imported from wtforms.validators.
DataRequired()
for restricting the user to not to leave the text field empty.
Length (min = x, max = y) for limiting the number of characters.
In case of an email attribute, we need to follow the same procedure as above. In addition to that we need an Email()
validator to verify the email, which can be imported from wtforms.validators.
In the case of the password field we need to provide a StringField which can be imported from wtforms. This allows us to create a text field with hidden characters (* characters), the only validator required in this is DataRequired (as it can’t be left empty)
For password confirmation, follow the same steps as password, in case of its validators, there is an extra EqualTo(‘password’) method which can be imported from wtforms.validators, to make sure that the text in password and confirm password are the same.
Finally we need to create a SubmitField(), which can be imported from wtforms, which takes a single argument, which is the name of the field.
II. CREATING THE LOGIN FORM
To create a login function, we can just copy the code of the registration form, as the login form also has the same fields plus the password confirmation and either username or email.
We also can create a checkbox, which will be used to remember the user logged in for some time after the browser is closed, using cookies.
This can be done with Boolean field which is imported from wtforms.
The signup button will be changed to login button.
III. CREATING A REGISTRATION ROUTE AND A LOGIN ROUTE.
Create a registration and login route using @app.route(‘/register’) and @app.route(‘/login’).
This will render regiser.html and login.html respectively. Using render_template().
IV. Login.html and register.html
A prior knowledge of fundamentals of HTML are required to make the webpage, users can deep dive into HTML by clicking here.
Open command prompt/ terminal and type:~ pip install Flask-MySQLdb
For MySQL database we are using MySQL.
For step by step installation of MySQL click here.
1. Create a new directory and inside that create three files named app.py, index.html and users.html.
2. Inside app.py
Import Flask from flask
From flask_mysqldb import MySQL for initialising database connection.
Create a single app route and inside it a function named index().
We need to configure the MySQL database using app.config for Host, User, Password and database, which are going to be localhost, root, null and database name as per mysql database.
Create a variable(mysql) which will initialise the configuration setting.
3. Inside index.html
Create a simple heading named “simple login form’
Create two text fields, username and email, using
Ex: <input type = ‘text’ name = ‘username’ required/>
Required is passed so that the field is not left empty.
We also need a submit button, which is going to be of type =’submit’
And inside the form the method will be of type ‘post’ and action will be ‘/’
for the home page.
If we run the program then we receive the following output.
4. Again inside app.py
In the route()
function we need to pass a method which is going to be either get or post.
And inside the index()
function we need to check that the request method is get or post using request.method == ‘POST’
If the request method is of type post we need to get the information which the user has typed.
We will store the name inside the username variable using request.form(‘username’)
for username and request.form(‘email’)
for email.
Make a new cursor variable(curr)
using mysql.connection.curser()
Execute the cursor using curr.execute()
and inside that we can give simple sql command to insert data‘INSERT INTO users (name, email) values(%s,%s)’,(username, email.)
Then we need to commit these changes using mysql.connection.commit()
Return success to see if everything works fine.
5. Open MySQL command line client.
Create a database using CREATE DATABASE flaskapp
USE flaskapp;
Create a table named with three columns, username and email.CREATE TABLE mytable (id INT, username VARCHAR(25), email VARCHAR(25));
6. Again app.py:
Create another route named users, which will display the name of all the users registered.
Create a function user to fetch the details from the database.
Make a cursor
Execute the cursor and store the value into a variableSELECT * FROM mytable;
To check that entries have been made into the database, we will check that the result value is greater than 0.
Inside the condition we will return the entries entered using cur.fetchall()
To display the data, we need to render a template named users.html
7. Inside users.html
Create a table using <table>
To iterate all the elements inside the table use a for loop.
In each row we will return the output of each row.
End the for loop.
End the table tag.
CODES: (app.py)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from flask
import Flask, render_template, request, redirect
from flask_mysqldb
import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'Pass@123'
app.config['MYSQL_DB'] = "flaskapp"
mysql = MySQL(app)
@app.route('/', methods = ['GET', 'POST'])
def index():
if (request.method == 'POST'):
username = request.form['username']
email = request.form['email']
cur = mysql.connection.cursor()
cur.execute("INSERT INTO mytable (username,email) VALUES (%s,%s)", (username, email))
mysql.connection.commit()
return redirect('/users')
return render_template('index.html')
@app.route('/users')
def users():
cur = mysql.connection.cursor()
resultValue = cur.execute('SELECT * FROM mytable')
if resultValue > 0:
userDetails = cur.fetchall()
render_template('users.html')
if __name__ == "__main__":
app.run(debug = True)
Index.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<html> <body> <h1>Simple Login Form</h1> <br> <form method = 'POST' , action = '/'> <br> Name: <input type = 'text' name="username" required/> <br> Email: <input type = 'email' name="email" required/> <br> <input type = 'submit'/> </form> </body> </html>
Users.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<table border = 1> {% for users in userDetails %} <tr>{{user[0]}}</tr> < tr > { { user[1] } } </tr> { % endfor % } </table>
Open MySQL command line client and use the database
Type: SELECT * FROM mytable;