开始在 Windows 上将 Python 用于 Web 开发Get started using Python for web development on Windows

下面是有关通过适用于 Linux 的 Windows 子系统 (WSL),开始在 Windows 上使用 Python 进行 Web 开发的分步指南。The following is a step-by-step guide to get you started using Python for web development on Windows, using the Windows Subsystem for Linux (WSL).

设置开发环境Set up your development environment

建议在构建 Web 应用程序时在 WSL 上安装 Python。We recommend installing Python on WSL when building web applications. 有关 Python Web 开发的许多教程和说明是面向 Linux 用户编写的,并使用基于 Linux 的打包和安装工具。Many of the tutorials and instructions for Python web development are written for Linux users and use Linux-based packaging and installation tools. 大多数 Web 应用也部署在 Linux 上,因此这会确保开发环境与生产环境之间的一致性。Most web apps are also deployed on Linux, so this will ensure you have consistency between your development and production environments.

如果是将 Python 用于 Web 开发以外的其他工作,则建议使用 Microsoft Store 直接在 Windows 10 上安装 Python。If you are using Python for something other than web development, we recommend you install Python directly on Windows 10 using the Microsoft Store. WSL 不支持 GUI 桌面或应用程序(例如 PyGame、Gnome、KDE 等)。WSL does not support GUI desktops or applications (like PyGame, Gnome, KDE, etc). 对于这些情况,请直接在 Windows 上安装并使用 Python。Install and use Python directly on Windows for these cases. 如果不熟悉 Python,请参阅我们的指南:开始在 Windows 上使用 Python(初学者)If you're new to Python, see our guide: Get started using Python on Windows for beginners. 如果对在操作系统上自动执行常见任务感兴趣,请参阅我们的指南:开始在 Windows 上将 Python 用于脚本和自动化If you're interested in automating common tasks on your operating system, see our guide: Get started using Python on Windows for scripting and automation. 对于某些高级方案,可能需要考虑直接从 python.org 下载特定 Python 版本或考虑安装替代实现,如 Anaconda、Jython、PyPy、WinPython、IronPython 等。建议仅当你是更高级的 Python 程序员并且有特定原因需要选择替代实现时才使用此方法。For some advanced scenarios, you may want to consider downloading a specific Python release directly from python.org or consider installing an alternative, such as Anaconda, Jython, PyPy, WinPython, IronPython, etc. We only recommend this if you are a more advanced Python programmer with a specific reason for choosing an alternative implementation.

安装适用于 Linux 的 Windows 子系统Install Windows Subsystem for Linux

通过 WSL,可运行与 Windows 和你喜欢的工具(如 Visual Studio Code 和 Outlook 等)直接集成的 GNU/Linux 命令行环境。WSL lets you run a GNU/Linux command line environment integrated directly with Windows and your favorite tools, like Visual Studio Code, Outlook, etc.

要启用和安装 WSL(或 WSL 2,由你的需求而定),请按照 WSL 安装文档中的步骤操作。To enable and install WSL (or WSL 2 depending on your needs), follow the steps in the WSL install documentation. 这些步骤将包含选择 Linux 发行版(例如 Ubuntu)。These steps will include choosing a Linux distribution (for example, Ubuntu).

安装 WSL 和 Linux 发行版后,打开 Linux 发行版(可在 Windows 的开始菜单中找到),并使用命令 lsb_release -dc 查看版本和代码名称。Once you have installed WSL and a Linux distribution, open the Linux distribution (it can be found in your Windows start menu) and check the version and codename using the command: lsb_release -dc.

建议定期更新 Linux 发行版,包括在安装之后立即更新,以确保具有最新的包。We recommend updating your Linux distribution regularly, including immediately after you install, to ensure you have the most recent packages. Windows 不会自动处理此更新。Windows doesn't automatically handle this update. 要更新发行版,请使用命令:sudo apt update && sudo apt upgradeTo update your distribution, use the command: sudo apt update && sudo apt upgrade.

提示

请考虑从 Microsoft Store 安装新的 Windows 终端,从而启用多个选项卡(在多个 Linux 命令行、Windows 命令提示符、PowerShell 和 Azure CLI 等之间快速切换)、创建键绑定(用于打开或关闭选项卡、复制粘贴等的快捷方式键)、使用搜索功能,以及设置自定义主题(配色方案、字体样式和大小、背景图像/模糊/透明度)。Consider installing the new Windows Terminal from the Microsoft Store to enable multiple tabs (quickly switch between multiple Linux command lines, Windows Command Prompt, PowerShell, Azure CLI, etc), create custom key bindings (shortcut keys for opening or closing tabs, copy+paste, etc.), use the search feature, and set up custom themes (color schemes, font styles and sizes, background image/blur/transparency). 了解详细信息Learn more.

设置 Visual Studio CodeSet up Visual Studio Code

