大众烧瓶

tech2023-06-19  116

Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions. – official flask documentation

Flask是基于Werkzeug,Jinja 2和良好意图的Python微框架。 – 烧瓶官方文件

To explain this quote a bit further, Werkzeug is a python utility library and Jinja 2 is a template engine for Python.

为了进一步解释此报价,Werkzeug是python实用程序库,Jinja 2是Python的模板引擎。

为什么选择烧瓶? (Why Flask?)

About a year ago, I was looking into another programming language outside of PHP. I’d been an active PHP developer for 10 years, and, to be honest, doing apps only in PHP gets a bit boring. It not having any standardized libraries or frameworks didn’t help either. I found myself spending half of my time reinventing the wheel just for the sake of reinventing something. Thinking I know better than the other PHP developers often leads to spending too much time on the project. This is very common in the PHP world – almost every other developer is building his own framework, and this can lead to certain types of chaos, but let’s not go there right now.

大约一年前,我正在研究PHP之外的另一种编程语言。 我已经成为活跃PHP开发人员已有10年了,老实说,仅使用PHP编写应用程序会有些无聊。 它没有任何标准化的库或框架也无济于事。 我发现自己花了一半的时间重新设计轮子,只是为了重新发明一些东西。 以为我比其他PHP开发人员更了解自己,常常导致在该项目上花费太多时间。 这在PHP世界中很常见-几乎所有其他开发人员都在构建自己的框架,这可能会导致某些类型的混乱,但是现在就不要去做。

I was searching for something new, and at work we had just started to use Django for serious web development. Django, at that point, seemed like too big of a framework and I wanted something small that I could build upon. Then, I stumbled upon Flask, and I’ve been using it for most of my personal development projects since.

我正在寻找新的东西,在工作中,我们刚开始使用Django进行认真的Web开发。 那时,Django似乎太大了,我希望可以在它之上构建一些小的东西。 然后,我偶然发现了Flask ,从那时起,我就将其用于大多数个人开发项目。

In this article, I will cover installing and configuring Flask and running a basic “hello world” example. Also, I’ll assume that you have a Linux machine installed (or a Mac) or that you’re running some sort of decent virtual machine, such as Homestead Improved.

在本文中,我将介绍如何安装和配置Flask以及如何运行基本的“ hello world”示例。 另外,我假设您已经安装了Linux计算机(或Mac),或者您正在运行某种不错的虚拟机,例如Homestead Enhanced 。

下载并安装 (Download & Install)

To get started you will need Python 2.6 or higher. In Homestead Improved, this is a default.

要开始使用,您将需要Python 2.6或更高版本。 在“ 宅基地改进”中 ,这是默认设置。

First, for clean development, we need virtualenv. As a Python developer, you will most likely build different applications. Different applications have different dependencies, maybe even different Python versions. To solve the problem of dependencies and used libraries stacking up on your machine, we use virtualenv. Virtualenv creates a separate environment for your application, so you can keep your environments fully isolated. For more info go to the docs.

首先,对于清洁开发,我们需要virtualenv 。 作为Python开发人员,您很可能会构建不同的应用程序。 不同的应用程序具有不同的依赖关系,甚至可能具有不同的Python版本。 为了解决依赖性问题以及在您的计算机上堆积使用的库,我们使用virtualenv。 Virtualenv为您的应用程序创建一个单独的环境,因此您可以保持环境完全隔离。 有关更多信息,请访问文档 。

Let’s install it:

让我们安装它:

sudo pip install virtualenv

You could even do something like

你甚至可以做类似的事情

sudo apt-get install python-virtualenv

Once virtualenv is installed, create a new environment.

安装virtualenv后 ,创建一个新环境。

mkdir flaskproject cd flaskproject virtualenv env New python executable in env/bin/python Installing distribute............done.

Now you have a directory called “flaskproject”. Inside that directory you have another one (with your environment) called “env”. To start using your environment, you need to “activate” it.

现在您有了一个名为“ flaskproject”的目录。 在该目录内,您还有一个名为“ env”的目录(与您的环境一起使用)。 要开始使用您的环境,您需要“激活”它。

. env/bin/activate

Finally, let’s install Flask.

最后,让我们安装Flask。

pip install Flask

You should see something like:

您应该看到类似以下内容:

Successfully installed Flask Werkzeug Jinja2 itsdangerous markupsafe Cleaning up...

If you inspect your folder, notice that you will still see only your env directory. That’s OK, because Flask is installed inside your env directory.

如果检查文件夹,请注意,您仍然只会看到env目录。 可以,因为Flask已安装在您的env目录中。

All the packages installed will be inside the site-packages subdirectory.

安装的所有软件包都将在site-packages子目录中。

env/lib/python2.6/site-packages

Or you can do pip list, which will list all installed packages inside your environment. Don’t be afraid if you see more than just Flask, because Flask installs its own dependencies too.

或者,您可以执行pip list ,它将列出环境中所有已安装的软件包。 如果您看到的不仅仅是Flask,不要害怕,因为Flask也会安装自己的依赖项。

pip list

You now have your environment and application ready to build upon.

现在,您已经可以在其环境和应用程序上进行构建了。

您的第一个Flask应用程序 (Your first Flask application)

Let’s create app.py inside our directory:

让我们在目录中创建app.py :

from flask import Flask app = Flask(__name__) app.debug = True @app.route('/') def main_method(): return "Hello everyone" if __name__ == '__main__': app.run()

