You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/python/tutorial-flask.md
+18-60Lines changed: 18 additions & 60 deletions
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,7 @@ Area: python
4
4
TOCTitle: Flask Tutorial
5
5
ContentId: 593d2dd6-20f0-4ad3-8ecd-067cc47ee217
6
6
PageTitle: Python and Flask Tutorial in Visual Studio Code
7
-
DateApproved: 10/27/2021
7
+
DateApproved: 01/20/2023
8
8
MetaDescription: Python Flask tutorial showing IntelliSense, debugging, and code navigation support in Visual Studio Code, the best Python IDE.
9
9
MetaSocialImage: images/tutorial/social.png
10
10
---
@@ -27,62 +27,30 @@ To successfully complete this Flask tutorial, you must do the following (which a
27
27
1. Install the [Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python).
28
28
29
29
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.
31
31
- (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`.
33
33
- (All operating systems) A download from [Anaconda](https://www.anaconda.com/download/) (for data science purposes).
34
34
35
35
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.
36
36
37
37
## Create a project environment for the Flask tutorial
38
38
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.
40
40
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`.
42
42
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.
44
44
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.
65
47
66
-

48
+

67
49
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, selectthe virtual environment in your project folder that starts with `./.venv` or `.\.venv`:
69
-
70
-

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.
73
51
74
52
> **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.
75
53
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
-

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
-
86
54
1. Install Flask in the virtual environment by running the following command in the VS Code Terminal:
87
55
88
56
```bash
@@ -200,7 +168,7 @@ Debugging gives you the opportunity to pause a running program on a particular l
200
168
201
169

202
170
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:
204
172
205
173

206
174
@@ -258,7 +226,7 @@ Debugging gives you the opportunity to pause a running program on a particular l
258
226
259
227

260
228
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, selectthe 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, selectthe code that reads `now.strftime("%A, %d %B, %Y at %X")`, then right-click and select**EvaluateinDebug Console** to send that code to the debug console, where it runs:
262
230
263
231
```bash
264
232
now.strftime("%A, %d %B, %Y at %X")
@@ -422,7 +390,7 @@ The following sections demonstrate both types of static files.
422
390
423
391
## Create multiple templates that extend a base template
424
392
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.)
426
394
427
395
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.
428
396
@@ -434,7 +402,7 @@ A base page template in Flask contains all the shared parts of a set of pages, i
434
402
435
403
The following steps demonstrate creating a base template.
436
404
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.
438
406
439
407
```html
440
408
<!DOCTYPE html>
@@ -464,7 +432,7 @@ The following steps demonstrate creating a base template.
464
432
</html>
465
433
```
466
434
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.
468
436
469
437
```css
470
438
.navbar {
@@ -502,11 +470,11 @@ You can run the app at this point, but because you haven't made use of the base
502
470
503
471
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.
504
472
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**.
506
474
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.
508
476
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):
@@ -636,16 +604,6 @@ Throughout this Flask tutorial, all the app code is contained in a single `app.p
636
604
return app.send_static_file("data.json")
637
605
```
638
606
639
-
1. Optional: Right-click in the editor and selectthe**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
-
649
607
1. In the `hello_app` folder, create a file `__init__.py` with the following contents:
0 commit comments