[go: up one dir, main page]

0% found this document useful (0 votes)
61 views69 pages

FLASK

This document provides an introduction to building visual reports with Flask, a Python microframework. It covers: - Creating a virtual environment for Flask projects to manage dependencies. - Running a "Hello World" Flask app and basic routing. - Using dynamic routes to pass variables to pages. - Enabling debug mode for catching errors. - Rendering HTML templates and passing variables between Python and templates.

Uploaded by

Nima Dorji
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)
61 views69 pages

FLASK

This document provides an introduction to building visual reports with Flask, a Python microframework. It covers: - Creating a virtual environment for Flask projects to manage dependencies. - Running a "Hello World" Flask app and basic routing. - Using dynamic routes to pass variables to pages. - Enabling debug mode for catching errors. - Rendering HTML templates and passing variables between Python and templates.

Uploaded by

Nima Dorji
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/ 69

Unit 5: Building visual reports

CSA202: Data Analytics and Visualization


Ms. Pema Wangmo

Gyalpozhing College of Information Technology


Royal University of Bhutan
BCS Year II, Sem I
Learning objective
● Introduction of flask
● Creating environment for flask
● Running hello world site
● Basic route
● Dynamic route
● Templates in flask
● Embedding static Bokeh plots in flask
● Embedding interactive Bokeh server plot in flask
FLASK
Flask
● Flask is a lightweight Python framework for web applications that provides the

basics for URL routing and page rendering.

● It is easy to learn and use. Flask is “beginner-friendly” because it does not have

boilerplate code or dependencies, which can distract from the primary function of

an application.
Features of Flask
● Some features which make Flask an ideal framework for web application

development are:

○ Flask provides a development server and a debugger.

○ It uses Jinja2 templates.

○ It is compliant with WSGI(Web Server Gateway Interface) 1.0.

○ It provides integrated support for unit testing.

○ Many extensions are available for Flask, which can be used to enhance its functionalities.
What is micro framework?
● Micro-frameworks are the opposite of full-stack frameworks, which also offer

additional modules for features such as authentication, database ORM, input

validation and sanitization, etc.


Why is Flask called a micro-framework?#
● Flask is called a "micro" framework because it doesn't directly provide features

like form validation, database abstraction, authentication, and so on.

● Such features are instead provided by special Python packages called Flask

extensions.

● The extensions integrate seamlessly with Flask so that they appear as if they were

part of Flask itself. For example, Flask doesn't provide a page template engine, but

installing Flask includes the Jinja templating engine by default.


Who is using flask?
● Netflix uses many
● Uber’s Marketplace team

micro-services for different has also used Flask to

tools, such as its Winston and control optimization and

Bolt products. These balancing of dynamic pricing,


micro-services are developed
supply positioning,
using Flask and Flask-RESTPlus.
intelligent matching, and

health.
Who is using flask?
● MIT’s technology stack also
● Mozilla has used Flask in

many of their projects as


includes Flask.
well, specifically to utilize

its easy CRUD support.


Flask Basics
Virtual environment
● Imagine you’ve launched your web application and you use some external

python library.

● Then that library gets updated to a newer version, the update has new

features, but also has breaking changes.

● What can we do?


Virtual environment
● Fortunately we can use virtual environments to help manage

dependencies!

● Each project we work on can have its own distinct environment.

● This is why we use Virtual Environments.


Virtual environment
● Anaconda comes with a built-in environment manager.

● We need to run some steps at our command line to create the

environment.
Use the terminal or an Anaconda Prompt for the following steps:
● To create an environment:

○ conda create --name myenv

● Replace myenv with the environment name you want to keep

● Conda may then ask you to proceed (y/n)? Go ahead and press y to

continue.
Virtual environment
● To create an environment with a specific package included:

○ conda create -n myenv numpy

● To create an environment with a specific version of Python you can do:

○ conda create --name myenv python=3.5


Virtual environment
● To create an environment with a specific package version included:

○ conda create -n myenv numpy=1.14

● To list out all your environments:

○ conda env list


Lets create flask environment
Install flask

Open your terminal and

type the above command


Activate the environment Deactivate the environment
● For windows ● For windows

○ activate myflaskenv ○ deactivate myflaskenv

● For mac or linux: ● For mac or linux:

○ source activate myflaskenv ○ source deactivate myflaskenv

***myflaskenv: name of your environment


Selecting the environment in VS code
● In the bottom right side of vs code, you will find the python version and the

environment you will be working on.

● Click on that if you are not in the environment you have activated and select the

environment accordingly.
Selecting the environment in VS code
● You will see the following output and select the virtual environment (myflaskenv)
Selecting the environment in VS code
● After selecting, you will finally land in your virtual environment you have created
“hello world” site
● Let’s create our first website with Flask!

● This is the simplest site possible.

● It will simply return Hello World on a webpage.

● Make sure you’ve installed Flask!


Run “hello world” site

Command to run the file:

python filename

helloWorld.py
“hello world” site
● flask is package and Flask is class imported from flask package

● __name__ : inbuilt variable

● app.route(‘/’) : route to homepage by default or you can specify the page you want to

land to also

Function index will be called and displayed on homepage

● __name__ == ‘__main__’ means if name variable is equal to main file(the current file

you are running) then run this application (app.run()) runs the file.
Route in flask
Basic Route
● We just saw how to create a web application with a single page

(returned in the form of a string).

● Let’s see how we can add multiple routes (multiple pages).

The key to this is in the @app.route() decorator.

