Python Web Development Libraries 简明教程
Flask Framework
Flask 是一种微框架,几乎不依赖于外部库。它是一种非常轻量的框架,让我们可以自由地做任何我们想做的事情。
Flask is micro-framework which has very little dependency on external libraries. It is a very light framework and gives us freedom to do whatever we want.
在本章中,我们将使用 Python 和 Flask 框架构建一个项目。
In this chapter, we are going to build a project using Python and Flask framework.
Flask Startup and Configuration
类似大多数广泛使用的 python 库,可以从 Python 程序包索引 (PPI) 安装 Flask 程序包。让我们首先创建一个目录(在本章中,我们创建了一个名为 flaskProject 的目录),然后创建一个虚拟环境(并将其称为 flaskEnv ),所有项目相关的依赖项都将加载到该环境中(包括 flask)。你还可以安装 flask-sqlalchemy,以便你的 flask 应用程序可以轻松地与 SQL 数据库通信。
Like most widely used python libraries, the Flask package is installable from the Python Package Index (PPI). Let’s create a directory first (In this chapter, we have created a directory called flaskProject) then created a virtual environment (and called it as flaskEnv) where all the project related dependencies will be loaded (including flask). You can also install flask-sqlalchemy so that your flask application has a simple way to communicate with SQL database.
安装 flask 之后,flaskEnv(我们的虚拟环境名称)将显示类似以下的内容:
After installing the flask, your flaskEnv (our virtualEnvironment name) will show something like below −

Creating an app with flask
通过安装 flask,我们可以使用如下所示的几行代码创建一个简单的“ hello application in flask ”:
By installing flask, we can create a simple “hello application in flask” with very few lines of code as follows −

在终端中键入以下内容:
Type the following in the terminal −
$python flaskapp.py
然后你可以看到以下输出:
And you can see the following output −
在 http://127.0.0.1:5000/ 或 localhost:5000 上运行
Running on http://127.0.0.1:5000/ or on localhost:5000

以下是我们示例代码中所执行功能的说明:
Below is the explanation of what we did in our example code −
-
Firstly, we import the Flask class library. An instance from this class is the WSGI app.
-
Secondly, we create an instance of this class. Application package or module name is our first argument. It is mandatory that flask knows where to find static files, templates and other files.
-
Next is the route() decorator we use to know which URL should trigger our method/function.
Creating URL Routing
URL 路由使 Web 应用程序中的 URL 便于记忆。我们现在将创建一些 URL 路由:
URL Routing makes URLs in your Web app easy to remember. We will now create some URL routes −
/hello
/members
/members/name
我们可以根据上面的 URL 编写下面的代码并保存为 app.py。
We can write the following code based on the above URL and save it as app.py.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return "Index!"
@app.route('/Hello')
def hello():
return "Hello, World!"
@app.route("/members")
def members():
return "Members"
@app.route("/members/<name>/")
def getMember(name):
return name
if __name__ == '__main__':
app.run(debug=True)
$ python app.py
Running on [role="bare"]http://localhost:5000/
Running on [role="bare"]http://localhost:5000/
我们在浏览器中获得下面的输出 −
We will get the following output in our browser −

我们可以在浏览器中尝试其他 URL,如下所示 −
We can try other URLs in our browser as follows −
Running on [role="bare"]http://localhost:5000/hello, will give the following output −
Running on [role="bare"]http://localhost:5000/hello, will give the following output −

Running on [role="bare"]http://localhost:5000/members, will give −
Running on [role="bare"]http://localhost:5000/members, will give −

Running on [role="bare"]http://localhost:5000/members/TutorialsPoint/, will give you the following output −
Running on [role="bare"]http://localhost:5000/members/TutorialsPoint/, will give you the following output −

