Getting Started with Flask and Visual Studio Code on Anvil
This example comes from Project 13 from Spring 2024 TDM 102.
Motivation: Flask is a web application framework that provides tools, libraries, and technologies to build a web application.
Context: In this guide, you’ll create a simple conceptual webpage using Flask
.
Scope: Python, Flask, Visual Studio Code
Step-by-Step Guide
Step 1: Set Up Visual Studio Code on Anvil
-
Follow the instructions from the Visual Studio Code Starter Guide to launch VS Code on Anvil.
-
Complete the Initial Configuration of VS Code and install the Python extension.
-
Select the Python interpreter path:
/anvil/projects/tdm/apps/lmodbin/python-seminar/python3
-
Open a new terminal in VS Code and confirm the Python interpreter path by running:
which python3
You should see /anvil/projects/tdm/apps/lmodbin/python-seminar/python3
as the output.
+
Launch VS Code on Anvil with the following options:
If prompted with "Do you trust the authors of the files in this folder?", click Yes, I trust the authors. |
See Code Editing in Visual Studio Code to learn how to edit and run code. |
Step 2: Create and Run a Simple Python Script
-
In VS Code, create a Python file named
helloWorld.py
. -
Add a simple greeting:
print("Hello, world!")
-
Run the file in the terminal:
python3 helloWorld.py
Step 3: Build a Basic Flask Application
-
Create a new Python file and enter the following code:
from flask import Flask app = Flask(__name__) if __name__ == '__main__': app.run(host='0.0.0.0', port=8050, debug=True)
-
Run the Python file. A message will appear indicating that your application is running on port 8050.
|
Step 4: Add a Route to Display a Message
-
Modify your Flask code to define a route for the homepage (
'/'
):from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hello World!' if __name__ == '__main__': app.run(host='0.0.0.0', port=8050, debug=True)
-
Re-run the Python file and refresh your browser to see the message.
To stop the server, click into the terminal and press |
Step 5: Use an HTML Template for the Homepage
-
In your project folder, create a directory named
templates
. -
Inside the
templates
folder, create a file namedindex.html
:<html> <head> The head of my example page. </head> <body> Greetings from Dr Ward and Cookie Monster! </body> </html>
-
Update your Flask app to use the
render_template
function:from flask import Flask, render_template app = Flask(__name__) @app.route('/') def hello(name=None): return render_template('index.html', name=name) if __name__ == '__main__': app.run(host='0.0.0.0', port=8050, debug=True)
-
Run the Python file again and open the browser to view the rendered HTML.
Ensure that the Example path:
|
You now have a basic understanding of how to launch VS Code on Anvil, create and run a Flask app, define routes, and serve HTML content using templates!