如何在Python 3中使用Flask制作Web应用程序

The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program. 作者选择了免费开放源基金来接受捐款,这是Write for DOnations计划的一部分。 介绍 (Introduction)Flask is a smal...
摘要由CSDN通过智能技术生成

介绍 (Introduction)

Flask is a small and lightweight Python web framework that provides useful tools and features that make creating web applications in Python easier. It gives developers flexibility and is a more accessible framework for new developers since you can build a web application quickly using only a single Python file. Flask is also extensible and doesn’t force a particular directory structure or require complicated boilerplate code before getting started.

Flask是一个小型轻量级的Python Web框架,提供有用的工具和功能,这些工具和功能使使用Python创建Web应用程序更加容易。 它为开发人员提供了灵活性,并且是新开发人员更易于访问的框架,因为您可以仅使用单个Python文件快速构建Web应用程序。 Flask也是可扩展的,在开始之前不需要强制特定的目录结构或需要复杂的样板代码。

As part of this tutorial, you’ll use the Bootstrap toolkit to style your application so it is more visually appealing. Bootstrap will help you incorporate responsive web pages in your web application so that it also works well on mobile browsers without writing your own HTML, CSS, and JavaScript code to achieve these goals. The toolkit will allow you to focus on learning how Flask works.

作为本教程的一部分,您将使用Bootstrap工具箱来设置应用程序的样式,从而在外观上更具吸引力。 Bootstrap将帮助您将响应性网页合并到Web应用程序中,从而使其在移动浏览器中也能很好地工作,而无需编写自己HTML,CSS和JavaScript代码来实现这些目标。 该工具包将使您可以专注于学习Flask的工作方式。

Flask uses the Jinja template engine to dynamically build HTML pages using familiar Python concepts such as variables, loops, lists, and so on. You’ll use these templates as part of this project.

Flask使用Jinja模板引擎使用熟悉的Python概念(例如变量,循环,列表等)动态构建HTML页面。 您将使用这些模板作为该项目的一部分。

In this tutorial, you’ll build a small web blog using Flask and SQLite in Python 3. Users of the application can view all the posts in your database and click on the title of a post to view its contents with the ability to add a new post to the database and edit or delete an existing post.

在本教程中,您将使用Python 3中的Flask和SQLite构建一个小型的Web博客。该应用程序的用户可以查看数据库中的所有帖子,并单击帖子标题以查看其内容并可以添加内容。将新帖子添加到数据库,然后编辑或删除现有帖子。

先决条件 (Prerequisites)

Before you start following this guide, you will need:

在开始遵循本指南之前,您需要:

第1步-安装Flask (Step 1 — Installing Flask)

In this step, you’ll activate your Python environment and install Flask using the pip package installer.

在此步骤中,您将激活Python环境并使用pip软件包安装程序安装Flask。

If you haven’t already activated your programming environment, make sure you’re in your project directory (flask_blog) and use the following command to activate the environment:

如果尚未激活编程环境,请确保您位于项目目录( flask_blog )中,并使用以下命令激活环境:

  • source env/bin/activate

    源ENV /斌/激活

Once your programming environment is activated, your prompt will now have an env prefix that may look as follows:

激活编程环境后,您的提示现在将带有一个env前缀,看起来可能如下:

This prefix is an indication that the environment env is currently active, which might have another name depending on how you named it during creation.

此前缀表示环境env当前处于活动状态,根据您在创建过程中的命名方式,环境env可能具有另一个名称。

Note: You can use Git, a version control system, to effectively manage and track the development process for your project. To learn how to use Git, you might want to check out our Introduction to Git Installation Usage and Branches article.

注意:您可以使用版本控制系统Git来有效管理和跟踪项目的开发过程。 要了解如何使用Git,您可能需要查看我们的《 Git安装用法和分支简介》文章。

If you are using Git, it is a good idea to ignore the newly created env directory in your .gitignore file to avoid tracking files not related to the project.

如果您使用的是Git,最好忽略.gitignore文件中新创建的env目录,以避免跟踪与项目无关的文件。

Now you’ll install Python packages and isolate your project code away from the main Python system installation. You’ll do this using pip and python.

现在,您将安装Python软件包,并将您的项目代码与主要的Python系统安装隔离开。 您将使用pippython进行此操作。

To install Flask, run the following command:

要安装Flask,请运行以下命令:

  • pip install flask

    点安装烧瓶

Once the installation is complete, run the following command to confirm the installation:

安装完成后,运行以下命令以确认安装:

  • python -c "import flask; print(flask.__version__)"

    python -c“导入烧瓶;打印(flask .__ version__)”

You use the python command line interface with the option -c to execute Python code. Next you import the flask package with import flask; then print the Flask version, which is provided via the flask.__version__ variable.

