Python And Flask Tutorial In Visual Studio Code

Flask Tutorial in Visual Studio Code

Flask is a lightweight Python framework for web applications that provides the basics for URL routing and page rendering.

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.

The completed code project for this Flask tutorial can be found on GitHub: python-sample-vscode-flask-tutorial.

If you have any problems, you can search for answers or ask a question on the Python extension Discussions Q&A.

Prerequisites

To successfully complete this Flask tutorial, you must do the following (which are the same steps as in the general Python tutorial):

  1. Install the Python extension.

  2. Install a version of Python 3 (for which this tutorial is written). Options include:

    • (All operating systems) A download from python.org; typically use the Download button that appears first on the page.
    • (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.
    • (macOS) An installation through Homebrew on macOS using brew install python3.
    • (All operating systems) A download from Anaconda (for data science purposes).
  3. 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.

Create a project environment for the Flask tutorial

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.

  1. On your file system, create a folder for this tutorial, such as hello_flask.

  2. 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.

  3. In VS Code, open the Command Palette (View > Command Palette or (⇧⌘P (Windows, Linux Ctrl+Shift+P))). 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.

    Note: If you want to create an environment manually, or run into error in the environment creation process, visit the Environments page.

    Flask tutorial: opening the Command Palette in VS Code

  4. After your virtual environment creation has been completed, run Terminal: Create New Terminal (⌃⇧` (Windows, Linux Ctrl+Shift+`))) from the Command Palette, which creates a terminal and automatically activates the virtual environment by running its activation script.

    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.

  5. Install Flask in the virtual environment by running the following command in the VS Code Terminal:

    from flask import Flask app = Flask(__name__)
  6. Also in app.py, add a function that returns content, in this case a simple string, and use Flask's app.route decorator to map the URL route / to that function:

    (.venv) D:\py\\hello_flask>python -m flask run * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

    If you see an error that the Flask module cannot be found, make sure you've run python -m pip install flask in your virtual environment as described at the end of the previous section.

    Also, if you want to run the development server on a different IP address or port, use the host and port command-line arguments, as with --host=0.0.0.0 --port=80.

  7. To open your default browser to the rendered page, Ctrl+click the http://127.0.0.1:5000/ URL in the terminal.

    Flask tutorial: the running app in a browser

  8. Observe that when you visit a URL like /, a message appears in the debug terminal showing the HTTP request:

    import re from datetime import datetime from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Hello, Flask!" @app.route("/hello/<name>") def hello_there(name): now = datetime.now() formatted_now = now.strftime("%A, %d %B, %Y at %X") # Filter the name argument to letters only using regular expressions. URL arguments # can contain arbitrary text, so we restrict to safe characters only. match_object = re.match("[a-zA-Z]+", name) if match_object: clean_name = match_object.group(0) else: clean_name = "Friend" content = "Hello there, " + clean_name + "! It's " + formatted_now return content

    The decorator used for the new URL route, /hello/<name>, defines an endpoint /hello/ that can accept any additional value. The identifier inside < and > in the route defines a variable that is passed to the function and can be used in your code.

    URL routes are case-sensitive. For example, the route /hello/<name> is distinct from /Hello/<name>. If you want the same function to handle both, use decorators for each variant.

    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.)

  9. Set a breakpoint at the first line of code in the hello_there function (now = datetime.now()) by doing any one of the following:

    • With the cursor on that line, press F9, or,
    • With the cursor on that line, select the Run > Toggle Breakpoint menu command, or,
    • Click directly in the margin to the left of the line number (a faded red dot appears when hovering there).

    The breakpoint appears as a red dot in the left margin:

    Flask tutorial: a breakpoint set on the first line of the hello_there function

  10. Switch to the Run and Debug view in VS Code (using the left-side activity bar or ⇧⌘D (Windows, Linux Ctrl+Shift+D)). 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:

    Flask tutorial: initial view of the debug panel

  11. 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.

  12. 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.

    now.strftime("%A, %d %B, %Y at %X") 'Wednesday, 31 October, 2018 at 18:13:39'

    Tip: The Debug Console also shows exceptions from within the app that may not appear in the terminal. For example, if you see a "Paused on exception" message in the Call Stack area of Run and Debug view, switch to the Debug Console to see the exception message.

  13. Copy that line into the > prompt at the bottom of the debug console, and try changing the formatting:

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Hello, Flask</title> </head> <body> {%if name %} <strong>Hello there, {{ name }}!</strong> It's {{ date.strftime("%A, %d %B, %Y at %X") }}. {% else %} What's your name? Provide it after /hello/ in the URL. {% endif %} </body> </html>

    Tip: Flask developers often use the flask-babel extension for date formatting, rather than strftime, as flask-babel takes locales and timezones into consideration.

  14. In app.py, import Flask's render_template function near the top of the file:

    @app.route("/hello/") @app.route("/hello/<name>") def hello_there(name = None): return render_template( "hello_there.html", name=name, date=datetime.now() )

    You can see that the code is now much simpler, and concerned only with data values, because the markup and formatting is all contained in the template.

  15. Start the program (inside or outside of the debugger, using ⌃F5 (Windows, Linux Ctrl+F5)), navigate to a /hello/name URL, and observe the results.

  16. Also try navigating to a /hello/name URL using a name like <a%20value%20that%20could%20be%20HTML> 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.

