Flask tutorial: simple login for your webpage (python)

TLDR ;In my first story, I wrote about how to create a mobile friendly homepage with flask. Now, I want to show you, how you can enhance your webpage with a simple login structure. Maybe, you want to login to your webpage and see hidden content or diagrams of a script, which is running in the background on pythonanywhere.com*.

To start, download or clone from my github repo the project: Repository. If you start from 0, read first my story: https://antonioblago.medium.com/build-your-own-mobile-friendly-website-with-flask-6fe208f029d9

Install following modules:

Flask==2.1.3
flask_login==0.6.1
Flask-Security-Too==4.1.4
SQLAlchemy==1.4.39

You can also install from a text file with pip. Just put the modules in text file and name it requirements.txt. The run follwoing command in your root folder, where the text file is.

pip install -r requirements.txt

The following example is from the documentation from https://flask-security-too.readthedocs.io/en/stable/quickstart.html and modified for our purpose.

Your root will look like this after our tutorial:

root- |
|
|--data
| |--test.db
|--static
| |--normalize.css
| |--skeleton.css
| |--style.css
|--templates
| |--layouts
| |--main.html
| |--example1.html
| |--home.html
|--database.py
|--models.py
|--requirments.txt
|__run.py

Modify the run.py with the importing modules:

import osfrom flask import Flask, render_template,request,redirect,flash, session, url_forfrom flask_security import Security, current_user, auth_required, hash_password, SQLAlchemySessionUserDatastorefrom database import db_session, init_db
from flask_login import login_required, logout_user, LoginManager
from models import User, Role

Add a login manager:

# Login Manager
login_manager = LoginManager()
login_manager.init_app(app)

Add a user model, create a new file which you call models.py and save it to your root.

from database import Base
from flask_security import UserMixin, RoleMixin
from sqlalchemy import create_engine
from sqlalchemy.orm import relationship, backref
from sqlalchemy import Boolean, DateTime, Column, Integer, String, ForeignKey
class RolesUsers(Base):
__tablename__ = 'roles_users'
id = Column(Integer(), primary_key=True)
user_id = Column('user_id', Integer(), ForeignKey('user.id'))
role_id = Column('role_id', Integer(), ForeignKey('role.id'))
class Role(Base, RoleMixin):
__tablename__ = 'role'
id = Column(Integer(), primary_key=True)
name = Column(String(80), unique=True)
description = Column(String(255))
class User(Base, UserMixin):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
email = Column(String(255), unique=True)
username = Column(String(255), unique=True, nullable=True)
password = Column(String(255), nullable=False)
last_login_at = Column(DateTime())
current_login_at = Column(DateTime())
last_login_ip = Column(String(100))
current_login_ip = Column(String(100))
login_count = Column(Integer)
active = Column(Boolean())
fs_uniquifier = Column(String(255), unique=True, nullable=False)
confirmed_at = Column(DateTime())
roles = relationship('Role', secondary='roles_users',
backref=backref('users', lazy='dynamic'))

Add a database.py file and put it also in your root.

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///data/test.db', convert_unicode=True, connect_args={'check_same_thread': False})
db_session = scoped_session(sessionmaker(autocommit=False,autoflush=False, bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
# import all modules here that might define models so that
# they will be registered properly on the metadata.Otherwise
# you will have to import them first before calling init_db()
import models Base.metadata.create_all(bind=engine)

Now we have to modify the run.py by adding the security

# Setup Flask-Securityuser_datastore = SQLAlchemySessionUserDatastore(db_session, User, Role)
security = Security(app, user_datastore)
# Create a user to test with
@app.before_first_request
def create_user():
init_db()
if not user_datastore.find_user(email="test@me.com"):
user_datastore.create_user(email="test@me.com",
password=hash_password("password"))
db_session.commit()

Adding new routes for login and logout:

We add also a example1.html and logout.html.

{% extends "layouts/main.html" %}{% block content%}</body><h5>{{textout}}</h5></body>{% endblock %}

All right, now start the app via python run.py. You should see this:

Press Login button, put the user info in and confirm:

email=test@me.com

password=password

You should see now:

You can also go to the Example tab:

In the end, just log out and your are logged out:

E voilà you are done! Just modify this example to your needs and upload it on pythonanywhere.com* for it. Here is the repo: https://github.com/AntonioBlago/Webpage_Tutorial_3.

Thanks for reading my article. I hope you liked it. Please feel free to like, share, and comment on it. Follow me on more content about cryptos, stocks, data analysis and web development. I am hosting my apps on pythonanywhere.com*.

  • Read my other article about creating a financial dashboard in flask

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store