Unit C Lesson C1
Screen 1 of 13
1) Installing Python
2) Creating a virtual environment
3) Installing Flask
4) Configuring Flask
5) Building your first local Flask app
6) Running your first Flask app
7) Understanding web servers
8) Deploying to PythonAnywhere
Unit C Lesson C1
Screen 2 of 13
Unit C Lesson C1
Screen 3 of 13
Unit C Lesson C1
Screen 4 of 13
The following components are required for your first Flask app:
The components are explained on the following slides.
Unit C Lesson C1
Screen 5 of 13
The import statement:
Imports the module Flask from the package flask
The Flask constructor:
Creates an instance of the Flask class. __name__ is a Python predefined variable.
from flask import Flask
app = Flask(__name__)
Unit C Lesson C1
Screen 6 of 13
Decorator:
Creates an association between the URL ('/') and the function that follows.
Unit C Lesson C1
Screen 7 of 13
@app.route('/')
Note: A more complex web site with multiple pages would require a separate decorator for each page. Example:
@app.route('/')
def home():
return render_template('index.html')
@app.route('/signup', methods=['POST'])
def signup():
...
return ...
@app.route('/message')
def message():
...
return ...
Unit C Lesson C1
Screen 8 of 13
def hello_world():
return 'Hello World!'
Function:
Defines the function which is called by accessing the URL. In this case a simple text message is returned.
Note: Instead of returning a simple text as above, a rendered template can be returned. Templates in the form of html pages stay in a folder "/templates". Example:
from flask import render_template
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html',
name=name)
The call of Flask's run method to locally run the application:
The correct way to tell Python to execute the code
if __name__ == '__main__':
app.run()
Unit C Lesson C1
Screen 9 of 13
Unit C Lesson C1
Screen 10 of 13
There are multiple ways to write Python code. You could...
Unit C Lesson C1
Screen 11 of 13
We recommend Notepad++, a light-weight, easy to learn editor for your first Python app.
Create a new file called app.py with the code fragments of the previous slides:
Save the new file with the name app.py into the c:\~\myproject\app folder.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
Having completed Unit C Lesson C1 you should now successfully be able to:
Unit C Lesson C1
Screen 12 of 13
Please perform the following steps before you proceed to Lesson 2:
Refer to the previous slides if necessary. Complete the assignment C1 once you are finished with above steps.
Unit C Lesson C1
Screen 13 of 13