Great things are done by a series of small things brought together – Vincent Van Gogh
伟大的事情由一系列小事情共同完成 – Vincent Van Gogh
This article's intention is to provide a easy-to-follow project-based process on how to create a RESTful API using the Flask framework.
本文旨在提供一个易于遵循的基于项目的过程,说明如何使用Flask框架创建RESTful API。
为什么选择烧瓶? (Why Flask?)
A bit of context – I've written a bunch of articles on Django-driven RESTful APIs. Though a great resource for Django enthusiasts, not everyone wants to code in Django. Besides, it's always good to acquaint yourself with other frameworks.
一些背景信息–我写了很多关于Django驱动的RESTful API的文章。 尽管这对Django爱好者来说是一个很好的资源,但并不是每个人都想在Django中进行编码。 此外,熟悉其他框架始终是一件好事。
Learning Flask is easier and faster. It's super easy to setup and get things running. Unlike Django (which is heavier), you'll never have functionality lying around that you aren't using.
学习Flask更容易,更快捷。 设置和运行程序超级容易。 与Django(较重)不同,您永远不会拥有不使用的功能。
Typical of all our web apps, we'll use the TDD approach. It's really simple. Here's how we do Test Driven Development:
在所有网络应用程序中,典型的做法是使用TDD方法。 真的很简单。 这是我们进行测试驱动开发的方法:
- Write a test. – The test will help flesh out some functionality in our app 编写测试。 –测试将有助于充实我们应用程序中的某些功能
- Then, run the test – The test should fail, since there's no code(yet) to make it pass. 然后,运行测试–测试应该失败,因为还没有代码可以通过。
- Write the code – To make the test pass 编写代码–通过测试
- Run the test – If it passes, we are confident that the code we've written meets the test requirements 运行测试–如果通过,我们有信心我们编写的代码符合测试要求
- Refactor code – Remove duplication, prune large objects and make the code more readable. Re-run the tests every time we refactor our code 重构代码–删除重复项,修剪大对象并使代码更具可读性。 每次我们重构代码时都重新运行测试
- Repeat – That's it! 重复–就这样!
我们将创造什么 ( What we'll create )
We're going to develop an API for a bucketlist. A bucketlist is a list of all the goals you want to achieve, dreams you want to fulfill and life experiences you desire to experience before you die (or hit the bucket). The API shall therefore have the ability to:
我们将为存储清单开发API。 遗愿清单是您要实现的所有目标,想要实现的梦想以及想要在去世(或遭受打击)之前经历的生活经验的列表。 因此,API应具有以下能力:
- Create a bucketlist (by giving it a name/title) 创建存储区列表(通过为其命名/标题)
- Retrieve an existing bucketlist 检索现有的存储桶列表
- Update it (by changing it's name/title) 更新(通过更改名称/标题)
- Delete an existing bucketlist 删除现有的存储区列表
先决条件 (Prerequisites)
- Python3 - A programming language that lets us work more quickly (The universe loves speed!). Python3-一种编程语言,它使我们可以更快地工作(Universe喜欢速度!)。
- Flask - A microframework for Python based on Werkzeug, Jinja 2 and good intentions Flask-基于Werkzeug,Jinja 2和良好意图的Python微框架
- Virtualenv - A tool to create isolated virtual environments Virtualenv-创建隔离虚拟环境的工具
Let's start with configuring our Flask app structure!
让我们从配置Flask应用程序结构开始!
虚拟环境 ( Virtual Environment )
First, we'll create our application directory. On the terminal, create an empty directory called bucketlist with mkdir bucketlist
. Then, Cd
into the directory. Create an isolated virtual environment:
首先,我们将创建应用程序目录。 在终端上,使用mkdir bucketlist
创建一个名为bucketlist的空目录。 然后,将Cd
放入目录。 创建一个隔离的虚拟环境:
$ virtualenv venv
Install Autoenv globally using pip install autoenv
Here's why – Autoenv helps us to set commands that will run every time we cd
into our directory. It reads the .env
file and executes for us whatever is in there.
使用pip install autoenv
autoenv 全局 pip install autoenv
的原因-Autoenv帮助我们设置每次cd
进入目录时都会运行的命令。 它读取.env
文件并为我们执行其中的任何内容。
Create a .env
file and add the following:
创建一个.env
文件并添加以下内容:
source env/bin/activate
export FLASK_APP="run.py"
export SECRET="some-very-long-string-of-random-characters-CHANGE-TO-YOUR-LIKING"
export APP_SETTINGS="development"
export DATABASE_URL="postgresql://localhost/flask_api"
The first line activates our virtual environment venv
that we just created. Line 2, 3 and 4 export our FLASK_APP, SECRET, APP_SETTINGS and DATABASE_URL
variables. We'll integrate these variables as we progress through the development process.
第一行激活我们刚刚创建的虚拟环境venv
。 第2、3和4行导出我们的FLASK_APP, SECRET, APP_SETTINGS and DATABASE_URL
变量。 在开发过程中,我们将整合这些变量。
Run the following to update and refresh your .bashrc:
运行以下命令以更新和刷新.bashrc:
$echo "source `which activate.sh`" >> ~/.bashrc
$ source ~/.bashrc
You will see something like this on your terminal
![](https://scotch-res.cloudinary.com/image/upload/w_auto,q_auto:good,f_auto/media/11238/3FKxYAQSm69xD75mXg7g_Screenshot%202017-04-19%2016.51.42.png)
您会在终端上看到类似的内容
Sometimes autoenv
might not work if you have zsh installed. A good workaround would be to simply source the .env
file and we are set.
如果安装了zsh,有时autoenv
可能无法正常工作。 一个好的解决方法是简单地获取.env
文件,然后设置好。
$source .env
Conversely, if you don't want to automate things for the long run, you don't have to use autoenv
. A simple export directly from the terminal would do.
相反,如果您不想长期实现自动化,则不必使用autoenv
。 直接从终端进行简单导出即可。
$export FLASK_APP="run.py"
$ export APP_SETTINGS="development"
$ export SECRET="a-long-string-of-random-characters-CHANGE-TO-YOUR-LIKING"
$ export DATABASE_URL="postgresql://localhost/flask_api"
Inside our virtual environment, we'll create a bunch of files to lay out our app directory stucture. Here's what it should look like:
在我们的虚拟环境中,我们将创建一堆文件来布置我们的应用程序目录结构。 它应该是这样的:
├── bucketlist(this is the directory we cd into)
├── app
│ ├── __init__.py
│ └── models.py
├── instance
│ └── __init__.py
├── manage.py
├── requirements.txt
├── run.py
└── test_bucketlist.py
After doing this, install Flask using pip.
完成之后,使用pip安装Flask。
(venv)$ pip install flask
环境配置 ( Environment Configurations )
Flask needs some sought of configuration to be available before the app starts. Since environments (development, production or testing) require specific settings to be configured, we'll have to set environment-specific things such as a secret key
, debug mode
and test mode
in our configurations file.
在应用启动之前,Flask需要一些寻求的配置才可用。 由于环境(开发,生产或测试)需要配置特定的设置,因此我们必须在配置文件中设置特定于环境的内容,例如secret key
, debug mode
和test mode
。
If you haven't already, create a directory and call it instance. Inside this directory, create a file called config.py and also init.py. Inside our config file, we'll add the following code:
如果尚未创建目录,则将其命名为instance 。 在这个目录里,创建一个名为config.py并初始化的.py。 在我们的配置文件中,我们将添加以下代码:
# /instance/config.py
import os
class Config(object):
"""Parent configuration class."""
DEBUG = False
CSRF_ENABLED = True
SECRET = os.getenv('SECRET')
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
class DevelopmentConfig(Config):
"""Configurations for Development."""
DEBUG = True
class TestingConfig(Config):
"""Configurations for Testing, with a separate test database."""
TESTING = True
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/test_db'
DEBUG = True
class StagingConfig(Config):
"""Configurations for Staging."""
DEBUG = True
class ProductionConfig(Config):
"""Configurations for Production."""
DEBUG = False
TESTING = False
app_config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'staging': StagingConfig,
'production': ProductionConfig,
}
The Config
class contains the general settings that we want all environments to have by default. Other environment classes inherit from it and can be used to set settings that are only unique to them. Additionally, the dictionary app_config
is used to export the 4 environments we've specified. It's convenient to have it so that we can import the config under its name tag in future.
Config
类包含我们希望所有环境默认具有的常规设置。 其他环境类继承自它,并且可以用于设置仅对它们唯一的设置。 此外,字典app_config
用于导出我们指定的4个环境。 拥有它很方便,以便将来我们可以在其名称标签下导入配置。
A couple of config variables to note:
需要注意几个配置变量:
- The SECRET_KEY – is a random string of characters that's used to generate hashes that secure various things in an app. It should never be public to prevent malicious attackers from accessing it. SECRET_KEY –是一个随机的字符串,用于生成可保护应用程序中各种内容的哈希。 它不应该是公共的,以防止恶意攻击者访问它。
- DEBUG – tells the app to run under debugg