visual studio 2019 python web_快速入门:使用 Visual Studio 创建 Python Web 应用 | Microsoft Docs...

快速入门:使用 Visual Studio 创建第一个 Python Web 应用Quickstart: Create your first Python web app using Visual Studio

03/07/2019

JoshuaPartlow.png?size=32

olprod.png?size=32

本文内容

在 5-10 分钟介绍“用作 Python IDE 的 Visual Studio”的简介中,你将基于 Flask 框架创建一个简单的 Python Web 应用程序。In this 5-10 minute introduction to Visual Studio as a Python IDE, you create a simple Python web application based on the Flask framework. 你将通过介绍 Visual Studio 基本功能的单独步骤创建项目。You create the project through discrete steps that help you learn about Visual Studio's basic features.

如果尚未安装 Visual Studio,请转到 Visual Studio 下载页免费安装。If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free. 在安装程序中,请确保选择“Python 开发”工作负荷 。In the installer, make sure to select the Python development workload.

如果尚未安装 Visual Studio,请转到 Visual Studio 下载页免费安装。If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free. 在安装程序中,请确保选择“Python 开发”工作负荷 。In the installer, make sure to select the Python development workload.

创建项目Create the project

以下步骤创建一个作为应用程序容器的空项目:The following steps create an empty project that serves as a container for the application:

打开 Visual Studio 2017。Open Visual Studio 2017.

从顶部菜单栏中选择“文件”>“新建”>“项目” 。From the top menu bar, choose File > New > Project.

在“新建项目”对话框右上角的搜索字段中输入“Python Web 项目”,在中间的列表中选择“Web 项目”,为项目命名(如“HelloPython”),然后选择“确定” 。In the New Project dialog box, enter "Python Web Project" in the search field on the upper right, choose Web project in the middle list, give the project a name like "HelloPython", then choose OK.

quickstart-python-00-web-project.png?view=vs-2017

如果找不到 Python 项目模板,请运行 Visual Studio 安装程序,选择“更多”>“修改”,选择“Python 开发”工作负载,然后选择“修改” 。If you don't see the Python project templates, run the Visual Studio Installer, select More > Modify, select the Python development workload, then choose Modify.

installation-python-workload.png?view=vs-2017

新项目在“解决方案资源管理器” 的右窗格中打开。The new project opens in Solution Explorer in the right pane. 项目此时已为空,因为它不含其他文件。The project is empty at this point because it contains no other files.

quickstart-python-01-empty-project.png?view=vs-2017

打开 Visual Studio 2019。Open Visual Studio 2019.

在开始屏幕上,选择“创建新项目” 。On the start screen, select Create a new project.

在“创建新项目”对话框中,在顶部的搜索字段中输入“Python web”,在中间列表中选择“Web 项目”,然后选择“下一步” :In the Create a new project dialog box, enter "Python web" in the search field at the top, choose Web Project in the middle list, then select Next:

quickstart-python-00-web-project-2019a.png?view=vs-2017

如果找不到 Python 项目模板,请运行 Visual Studio 安装程序,选择“更多”>“修改”,选择“Python 开发”工作负载,然后选择“修改” 。If you don't see the Python project templates, run the Visual Studio Installer, select More > Modify, select the Python development workload, then choose Modify.

installation-python-workload.png?view=vs-2017

在接下来的“配置新项目”对话框中,输入“HelloPython”作为项目名称,指定一个位置,然后选择“创建” 。In the Configure your new project dialog that follows, enter "HelloPython" for Project name, specify a location, and select Create. (解决方案名称自动设置为匹配项目名称。 )(The Solution name is automatically set to match the Project name.)

quickstart-python-00-web-project-2019b.png?view=vs-2017

新项目在“解决方案资源管理器” 的右窗格中打开。The new project opens in Solution Explorer in the right pane. 项目此时已为空,因为它不含其他文件。The project is empty at this point because it contains no other files.

quickstart-python-01-empty-project-2019.png?view=vs-2017

问:在 Visual Studio 中为 Python 应用程序创建项目有何优势?Question: What's the advantage of creating a project in Visual Studio for a Python application?

