falcon框架_如何使用Falcon构建RESTful API

本文介绍了如何使用Falcon框架快速构建RESTful API。Falcon是一个微框架,具有速度快、代码清晰、可扩展性强等特点。通过创建HTTP资源类,定义REST操作,结合WSGI实现跨Python版本支持。文中通过一个展示当前UTC时间和对应UNIX时间的API示例,详细解释了Falcon的资源定义和服务器设置。掌握Falcon后,可以方便地构建与数据库或消息队列交互的API。
摘要由CSDN通过智能技术生成

falcon框架

介绍 (Introduction)

RESTful APIs are a major component of any well-architected stack, and Python happens to have some brilliant frameworks for quickly composing APIs.

RESTful API是任何结构良好的堆栈的主要组成部分,而Python恰好具有一些出色的框架,可以快速组成API。

One of these frameworks is called Falcon - and it’s great! Essentially a microframework, it ships with a sizable number of advantages:

这些框架之一称为Falcon-太好了! 本质上是微框架,它具有许多优点:

  1. It’s fast. Really fast. Check out the benchmarks here.

    它很快。 真快。 在此处查看基准。

  2. HTTP Resources are defined as classes, with class methods being used for different REST operations on these resources. This helps maintaining a clean codebase.

    HTTP资源被定义为类,其中类方法用于这些资源上的不同REST操作。 这有助于维护干净的代码库。
  3. It’s quite extensible - check out this section on their wiki, to get a feel for it.

    它是相当可扩展的-在他们的Wiki上查看此部分 ,以了解它。

  4. It’s based on WSGI - the Pythonic standard for web apps - so it works with Python 2.6, 2.7, and 3.3+. And if you need more performance, run it using PyPy!

    它基于WSGI(Web应用程序的Pythonic标准),因此可与Python 2.6、2.7和3.3+一起使用。 如果您需要更高的性能,请使用PyPy来运行它!

入门 (Getting started)

First, let’s prepare our environment. Personally, it’s always great to work in virtual environments - you can use virtualenv, virtualenvwrapper or venv. Next, install Falcon using pip: pip install falcon.

首先,让我们准备环境。 就个人而言,在虚拟环境中工作总是很棒–您可以使用virtualenvvirtualenvwrappervenv 。 接下来,使用pip安装Falcon: pip install falcon

We’re going to develop a small sample API that does very basic time-zone manipulations for us. It will display the current time in UTC, as well as the corresponding epoch time. To that end, we’ll grab a nifty library called arrow: pip install arrow.

我们将开发一个小的示例API,为我们执行非常基本的时区操作。 它将以UTC显示当前时间以及相应的纪元时间。 为此,我们将获取一个名为arrow的漂亮库: pip install arrow

You can find the finished sample at https://github.com/rudimk/freecodecamp-guides-rest-api-falcon.

您可以在https://github.com/rudimk/freecodecamp-guides-rest-api-falcon中找到完成的示例。

资源资源 (Resources)

Think of a resource as an entity that your API needs to manipulate. In our case, the best resource would be a Timestamp. Our routing would typically be something like this:

将资源视为您的API需要操纵的实体。 在我们的例子中,最好的资源是Timestamp 。 我们的路由通常如下所示:

GET /timestamp

Here, GET is the HTTP verb used to call this endpoint, and /timestamp is the URL itself. Now that we’ve gotten this bit out of the way, let’s create a module!

此处, GET是用于调用此终结点的HTTP动词,而/timestamp是URL本身。 现在我们已经解决了这一点,让我们创建一个模块!

$ touch timestamp.py

$ touch timestamp.py

Time to import the Falcon library:

是时候导入Falcon库了:

import json

import falcon

import arrow

Note we’ve also import the json package and the arrow library. Now, let’s define a class for our resource:

请注意,我们还导入了json包和arrow库。 现在,让我们为资源定义一个类:

class Timestamp(object):

	def on_get(self, req, resp):
		payload = {}
		payload['utc'] = arrow.utcnow().format('YYYY-MM-DD HH:mm:SS')
		payload['unix'] = arrow.utcnow().timestamp

		resp.body = json.dumps(payload)
		resp.status = falcon.HTTP_200

Let’s go through this snippet. We’ve defined a Timestamp class, and defined a class method called on_get - this function tells Falcon that when a GET request is issued to an endpoint for this resource, run the on_get function and provide the request and response objects as parameters.

让我们看一下这段代码。 我们已经定义了一个Timestamp类,并定义了一个名为on_get的类方法-该函数告诉Falcon,当向该资源的端点发出GET请求时,运行on_get函数并将请求和响应对象作为参数提供。

After that, it’s smooth sailing - we create an empty dictionary, fill it up with the current UTC and UNIX timestamps, convert it to JSON and attach it to the response object.

之后,一切顺利-我们创建一个空字典,用当前的UTC和UNIX时间戳填充它,将其转换为JSON并将其附加到响应对象。

Pretty simple, right? But sadly, that’s not all. We now need to create a Falcon server and hook up the resource class we’ve just defined to an actual endpoint.

很简单,对吧? 但是可悲的是,这还不是全部。 现在,我们需要创建一个Falcon服务器,并将刚刚定义的资源类连接到实际的端点。

$ touch app.py

$ touch app.py

Now, add the code below:

现在,添加以下代码:

import falcon

from timestamp import Timestamp

api = application = falcon.API()

timestamp = Timestamp()

api.add_route('/timestamp', timestamp)

Here, we’ve defined a Falcon API, and initialized an instance of the resource class we created earlier. Then, we’ve hooked up the /timestamp endpoint with the class instance - and now we’re good to go! To test this API install gunicorn(pip install gunicorn), and run gunicorn app. Use Postman or simple cURL to test this:

在这里,我们定义了Falcon API,并初始化了我们先前创建的资源类的实例。 然后,我们将/timestamp端点与类实例连接在一起-现在我们可以开始了! 要测试此API,请安装gunicorn ( pip install gunicorn ),然后运行gunicorn app 。 使用Postman或简单的cURL对此进行测试:

$ curl http://localhost:8000/timestamp                                                    
{"utc": "2017-10-20 06:03:14", "unix": 1508479437}

And that does it!

做到了!

继续 (Moving on)

Once you’ve got the hang of Falcon, composing powerful RESTful APIs that interact with databases or messaging queues is very easy. Do check out the Falcon docs, as well as PyPI for interesting Falcon modules that keep popping up.

一旦掌握了Falcon,就可以轻松构建与数据库或消息传递队列进行交互的强大RESTful API。 请检查Falcon文档以及PyPI,以获取不断弹出的有趣Falcon模块。

翻译自: https://www.freecodecamp.org/news/build-restful-apis-with-falcon/

falcon框架

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值