但通常我们不想返回字符串(如上),我们返回模板。为此,我们想要从 flask 中使用函数 “ render_template ”,并使用一些输入返回 render_template。所以,下面的函数将完成我们的工作 −
But normally we don’t want to return a string (as above), we return templates. For that we want to use a function “render_template” from flask, and return render_template with some input. So, below function will do our work −
from flask import render_template
return render_template(‘home.html’)
让我们创建一个文件夹模板并在其中放置 home.html 文件。
Let us create a folder template and place home.html file in it.
接下来,我们将讨论布局。我们不会为每个单独的模板使用 html head 标签和 body 标签,而是设计一个布局来包含 head 和 body 标签,并包装当前视图或当前模板。为此,我们必须创建一个单独的文件并将其称为 layout.html 。在此,我们可以放置我们的正常 head 标签、body 标签和其他所有必需的标签。
Next, we will discuss about layout. Instead of using html head tag and body tag for every single template, we will design a layout to include head & body tags and wrap the current views or current template. For that, we have to create one separate file and call it layout.html. In this, we can put our normal head tag, body tag and all the other required tags.
我们可以使用下面的代码行创建我们的新 layout.html −
We can create our new layout.html with the following lines of code −
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyFlaskApp</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
{% include 'includes/_navbar.html' %}
<div class="container">
{% block body %}
{% endblock %}
</div>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js">
</script>
</body>
</html>
在上面的代码中,我们给出了标题曲目 MyFlaskAp,在 head 中使用 css cdn,在 body 块中使用 javascript 来启用引导程序。
In above code, we have given the title track, MyFlaskAp, use css cdn in the head, and javascript in body block to enable the bootstrap.
现在,我们必须为每个单独的页面创建导航栏。为此,我们必须首先创建一个包含文件夹,然后在其中创建 _navbar.html 文件。现在在 _navbar.html 中,我们必须使用 getbootstrap.com 提供的标准启动程序模板。新创建的 _navbar.html 文件如下所示 −
Now, we have to create navbar for every single page. For that, we have to first create an include folder and then create _navbar.html file inside it. Now in the _navbar.html, we have to use the standard starter template from getbootstrap.com. The newly created _navbar.html file will be as follows −

并将此 _navbar.html 文件包含到我们的 layout.html 文件中。
And include this _navbar.html file into our layout.html file.
{% include 'includes/_navbar.html' %}
当我们拥有布局块时,我们能够在我们的主页文件 (home.html) 中扩展此块。
As we have the layout block, we can extend this block in our home file (home.html).
我们的 home.html 文件可以使用下面的代码创建 −
Our home.html file can be created using the below code −
{% extends 'layout.html' %}
{% block body %}
<div class="jumbotron text-center">
<h1>Welcome to FlaskApp</h1>
<p>This application is built on Flask webframework!</p>
</div>
{% endblock %}
使用此内容如果我们尝试运行我们的 flaskapp.py 文件,那么我们可以在我们的浏览器中看到下面的输出 −
Using this if we try to run our flaskapp.py file, then we could see the below output in our browser −

现在,我们希望激活(当前标签无效)我们的 about 标签。为 about 标签创建一个路由并创建一个模板文件 about.html 。
Now we want to activate (currently the tabs are not working) our about tab. Create a route for the about tab and create a template file, about.html.
appflask.py 中的 about 标签路由如下所示 −
About tab route in appflask.py will be as shown below −

about.html 文件的内容如下所示 −
about.html file will have the below content −

因此现在已处理了 Home 和 About。对于文章,我们可以在根目录中创建新文件 (data.py),其中我们放置数据并在我们的网页中调用该数据。
So Home and About are now taken care of. For Articles, we can create a new file (data.py) in the root directory, where we put the data and call it in our webpage.
data.py
def Articles():
articles = [
{
'uid': 1,
'title': 'Article_One',
'body': 'Flask, being a microframework, often requires some repetitive step
to get a third party library working. Because very often these steps could
be abstracted to support multiple projects the Flask Extension Registry
was created.',
'Author': 'Rajesh Joshi',
'Created-on': '07-09-2018'
},
{
'uid': 2,
'title': 'Article_Two',
'body': "Flask, being a microframework, often requires some repetitive steps
to get a third party library working. Because very often these steps could
be abstracted to support multiple projects the Flask Extension Registry
was created.",
'Author': 'Rajesh J',
'Created-on': '07-09-2018'
},
{
'uid': 3,
'title': 'Article_Three',
'body': 'Flask, being a microframework, often requires some repetitive steps
to get a third party library working. Because very often these steps could be
abstracted to support multiple projects the Flask Extension Registry
was created.',
'Author': 'Joshi Rajesh',
'Created-on': '07-09-2018'
}
]
return articles
以下是 articles.html 的代码,该代码将显示每个 uid 的文章标题。
Below is the code for articles.html, which will display article titles for each uid.
{% extends 'layout.html' %}
{% block body %}
<h1>Articles</h1>
{% for article in articles %}
<li class="list-group-item">
<a href="article/{{article.uid}}"> {{article.title}}</a>
</li>
{% endfor %}
{% endblock %}
总结来说,Flask 是目前最流行的 Python Web 框架之一,因为它的轻量级。尽管它是微型的,但它是一个可扩展的 Python Web 框架。通过提供所需的功能,Flask 可加速简单 Web 应用程序的开发。因此,Flask 更适合较小、不太复杂的应用程序。
To summarize, Flask is one of the most popular python web frameworks because of its lightweight. Although it is micro it is an extensible python web framework. By providing the required functionality, flask accelerates the development of simple web application. So Flask, is more suitable for smaller, less complicated applications.