答:通常只使用文件夹和文件定义 Python 应用程序,但如果程序变大,可能涉及到自动生成的文件和适用于 Web 应用程序的 JavaScript 等,这种简单的结构就变得很繁琐。Answer: Python applications are typically defined using only folders and files, but this simple structure can become burdensome as applications become larger and perhaps involve auto-generated files, JavaScript for web applications, and so on. Visual Studio 项目帮助管理复杂性问题。A Visual Studio project helps manage this complexity. 该项目( .pyproj 文件)标识与项目关联的所有源文件和内容文件,包含每个文件的生成信息,维护这些信息并与源代码管理系统集成,并帮助你将应用程序组织为逻辑组件。The project (a .pyproj file) identifies all the source and content files associated with your project, contains build information for each file, maintains the information to integrate with source-control systems, and helps you organize your application into logical components.

问:解决方案资源管理器中显示的“解决方案”是指什么?Question: What is the "solution" shown in Solution Explorer?

答:Visual Studio 解决方案是一个容器,可帮助你将一个或多个相关项目作为一个组进行管理,并存储不特定于项目的配置设置。Answer: A Visual Studio solution is a container that helps you manage for one or more related projects as a group, and stores configuration settings that aren't specific to a project. 解决方案中的项目还可相互引用,例如运行一个项目(Python 项目)会再自动生成一个项目(例如 Python 应用中使用的 C++ 扩展)。Projects in a solution can also reference one another, such that running one project (a Python app) automatically builds a second project (such as a C++ extension used in the Python app).

安装 Flask 库Install the Flask library

Python 中的 Web 应用几乎总是使用众多可用 Python 库中的一个来处理低级别详细信息,如路由 Web 请求和调整响应。Web apps in Python almost always use one of the many available Python libraries to handle low-level details like routing web requests and shaping responses. 为此,Visual Studio 为 Web 应用提供了各种模板,稍后我们将在快速入门中使用其中的一个模板。For this purpose, Visual Studio provides a variety of templates for web apps, one of which you use later in this Quickstart.

在此按以下步骤将 Flask 库安装到 Visual Studio 用于此项目的默认“全局环境”。Here, you use the following steps to install the Flask library into the default "global environment" that Visual Studio uses for this project.

展开项目中的“Python 环境” 节点,查看项目的默认环境。Expand the Python Environments node in the project to see the default environment for the project.

quickstart-python-02-default-environment.png?view=vs-2017

右键单击环境并选择“安装 Python 包” 。Right-click the environment and select Install Python Package. 此命令将打开“包” 选项卡上的“Python 环境” 窗口。This command opens the Python Environments window on the Packages tab.

在搜索字段中输入“flask”,再选择 [PyPI 中的“pip install flask”] 。Enter "flask" in the search field and select pip install flask from PyPI. 接受任何管理员权限提示,查看 Visual Studio 中的“输出” 窗口了解进度。Accept any prompts for administrator privileges and observe the Output window in Visual Studio for progress. (当全局环境的包文件夹位于类似于 C:\Program Files 这样的受保护区域时,会出现提升提示。)(A prompt for elevation happens when the packages folder for the global environment is located within a protected area like C:\Program Files.)

quickstart-python-03-install-package.png?view=vs-2017

展开项目中的“Python 环境” 节点,查看项目的默认环境。Expand the Python Environments node in the project to see the default environment for the project.

quickstart-python-02-default-environment-2019.png?view=vs-2017

右键单击环境并选择“管理 Python 包...” 。此命令将打开“包 (PyPI)”选项卡上的“Python 环境”窗口 。Right-click the environment and select Manage Python Packages.... This command opens the Python Environments window on the Packages (PyPI) tab.

在搜索字段中输入"flask"。Enter "flask" in the search field. 如果 Flask 出现在搜索框下方,可跳过此步骤 。If Flask appears below the search box, you can skip this step. 否则选择“运行命令: pip install flask” 。Otherwise select Run command: pip install flask. 接受任何管理员权限提示,查看 Visual Studio 中的“输出” 窗口了解进度。Accept any prompts for administrator privileges and observe the Output window in Visual Studio for progress. (当全局环境的包文件夹位于类似于 C:\Program Files 这样的受保护区域时,会出现提升提示。)(A prompt for elevation happens when the packages folder for the global environment is located within a protected area like C:\Program Files.)