您可以将python命令行界面-c选项一起使用来执行Python代码。 接下来,使用import flask;导入flaskimport flask; 然后打印Flask版本,该版本通过flask.__version__变量提供。

The output will be a version number similar to the following:

输出将是类似于以下内容的版本号:


   
   
   
Output
1.1.2

You’ve created the project folder, a virtual environment, and installed Flask. You’re now ready to move on to setting up your base application.

您已经创建了项目文件夹,虚拟环境并安装了Flask。 现在您可以继续设置基本应用程序了。

第2步-创建基础应用程序 (Step 2 — Creating a Base Application)

Now that you have your programming environment set up, you’ll start using Flask. In this step, you’ll make a small web application inside a Python file and run it to start the server, which will display some information on the browser.

现在您已经设置了编程环境,您将开始使用Flask。 在此步骤中,您将在Python文件中创建一个小型Web应用程序,然后运行该应用程序以启动服务器,该服务器将在浏览器上显示一些信息。

In your flask_blog directory, open a file named hello.py for editing, use nano or your favorite text editor:

flask_blog目录中,打开一个名为hello.py的文件进行编辑,使用nano或您喜欢的文本编辑器:

  • nano hello.py

    纳米hello.py

This hello.py file will serve as a minimal example of how to handle HTTP requests. Inside it, you’ll import the Flask object, and create a function that returns an HTTP response. Write the following code inside hello.py:

hello.py文件将作为如何处理HTTP请求的最小示例。 在其中,您将导入Flask对象 ,并创建一个返回HTTP响应的函数。 在hello.py编写以下代码:

flask_blog/hello.py
flask_blog / hello.py
from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello():
    return 'Hello, World!'

In the preceding code block, you first import the Flask object from the flask package. You then use it to create your Flask application instance with the name app. You pass the special variable __name__ that holds the name of the current Python module. It’s used to tell the instance where it’s located—you need this because Flask sets up some paths behind the scenes.

在前面的代码块中,您首先从flask包中导入Flask对象。 然后,您可以使用它来创建名为app Flask应用程序实例。 您传递包含当前Python模块名称的特殊变量__name__ 。 它用来告诉实例它的位置,您需要它,因为Flask在后台设置了一些路径。

Once you create the app instance, you use it to handle incoming web requests and send responses to the user. @app.route is a decorator that turns a regular Python function into a Flask view function, which converts the function’s return value into an HTTP response to be displayed by an HTTP client, such as a web browser. You pass the value '/' to @app.route() to signify that this function will respond to web requests for the URL /, which is the main URL.

创建app实例后,就可以使用它来处理传入的Web请求并将响应发送给用户。 @app.route是一个修饰器 ,它将常规的Python函数转换为Flask 视图函数 ,该函数将函数的返回值转换为HTTP响应,以由HTTP客户端(例如网络浏览器)显示。 您将值'/'传递给@app.route()表示此函数将响应Web对URL /请求,URL是主URL。

The hello() view function returns the string 'Hello, World!' as a response.

hello()视图函数返回字符串'Hello, World!' 作为回应。

Save and close the file.

保存并关闭文件。

To run your web application, you’ll first tell Flask where to find the application (the hello.py file in your case) with the FLASK_APP environment variable:

要运行您的Web应用程序,您首先要使用FLASK_APP环境变量告诉Flask在哪里找到该应用程序(在您的情况下为hello.py文件):

  • export FLASK_APP=hello

    出口FLASK_APP =你好

Then run it in development mode with the FLASK_ENV environment variable:

然后使用FLASK_ENV环境变量在开发模式下运行它:

  • export FLASK_ENV=development

    出口FLASK_ENV =发展

Lastly, run the application using the flask run command:

最后,使用flask run命令运行该应用程序:

  • flask run

    烧瓶运行

Once the application is running the output will be something like this:

一旦应用程序运行,输出将如下所示:


   
   
   
Output
* Serving Flask app "hello" (lazy loading) * Environment: development * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 813-894-335

The preceding output has several pieces of information, such as:

前面的输出包含一些信息,例如:

  • The name of the application you’re running.

    您正在运行的应用程序的名称。
  • The environment in which the application is being run.

    运行应用程序的环境。
  • Debug mode: on signifies that the Flask debugger is running. This is useful when developing because it gives us detailed error messages when things go wrong, which makes troubleshooting easier.

    Debug mode: on亮起表示Flask调试器正在运行。 这在开发时很有用,因为当出现问题时它会向我们提供详细的错误消息,这使故障排除更加容易。

  • The application is running locally on the URL http://127.0.0.1:5000/, 127.0.0.1 is the IP that represents your machine’s localhost and :5000 is the port number.

    该应用程序在URL http://127.0.0.1:5000/上本地运行, 127.0.0.1是代表您计算机的localhost的IP,而:5000是端口号。