通过 VS Code 可利用 IntelliSenseLinting调试支持代码片段单元测试Take advantage of IntelliSense, Linting, Debug support, Code snippets, and Unit testing by using VS Code. VS Code 与适用于 Linux 的 Windows 子系统完美集成,可提供一个内置终端,用于在代码编辑器和命令行之间建立无缝工作流,此外还通过直接内置在 UI 中的常用 Git 命令(添加、提交、推送、拉取)支持 Git 进行版本控制VS Code integrates nicely with the Windows Subsystem for Linux, providing a built-in terminal to establish a seamless workflow between your code editor and your command line, in addition to supporting Git for version control with common Git commands (add, commit, push, pull) built right into the UI.

  1. 下载和安装适用于 Windows 的 VS CodeDownload and install VS Code for Windows. VS Code 也适用于 Linux,但适用于 Linux 的 Windows 子系统不支持 GUI 应用,因此需要在 Windows 上安装它。VS Code is also available for Linux, but Windows Subsystem for Linux does not support GUI apps, so we need to install it on Windows. 不必担心,仍可以使用 Remote - WSL 扩展与 Linux 命令行和工具集成。Not to worry, you'll still be able to integrate with your Linux command line and tools using the Remote - WSL Extension.

  2. 在 VS Code 上安装 Remote - WSL 扩展Install the Remote - WSL Extension on VS Code. 这使你可以将 WSL 用作集成开发环境,并且会为你处理兼容性和路径。This allows you to use WSL as your integrated development environment and will handle compatibility and pathing for you. 了解详细信息Learn more.

重要

如果已安装 VS Code,则需要确保具有 1.35 5 月版本或更高版本,以便安装 Remote - WSL 扩展If you already have VS Code installed, you need to ensure that you have the 1.35 May release or later in order to install the Remote - WSL Extension. 建议不要在没有 Remote - WSL 扩展的情况下在 VS Code 中使用 WSL,因为会失去对自动完成、调试、linting 等的支持。趣味事实:此 WSL 扩展安装在 $HOME/.vscode-server/extensions 中。We do not recommend using WSL in VS Code without the Remote-WSL extension as you will lose support for auto-complete, debugging, linting, etc. Fun fact: This WSL extension is installed in $HOME/.vscode-server/extensions.

创建新项目Create a new project

让我们在 Linux (Ubuntu) 文件系统上创建一个新项目目录,我们随后会使用 VS Code 处理 Linux 应用和工具。Let's create a new project directory on our Linux (Ubuntu) file system that we will then work on with Linux apps and tools using VS Code.

  1. 关闭 VS Code,然后转到“开始”菜单(左下方 Windows 图标)并输入以下内容,以便打开 Ubuntu 18.04(WSL 命令行):“Ubuntu 18.04”。Close VS Code and open Ubuntu 18.04 (your WSL command line) by going to your Start menu (lower left Windows icon) and typing: "Ubuntu 18.04".

  2. 在 Ubuntu 命令行中,导航到要在其中放置项目的位置,并为项目创建目录:mkdir HelloWorldIn your Ubuntu command line, navigate to where you want to put your project, and create a directory for it: mkdir HelloWorld.

Ubuntu 终端

提示

使用适用于 Linux 的 Windows 子系统 (WSL) 时要记住的一个重要事项是,现在是在两个不同文件系统之间工作:1) Windows 文件系统,以及 2) Linux 文件系统 (WSL)(对于我们的示例为 Ubuntu)。An important thing to remember when using Windows Subsystem for Linux (WSL) is that you are now working between two different file systems: 1) your Windows file system, and 2) your Linux file system (WSL), which is Ubuntu for our example. 需要注意安装包和存储文件的位置。You will need to pay attention to where you install packages and store files. 可以在 Windows 文件系统中安装一个版本的工具或包,并在 Linux 文件系统中安装完全不同的版本。You can install one version of a tool or package in the Windows file system and a completely different version in the Linux file system. 在 Windows 文件系统中更新工具不会影响 Linux 文件系统中的工具,反之亦然。Updating the tool in the Windows file system will have no effect on the tool in the Linux file system, and vice-versa. WSL 会将固定驱动器装载到计算机上 Linux 发行版本中的 /mnt/<drive> 文件夹下。WSL mounts the fixed drives on your computer under the /mnt/<drive> folder in your Linux distribution. 例如,Windows C: 驱动器装载在 /mnt/c/ 下。For example, your Windows C: drive is mounted under /mnt/c/. 可以从 Ubuntu 终端访问 Windows 文件,并对这些文件使用 Linux 应用和工具,反之亦然。You can access your Windows files from the Ubuntu terminal and use Linux apps and tools on those files and vice-versa. 考虑到许多 Web 工具最初是针对 Linux 所编写的,并部署在 Linux 生产环境中,因此建议在 Linux 文件系统中进行 Python Web 开发。We recommend working in the Linux file system for Python web development given that much of the web tooling is originally written for Linux and deployed in a Linux production environment. 这还可避免混合文件系统语义(如 Windows 在文件名方面不区分大小写)。It also avoids mixing file system semantics (like Windows being case-insensitive regarding file names). 也就是说,WSL 现在支持在 Linux 与 Windows 文件系统之间跳转,因此可以将文件托管在其中一个系统上。That said, WSL now supports jumping between the Linux and Windows files systems, so you can host your files on either one. 了解详细信息Learn more.

