0% found this document useful (0 votes)
21 views

Lecture 6

This document provides an introduction to web development with Flask. It discusses what web development is, why Flask is a popular Python framework for it, and how to get started with a basic Flask application. It also covers setting up a database with Flask-SQLAlchemy and Flask-Migrate to store and manage application data, including creating database models and migrations.

Uploaded by

hrcepheix
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Lecture 6

This document provides an introduction to web development with Flask. It discusses what web development is, why Flask is a popular Python framework for it, and how to get started with a basic Flask application. It also covers setting up a database with Flask-SQLAlchemy and Flask-Migrate to store and manage application data, including creating database models and migrations.

Uploaded by

hrcepheix
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Python Programming for

non-Programmers

Introduction into
Web development with Flask
2020-11-14
Lecture 6: Introduction into
Web development with Flask

14.12.2020 Python Programming for non-Programmers 2


Web development

Conzeptualizing, creating, deploying and


operating applications and interfaces for
the web

Many different frameworks available

Flask, Django, Bottle, etc.


Web development: https://www.fullstackpython.com/web-development.html

14.12.2020 Python Programming for non-Programmers 3


Why Flask?

Popular and flexible Python framework


to create web applications

Micro framework
The core of flask is very simple, but extendable
Getting started is quick and easy, but the project
can be scaled up to complex applications
Web development: https://www.fullstackpython.com/web-development.html

14.12.2020 Python Programming for non-Programmers 4


Installing Flask

Create a new project in


PyCharm and use the
PyCharm terminal
Setting the environment
venv in the project python –m venv venv terminal

directory
After that, you need to
venv\Scripts\activate terminal
activate the virtual
environment

Then you can create a mkdir app terminal


directory called app

14.12.2020 Python Programming for non-Programmers 5


Installing Flask

Installing Flask with pip


Python Programming for non-Programmers
pip install flask terminal

Proof installation by importing flask in


the Python terminal
python terminal

>>> import flask terminal

14.12.2020 Python Programming for non-Programmers 6


Getting started

Create __init__.py in your app directory

Open __init__.py and add the following code:


__init__.py

from flask import Flask Creating the application object as an instance


of the class Flask
__name__ is set to the name of the module in
app = Flask(__name__) which it is used

routes module includes the different URLs that


from app import routes
the application implements

14.12.2020 Python Programming for non-Programmers 7


Getting started

Create the class routes.py inside the app package and add the following
code:
routes.py
from app import app

@app.route('/')
@app.route('/index')
Creating the URL
def index(): Define what should happen when using the
return "Hello, World!" URL

Define a top-level Python script as the Flask application instance is created in


the Flask project package
Here it is called main.py and simply consists of the following code:
main.py
from app import app

14.12.2020 Python Programming for non-Programmers 8


Getting started

The first version of your web application is ready

At first you need to set the environment variable FLASK_APP


Thus the program does not remember FLASK_APP throughout the terminal
session install python-dotenv and create a file called .flaskenv containing
your main file
pip install python-dotenv terminal

.flaskenv
FLASK_APP=main.py

The following command then starts your application


terminal
flask run

14.12.2020 Python Programming for non-Programmers 9


Getting started

After running the command flask run inside your PyCharm


terminal the folling output should appear:

By hitting the URL or typing the URL into your browser you
should see:

14.12.2020 Python Programming for non-Programmers 10


Create a database – what is a database?

A database is a place to store data in an efficient way


Became more and more important, because of the growing mass of
data
Requires typically a Database Management System to
allow the user to interact with the data
Retrieve data from, update and manage the database

Many different Database Systems


SQLite, MySQL, MongoDB, PostgreSQL, etc.

14.12.2020 Python Programming for non-Programmers 11


Create a database

In Flask you can choose between several databases


provided by the extension Flask-SQLAlchemy

A second extension we use is flask-migrate


To have a robust way to make changes to your database
terminal
pip install flask-sqlalchemy

terminal
pip install flask-migrate

14.12.2020 Python Programming for non-Programmers 12


Create a database

Setting the database configuration in a


config.py in your top-level package to
store configuration variables in it containing:
import os config.py
basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False

14.12.2020 Python Programming for non-Programmers 13


Create a database

After that you need to add the configuration file


to your __init__.py as well as the information
about your database so that it looks as follows:
from flask import Flask __init__.py
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)

from app import routes, models

14.12.2020 Python Programming for non-Programmers 14


Create a database model - example

At first, we need to create a class of the table we want to