Open a browser and type in the URL http://127.0.0.1:5000/, you will receive the string Hello, World! as a response, this confirms that your application is successfully running.

打开浏览器,输入URL http://127.0.0.1:5000/ ,您将收到字符串Hello, World! 作为响应,这确认您的应用程序已成功运行。

Warning Flask uses a simple web server to serve our application in a development environment, which also means that the Flask debugger is running to make catching errors easier. This development server should not be used in a production deployment. See the Deployment Options page on the Flask documentation for more information, you can also check out this Flask deployment tutorial.

警告 Flask使用简单的Web服务器在开发环境中为我们的应用程序提供服务,这也意味着Flask调试器正在运行,以使捕获错误变得更加容易。 此开发服务器不应在生产部署中使用。 有关更多信息,请参见Flask文档上的Deployment Options页面。您还可以查看此Flask部署教程

You can now leave the development server running in the terminal and open another terminal window. Move into the project folder where hello.py is located, activate the virtual environment, set the environment variables FLASK_ENV and FLASK_APP, and continue to the next steps. (These commands are listed earlier in this step.)

现在,您可以使开发服务器在终端中运行,并打开另一个终端窗口。 移入hello.py所在的项目文件夹,激活虚拟环境,设置环境变量FLASK_ENVFLASK_APP ,然后继续下一步。 (这些命令在本步骤的前面列出。)

Note: When opening a new terminal, it is important to remember activating the virtual environment and setting the environment variables FLASK_ENV and FLASK_APP.

注意 :打开新终端时,切记要激活虚拟环境并设置环境变量FLASK_ENVFLASK_APP ,这一点很重要。

While a Flask application’s development server is already running, it is not possible to run another Flask application with the same flask run command. This is because flask run uses the port number 5000 by default, and once it is taken, it becomes unavailable to run another application on so you would receive an error similar to the following:

当Flask应用程序的开发服务器已经在运行时,无法使用相同的flask run命令运行另一个Flask应用程序。 这是因为默认情况下, flask run使用端口号5000 ,一旦被占用,它将无法在其上运行另一个应用程序,因此您将收到类似于以下内容的错误:


   
   
   
Output
OSError: [Errno 98] Address already in use

To solve this problem, either stop the server that’s currently running via CTRL+C, then run flask run again, or if you want to run both at the same time, you can pass a different port number to the -p argument, for example, to run another application on port 5001 use the following command:

要解决此问题,请停止通过CTRL+C停止当前正在运行的服务器,然后再次运行flask run ,或者如果要同时运行两者,则可以将不同的端口号传递给-p参数,例如,要在端口5001上运行另一个应用程序,请使用以下命令:

  • flask run -p 5001

    烧瓶运行-p 5001

You now have a small Flask web application. You’ve run your application and displayed information on the web browser. Next, you’ll use HTML files in your application.

您现在有了一个小的Flask Web应用程序。 您已经运行了应用程序,并在Web浏览器上显示了信息。 接下来,您将在应用程序中使用HTML文件。

第3步-使用HTML模板 (Step 3 — Using HTML templates)

Currently your application only displays a simple message without any HTML. Web applications mainly use HTML to display information for the visitor, so you’ll now work on incorporating HTML files in your app, which can be displayed on the web browser.

当前,您的应用程序仅显示一条简单的消息,没有任何HTML。 Web应用程序主要使用HTML来显示访问者的信息,因此您现在要在应用程序中合并HTML文件,该文件可以在Web浏览器上显示。

Flask provides a render_template() helper function that allows use of the Jinja template engine. This will make managing HTML much easier by writing your HTML code in .html files as well as using logic in your HTML code. You’ll use these HTML files, (templates) to build all of your application pages, such as the main page where you’ll display the current blog posts, the page of the blog post, the page where the user can add a new post, and so on.

Flask提供了render_template()帮助函数,该函数允许使用Jinja模板引擎 。 通过在.html文件中编写HTML代码以及在HTML代码中使用逻辑,这将使管理HTML更加容易。 您将使用这些HTML文件( 模板 )来构建所有应用程序页面,例如用于显示当前博客文章的主页,博客文章的页面,用户可以在其中添加新页面的页面。发布等等。

In this step, you’ll create your main Flask application in a new file.

在这一步中,您将在一个新文件中创建您的主Flask应用程序。

First, in your flask_blog directory, use nano or your favorite editor to create and edit your app.py file. This will hold all the code you’ll use to create the blogging application:

首先,在flask_blog目录中,

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值