安装 Python、pip 和 venvInstall Python, pip, and venv

Ubuntu 18.04 LTS 已安装了 Python 3.6,但不附带你可能期望随其他 Python 安装一起获得的某些模块。Ubuntu 18.04 LTS comes with Python 3.6 already installed, but it does not come with some of the modules that you may expect to get with other Python installations. 我们仍需要安装 pip、Python 的标准包管理器和 venv(用于创建和管理轻型虚拟环境的标准模块)。We will still need to install pip, the standard package manager for Python, and venv, the standard module used to create and manage lightweight virtual environments.

  1. 打开 Ubuntu 终端并输入 python3 --version,以便确认已安装了 Python3。Confirm that Python3 is already installed by opening your Ubuntu terminal and entering: python3 --version. 这应该返回 Python 版本号。This should return your Python version number. 如果需要更新 Python 版本,请先通过输入以下内容来更新 Ubuntu 版本:sudo apt update && sudo apt upgrade,然后使用 sudo apt upgrade python3 更新 Python。If you need to update your version of Python, first update your Ubuntu version by entering: sudo apt update && sudo apt upgrade, then update Python using sudo apt upgrade python3.

  2. 通过输入以下内容来安装 pip:sudo apt install python3-pipInstall pip by entering: sudo apt install python3-pip. 通过 pip 可以安装和管理不属于 Python 标准库的其他包。Pip allows you to install and manage additional packages that are not part of the Python standard library.

  3. 通过输入以下内容来安装 venv:sudo apt install python3-venvInstall venv by entering: sudo apt install python3-venv.

创建虚拟环境Create a virtual environment

对于 Python 开发项目,使用虚拟环境是推荐最佳做法。Using virtual environments is a recommended best practice for Python development projects. 通过创建虚拟环境,可以将项目工具隔离开来,避免与其他项目的工具发生版本冲突。By creating a virtual environment, you can isolate your project tools and avoid versioning conflicts with tools for your other projects. 例如,你可能在维护一个需要 Django 1.2 Web 框架的旧 Web 项目,但随后会进行一个使用 Django 2.2 的令人兴奋的新项目。For example, you may be maintaining an an older web project that requires the Django 1.2 web framework, but then an exciting new project comes along using Django 2.2. 如果在虚拟环境外部全局更新 Django,则以后可能会遇到一些版本控制问题。If you update Django globally, outside of a virtual environment, you could run into some versioning issues later on. 除了防止意外的版本冲突以外,虚拟环境允许在没有管理权限的情况下安装和管理包。In addition to preventing accidental versioning conflicts, virtual environments let you install and manage packages without administrative privileges.

  1. 打开终端,在 HelloWorld 项目文件夹中,使用以下命令创建名为 .venv 的虚拟环境:python3 -m venv .venvOpen your terminal and, inside your HelloWorld project folder, use the following command to create a virtual environment named .venv: python3 -m venv .venv.

  2. 若要激活虚拟环境,请输入:source .venv/bin/activateTo activate the virtual environment, enter: source .venv/bin/activate. 如果它已正常工作,则应该在命令提示符之前看到 (.venv)。If it worked, you should see (.venv) before the command prompt. 现在已准备好了一个可用于编写代码和安装包的独立环境。You now have a self-contained environment ready for writing code and installing packages. 使用完虚拟环境后,输入以下命令可停用它:deactivateWhen you're finished with your virtual environment, enter the following command to deactivate it: deactivate.

    创建虚拟环境

提示

