Skip to content

Commit a128e0b

Browse files
authored
Merge pull request #5964 from luabud/updateflasktutorial
Update Flask tutorial
2 parents aeb2cc3 + 4f5b4b2 commit a128e0b

File tree

6 files changed

+29
-68
lines changed

6 files changed

+29
-68
lines changed
Lines changed: 3 additions & 0 deletions
Loading
Lines changed: 2 additions & 2 deletions
Loading
Lines changed: 2 additions & 2 deletions
Loading
Lines changed: 2 additions & 2 deletions
Loading
Lines changed: 2 additions & 2 deletions
Loading

docs/python/tutorial-flask.md

Lines changed: 18 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ Area: python
44
TOCTitle: Flask Tutorial
55
ContentId: 593d2dd6-20f0-4ad3-8ecd-067cc47ee217
66
PageTitle: Python and Flask Tutorial in Visual Studio Code
7-
DateApproved: 10/27/2021
7+
DateApproved: 01/20/2023
88
MetaDescription: Python Flask tutorial showing IntelliSense, debugging, and code navigation support in Visual Studio Code, the best Python IDE.
99
MetaSocialImage: images/tutorial/social.png
1010
---
@@ -27,62 +27,30 @@ To successfully complete this Flask tutorial, you must do the following (which a
2727
1. Install the [Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python).
2828

2929
1. Install a version of Python 3 (for which this tutorial is written). Options include:
30-
- (All operating systems) A download from [python.org](https://www.python.org/downloads/); typically use the **Download Python 3.9.1** button that appears first on the page (or whatever is the latest version).
30+
- (All operating systems) A download from [python.org](https://www.python.org/downloads/); typically use the **Download** button that appears first on the page.
3131
- (Linux) The built-in Python 3 installation works well, but to install other Python packages you must run `sudo apt install python3-pip` in the terminal.
32-
- (macOS) An installation through [Homebrew](https://brew.sh/) on macOS using `brew install python3` (the system install of Python on macOS is not supported).
32+
- (macOS) An installation through [Homebrew](https://brew.sh/) on macOS using `brew install python3`.
3333
- (All operating systems) A download from [Anaconda](https://www.anaconda.com/download/) (for data science purposes).
3434

3535
1. On Windows, make sure the location of your Python interpreter is included in your PATH environment variable. You can check the location by running `path` at the command prompt. If the Python interpreter's folder isn't included, open Windows Settings, search for "environment", select **Edit environment variables for your account**, then edit the **Path** variable to include that folder.
3636

3737
## Create a project environment for the Flask tutorial
3838

39-
In this section, you create a virtual environment in which Flask is installed. Using a virtual environment avoids installing Flask into a global Python environment and gives you exact control over the libraries used in an application. A virtual environment also makes it easy to [Create a requirements.txt file for the environment](#create-a-requirementstxt-file-for-the-environment).
39+
In this section, you will create a virtual environment in which Flask is installed. Using a virtual environment avoids installing Flask into a global Python environment and gives you exact control over the libraries used in an application.
4040

41-
1. On your file system, create a project folder for this tutorial, such as `hello_flask`.
41+
1. On your file system, create a folder for this tutorial, such as `hello_flask`.
4242

43-
1. In that folder, use the following command (as appropriate to your computer) to create and activate a virtual environment named `.venv` based on your current interpreter:
43+
1. Open this folder in VS Code by navigating to the folder in a terminal and running `code .`, or by running VS Code and using the **File** > **Open Folder** command.
4444

45-
```bash
46-
# Linux
47-
sudo apt-get install python3-venv # If needed
48-
python3 -m venv .venv
49-
source .venv/bin/activate
50-
51-
# macOS
52-
python3 -m venv .venv
53-
source .venv/bin/activate
54-
55-
# Windows
56-
py -3 -m venv .venv
57-
.venv\scripts\activate
58-
```
59-
60-
> **Note**: Use a stock Python installation when running the above commands. If you use `python.exe` from an Anaconda installation, you see an error because the ensurepip module isn't available, and the environment is left in an unfinished state.
61-
62-
1. Open the project folder in VS Code by running `code .`, or by running VS Code and using the **File** > **Open Folder** command.
63-
64-
1. In VS Code, open the Command Palette (**View** > **Command Palette** or (`kb(workbench.action.showCommands)`)). Then select the **Python: Select Interpreter** command:
45+
1. In VS Code, open the Command Palette (**View** > **Command Palette** or (`kb(workbench.action.showCommands)`)). Then select the **Python: Create Environment** command to create a virtual environment in your workspace. Select `venv` and then the Python environment you want to use to create it.
46+
> **Note**: If you want to create an environment manually, or run into error in the environment creation process, visit the [Environments](/docs/python/environments.md#create-a-virtual-environment-in-the-terminal) page.
6547
66-
![Flask tutorial: opening the Command Palette in VS Code](images/shared/command-palette.png)
48+
![Flask tutorial: opening the Command Palette in VS Code](images/flask-tutorial/command-palette.png)
6749

68-
1. The command presents a list of available interpreters that VS Code can locate automatically (your list will vary; if you don't see the desired interpreter, see [Configuring Python environments](/docs/python/environments.md)). From the list, select the virtual environment in your project folder that starts with `./.venv` or `.\.venv`:
69-
70-
![Flask tutorial: selecting the virtual environment for Python](images/shared/select-virtual-environment.png)
71-
72-
1. Run [**Terminal: Create New Terminal**](/docs/terminal/basics.md) (`kb(workbench.action.terminal.new)`)) from the Command Palette, which creates a terminal and automatically activates the virtual environment by running its activation script.
50+
1. After your virtual environment creation has been completed, run [**Terminal: Create New Terminal**](/docs/terminal/basics.md) (`kb(workbench.action.terminal.new)`)) from the Command Palette, which creates a terminal and automatically activates the virtual environment by running its activation script.
7351

7452
> **Note**: On Windows, if your default terminal type is PowerShell, you may see an error that it cannot run activate.ps1 because running scripts is disabled on the system. The error provides a link for information on how to allow scripts. Otherwise, use **Terminal: Select Default Shell** to set "Command Prompt" or "Git Bash" as your default instead.
7553
76-
1. The selected environment appears on the right side of the VS Code status bar, and notice the **('.venv': venv)** indicator that tells you that you're using a virtual environment:
77-
78-
![Flask tutorial: selected environment showing in the VS Code status bar](images/shared/environment-in-status-bar.png)
79-
80-
1. Update pip in the virtual environment by running the following command in the VS Code Terminal:
81-
82-
```bash
83-
python -m pip install --upgrade pip
84-
```
85-
8654
1. Install Flask in the virtual environment by running the following command in the VS Code Terminal:
8755

8856
```bash
@@ -200,7 +168,7 @@ Debugging gives you the opportunity to pause a running program on a particular l
200168
201169
![Flask tutorial: a breakpoint set on the first line of the hello_there function](images/flask-tutorial/debug-breakpoint-set.png)
202170
203-
1. Switch to **Run** view in VS Code (using the left-side activity bar or `kb(workbench.action.debug.start)`). You may see the message "To customize Run and Debug create a launch.json file". This means that you don't yet have a `launch.json` file containing debug configurations. VS Code can create that for you if you click on the **create a launch.json file** link:
171+
1. Switch to the **Run and Debug** view in VS Code (using the left-side activity bar or `kb(workbench.view.debug)`). You may see the message "To customize Run and Debug create a launch.json file". This means that you don't yet have a `launch.json` file containing debug configurations. VS Code can create that for you if you click on the **create a launch.json file** link:
204172
205173
![Flask tutorial: initial view of the debug panel](images/shared/debug-panel-initial-view.png)
206174
@@ -258,7 +226,7 @@ Debugging gives you the opportunity to pause a running program on a particular l
258226
259227
![Flask tutorial: local variables and arguments in VS Code during debugging](images/flask-tutorial/debug-local-variables.png)
260228
261-
1. When a program is paused, the **Debug Console** panel (which is different from the "Python Debug Console" in the Terminal panel) lets you experiment with expressions and try out bits of code using the current state of the program. For example, once you've stepped over the line `now = datetime.now()`, you might experiment with different date/time formats. In the editor, select the code that reads `now.strftime("%A, %d %B, %Y at %X")`, then right-click and select **Debug: Evaluate** to send that code to the debug console, where it runs:
229+
1. When a program is paused, the **Debug Console** panel (which is different from the "Python Debug Console" in the Terminal panel) lets you experiment with expressions and try out bits of code using the current state of the program. For example, once you've stepped over the line `now = datetime.now()`, you might experiment with different date/time formats. In the editor, select the code that reads `now.strftime("%A, %d %B, %Y at %X")`, then right-click and select **Evaluate in Debug Console** to send that code to the debug console, where it runs:
262230
263231
```bash
264232
now.strftime("%A, %d %B, %Y at %X")
@@ -422,7 +390,7 @@ The following sections demonstrate both types of static files.
422390
423391
## Create multiple templates that extend a base template
424392
425-
Because most web apps have more than one page, and because those pages typically share many common elements, developers separate those common elements into a base page template that other page templates can then extend. (This is also called template inheritance.)
393+
Because most web apps have more than one page, and because those pages typically share many common elements, developers separate those common elements into a base page template that other page templates can then extend (this is also called template inheritance.)
426394
427395
Also, because you'll likely create many pages that extend the same template, it's helpful to create a code snippet in VS Code with which you can quickly initialize new page templates. A snippet helps you avoid tedious and error-prone copy-paste operations.
428396
@@ -434,7 +402,7 @@ A base page template in Flask contains all the shared parts of a set of pages, i
434402
435403
The following steps demonstrate creating a base template.
436404
437-
1. In the `templates` folder, create a file named `layout.html` with the contents below, which contains blocks named "title" and "content". As you can see, the markup defines a simple nav bar structure with links to Home, About, and Contact pages, which you create in a later section. Each link again uses Flask's `url_for` tag to generate a link at runtime for the matching route.
405+
1. In the `templates` folder, create a file named `layout.html` with the contents below, which contains blocks named "title" and "content". As you can see, the markup defines a simple nav bar structure with links to Home, About, and Contact pages, which you will create in a later section. Each link again uses Flask's `url_for` tag to generate a link at runtime for the matching route.
438406
439407
```html
440408
<!DOCTYPE html>
@@ -464,7 +432,7 @@ The following steps demonstrate creating a base template.
464432
</html>
465433
```
466434
467-
1. Add the following styles to `static/site.css` below the existing "message" style, and save the file. (This walkthrough doesn't attempt to demonstrate responsive design; these styles simply generate a reasonably interesting result.)
435+
1. Add the following styles to `static/site.css`, below the existing "message" style, and save the file. Note that this walkthrough doesn't attempt to demonstrate responsive design; these styles simply generate a reasonably interesting result.
468436
469437
```css
470438
.navbar {
@@ -502,11 +470,11 @@ You can run the app at this point, but because you haven't made use of the base
502470
503471
Because the three pages you create in the next section extend `layout.html`, it saves time to create a **code snippet** to initialize a new template file with the appropriate reference to the base template. A code snippet provides a consistent piece of code from a single source, which avoids errors that can creep in when using copy-paste from existing code.
504472
505-
1. In VS Code, select the **File** (Windows/Linux) or **Code** (macOS), menu, then select **Preferences** > **User snippets**.
473+
1. In VS Code, select **File** (**Code** on macOS) > **Preferences** > **Configure User Snippets**.
506474
507-
1. In the list that appears, select **html**. (The option may appear as "html.json" in the **Existing Snippets** section of the list if you've created snippets previously.)
475+
1. In the list that appears, select **html**. The option may appear as "html.json" in the **Existing Snippets** section of the list if you've created snippets previously.
508476
509-
1. After VS code opens `html.json`, add the following entry within the existing curly braces (the explanatory comments, not shown here, describe details such as how the `$0` line indicates where VS Code places the cursor after inserting a snippet):
477+
1. After VS Code opens `html.json`, add the following entry within the existing curly braces (the explanatory comments, not shown here, describe details such as how the `$0` line indicates where VS Code places the cursor after inserting a snippet):
510478
511479
```json
512480
"Flask Tutorial: template extending layout.html": {
@@ -636,16 +604,6 @@ Throughout this Flask tutorial, all the app code is contained in a single `app.p
636604
return app.send_static_file("data.json")
637605
```
638606
639-
1. Optional: Right-click in the editor and select the **Sort Imports** command, which consolidates imports from identical modules, removes unused imports, and sorts your import statements. Using the command on the code above in `views.py` changes the imports as follows (you can remove the extra lines, of course):
640-
641-
```python
642-
from datetime import datetime
643-
644-
from flask import Flask, render_template
645-
646-
from . import app
647-
```
648-
649607
1. In the `hello_app` folder, create a file `__init__.py` with the following contents:
650608
651609
```python

0 commit comments

Comments
 (0)