DEV Community

Cover image for Mastering Python For Web Development
Nyareki Gospel
Nyareki Gospel

Posted on

Mastering Python For Web Development

Web Development is defined as building and maintaining of websites. When doing this, web developers design, program, publish and maintain databases. The programming exercise is done using html( a mark-up language), css and javascript. Python can be used as well. Python has a couple of frameworks such as Django and Flask that are used to develop websites. In this article, I document the development of an authentication system using Flask, a python framework, in a windows pc. The link to the deployed website is HERE.

Setting Up The Environment.

The first step is to set up a flask environment in which the flask app will be developed. In your desired location, create a folder and name it FlaskAuthSys to stand for Flask Authentication System. Open the Command Prompt. Using cd navigate to the folder FlaskAuthSys. Run the code below:

pip install flask
Enter fullscreen mode Exit fullscreen mode

Use the following code to check the installed packages.

pip freeze
Enter fullscreen mode Exit fullscreen mode

We will also be in need of flask_sqlalchemy, flask_login, flask_wtf and flask_bootstrap. The following lines of code will help you install these requirements. Copy each line separately pasting it on the Command Prompt window then run it.

pip install flask_sqlalchemy
pip install flask_login
pip install flask_wtf
pip install flask_bootstrap
Enter fullscreen mode Exit fullscreen mode

Once this is done, pip freeze will show all the installed features.

Setting Up The Flask Application.

Create a python file myapp.py in the FlaskAuthSys folder. In it, initialise the file by importing all features important to the authentication system with the python code below.

# import flask itself, request, render_template, resirect and url_for
from flask import Flask,request,render_template,redirect,url_for
# import FlaskForm for the authentication details form
from flask_wtf import FlaskForm
# import fields to be used in the form
from wtforms import StringField, PasswordField
# import validation features from wtf
from wtforms.validators import InputRequired, Email, Length
# import python flask bootstrap
from flask_bootstrap import Bootstrap
# import sqlqlchemy for the database we will need later on
from flask_sqlalchemy import SQLAlchemy
# import login features
from flask_login import LoginManager,UserMixin,login_user,login_required,logout_user

import os
import sqlite3
import flask

Enter fullscreen mode Exit fullscreen mode

Let's create our app instance now. Below the above code, type in this:

myapp=Flask(__name__)
if __name__ == '__main__':
    myapp.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Right below the myapp=Flask(__name__) app instance line, type in the following code block:

@myapp.route('/')
def index():
    return render_template('index.html')
# login section
@myapp.route('/login')
def login():
    return render_template('login.html')
# sign up section
@myapp.route('/signup')
def login():
    return render_template('signup.html')
# the dashboard
@myapp.route('/dashboard')
def login():
    return render_template('dashboard.html')
# log out procedure
@myapp.route('/logout')
def login():
    return redirect(url_for('index'))

Enter fullscreen mode Exit fullscreen mode

Initializing The Database.

The information collected by the user's registration is stored in a database. To begin, install splite3 in your PC referring to this tutorial. Open Command Prompt and navigate to the file FlaskAuth Sys and paste the following code to create a database we will use to store our data.

sqlite3 database.db
Enter fullscreen mode Exit fullscreen mode

to exit sqlite3 type in:

.exit
Enter fullscreen mode Exit fullscreen mode

Back in our myapp.py file, create the fields to be used in data storage and the table Users. Here is how to do this:

class Users(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True)
    email = db.Column(db.String(50), unique=True)
    password = db.Column(db.String(80))
Enter fullscreen mode Exit fullscreen mode

Next we import the table Users to the created database.db. In the Command Prompt open python with:

python
Enter fullscreen mode Exit fullscreen mode

Next, run the following lines in the Command Prompt, one line at a time, to import the table created in myapp.py to the database.db;

from myapp import db
db.create_all()
Enter fullscreen mode Exit fullscreen mode

The table users is now created in the database.

Registration.

When the website user has no account yet, he is not allowed to log in. So that the user logs in the account is first created using the sign up page. Using this code create a sign up page named: signup.html. Store this html file in a folder named templates in the FlaskAuthSys folder.

Back in our myapp.py file, create a registration instance with the code below to specify what way data is to be received for storage:

class RegisterForm(FlaskForm):
    username = StringField('username', validators=[InputRequired(), Length(min=4, max=20)])
    password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])
    email = StringField('email', validators=[InputRequired(), Email(message='Invalid Email'), Length(max=50)])
Enter fullscreen mode Exit fullscreen mode

Next, update the sign up section with the following code:

@myapp.route('/signup', methods=['GET','POST'])
def signup():
    form = RegisterForm()   
    if form.validate_on_submit():
        new_users = Users(username=form.username.data, email=form.email.data, password=form.password.data)
        db.session.add(new_users)
        db.session.commit()

        return '<h1>New user has been created!</h1>'
    return render_template('signup.html', form = form)

Enter fullscreen mode Exit fullscreen mode

The sign up section is completed for now.

Loging In.

This is simple since the table is already created. Create a html file in templates called login.html. Here is my login page.

In the myapp.py python page, create a login instance with this code:

class LoginForm(FlaskForm):
    username = StringField('username', validators=[InputRequired(), Length(min=4, max=20)])
    password = PasswordField('password', validators=[InputRequired(), Length(min=8, max=80)])

Enter fullscreen mode Exit fullscreen mode

Update the login code as follows:

@myapp.route('/login', methods=['GET','POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
       users = Users.query.filter_by(username=form.username.data).first()
       if users:
           if users.password == form.password.data:
               login_user(users)
               return redirect(url_for('dashboard'))
       return '<h1> Invalid username or password</h1>'
    return render_template('login.html', form = form)


Enter fullscreen mode Exit fullscreen mode

Up to here, the Registration and login in is Taken care of. The rest of the code for this project is in this GitHub Repository FlakHostedAuthSys. Thank you for reading this article. Find me on twitter @i_njili Leave me a comment in the comment section bellow. Good Day:)

Top comments (0)