falcon框架
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-太好了! 本质上是微框架,它具有许多优点:
It’s fast. Really fast. Check out the benchmarks here. 它很快。 真快。 在此处查看基准。
HTTP Resources are defined as classes, with class methods being used for different REST operations on these resources. This helps maintaining a clean codebase.
It’s quite extensible - check out this section on their wiki, to get a feel for it. 它是相当可扩展的-在他们的Wiki上查看此部分 ,以了解它。
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!
入门 (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.
首先,让我们准备环境。 就个人而言,在虚拟环境中工作总是很棒–您可以使用virtualenv , virtualenvwrapper或venv 。 接下来,使用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框架