Serve static files

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.

The second type are those that you want to address in code, such as when you want to implement an API endpoint that returns a static file. For this purpose, the Flask object contains a built-in method, send_static_file, which generates a response with a static file contained within the app's static folder.

The following sections demonstrate both types of static files.

Refer to static files in a template

  1. In the hello_flask folder, create a folder named static.

  2. Within the static folder, create a file named site.css with the following contents. After entering this code, also observe the syntax highlighting that VS Code provides for CSS files, including a color preview:

    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='site.css')}}" />

    Flask's url_for tag that is used here, creates the appropriate path to the file. Because it can accept variables as arguments, url_for allows you to programmatically control the generated path, if desired.

  3. Also in templates/hello_there.html, replace the contents <body> element with the following markup that uses the message style instead of a <strong> tag (and also displays a message if you just use a hello/ URL without a name):

    { "01": { "note": "This data is very simple because we're demonstrating only the mechanism." } }
  4. In app.py, add a function with the route /api/data that returns the static data file using the send_static_file method:

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='site.css')}}" /> </head> <body> <div class="navbar"> <a href="{{ url_for('home') }}" class="navbar-brand">Home</a> <a href="{{ url_for('about') }}" class="navbar-item">About</a> <a href="{{ url_for('contact') }}" class="navbar-item">Contact</a> </div> <div class="body-content"> {% block content %} {% endblock %} <hr/> <footer> <p>&copy; 2018</p> </footer> </div> </body> </html>
  5. 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.

    "Flask Tutorial: template extending layout.html": { "prefix": "flextlayout", "body": [ "{% extends \"layout.html\" %}", "{% block title %}", "$0", "{% endblock %}", "{% block content %}", "{% endblock %}" ], "description": "Boilerplate template that extends layout.html" },
  6. Save the html.json file (⌘S (Windows, Linux Ctrl+S)).

  7. Now, whenever you start typing the snippet's prefix, such as flext, VS Code provides the snippet as an autocomplete option, as shown in the next section. You can also use the Insert Snippet command to choose a snippet from a menu.

For more information on code snippets in general, refer to Creating snippets.

Use the code snippet to add pages

With the code snippet in place, you can quickly create templates for the Home, About, and Contact pages.

  1. In the templates folder, create a new file named home.html, Then start typing flext to see the snippet appear as a completion:

    Flask tutorial: autocompletion for the flextlayout code snippet

    When you select the completion, the snippet's code appears with the cursor on the snippet's insertion point:

    Flask tutorial: insertion of the flextlayout code snippet

  2. At the insertion point in the "title" block, write Home, and in the "content" block, write <p>Home page for the Visual Studio Code Flask tutorial.</p>, then save the file. These lines are the only unique parts of the extended page template:

  3. In the templates folder, create about.html, use the snippet to insert the boilerplate markup, insert About us and <p>About page for the Visual Studio Code Flask tutorial.</p> in the "title" and "content" blocks, respectively, then save the file.

  4. Repeat the previous step to create templates/contact.html using Contact us and <p>Contact page for the Visual Studio Code Flask tutorial.</p> in the two content blocks.

  5. In app.py, add functions for the /about/ and /contact/ routes that refer to their respective page templates. Also modify the home function to use the home.html template.

    from flask import Flask from flask import render_template from datetime import datetime from . import app @app.route("/") def home(): return render_template("home.html") @app.route("/about/") def about(): return render_template("about.html") @app.route("/contact/") def contact(): return render_template("contact.html") @app.route("/hello/") @app.route("/hello/<name>") def hello_there(name = None): return render_template( "hello_there.html", name=name, date=datetime.now() ) @app.route("/api/data") def get_data(): return app.send_static_file("data.json")
  6. In the hello_app folder, create a file __init__.py with the following contents:

    # Entry point for the application. from . import app # For application discovery by the 'flask' command. from . import views # For import side-effects of setting up routes.
  7. Open the debug configuration file launch.json and update the env property as follows to point to the startup object:

Từ khóa » Cài đặt Visual Studio Code Python