- 首页
- 正文
建立一个简单hello world的Flask API 应用【翻译】
介绍
在这个教程中,我将会使用 先前教程 的文件结构来创建一个基本的 hello-world Flask 应用,这个应用将会在 api/helloworld/helloworld
中简单地创建一个api终端和用json的格式返回一个 helloworld
的消息
源码
你可以从 github 上下载这个源代码
建立环境和安装需要的依赖
让我们先创建一个应用的文件夹。为达到目的,我将会指定我们的应用为 DoubleDibz
$ cd [to where you want your application folder to be]
$ mkdir DoubleDibz
在创建更多的文件夹和文件之前,我们需要先建立一个环境。在这里我假定你已经安装了 python
,pip
,和 virtualenv
。如果你没有,请看 这里。通常,最好不要把依赖项安装在python的全局包里,而是为你的每个应用程序创建一个隔离环境来进行安装。
为 DoubleDibz 创建虚拟的环境,可以这样做:
$ cd DoubleDibz
$ virtualenv .pyenv
New python executable in .pyenv/bin/python
Installing setuptools, pip...done.
现在虚拟环境在 .pyenv
文件夹里。让我们来激活这个环境!
$ source .pyenv/bin/activate
在这一刻,虚拟环境 .pyenv
应该会出现在你的命令提示符的左侧
(.pyenv)UserName@Your-Computer:Some-folder/DoubleDibz $
从现在开始,通过pip安装的任何包都会被安装到跟本地的 .pyenv
文件夹里,它是跟全局的依赖是分开的。 好的,现在让我们继续安装我们需要的应用程序。
$ pip install Flask
$ pip freeze > requirements.txt
$ cat requirements.txt
Flask==0.10.1
Jinja2==2.8
MarkupSafe==0.23
Werkzeug==0.10.4
itsdangerous==0.24
wsgiref==0.1.2
现在我们已经为应用程序安装了所有需要的依赖项。你可以通过在当前环境中用 pip freeze
命令看见所有已经安装包的列表和版本,请注意我们是怎么保存输出到 requirements.txt
文件的。这允许您或其他开发人员重新创建相同的环境,以确保开发和部署的一致性(在实际服务器上安装依赖项)
$ pip install -r requirements.txt
记住要从你的版本控制中添加忽略列表(如果你是使用git的,就用 .gitignore
)来排队这个虚拟环境(.pyenv
或者你自己命名的)
第一步:创建文件的布局
mkdir app
mkdir app/templates
mkdir app/static
mkdir app/frontend
mkdir app/common
mkdir app/api # 注意这是文章中缺少的
touch run.py
touch app/__init__.py
touch app/config.py
touch app/app.py
touch app/extensions.py
touch app/api/helloworld.py
touch app/api/__init__.py
touch app/common/constants.py
touch app/common/__init__.py
我们当前的结构:
DoubleDibz
├── app
│ ├── __init__.py
│ ├── api
│ │ ├── __init__.py
│ │ └── helloworld.py
│ ├── app.py
│ ├── common
│ │ ├── __init__.py
│ │ └── constants.py
│ ├── config.py
│ ├── extensions.py
│ ├── static
│ └── templates
└── run.py
第二步:编辑 app/app.py
让我们从应用程序的核心功能开始。
$ vim app/app.py
import os
from flask import Flask
import config as Config
from .common import constants as COMMON_CONSTANTS
from .api import helloworld
# For import *
__all__ = ['create_app']
DEFAULT_BLUEPRINTS = [
helloworld
]
def create_app(config=None, app_name=None, blueprints=None):
"""Create a Flask app."""
if app_name is None:
app_name = Config.DefaultConfig.PROJECT
if blueprints is None:
blueprints = DEFAULT_BLUEPRINTS
app = Flask(app_name, instance_path=COMMON_CONSTANTS.INSTANCE_FOLDER_PATH, instance_relative_config=True)
configure_app(app, config)
configure_hook(app)
configure_blueprints(app, blueprints)
configure_extensions(app)
configure_logging(app)
configure_error_handlers(app)
return app
def configure_app(app, config=None):
"""Different ways of configurations."""
# http://flask.pocoo.org/docs/api/#configuration
app.config.from_object(Config.DefaultConfig)
if config:
app.config.from_object(config)
return
# get mode from os environment
application_mode = os.getenv('APPLICATION_MODE', 'LOCAL')
app.config.from_object(Config.get_config(application_mode))
def configure_extensions(app):
pass
def configure_blueprints(app, blueprints):
for blueprint in blueprints:
app.register_blueprint(blueprint)
def configure_logging(app):
pass
def configure_hook(app):
@app.before_request
def before_request():
pass
def configure_error_handlers(app):
# example
@app.errorhandler(500)
def server_error_page(error):
return "ERROR PAGE!"
app/app.py
所暴露的函数 create_app
是用所希望的配置来建立 Flask 应用。这个文件抽象出了在多阶段中配置的过程
configure_app
: 用正确的配置方式初始化Flask应用程序。我用了3种配置方式来建立我的应用程序:本地的,分期的和生产(见app/config.py
)。此函数将尝试使用传入配置对象或者从环境变量识别模式来加载正确的模式(这种对于配置阶段和生产服务器是最灵活的)configure_blueprints
: 登记给定蓝图模式列表的应用程序。常用的工厂设计模式把应用程序分解成多个蓝图模块,从而大大简化了复杂性。configure_extensions
: 初始化扩展应用程序。稍后我们将会看到怎么样使用这些函数来初始化 Flask-WTF, Flask-Script and Flask-SQLAlchemy.configure_logging
: 配置我们想记录数据的方式。根据环境,我们将会采取不同的方法。例如,当在本地测试,你可能只是想在标准输出控制台查看数据,但对于生产服务器,你想保存一些日志文件。configure_hook
: 这个有点不太具体。通常,我用它来处理请求和响应。例如,我使用它来记录每一次传入的请求或者计算服务器为每个请求生成响应所需要的时间。def configure_hook(app): // log every incoming requests @app.before_request def before_request(): app.logger.debug('Hitting %s' % request.url)
configure_error_handlers
:设置我们怎么处理错误。为了达到这个目的,我们将在 API 的 json 格式中返回错误信息
第三步:编辑 app/config.py
$ vim app/config.py
import os
from common.constants import INSTANCE_FOLDER_PATH
class BaseConfig(object):
PROJECT = "app"
# Get app root path, also can use flask.root_path.
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DEBUG = False
TESTING = False
ADMINS = ['youremail@yourdomain.com']
# http://flask.pocoo.org/docs/quickstart/#sessions
SECRET_KEY = 'secret key'
class DefaultConfig(BaseConfig):
# Statement for enabling the development environment
DEBUG = True
# Secret key for signing cookies
SECRET_KEY = 'development key'
class LocalConfig(DefaultConfig):
# config for local development
pass
class StagingConfig(DefaultConfig):
# config for staging environment
pass
class ProdConfig(DefaultConfig):
# config for production environment
pass
def get_config(MODE):
SWITCH = {
'LOCAL' : LocalConfig,
'STAGING' : StagingConfig,
'PRODUCTION': ProdConfig
}
return SWITCH[MODE]
这里的目标是有足够的灵活性适应不同的环境。你可以看到,我们已经有三个配置模式: LocalConfig
, StagingConfig
和ProdConfig
。所有的都是继承自 DefaultConfig
文件,定义了一系列标准设置,比如说项目根目录和项目名。
第四步:建立 helloworld 终端
现在你有所有的基础知识和最后一步就你要创建API终端
$ vim app/api/helloworld.py
"""
Simple API endpoint for returning helloworld
"""
from flask import (Blueprint, render_template, current_app, request,
flash, url_for, redirect, session, abort, jsonify, make_response)
helloworld = Blueprint('helloworld', __name__, url_prefix='/api/helloworld')
@helloworld.route('/helloworld', methods=['GET'])
def index():
data = {
'message' : "helloworld"
}
return make_response(jsonify(data))
第三步: 创建 __init__
文件
对于我们创建的每一个目录,我们需要创建一个 __init__.py
文件来标记这个目录是一个 python 的包。__init__.py
通常是空的,但是能够用它来暴露包的选定部分或者重命名他们为更方便更具体的名字。
$ vim app/__init__.py
from app import create_app
$ vim app/api/__init__.py
from .helloworld import helloworld
这将会创建一个API包来公开不同的API蓝图,而不显示单个文件或者实现的细节。这允许 app.py
从 api/
目录导入 helloworld
的蓝图
// in app.py
from .api import helloworld
// instead of loading from the specific api file
from .api.helloworld import helloworld
每六步,编辑 constants.py
这个 app/common/
目录存储的是为我们创建的每一个模块所需要的常量、函数和对象(因此通用名称)。现在,我们只需要一个 constants.py
文件。
$ vim app/common/constants.py
将下面的内容定义为实例目录的路径
Place the following content that defines the directory path for the instance folder.
import os
# Instance folder path, make it independent.
INSTANCE_FOLDER_PATH = os.path.join('/tmp', 'instance')
第七步:运行并查看!
当冷你运行本地的服务器,我们将使用 run.py
$ vim run.py
如下内容:
import os
from app import create_app
app = create_app()
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host='0.0.0.0', port=port, debug=True)
运行这个文件将会创建一个本地的5000端口的 Flask 服务
$ python run.py
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
现在你可以点击浏览器的地址:http://localhost:5000/api/helloworld/helloworld 来查看 API 终端是否正确的运行。另外,你也可以用 curl 来测试:
$ curl http://localhost:5000/api/helloworld/helloworld
{
"message": "helloworld"
}
是的,运行得很好!干得好。现在你已经成功地用合适的结构来建立了一个基本的 Flask 应用程序。现在让我们在下一章节中得到更高级的内容,在 Flask 中创建用户认证。
参考网站
【上一篇】Linux下的find命令详解