quickstart-python-03-install-package-2019.png?view=vs-2017

安装完成后,库显示在“解决方案资源管理器” 的环境中,这意味着可以在 Python 代码中使用它。Once installed, the library appears in the environment in Solution Explorer, which means that you can make use of it in Python code.

quickstart-python-04-package-installed.png?view=vs-2017

quickstart-python-04-package-installed-2019.png?view=vs-2017

备注

开发人员通常会创建一个虚拟环境用于安装特定项目的库,而不是在全局环境中安装库。Instead of installing libraries in the global environment, developers typically create a "virtual environment" in which to install libraries for a specific project. Visual Studio 模板通常会提供此选项,如快速入门 - 使用模板创建 Python 项目中所述。Visual Studio templates typically offer this option, as discussed in Quickstart - Create a Python project using a template.

问:我可在何处深入了解其他可用的 Python 包?Question: Where do I learn more about other available Python packages?

添加代码文件Add a code file

现已准备好添加一点 Python 代码来实现最小的 Web 应用。You're now ready to add a bit of Python code to implement a minimal web app.

在“解决方案资源管理器” 中右键单击该项目,然后选择“添加”>“新建项” 。Right-click the project in Solution Explorer and select Add > New Item.

在出现的对话框中,选择“空 Python 文件” ,将其命名为 app.py ,然后选择“添加” 。In the dialog that appears, select Empty Python File, name it app.py, and select Add. Visual Studio 会自动在编辑器窗口中打开该文件。Visual Studio automatically opens the file in an editor window.

复制以下代码,并将其粘贴到 app.py :Copy the following code and paste it into app.py:

from flask import Flask

# Create an instance of the Flask class that is the WSGI application.

# The first argument is the name of the application module or package,

# typically __name__ when using a single module.

app = Flask(__name__)

# Flask route decorators map / and /hello to the hello function.

# To add other resources, create functions that generate the page contents

# and add decorators to define the appropriate resource locators for them.

@app.route('/')

@app.route('/hello')

def hello():

# Render the page

return "Hello Python!"

if __name__ == '__main__':

# Run the app server on localhost:4449

app.run('localhost', 4449)

你可能已注意到,“添加”>“新建项” 对话框显示了很多可添加到 Python 项目的其他类型的文件,例如 Python 类、Python 包、Python 单元测试和 web.config 文件等。You may have noticed that the Add > New Item dialog box displays many other types of files you can add to a Python project, including a Python class, a Python package, a Python unit test, web.config files, and more. 通常,可利用这些所谓的项模板通过有用的样本代码创建文件。In general, these item templates, as they're called, are a great way to quickly create files with useful boilerplate code.

问:我可在何处了解 Flask 的详细信息?Question: Where can I learn more about Flask?

答:请参阅 Flask 文档,首先是 Flask 快速入门。Answer: Refer to the Flask documentation, starting with the Flask Quickstart.

运行此应用程序Run the application

在“解决方案资源管理器”中右键单击 app.py ,然后选择“设置为启动文件” 。Right-click app.py in Solution Explorer and select Set as startup file. 此命令可标识运行应用时要在 Python 中启动的代码文件。This command identifies the code file to launch in Python when running the app.

quickstart-python-05-set-as-startup-file.png?view=vs-2017

quickstart-python-05-set-as-startup-file-2019.png?view=vs-2017

右键单击“解决方案资源管理器”中的项目,再选择“属性” 。Right-click the project in Solution Explorer and select Properties. 然后选择“调试” 选项卡并将“端口号” 属性设置为 4449。Then select the Debug tab and set the Port Number property to 4449. 此步骤可保证 Visual Studio 启动带 localhost:4449 的浏览器与代码中的 app.run 参数进行匹配。This step ensures that Visual Studio launches a browser with localhost:4449 to match the app.run arguments in the code.

