Flask Setup and Basic

Posted on March 21, 2021

### Step1: Create virtualenv

>python -m virtualenv env


Create Virtual environment for ubuntu/linux machine and activate

>python -m venv env

>source env/bin/activate

### Step2: Creating Project

>mkdir demo_project

>cd demo_project


### Step3: Creating python file

from flask import Flask

app = Flask(__name__)


def test():

return "Hello this is for testing and print in console!"


def harry():

return "this is second route url which in /demo"

### step5: Run server


##Tutorial2: Static and Templates folder

What is Static in flask?

This folder is public, client can access it. it may be images, css, javascript and other files.

These files can also be viewed using the address.

What is Templates in flask?

Templates folder is private, client can not access it. All the sensitive data is put in it.

Flask uses its template folder for storing the raw templates which can be filled through the python program.

Flask will look for templates in the templates folder.

So if your application is a module, this folder is next to that module,

if it’s a package it’s actually inside your package:

Case 1: a module:




Case 2: a module:





Step1: Creating Static folder and templates

>mkdir static

>mkdir templates

What is render_template() function and where is use it?

render_template() function return a template(HTML page) through our python file.

Ex: render_template(‘html_file_name.html’, params={}) #as shown in the code below

return render_template('index.html', params={"title":"Home Page",

"keywords": "python, programming, numpy, pandas",

"description":"Python Tutorial for Beginners." },

"image_url": url_for("user_image", filename=user.image)


How can get Variable, images, css, js and include child html files in parent html?

Load Image

<img src="{{ url_for('static', filename='1.png') }}">

<img src="{{ url_for('static', filename='subfolder/2.png') }}">

<img src="/static/2.png">

Get python variable in html

<h1>Hi I am {{ variable_name }}!</h1>

<img src="{{ params.image_url }}">

<meta name="keywords" content="{{ params.keywords }}">

<meta name="Description" content="{{ params.description }}">

<title>{{ params.title }}</title>

For Loop In Template

{% for post in posts %}



{% endfor %}

How can set variable in Flask(Jinda) Template

{% set image_url = 'images/' + params.image_url %}

<img src="{{ url_for('static', filename=image_url) }}">

Inherit/include html files

{% include 'include/header.html' %}

{% include 'include/footer.html' %}

Load JS and CSS

<script src="/static/common/js/codemirror/lib/codemirror.js"></script>

<img src="{{ url_for('static', filename='js/jquery-3.5.1.min.js') }}">

<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">

<link rel="stylesheet" href="">\

Variable Rules

You can add variable sections to a URL by marking sections with <variable_name>.

Your function then receives the <variable_name> as a keyword argument.

Optionally, you can use a converter to specify the type of the argument like <converter:variable_name>.

string (default): accepts any text without a slash

int :accepts positive integers

float: accepts positive floating point values

path: like string but also accepts slashes

uuid: accepts UUID strings

from markupsafe import escape


def show_user_profile(username):

# show the user profile for that user

return 'User %s' % escape(username)


def show_post(post_id):

# show the post with the given id, the id is an integer

return 'Post %d' % post_id


def show_subpath(subpath):

# show the subpath after /path/

return 'Subpath %s' % escape(subpath)

Unique URLs / Redirection Behavio(Redirect with traling slash)

The following two rules differ in their use of a trailing slash.

#If you access the URL without a trailing slash, Flask redirects you to the canonical URL with the trailing slash.


def projects():

return 'The project page'


def about():

return 'The about page'

URL Building

To build a URL to a specific function, use the url_for() function.

It accepts the name of the function as its first argument and any number of keyword arguments, each corresponding to a variable part of the URL rule.

Unknown variable parts are appended to the URL as query parameters

test_request_context() method to try out url_for(). test_request_context() tells Flask to behave as though it’s handling a request even while we use a Python shell.

from flask import url_for

with app.test_request_context():



print(url_for('projects', next='/'))

print(url_for('user', username='John Doe'))

HTTP Methods:

Web applications use different HTTP methods when accessing URLs.

You should familiarize yourself with the HTTP methods as you work with Flask.

By default, a route only answers to GET requests.

You can use the methods argument of the route() decorator to handle different HTTP methods.

from flask import request

@app.route('/login', methods=['GET', 'POST'])

def login():

if request.method == 'POST':

return do_the_login()


return show_the_login_form()

The Request Object:

from flask import request

def log_the_user_in(username):


return username

def valid_login(username, password):

print(username, password)

return True

@app.route('/user-login', methods=['POST', 'GET'])

def login():

error = None

if request.method == 'POST':

if valid_login(request.form['username'],


return log_the_user_in(request.form['username'])


error = 'Invalid username/password'

# the code below is executed if the request method

# was GET or the credentials were invalid

return render_template('user-login.html', error=error)

To access parameters submitted in the URL (?key=value) you can use the args attribute:

searchword = request.args.get('key', '')

File Uploads:

set the enctype="multipart/form-data" attribute on your HTML form,

otherwise the browser will not transmit your files at all.

Uploaded files are stored in memory or at a temporary location on the filesystem.

You can access those files by looking at the files attribute on the request object.

Each uploaded file is stored in that dictionary.

It behaves just like a standard Python file object, but it also has a save() method that allows you to store that file on the filesystem of the server.

Here is a simple example showing how that works:

from os.path import join, dirname, realpath

from werkzeug.utils import secure_filename

@app.route('/upload', methods=['GET', 'POST'])

def upload_file():

if request.method == 'POST':

file = request.files['my-file']

filename = secure_filename(file.filename)

UPLOADS_PATH = join(dirname(realpath(__file__)), f'static/uploads/{filename}'), filename)

return render_template('file-upload.html' , message="File Uploaded Successfully.")

if request.method == 'GET':

return render_template('file-upload.html' , message="")


To access cookies you can use the cookies attribute.

To set cookies you can use the set_cookie method of response objects.

The cookies attribute of request objects is a dictionary with all the cookies the client transmits.

If you want to use sessions, do not use the cookies directly but instead

use the Sessions in Flask that add some security on top of cookies for you.


def set_cookies():

username = request.cookies.get('username')

# use cookies.get(key) instead of cookies[key] to not get a

# KeyError if the cookie is missing.

render_template('cokkies.html', username=username)

#Storing cookies:

from flask import make_response


def get_cookies():

resp = make_response(render_template('cokkies.html'))

resp.set_cookie('username', 'the username')

return resp

Redirects and Errors:

To redirect a user to another endpoint, use the redirect() function;

to abort a request early with an error code, use the abort() function:

from flask import abort, redirect, url_for

def this_is_never_executed():

return "This is never executed"


def redirect():

return redirect(url_for('redirect-login'))


def redirect_login():




In order to use sessions you have to set a secret key. Here is how sessions work:

from flask import Flask, session, redirect, url_for, request

from markupsafe import escape

app = Flask(__name__)

# Set the secret key to some random bytes. Keep this really secret!

app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'


def index():

if 'username' in session:

return 'Logged in as %s' % escape(session['username'])

return 'You are not logged in'

@app.route('/login', methods=['GET', 'POST'])

def login():

if request.method == 'POST':

session['username'] = request.form['username']

return redirect(url_for('index'))

return '''

<form method="post">

<p><input type=text name=username>

<p><input type=submit value=Login>




def logout():

# remove the username from the session if it's there

session.pop('username', None)

return redirect(url_for('index'))

# Logging

This might be caused by a user tampering with the data, or the client code failing.

Most of the time it’s okay to reply with 400 Bad Request in that situation,

but sometimes that won’t do and the code has to continue working.

app.logger.debug('A value for debugging')

app.logger.warning('A warning occurred (%d apples)', 42)

app.logger.error('An error occurred')


#pip install flask-sqlalchemy

from flask_sqlalchemy import SQLAlchemy

from datetime import datetime

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/test_db'

db = SQLAlchemy(app)

class Contacts(db.Model):

sno = db.Column(db.Integer, primary_key=True)

name = db.Column(db.String(80), nullable=False)

phone_num = db.Column(db.String(12), nullable=False)

msg = db.Column(db.String(120), nullable=False)

date = db.Column(db.String(12), nullable=True)

email = db.Column(db.String(20), nullable=False)

@app.route("/contact", methods = ['GET', 'POST'])

def contact():


'''Add entry to the database'''

name = request.form.get('name')

email = request.form.get('email')

phone = request.form.get('phone')

message = request.form.get('message')

entry = Contacts(name=name, phone_num = phone, msg = message, date=,email = email )



return render_template('contact.html')

Admin DashBoard Access

@app.route('/dashboard', methods=['GET', 'POST'])

def dashboard():

if 'user' in session AND session['user']==params['admin_user']:

// Access dashboard template

if request.method=='POST':

username= request.form.get('username')

password= request.form.get('password')

if username==params['admin_user'] AND password==params['password']:


// Access dashboard template

// Access Login Template


// access Login template

@app.route('/edit/<string:sno>', methods=['GET', 'POST'])

def edit(sno):

if 'user' in session AND session['user']==params['admin_user']:

if request.method=='POST':

username= request.form.get('username')

password= request.form.get('password')

if username==params['admin_user'] AND password==params['password']:

title= request.form.get('title')

content= request.form.get('content')


@app.route('/upload', methods=['GET', 'POST'])

def upload():


if request.method=='POST':

f=request.files['file_name']['UPLOAD_FOLDER'], secure_filename(f.filename)))

return "File has been uploaded successfully"

@app.route('/pagination', methods=['GET', 'POST'])

def pagination():




if (not str(page).isnumeric()):

page =1

all_post=all_post[(page-1)*no_of_post: (page-1)*no_of_post+no_of_post]

if page==1:



elif page==last_post:






return render_template("post.html", params=params, posts=posts, prev=prev, next=next)

Sign In for comment and like the post.