make
We create a class models.py in the app package

from app import db models.py

class Customer(db.Model):
id = db.Column(db.Integer, primary_key=True, unique = True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))

def __repr__(self):
return '<Customer {}>'.format(self.username)

14.12.2020 Python Programming for non-Programmers 15


Creating the migration repository

Initialize the database in your terminal


terminal
flask db init

After that you can create the table typing:


terminal
flask db migrate –m “customers table”

Using upgrade/downgrade to accept/refuse your changes


terminal
flask db upgrade

14.12.2020 Python Programming for non-Programmers 16


Creating database relationships

Adding a new table orders to the database so that


customers are enabled to make orders
This can be done by adding the new table to models.py
customer_id is used as a foreign key to point to the customers table and
makes a reference from Customers to Orders
class Customer(db.Model): models.py

orders = db.relationship('Orders', backref = "Customer", lazy = "dynamic")

class Orders(db.Model):
order_id = db.Column(db.Integer, primary_key=True, unique=True)
description = db.Column(db.String(64), index=True)
customer_id = db.Column(db.Integer, db.ForeignKey('customer.id'))

def __repr__(self):
return '<Order {}>'.format(self.description)

14.12.2020 Python Programming for non-Programmers 17


Creating database relationships

After that we need to create the new


table inside the database:
terminal
flask db migrate –m "orders table"

flask db upgrade terminal

14.12.2020 Python Programming for non-Programmers 18


Fill the database

There exist different ways to fill the database

Open the python terminal in your PyCharm

At first we need to import the modules


python Python terminal

>>> from app import db


>>> from app.models import Customer, Orders

14.12.2020 Python Programming for non-Programmers 19


Fill the database

Adding new customers to the database (same Python terminal)


>>> c = Customer(id=12345, username = "Lars", email = "[email protected]") Python terminal
>>> db.session.add(c)
>>> db.session.commit()
>>> c = Customer(id=54321, username = "Kevin", email = "[email protected]")
>>> db.session.add(c)
>>> db.session.commit()

Adding orders for the customers (same Python terminal)


>>> c = Customer.query.get(1) Python terminal
>>> o = Orders(order_id=6789, description = "Chair", customer_id = 12345, Customer = c)
>>> db.session.add(o)
>>> db.session.commit()
>>> c = Customer.query.get(2)
>>> o = Orders(order_id=9876, description = "TV", customer_id = 54321, Customer = c)
>>> db.session.add(o)
>>> db.session.commit()

14.12.2020 Python Programming for non-Programmers 20


Visualize your data in a table I
terminal
pip install flask_table

After that we need a definition for our tables called tables.py

from flask_table import Table, Col tables.py

class Customer_table(Table):
id = Col('Id')
username = Col('Username')
email = Col('E-Mail')

class Orders_table(Table):
order_id = Col('Order_Id')
description = Col('Description')
customer_id = Col('Customer_Id')

14.12.2020 Python Programming for non-Programmers 21


Visualize your data in a table

Create a directory templates to separate the logic from the visualization


which is html-based and make a new file called tables.html
The html-files include the information about what will be seen on your website

<!DOCTYPE html> tables.html


<html lang="en">
<head>
<meta charset="UTF-8">
<title>Data Visualization</title>
</head>
<body>
{{table1 }}
{{table2 }} These are the variables of your tables
</body>
</html>

14.12.2020 Python Programming for non-Programmers 22


Visualize your data in a table

Lastly, we must add the tables to an URL in routes.py


from app import app, tables, models routes.py
from flask import render_template

@app.route('/tables')
def create_tables():
# create a table for the customers
customer_db = models.Customer.query.all()
table_customers = tables.Customer_table(customer_db)
table_customers.border = True
# create a table for the orders
orders_db = models.Orders.query.all()
table_orders = tables.Orders_table(orders_db)
table_orders.border = True
return render_template('tables.html', table1=table_customers, table2 = table_orders)

14.12.2020 Python Programming for non-Programmers 23


Visualize your data in a table

Running the application and navigate to the URL /tables


shows the data inside the database

14.12.2020 Python Programming for non-Programmers 24


Project information

The projects starts tomorrow 10:00 am and should


be finished until 2021-02-28 11:59 pm

Short presentation of your project after the exams


About 10 min

Implement a demo web application


Develop functions to work manually with a database
Analyze and visualize data from a given database
14.12.2020 Python Programming for non-Programmers 25
Thanks for your attention!
Next lecture: 2021-01-04

You might also like