依次选择“调试”和“开始执行(不调试)” (Ctrl+F5 ),这会将更改保存至文件并运行应用。Select Debug > Start Without Debugging (Ctrl+F5), which saves changes to files and runs the app.

命令窗口中会显示消息“在 https://localhost:4449 中运行”,并且浏览器窗口应打开至 localhost:4449,可在其中看到消息“Hello, Python!”A command window appears with the message Running in https://localhost:4449, and a browser window should open to localhost:4449 where you see the message, "Hello, Python!" 状态为 200 的命令窗口中还显示 GET 请求。The GET request also appears in the command window with a status of 200.

如果浏览器未自动打开,请启动所选的浏览器并导航到 localhost:4449。If a browser does not open automatically, start the browser of your choice and navigate to localhost:4449.

如果只在命令窗口中看到 Python 交互式 shell,或者如果该窗口在屏幕上短暂地闪烁,请确保在上述第 1 步中将 app.py 设为启动文件。If you see only the Python interactive shell in the command window, or if that window flashes on the screen briefly, ensure that you set app.py as the startup file in step 1 above.

导航到 localhost:4449/hello,测试确保 /hello 资源的修饰器也正常运行。Navigate to localhost:4449/hello to test that the decorator for the /hello resource also works. 同样的,状态为 200 的命令窗口会显示 GET 请求。Again, the GET request appears in the command window with a status of 200. 随时可尝试其他 URL,查看它们是否在命令窗口中显示 404 状态代码。Feel free to try some other URL as well to see that they show 404 status codes in the command window.

关闭命令窗口以停止应用,然后关闭浏览器窗口。Close the command window to stop the app, then close the browser window.

问:“开始执行(不调试)”命令和“启动调试”有何区别?Question: What's the difference between the Start Without Debugging command and Start Debugging?

答:使用“启动调试”是在 Visual Studio 调试器的上下文中运行应用,让你能够设置断点、检查变量和逐行执行代码 。Answer: You use Start Debugging to run the app in the context of the Visual Studio debugger, allowing you to set breakpoints, examine variables, and step through your code line by line. 由于实现调试的挂钩各式各样,应用在调试器中的运行速度可能较慢。Apps may run slower in the debugger because of the various hooks that make debugging possible. 与此相反,“开始执行(不调试)”直接运行应用,如同从命令行运行应用一样,但不调用上下文;而且此命令还自动启动浏览器并导航到项目属性的“调试”选项卡中指定的 URL 。Start Without Debugging, in contrast, runs the app directly as if you ran it from the command line, with no debugging context, and also automatically launches a browser and navigates to the URL specified in the project properties' Debug tab.

后续步骤Next steps

祝贺你通过 Visual Studio 运行了第一个 Python 应用,这表示你初步了解了如何将 Visual Studio 用作 Python IDE!Congratulations on running your first Python app from Visual Studio, in which you've learned a little about using Visual Studio as a Python IDE!

此快速入门中的步骤比较笼统,你可能已猜到它们可以且应当自动执行。Because the steps you followed in this Quickstart are fairly generic, you've probably guessed that they can and should be automated. 此类自动化由 Visual Studio 项目模板执行。Such automation is the role of Visual Studio project templates. 浏览快速入门 - 使用模板创建 Python 项目获得演示,如何通过更少的步骤创建一个与本文创建的 Web 应用相类似的 Web 应用。Go through Quickstart - Create a Python project using a template for a demonstration that creates a web app similar to the one you created in this article, but with fewer steps.

若要继续在 Visual Studio 中了解更完整的 Python 教程(包括使用交互式窗口、调试、数据可视化效果以及使用 Git),请浏览教程:Visual Studio 中的 Python 入门。To continue with a fuller tutorial on Python in Visual Studio, including using the interactive window, debugging, data visualization, and working with Git, go through Tutorial: Get started with Python in Visual Studio.

若要了解更多 Visual Studio 产品,请选择以下链接。To explore more that Visual Studio has to offer, select the links below.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值