If we run this code from the console, we will get something like

如果我们从控制台运行此代码,我们将得到类似

python app.py Running on http://127.0.0.1:5000/

If you fire up your browser and go to the given address (or the vhost you defined, if using VMs with Vagrant), you should see your message.

如果启动浏览器并转到给定的地址(或者,如果将虚拟机与Vagrant一​​起使用,则转到您定义的虚拟主机),则应该会看到消息。

Let’s explain what’s going on:

让我们解释发生了什么:

from flask import Flask app = Flask(__name__)

This imports the flask library from Flask, and creates a new instance of the Flask class.

这将从Flask导入flask库,并创建Flask类的新实例。

While in development, I often have debug mode on. That’s what the app.debug = True line is for. It gives me plenty of messages, automatically reloads the server when I change some files.

在开发过程中,我经常启用调试模式。 这就是app.debug = True行的用途。 它给了我很多信息,当我更改某些文件时会自动重新加载服务器。

Next we create a method that will return a simple string.

接下来,我们创建一个将返回简单字符串的方法。

def main_method(): return "Hello everyone"

And above our method we use the routing decorator (@app.route('/')) to specify a URL for it. Any request coming to / will be redirected to main_method. Simple, right?

在我们的方法之上,我们使用路由装饰器( @app.route('/') )为它指定一个URL。 向/发送的任何请求都将重定向到main_method 。 简单吧?

This final piece of code checks if the script is being called directly, and not like an imported module. If that’s the case, it will run the code automatically.

这最后一部分代码检查是否直接调用了脚本,而不是像导入的模块一样。 如果是这种情况,它将自动运行代码。

if __name__ == '__main__': app.run()

模板的乐趣 (Fun with Templates)

Now, let’s create a URL that will receive a parameter and pass it to the template, like so: /fun/params/optional_parameter

现在,让我们创建一个将接收参数并将其传递给模板的URL,如下所示: /fun/params/optional_parameter

Add these lines to app.py

将这些行添加到app.py

@app.route('/fun/urls/<param>') def fun_url(param=None): return render_template('fun_url.html')

In the first directive, we have a new route that will redirect to our new method. Because we defined a parameter at the end, our method expects that parameter. After that, we return the template with render_template method.

在第一个指令中,我们有一条新的路由,它将重定向到我们的新方法。 因为我们在最后定义了一个参数,所以我们的方法需要该参数。 之后,我们使用render_template方法返回模板。

If you save app.py, and have an active server running it will break with an error of unknown method render_template. This is because we are calling a method that does not exist – or at least it was not imported. In our case, we still need to import this method.

如果保存app.py并有活动的服务器运行,它将因unknown method render_template的错误而中断。 这是因为我们正在调用一个不存在的方法-或至少没有将其导入。 在我们的情况下,我们仍然需要导入此方法。

On top of our file add this:

在我们文件的顶部添加以下内容:

from flask import render_template

By default, Flask expects template files to be located in the templates directory relative to our app.py. So, we need to create a new directory there.

默认情况下,Flask希望模板文件位于相对于我们app.py的模板目录中。 因此,我们需要在此处创建一个新目录。

mkdir templates cd templates touch fun_url.html

Now, if we restart our application

现在,如果我们重新启动应用程序

python app.py * Running on http://127.0.0.1:5000/

And we open a URL like /fun/url/test, we should see an empty page. Please try to add something to that file and restart the server. You should be able to see your updated template file results.

然后我们打开/fun/url/test类的URL,我们应该看到一个空白页面。 请尝试向该文件添加内容,然后重新启动服务器。 您应该能够看到更新的模板文件结果。

Now let’s pass a parameter to the template. Change the render_template line to the following:

现在让我们将参数传递给模板。 将render_template行更改为以下内容:

return render_template('fun_url.html', fun_param=param)

With this, we tell therender_template method to render our template and pass a param into it as fun_param. If we open fun_url.html and add:

这样,我们告诉render_template方法渲染模板并将参数作为fun_param传递给模板。 如果我们打开fun_url.html并添加:

Parameter passed is: {{ fun_param }}

we should get this response after restarting the server:

重新启动服务器后,我们应该得到以下响应:

http://127.0.0.1:5000/fun/url/test Parameter passed is: test http://127.0.0.1:5000/fun/url/test1 Parameter passed is: test1

从这往哪儿走 (Where to go from here)

There are a lot more of things you can do with Flask – this is more of a beginner introduction so you can get a feel for how Flask works. When you start working with databases, user access, REST API – that’s where things get surprisingly simple. For now, the best place to start is the official Flask documentation

Flask可以做很多事情–这更多是初学者的介绍,因此您可以了解Flask的工作方式。 当您开始使用数据库,用户访问,REST API时,事情就变得如此简单。 目前,最好的起点是官方的Flask文档

Also, a really great article that covers almost everything you will need in further development is the Flask Mega-Tutorial.

另外, Flask Mega-Tutorial是一篇非常出色的文章,涵盖了进一步开发所需的几乎所有内容。

Did you like this introduction? Would you like to see more advanced examples? Let me know in the comments!

你喜欢这个介绍吗? 您想查看更多高级示例吗? 在评论中让我知道!

翻译自: https://www.sitepoint.com/flask-masses/

相关资源:jdk-8u281-windows-x64.exe
最新回复(0)