建议在计划处理项目的目录中创建虚拟环境。We recommend creating the virtual environment inside the directory in which you plan to have your project. 由于每个项目都应具有自己的单独目录,这样各自具有自己的虚拟环境,因此无需唯一命名。Since each project should have it's own separate directory, each will have it's own virtual environment, so there is not a need for unique naming. 建议使用名称 .venv 以遵循 Python 约定。Our suggestion is to use the name .venv to follow the Python convention. 如果安装在项目目录中,则某些工具(如 pipenv)也会默认为此名称。Some tools (like pipenv) also default to this name if you install into your project directory. 你不会希望使用 .env,因为这会与环境变量定义文件冲突。You don't want to use .env as that conflicts with environment variable definition files. 通常不推荐使用非点开头的名称,因为不需要 ls 经常提醒目录已存在。We generally do not recommend non-dot-leading names, as you don't need ls constantly reminding you that the directory exists. 还建议将 .venv 添加到 .gitignore 文件。We also recommend adding .venv to your .gitignore file. (此处是GitHub 用于 Python 的默认 gitignore 模板,可供参考。)有关在 VS Code 中使用虚拟环境的更多信息,请参阅在 VS Code中使用 Python 环境(Here is GitHub's default gitignore template for Python for reference.) For more information about working with virtual environments in VS Code, see Using Python environments in VS Code.

打开 WSL - Remote 窗口Open a WSL - Remote window

VS Code 使用 Remote - WSL 扩展(之前已安装)将 Linux 子系统视为远程服务器。VS Code uses the Remote - WSL Extension (installed previously) to treat your Linux subsystem as a remote server. 这使你可以使用 WSL 作为集成开发环境。This allows you to use WSL as your integrated development environment. 了解详细信息Learn more.

  1. 通过输入以下内容从 Ubuntu 终端在 VS Code 中打开项目文件夹:code .(“.”告知 VS Code 打开当前文件夹)。Open your project folder in VS Code from your Ubuntu terminal by entering: code . (the "." tells VS Code to open the current folder).

  2. 一个安全警报会从 Windows Defender 弹出,选择“允许访问”。A Security Alert will pop-up from Windows Defender, select "Allow access". VS Code 打开后,你应该在左下角看到远程连接主机指示器,让你知道正在“WSL:Ubuntu-18.04”上进行编辑。Once VS Code opens, you should see the Remote Connection Host indicator, in the bottom-left corner, letting you know that you are editing on WSL: Ubuntu-18.04.

    VS Code 远程连接主机指示器

  3. 关闭 Ubuntu 终端。Close your Ubuntu terminal. 接下来会使用集成到 VS Code 中的 WSL 终端。Moving forward we will use the WSL terminal integrated into VS Code.

  4. 通过按 Ctrl+'(使用反撇号字符)或选择“视图” > “终端”,在 VS Code 中打开 WSL 终端。Open the WSL terminal in VS Code by pressing Ctrl+` (using the backtick character) or selecting View > Terminal. 这会打开一个指向在 Ubuntu 终端中创建的项目文件夹路径的 bash (WSL) 命令行。This will open a bash (WSL) command-line opened to the project folder path that you created in your Ubuntu terminal.

    带有 WSL 终端的 VS Code

安装 Microsoft Python 扩展Install the Microsoft Python extension

需要安装 Remote - WSL 的所有 VS Code 扩展。You will need to install any VS Code extensions for your Remote - WSL. 已在 VS Code 上本地安装的扩展不会自动可用。Extensions already installed locally on VS Code will not automatically be available. 了解详细信息Learn more.

  1. 通过输入 Ctrl+Shift+X 来打开 VS Code 扩展窗口(或使用菜单导航到“视图” > “扩展”)。Open the VS Code Extensions window by entering Ctrl+Shift+X (or use the menu to navigate to View > Extensions).

  2. 在顶部的“在应用商店中搜索扩展”框中,输入:Python。In the top Search Extensions in Marketplace box, enter: Python.

  3. 找到“Python (ms-python.python) by Microsoft”扩展,然后选择绿色的“安装”按钮。Find the Python (ms-python.python) by Microsoft extension and select the green Install button.

  4. 扩展安装完成后,需要选择蓝色的“需要重新加载”按钮。Once the extension is finished installing, you will need to select the blue Reload Required button. 这会重新加载 VS Code 并在 VS Code 扩展窗口(其中显示已安装 Python 扩展)中显示“WSL:UBUNTU-18.04 - 已安装”部分。This will reload VS Code and display a WSL: UBUNTU-18.04 - Installed section in your VS Code Extensions window showing that you've installed the Python extension.

运行一个简单 Python 程序Run a simple Python program

Python 是一种解释型语言,支持不同类型的解释器(Python2、Anaconda、PyPy 等)。Python is an interpreted language and supports different types of interpretors (Python2, Anaconda, PyPy, etc). VS Code 应默认为与项目关联的解释器。VS Code should default to the interpreter associated with your project. 如果有理由需要更改解释器,请选择当前显示在 VS Code 窗口底部蓝色栏中的解释器,或打开“命令面板”(Ctrl+Shift+P),然后输入命令“Python:选择解释器”。If you have a reason to change it, select the interpreter currently displayed in blue bar on the bottom of your VS Code window or open the Command Palette (Ctrl+Shift+P) and enter the command Python: Select Interpreter. 这会显示当前已安装的 Python 解释器列表。This will display a list of the Python interpreters that you currently have installed. 详细了解如何配置 Python 环境Learn more about configuring Python environments.

我们来创建并运行一个简单 Python 程序作为测试,并确保已选择正确的 Python 解释器。Let's create and run a simple Python program as a test and ensure that we have the correct Python interpreter selected.

  1. 通过输入 Ctrl+Shift+E 来打开 VS Code 文件资源管理器窗口(或使用菜单导航到“视图” > “资源管理器”)。Open the VS Code File Explorer window by entering Ctrl+Shift+E (or use the menu to navigate to View > Explorer).

  2. 如果集成 WSL 终端尚未打开,请通过输入 Ctrl+Shift+' 来打开它,并确保选择 HelloWorld python 项目文件夹。If it's not already open, open your integrated WSL terminal by entering Ctrl+Shift+` and ensure that your HelloWorld python project folder is selected.

  3. 通过输入以下内容来创建一个 python 文件:touch test.pyCreate a python file by entering: touch test.py. 你应看到刚才创建的文件出现在资源管理器窗口中的 .venv 和 .vscode 文件夹(已在项目目录中)下。You should see the file you just created appear in your Explorer window under the .venv and .vscode folders already in your project directory.

  4. 选择刚才在资源管理器窗口中创建的 test.py 文件以在 VS Code 中打开它。Select the test.py file that you just created in your Explorer window to open it in VS Code. 由于文件名中的 .py 向 VS Code 告知这是 Python 文件,因此之前加载的 Python 扩展会自动选择并加载 Python 解释器(会显示在 VS Code 窗口底部)。Because the .py in our file name tells VS Code that this is a Python file, the Python extension you loaded previously will automatically choose and load a Python interpreter that you will see displayed on the bottom of your VS Code window.

    在 VS Code 中选择 Python 解释器

  5. 将此 Python 代码粘贴到 test.py 文件中,然后保存该文件 (Ctrl+S):Paste this Python code into your test.py file and then save the file (Ctrl+S):

    print("Hello World")
    
  6. 若要运行刚才创建的 Python“Hello World”程序,请在 VS Code 资源管理器窗口中选择“test.py”文件,然后右键单击该文件以显示选项菜单。To run the Python "Hello World" program that we just created, select the test.py file in the VS Code Explorer window, then right-click the file to display a menu of options. 选择“在终端中运行 Python 文件”。Select Run Python File in Terminal. 或者,在集成 WSL 终端窗口中,输入 python test.py 以运行“Hello World”程序。Alternatively, in your integrated WSL terminal window, enter: python test.py to run your "Hello World" program. Python 解释器会在终端窗口中打印“Hello World”。The Python interpreter will print "Hello World" in your terminal window.

祝贺你。Congratulations. 已全部设置好,可创建和运行 Python 程序!You're all set up to create and run Python programs! 现在,我们来尝试使用最受欢迎的 Python Web 框架中的两个创建 Hello World 应用:Flask 和 Django。Now let's try creating a Hello World app with two of the most popular Python web frameworks: Flask and Django.

适用于 Flask 的 Hello World 教程Hello World tutorial for Flask

Flask 是一种适用于 Python 的 Web 应用程序框架。Flask is a web application framework for Python. 在此简要教程中,会使用 VS Code 和 WSL 创建一个小型“Hello World”Flask 应用。In this brief tutorial, you'll create a small "Hello World" Flask app using VS Code and WSL.

  1. 转到“开始”菜单(左下方 Windows 图标)并输入以下内容,以便打开 Ubuntu 18.04(WSL 命令行):“Ubuntu 18.04”。Open Ubuntu 18.04 (your WSL command line) by going to your Start menu (lower left Windows icon) and typing: "Ubuntu 18.04".

  2. 为项目创建目录:mkdir HelloWorld-Flask,然后执行 cd HelloWorld-Flask 以进入该目录。Create a directory for your project: mkdir HelloWorld-Flask, then cd HelloWorld-Flask to enter the directory.

  3. 创建虚拟环境以安装项目工具:python3 -m venv .venvCreate a virtual environment to install your project tools: python3 -m venv .venv

  4. 通过输入以下命令,在 VS Code 中打开 HelloWorld-Flask 项目:code .Open your HelloWorld-Flask project in VS Code by entering the command: code .

  5. 在 VS Code 中打开集成 WSL 终端(也称为 Bash),具体方法是输入 Ctrl+Shift+'(应已选择 HelloWorld-Flask 项目文件夹)。Inside VS Code, open your integrated WSL terminal (aka Bash) by entering Ctrl+Shift+` (your HelloWorld-Flask project folder should already be selected). 关闭 Ubuntu 命令行,因为我们接下来会在与 VS Code 集成的 WSL 终端中工作。Close your Ubuntu command line as we will be working in the WSL terminal integrated with VS Code moving forward.

  6. 在 VS Code 中使用 Bash 终端激活在步骤 #3 中创建的虚拟环境:source .venv/bin/activateActivate the virtual environment that you created in step #3 using your Bash terminal in VS Code: source .venv/bin/activate. 如果它已正常工作,则应该在命令提示符之前看到 (.venv)。If it worked, you should see (.venv) before the command prompt.

  7. 通过输入以下内容,在虚拟环境中安装 Flask:python3 -m pip install flaskInstall Flask in the virtual environment by entering: python3 -m pip install flask. 通过输入以下内容来验证它是否已安装:python3 -m flask --versionVerify that it's installed by entering: python3 -m flask --version.

  8. 为 Python 代码创建新文件:touch app.pyCreate a new file for your Python code: touch app.py

  9. 在 VS Code 的文件资源管理器中打开 app.py 文件(Ctrl+Shift+E,然后选择 app.py 文件)。Open your app.py file in VS Code's File Explorer (Ctrl+Shift+E, then select your app.py file). 这会激活 Python 扩展以选择解释器。This will activate the Python Extension to choose an interpreter. 它应默认为“Python 3.6.8 64 位('.venv': venv)”。It should default to Python 3.6.8 64-bit ('.venv': venv). 请注意,它还会检测到虚拟环境。Notice that it also detected your virtual environment.

    激活虚拟环境

  10. 在 app.py 中,添加代码以导入 Flask 并创建 Flask 对象的实例:In app.py, add code to import Flask and create an instance of the Flask object:

    from flask import Flask
    app = Flask(__name__)
    
  11. 此外在 app.py 中,添加一个返回内容(在本例中为简单字符串)的函数。Also in app.py, add a function that returns content, in this case a simple string. 使用 Flask 的 app.route 修饰器将 URL 路由“/”映射到该函数:Use Flask's app.route decorator to map the URL route "/" to that function:

    @app.route("/")
    def home():
        return "Hello World! I'm using Flask."
    

    提示

    可以根据映射到相同函数的不同路由的数量,对相同函数使用多个修饰器(每行一个)。You can use multiple decorators on the same function, one per line, depending on how many different routes you want to map to the same function.

  12. 保存 app.py 文件 (Ctrl+S)。Save the app.py file (Ctrl+S).

  13. 在终端中,输入以下命令来运行应用:In the terminal, run the app by entering the following command:

    python3 -m flask run
    

    这会运行 Flask 开发服务器。This runs the Flask development server. 默认情况下,开发服务器会查找 app.py。The development server looks for app.py by default. 运行 Flask 时,应看到类似于以下内容的输出:When you run Flask, you should see output similar to the following:

    (env) user@USER:/mnt/c/Projects/HelloWorld$ python3 -m flask run
     * Environment: production
       WARNING: This is a development server. Do not use it in a production deployment.
       Use a production WSGI server instead.
     * Debug mode: off
     * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
    
  14. 打开默认 Web 浏览器到呈现的页面,在终端中 Ctrl+单击 http://127.0.0.1:5000/ URL。Open your default web browser to the rendered page, Ctrl+Click the http://127.0.0.1:5000/ URL in the terminal. 应在浏览器中看到以下消息:You should see the following message in your browser:

    Hello, Flask!

  15. 请注意,在访问类似于“/”的 URL 时,调试终端中会出现一个消息,其中显示 HTTP 请求:Observe that when you visit a URL like "/", a message appears in the debug terminal showing the HTTP request:

    127.0.0.1 - - [19/Jun/2019 13:36:56] "GET / HTTP/1.1" 200 -
    
  16. 在终端中使用 Ctrl+C 停止应用。Stop the app by using Ctrl+C in the terminal.

提示

如果要使用与 app.py 不同的文件名(如 program.py),请定义名为 FLASK_APP 的环境变量,并将其值设置为所选文件。If you want to use a different filename than app.py, such as program.py, define an environment variable named FLASK_APP and set its value to your chosen file. Flask 的开发服务器随后会使用 FLASK_APP 的值而不是默认文件 app.py。Flask's development server then uses the value of FLASK_APP instead of the default file app.py. 有关更多信息,请参阅 Flask 的命令行界面文档For more information, see Flask's Command Line Interface documentation.

恭喜,你已使用 Visual Studio Code 和适用于 Linux 的 Windows 子系统创建了一个 Flask Web 应用程序!Congratulations, you've created a Flask web application using Visual Studio Code and Windows Subsystem for Linux! 有关使用 VS Code 和 Flask 的更深入教程,请参阅 Visual Studio Code中的 Flask 教程For a more in-depth tutorial using VS Code and Flask, see Flask Tutorial in Visual Studio Code.

适用于 Django 的 Hello World 教程Hello World tutorial for Django

Django 是一种适用于 Python 的 Web 应用程序框架。Django is a web application framework for Python. 在此简要教程中,会使用 VS Code 和 WSL 创建一个小型“Hello World”Django 应用。In this brief tutorial, you'll create a small "Hello World" Django app using VS Code and WSL.

  1. 转到“开始”菜单(左下方 Windows 图标)并输入以下内容,以便打开 Ubuntu 18.04(WSL 命令行):“Ubuntu 18.04”。Open Ubuntu 18.04 (your WSL command line) by going to your Start menu (lower left Windows icon) and typing: "Ubuntu 18.04".

  2. 为项目创建目录:mkdir HelloWorld-Django,然后执行 cd HelloWorld-Django 以进入该目录。Create a directory for your project: mkdir HelloWorld-Django, then cd HelloWorld-Django to enter the directory.

  3. 创建虚拟环境以安装项目工具:python3 -m venv .venvCreate a virtual environment to install your project tools: python3 -m venv .venv

  4. 通过输入以下命令,在 VS Code 中打开 HelloWorld-DJango 项目:code .Open your HelloWorld-DJango project in VS Code by entering the command: code .

  5. 在 VS Code 中打开集成 WSL 终端(也称为 Bash),具体方法是输入 Ctrl+Shift+'(应已选择 HelloWorld-Django 项目文件夹)。Inside VS Code, open your integrated WSL terminal (aka Bash) by entering Ctrl+Shift+` (your HelloWorld-Django project folder should already be selected). 关闭 Ubuntu 命令行,因为我们接下来会在与 VS Code 集成的 WSL 终端中工作。Close your Ubuntu command line as we will be working in the WSL terminal integrated with VS Code moving forward.

  6. 在 VS Code 中使用 Bash 终端激活在步骤 #3 中创建的虚拟环境:source .venv/bin/activateActivate the virtual environment that you created in step #3 using your Bash terminal in VS Code: source .venv/bin/activate. 如果它已正常工作,则应该在命令提示符之前看到 (.venv)。If it worked, you should see (.venv) before the command prompt.

  7. 使用以下在虚拟环境中安装 Django:python3 -m pip install djangoInstall Django in the virtual environment with the command: python3 -m pip install django. 通过输入以下内容来验证它是否已安装:python3 -m django --versionVerify that it's installed by entering: python3 -m django --version.

  8. 接下来,运行以下命令来创建 Django 项目:Next, run the following command to create the Django project:

    django-admin startproject web_project .
    

    startproject 命令假设(通过在末尾使用 .)当前文件夹是项目文件夹,并在其中创建以下内容:The startproject command assumes (by use of . at the end) that the current folder is your project folder, and creates the following within it:

    • manage.py:项目的 Django 命令行管理实用工具。manage.py: The Django command-line administrative utility for the project. 使用 python manage.py <command> [options] 为项目运行管理命令。You run administrative commands for the project using python manage.py <command> [options].

    • 一个名为 web_project 的子文件夹,其中包含以下文件:A subfolder named web_project, which contains the following files:

      • __init__.py:一个空文件,向 Python 告知此文件夹是 Python 包。__init__.py: an empty file that tells Python that this folder is a Python package.
      • wsgi.py:供与 WSGI 兼容的 Web 服务器为项目提供服务的入口点。wsgi.py: an entry point for WSGI-compatible web servers to serve your project. 通常将此文件原样保留,因为它为生产 Web 服务器提供挂钩。You typically leave this file as-is as it provides the hooks for production web servers.
      • settings.py:包含 Django 项目的设置,可以在开发 Web 应用的过程中进行修改。settings.py: contains settings for Django project, which you modify in the course of developing a web app.
      • urls.py:包含 Django 项目的目录,也可以在开发过程中进行修改。urls.py: contains a table of contents for the Django project, which you also modify in the course of development.
  9. 若要验证 Django 项目,请使用命令 python3 manage.py runserver 启动 Django 的开发服务器。To verify the Django project, start Django's development server using the command python3 manage.py runserver. 服务器在默认端口 8000 上运行,应会在终端窗口中看到类似于以下输出的输出:The server runs on the default port 8000, and you should see output like the following output in the terminal window:

    Performing system checks...
    
    System check identified no issues (0 silenced).
    
    June 20, 2019 - 22:57:59
    Django version 2.2.2, using settings 'web_project.settings'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
    

    首次运行服务器时,它会在文件 db.sqlite3 中创建默认 SQLite 数据库,该数据库旨在用于开发,但是可以在生产中用于低容量 Web 应用。When you run the server the first time, it creates a default SQLite database in the file db.sqlite3, which is intended for development purposes, but can be used in production for low-volume web apps. 此外,Django 的内置 Web 服务器旨在仅用于本地开发。Also, Django's built-in web server is intended only for local development purposes. 但是在部署到 Web 主机时,Django 会改用主机的 Web 服务器。When you deploy to a web host, however, Django uses the host's web server instead. Django 项目中的 wsgi.py 模块负责挂钩到生产服务器。The wsgi.py module in the Django project takes care of hooking into the production servers.

    如果要使用与默认值 8000 不同的端口,请在命令行中指定端口号,如 python3 manage.py runserver 5000If you want to use a different port than the default 8000, specify the port number on the command line, such as python3 manage.py runserver 5000.

  10. 在终端输出窗口中 Ctrl+click``http://127.0.0.1:8000/ URL,以将默认浏览器打开到该地址。Ctrl+click the http://127.0.0.1:8000/ URL in the terminal output window to open your default browser to that address. 如果 Django 安装正确且项目有效,则会看到默认页面。If Django is installed correctly and the project is valid, you'll see a default page. VS Code 终端输出窗口还会显示服务器日志。The VS Code terminal output window also shows the server log.

  11. 完成后,关闭浏览器窗口,并按照终端输出窗口中的指示使用 Ctrl+C 在 VS Code 中停止服务器。When you're done, close the browser window and stop the server in VS Code using Ctrl+C as indicated in the terminal output window.

  12. 现在,若要创建 Django 应用,请在项目文件夹(manage.py 驻留的位置)中运行管理实用工具的 startapp 命令:Now, to create a Django app, run the administrative utility's startapp command in your project folder (where manage.py resides):

    python3 manage.py startapp hello
    

    该命令会创建名为 hello 的文件夹,其中包含一些代码文件和一个子文件夹。The command creates a folder called hello that contains a number of code files and one subfolder. 在这些文件下,会经常使用 views.py (包含用于定义 Web 应用中的页面的函数)和 models.py(包含用于定义数据对象的类)。Of these, you frequently work with views.py (that contains the functions that define pages in your web app) and models.py (that contains classes defining your data objects). migrations 文件夹由 Django 的管理实用工具用于管理数据库版本,如本教程后面部分所述。The migrations folder is used by Django's administrative utility to manage database versions as discussed later in this tutorial. 还有文件 apps.py(应用配置)、admin.py(用于创建管理界面)和 tests.py (用于测试)未在此处进行介绍。There are also the files apps.py (app configuration), admin.py (for creating an administrative interface), and tests.py (for tests), which are not covered here.

  13. 修改 hello/views.py 以匹配以下代码,这会为应用的主页创建单个视图:Modify hello/views.py to match the following code, which creates a single view for the app's home page:

    from django.http import HttpResponse
    
    def home(request):
        return HttpResponse("Hello, Django!")
    
  14. 使用以下内容创建文件 hello/urls.pyCreate a file, hello/urls.py, with the contents below. urls.py 文件用于指定模式,以将不同 URL 路由到相应的视图。The urls.py file is where you specify patterns to route different URLs to their appropriate views. 下面的代码包含一个路由,用于将应用的根 URL("")映射到刚才添加到 hello/views.pyviews.home 函数:The code below contains one route to map root URL of the app ("") to the views.home function that you just added to hello/views.py:

    from django.urls import path
    from hello import views
    
    urlpatterns = [
        path("", views.home, name="home"),
    ]
    
  15. web_project 文件夹还包含 urls.py 文件,该文件是实际处理 URL 路由的位置。The web_project folder also contains a urls.py file, which is where URL routing is actually handled. 打开 web_project/urls.py 并进行修改以匹配以下代码(如果需要,可以保留指导注释)。Open web_project/urls.py and modify it to match the following code (you can retain the instructive comments if you like). 此代码使用 django.urls.include 拉取应用的 hello/urls.py(这会使应用的路由包含在应用中)。This code pulls in the app's hello/urls.py using django.urls.include, which keeps the app's routes contained within the app. 当项目包含多个应用时,此分隔会非常有用。This separation is helpful when a project contains multiple apps.

    from django.contrib import admin
    from django.urls import include, path
    
    urlpatterns = [
        path("", include("hello.urls")),
    ]
    
  16. 保存所有已修改的文件。Save all modified files.

  17. 在 VS Code 终端中,使用 python3 manage.py runserver 运行开发服务器,并打开浏览器到 http://127.0.0.1:8000/ 以查看呈现“Hello, Django”的页面。In the VS Code Terminal, run the development server with python3 manage.py runserver and open a browser to http://127.0.0.1:8000/ to see a page that renders "Hello, Django".

恭喜,你已使用 VS Code 和适用于 Linux 的 Windows 子系统创建了一个 Django Web 应用程序!Congratulations, you've created a Django web application using VS Code and Windows Subsystem for Linux! 有关使用 VS Code 和 Django 的更深入教程,请参阅 Visual Studio Code中的 Django 教程For a more in-depth tutorial using VS Code and Django, see Django Tutorial in Visual Studio Code.

其他资源Additional resources