Mastering Python For Web Development
Tags: beginners, webdev, programming, tutorial
Published: 2022-05-15 03:16:42

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](http://injili.pythonanywhere.com/).

## 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
```
Use the following code to check the installed packages.

```
pip freeze
```
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
```
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.

```python
# 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

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

```python
myapp=Flask(__name__)
if __name__ == '__main__':
    myapp.run(debug=True)
```
Right below the `myapp=Flask(__name__)` app instance line, type in the following code block:

```python
@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'))

```

## Initializing The Database.
The information collected by the user's registration is stored in a database. To begin, install [splite3](https://sqlite.org/download.html) in your PC referring to [this](https://youtu.be/wXEZZ2JT3-k) 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
```
to exit sqlite3 type in:

```
.exit
```
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:

```python
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))
```
Next we import the table `Users` to the created `database.db`. In the Command Prompt open python with:

```
python
```
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()
```
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](https://github.com/injili/FlaskHostedAuthSys/blob/main/templates/signup.html) 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:

```python
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)])
```
Next, update the sign up section with the following code:

```python
@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)

```

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](https://github.com/injili/FlaskHostedAuthSys/blob/main/templates/login.html) is my login page.

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

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

```
Update the login code as follows:

```python
@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)


```

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](https://github.com/injili/FlaskHostedAuthSys). Thank you for reading this article. Find me on twitter @[i_njili](https://twitter.com/i_njili) Leave me a comment in the comment section bellow. Good Day:)