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. For convenience, we typically speak of these defaults as part of Flask.
In this Flask tutorial, you create a simple Flask app with three pages that use a common base template. Along the way, you experience a number of features of Visual Studio Code including using the terminal, the editor, the debugger, code snippets, and more.
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.
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.
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 Profile to set "Command Prompt" or "Git Bash" as your default instead.
You now have a self-contained environment ready for writing Flask code. VS Code activates the environment automatically when you use Terminal: Create New Terminal. If you open a separate command prompt or terminal, activate the environment by running source .venv/bin/activate (Linux/macOS) or .venv\Scripts\Activate.ps1 (Windows). You know the environment is activated when the command prompt shows (.venv) at the beginning.
In the Integrated Terminal, run the app by entering python -m flask run, which runs the Flask development server. The development server looks for app.py by default. When you run Flask, you should see output similar to the following:
Tip: When using a different filename than app.py, such as webapp.py, you will need to define an environment variable named FLASK_APP and set its value to your chosen file. Flask's development server then uses the value of FLASK_APP instead of the default file app.py. For more information, see Flask command line interface.
Debugging gives you the opportunity to pause a running program on a particular line of code. When a program is paused, you can examine variables, run code in the Debug Console panel, and otherwise take advantage of the features described on Debugging. Running the debugger also automatically saves any modified files before the debugging session begins.
Before you begin: Make sure you've stopped the running app at the end of the last section by using Ctrl+C in the terminal. If you leave the app running in one terminal, it continues to own the port. As a result, when you run the app in the debugger using the same port, the original running app handles all the requests and you won't see any activity in the app being debugged and the program won't stop at breakpoints. In other words, if the debugger doesn't seem to be working, make sure that no other instance of the app is still running.
The decorator used for the new URL route, /hello/, defines an endpoint /hello/ that can accept any additional value. The identifier inside in the route defines a variable that is passed to the function and can be used in your code.
As described in the code comments, always filter arbitrary user-provided information to avoid various attacks on your app. In this case, the code filters the name argument to contain only letters, which avoids injection of control characters, HTML, and so forth. (When you use templates in the next section, Flask does automatic filtering and you won't need this code.)
Select the link and VS Code will prompt for a debug configuration. Select Flask from the dropdown and VS Code will populate a new launch.json file with a Flask run configuration. The launch.json file contains a number of debugging configurations, each of which is a separate JSON object within the configuration array.
Scroll down to and examine the configuration, which is named "Python: Flask". This configuration contains "module": "flask",, which tells VS Code to run Python with -m flask when it starts the debugger. It also defines the FLASK_APP environment variable in the env property to identify the startup file, which is app.py by default, but allows you to easily specify a different file. If you want to change the host and/or port, you can use the args array.
Note: If the env entry in your configuration contains "FLASK_APP": "$workspaceFolder/app.py", change it to "FLASK_APP": "app.py" as shown above. Otherwise you may encounter error messages like "Cannot import module C" where C is the drive letter where your project folder resides.
Note: Once launch.json is created, an Add Configuration button appears in the editor. That button displays a list of additional configurations to add to the beginning of the configuration list. (The Run > Add Configuration menu command does the same action.).
Output appears in a "Python Debug Console" terminal. Ctrl+click the :5000/ link in that terminal to open a browser to that URL. In the browser's address bar, navigate to :5000/hello/VSCode. Before the page renders, VS Code pauses the program at the breakpoint you set. The small yellow arrow on the breakpoint indicates that it's the next line of code to run.
On the left side of the VS Code window, you see a Variables pane that shows local variables, such as now, as well as arguments, such as name. Below that are panes for Watch, Call Stack, and Breakpoints (see VS Code debugging for details). In the Locals section, try expanding different values. You can also double-click values (or use Enter (Windows, Linux F2)) to modify them. Changing variables such as now, however, can break the program. Developers typically make changes only to correct values when the code didn't produce the right value to begin with.
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:
Change the line in the code to use different datetime format, for example now.strftime("%a, %d %b, %y at %X"), and then save the file. The Flask server will automatically reload, which means the changes will be applied without the need to restart the debugger. Refresh the page on the browser to see the update.
Tip: To make it easier to repeatedly navigate to a specific URL like :5000/hello/VSCode, output that URL using a print statement. The URL appears in the terminal where you can use Ctrl+click to open it in a browser.
During your work with Flask or any other library, you may want to examine the code in those libraries themselves. VS Code provides two convenient commands that navigate directly to the definitions of classes and other objects in any code:
The app you've created so far in this tutorial generates only plain text web pages from Python code. Although it's possible to generate HTML directly in code, developers avoid such a practice because it opens the app to cross-site scripting (XSS) attacks. In the hello_there function of this tutorial, for example, one might think to format the output in code with something like content = "Hello there, " + clean_name + "!", where the result in content is given directly to a browser. This opening allows an attacker to place malicious HTML, including JavaScript code, in the URL that ends up in clean_name and thus ends up being run in the browser.
In this section, you create a single page using a template. In the sections that follow, you configure the app to serve static files, and then create multiple pages to the app that each contains a nav bar from a base template.
In the templates folder, create a file named hello_there.html with the contents below. This template contains two placeholders named "name" and "date", which are delineated by pairs of curly braces, and . As you can see, you can also include formatting code in the template directly:
Also in app.py, modify the hello_there function to use render_template to load a template and apply the named values (and add a route to recognize the case without a name). render_template assumes that the first argument is relative to the templates folder. Typically, developers name the templates the same as the functions that use them, but matching names are not required because you always refer to the exact filename in your code.
Also try navigating to a /hello/name URL using a name like to see Flask's automatic escaping at work. The "name" value shows up as plain text in the browser rather than as rendering an actual element.
Static files are of two types. First are those files like stylesheets to which a page template can just refer directly. Such files can live in any folder in the app, but are commonly placed within a static folder.
b37509886e