● The string parameter passed into the decorator determines the URL

extension that will link to the function (a.k.a view).


Basic Route
● Currently our homepage or domain is locally represented as

http://127.0.0.1:5000/

● We use decorators to add on to this

@app.route(“/some_page”)

● http://127.0.0.1:5000/some_page

● Once a page is deployed, 127.0.0.1 will be replaced by the domain (www.site.com)


Output

basicRoute.py
Dynamic Route
• Often we will want URL route extensions to be dynamic based on the situation.

• For example we may want a page per user, so that the extension is in the form:

• www.site.com/user/unique_user_name

• To achieve this effect we can use dynamic routes.

• Dynamic routes have 2 key aspects

1) A variable in the route <variable>

2) A parameter passed in to the function


dynamicRoute.py
Debug mode
● As we learn we’ll definitely make some mistakes along the way!

● We can set debug=True in our application to help us catch errors.

● Debug mode also gives us access to a console in the browser!

● When you are ready for deployment, debug mode should be set to false.

Else the traceback error will be displayed to user also.


debug.py
Exercise
● Let’s test you on everything we’ve covered so far with an exercise!

● You will be creating a simple web page that converts puppy names into puppy latin (a

made up language similar to pig latin)

Puppy Latin Rules:

If a puppy name does not end in a y add on a y to the name

Example: Rufus → Rufusy Spot → Spoty

If a puppy name does end in a y, replace it with iful instead

Example: Sparky → Sparkiful Spoty → Spotiful


Expected Output
● Your web application will have a

route:

● /puppy_latin/<name>

● This route will take in the name

passed and then display the puppy

latin version on the page.


Template in flask
Basic template
● So far we’ve only returned back HTML manually through a Python string.

● Realistically we will want to connect a view function to render HTML templates

● Flask will automatically look for HTML Templates in the templates directory.

● We can render templates simply by importing the render_template function from

flask and returning an .html file from our view function.

● Let’s see this in action!


● Create templates folder and under that folder, create html files

● Create static folder and store image file under this folder.

basic.html
● Create a python file which will render html file inside the templates folder

basic_template.py
Output
Template variables
● We want a way to be able to use Python code in our app, changing and updating variables

and logic, and then send that information to the template.

● We can use the Jinja template engine to do this.

● Jinja templating will let us directly insert variables from our Python code to the HTML

file.

● The syntax for inserting a variable is

{{ some_variable}}
Template variables
● We can pass in python strings, lists, dictionaries, and more into the templates.

● We set parameters (of our choice) in the render_template function and then use

the {{ }} syntax to insert them in the template.

● Let’s explore some examples!


templates_variable.py

templates_variable.html
Output
Template control flow
● With Jinja templating we can pass variables using {{ variable }} syntax.

● We also have access to control flow syntax in our templates such as for loops and

if statements.

● These use a {% %} syntax


template_control.py
template_control.html
Template inheritance
● We know we can create view functions that directly link to an HTML template.

● But that still means we need to make an HTML template for every page.

● Usually pages across a web application already share a lot of features (e.g.

navigation bar, footer, etc..)


Template inheritance
● A great solution is template inheritance.

● We set up a base.html template file with the re-usable aspects of the site.

● Then we use {% extend “base.html” %} and {% block %} statements to extend

these re-usable aspects to other pages.


Template inheritance
template_inheritance.py
home.html Result page

Derived
from Base
page

Home page
puppy.html
Embedding static Bokeh
plots in flask
bokeh.embed
● Provide functions for embedding Bokeh standalone and server content in web

pages.

● Component

Return HTML components to embed a Bokeh plot. The data for the plot is stored

directly in the returned HTML.

returns (script, div[s])


bokeh.resources
● The resources module provides the resources class for easily configuring how BokehJS

code and CSS resources should be located, loaded, and embedded in Bokeh documents.

● Once configured, a resource object exposes the following public attributes:

● js_files

URLs of any JS files that need to be loaded by <script> tags

● css_files

URLs of any CSS files that need to be loaded by <link> tags


basic_line.py
Flask file: app.py

From basic_line.py,
import variables
which are used to
load Bokeh plot in
flask
index.html

main.css under
static/css folder
Running the file and output

Run your flask app with the


command

python app.py

filename
Embedding interactive
Bokeh server plot in flask
bokeh.client
● pull_session: Create a session by loading the current server-side document.

● Session id for the below file is generated

● url=http://localhost:5006/bokeh_labelWidget
bokeh.embed
● server_session: Return a script tag that embeds content from a specific existing

session on a Bokeh server.

● This function is typically only useful for serving from a specific session that was

previously created using the bokeh.client API.


app.py
bokeh_labelWidget.py
● We will be using the same file we

used for generating interactive

Bokeh server plot displaying the

widgets
index.html
Running the file
● You are running Bokeh server on port 5006 and flask on port 5000
● Because of some security feature issue, to embed Bokeh server plot in flask, you
need to run the following command to initialize Bokeh server plot

● bokeh serve --allow-websocket-origin=127.0.0.1:5000 bokeh_labelWidget.py OR

● bokeh serve --allow-websocket-origin=localhost:5000 bokeh_labelWidget.py

Filename of Bokeh
server plot
The command means giving permission
to url “127.0.0.1:5000” to run Bokeh server app
Running the file
● After you run the command, Bokeh server plot will be initialized and you need to
run your flask app

python app.py

filename
Output
any questions??
Find me at pemawangmo.gcit@rub.edu.bt

You might also like