Liệp ưng dàn giáo tóm tắt

Falcon là một cái nhẹ lượng cấp Python Web API dàn giáo, chuyên chú với xây dựng cao tính năng cải trang vụ cùng ứng dụng sau đoan. Bổn giáo trình đem dẫn đường người đọc hiểu biết Falcon chủ yếu đặc tính, cũng thông qua ví dụ thực tế triển lãm như thế nào trang bị cùng sáng tạo một cái đơn giản RESTful API.
Trích yếu từ CSDN thông qua trí năng kỹ thuật sinh thành

Falcon is a light-weight Python web API framework for building high-performance microservices, app backends, and higher-level frameworks. This tutorial will give an introduction to Falcon, its major features, and how to install Falcon. We’ll also build a simple RESTful API with Falcon.

Falcon là một cái nhẹ lượng cấp Python Web API dàn giáo, dùng cho xây dựng cao tính năng cải trang vụ, ứng dụng trình tự sau đoan cùng càng cao cấp bậc dàn giáo. Bổn giáo trình đem giới thiệu Falcon, này chủ yếu công năng cùng với như thế nào trang bị Falcon. Chúng ta còn đem sử dụng Falcon xây dựng một cái đơn giản RESTful API.

Falcon cùng mặt khác dàn giáo so sánh với ưu thế(Advantages of Falcon Compared to Other Frameworks)

According to thedocumentation,some of the features of Falcon that make it superior to other Python frameworks include:

Căn cứHồ sơ,Falcon làm này trội hơn mặt khác Python dàn giáo một ít công năng bao gồm:

SpeedFalcon requests work several times faster than most other Python frameworks. Additionally, Falcon works well when combined withCython,giving it an extra speed boost; it also works well withPyPy.

Tốc độFalcon thỉnh cầu công tác tốc độ so đại đa số mặt khác Python dàn giáo mau vài lần. Ngoài ra, Falcon cùngCythonKết hợp sử dụng khi hiệu quả thực hảo, do đó có thể thêm vào đề cao tốc độ. Nó cũng có thể cùngPyPy cùng nhau sử dụng.

Flexibility— Falcon leaves a lot of the implementation details to you, the developer; hence there’s freedom to customize your implementation.

Linh hoạt tính- liệp ưng hướng khai phá nhân viên để lại rất nhiều thực thi chi tiết; bởi vậy, có thể tự do định chế ngài thực hiện.

Ease of debugging— In Falcon, logic paths are understandable and straightforward, which makes it easier to reason with the code and perform code debugging.

Dễ dàng điều chỉnh thử- ở Falcon trung, logic đường nhỏ là dễ dàng lý giải cùng trực tiếp, cảnh này khiến đối số hiệu tiến hành trinh thám cùng chấp hành số hiệu điều chỉnh thử càng thêm dễ dàng.

Đặc thù(Features)

  • Highly-optimized code base

    Độ cao ưu hoá số hiệu kho
  • Intuitive routing via URI templates and REST-inspired resource classes

    Thông qua URI khuôn mẫu cùng chịu REST dẫn dắt tài nguyên loại tiến hành trực quan lộ từ
  • Easy access to headers and bodies through request and response classes

    Thông qua thỉnh cầu cùng hưởng ứng loại nhẹ nhàng phỏng vấn tiêu đầu cùng chính văn
  • DRY request processing via middleware components and hooks

    Thông qua trung gian kiện lắp ráp cùng móc nối tiến hành DRY thỉnh cầu xử lý
  • Idiomatic HTTP error responses

    Quen dùng HTTP sai lầm hưởng ứng
  • Straightforward exception handling

    Đơn giản dị thường xử lý

Sử dụng Falcon xây dựng RESTful API(Building a RESTful API With Falcon)

In this example, you will build a bucket list API. Abucket listis simply a list of things you’d like to do before you die. Let’s get started. Create the project directory and set up a virtual environment.

Tại đây thí dụ mẫu trung, ngài đem xây dựng tồn trữ thùng danh sách API.Di nguyện danh sáchChỉ là tử vong trước ngài muốn làm sự tình danh sách. Làm chúng ta bắt đầu đi. Sáng tạo hạng mục mục lục cũng thiết trí giả thuyết hoàn cảnh.

mkdir bucketlist
cd bucketlist
virtualenv.venv
source.venv/bin/activate

Trang bị liệp ưng(Install Falcon)

Installing Falcon is as simple as:

Trang bị Falcon phi thường đơn giản:

pip install falcon

Create another folderappinside thebucketlistdirectory and mark it as a Python module by creating an empty__init__.pyfile in it:

bucketlistMục lục trung sáng tạo một cái khác folderapp,Cũng thông qua ở trong đó sáng tạo một cái trống không__init__.pyVăn kiện đem này đánh dấu vì Python mô khối:

mkdir app
touch app/__init__.py

Inside the app folder, create a filemain.pyand add the following code.

Ở app folder trung, sáng tạo văn kiệnmain.pyCũng tăng thêm dưới số hiệu.

import falcon
application = falcon.API()
if __name__ == "__main__":
application.run(host= "0.0.0.0", debug=True)

Falcon framework uses the concept of a resource. Resources are things that can be accessed by a URL. We will discuss this further when we start building the views for our application.

Falcon dàn giáo sử dụng tài nguyên khái niệm. Tài nguyên là có thể thông qua URL phỏng vấn đồ vật. Khi chúng ta bắt đầu vì ứng dụng trình tự xây dựng đồ thị hình chiếu khi, chúng ta đem tiến thêm một bước thảo luận.

Editmain.pyfile to look something like this:

Biên tậpmain.pyVăn kiện, như sau sở kỳ:

import falcon
import json


class IndexResource(object):
def on_get(self, req, res):
res.status = falcon.HTTP_200
res.body = json.dumps({ "success": "My first falcon app" })




application = falcon.API()
application.add_route('/', IndexResource())




if __name__ == "__main__":
application.run(host= "0.0.0.0", debug=True)

Falcon speaks WSGI, and so to serve a Falcon app, you will need a WSGI server. In this tutorial, we will be usingGunicornto serve our app, so let’s install Gunicorn.

Falcon nói WSGI, bởi vậy muốn cung cấp Falcon ứng dụng trình tự, ngài đem yêu cầu WSGI server. Ở bổn giáo trình trung, chúng ta đem sử dụngGunicornPhục vụ chúng ta ứng dụng trình tự, bởi vậy làm chúng ta trang bị Gunicorn.

pip install gunicorn

Now run your application by issuinggunicorn -b 0.0.0.0:8000 — reload main:application.Navigate tohttp://127.0.0.1,and you should see your representation of theIndexResource.

Hiện tại, thông qua phát ragunicorn -b 0.0.0.0:8000 — reload main:applicationVận hành ngài ứng dụnggunicorn -b 0.0.0.0:8000 — reload main:application.Hướng dẫn đếnhttp://127.0.0.1,Ngài hẳn là nhìn đếnIndexResourceTỏ vẻIndexResource.

Image for post

Let’s now get started on creating the blocks for our application:

Hiện tại làm chúng ta bắt đầu cho chúng ta ứng dụng trình tự sáng tạo khối:

Phối trí cơ sở dữ liệu(Configure database)

We will use thePostgreSQLdatabase because it’s robust and stable.

Chúng ta đem sử dụngPostgreSQLCơ sở dữ liệu, bởi vì nó đã cường tráng lại ổn định.

PostgreSQL should be installed on your machine. Install the psycopg2 driver library in our application

PostgreSQL hẳn là trang bị ở ngài máy móc thượng. Ở chúng ta ứng dụng trình tự trung trang bị psycopg2 điều khiển trình tự kho

pip install psycopg2

Sáng tạo cơ sở dữ liệu cùng người dùng(Create database and user)

Create a database “bucketlist” and assign a user.

Sáng tạo một số liệu kho “bucketlist” cũng phân phối một người dùng.

Switch over to the Postgres account on your machine by typing:

Thông qua đưa vào dưới mệnh lệnh cắt đến máy tính thượng Postgres tài khoản:

sudo su postgres

Access a Postgres prompt:

Phỏng vấn Postgres nhắc nhở:

psql

Create bucketlist database:

Sáng tạo tồn trữ thùng danh sách cơ sở dữ liệu:

CREATE DATABASE bucketlist;

Create role:

Sáng tạo nhân vật:

CREATE ROLE pat WITH LOGIN PASSWORD ‘my_password’;

Grant access to the user:

Hướng người dùng trao tặng phỏng vấn quyền hạn:

GRANT ALL PRIVILEGES ON DATABASE bucketlist TO pat;

We will use theSQLAlchemyextension to manage our application. This extension provides an ORM wrapper for the SQLAlchemy project.

Chúng ta đem sử dụngSQLAlchemyMở rộng tới quản lý chúng ta ứng dụng trình tự. Nên mở rộng vì SQLAlchemy hạng mục cung cấp một cái ORM đóng gói khí.

Create a fileconfig.pyin the app directory and add the configurations you set up for the database above. The config file should look something like this.

Ở app mục lục trung sáng tạo một văn kiệnconfig.py,Cũng ở mặt trên tăng thêm ngài vì số liệu kho thiết trí phối trí. Phối trí văn kiện ứng như sau sở kỳ.

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
import logging


DATABASE_URL = 'postgresql+psycopg2://pat:my_password@localhost/bucketlist'
DB_ECHO = False
DB_AUTOCOMMIT = True




def get_engine(uri):
logging.info('Connecting to database..')
options = {
'echo': DB_ECHO,
'execution_options': {
'autocommit': DB_AUTOCOMMIT
}
}
return create_engine(uri, **options)




db_session = scoped_session(sessionmaker())
engine = get_engine(DATABASE_URL)

Thành lập mô hình(Create models)

Create a filemodels.pyin the app directory and write the following code.

Ở ứng dụng mục lục trung sáng tạo một văn kiệnmodels.pyCũng biên soạn dưới số hiệu.

from sqlalchemy import Column, Integer, String
from sqlalchemy import DateTime, func
from sqlalchemy.ext.declarative import declarative_base, declared_attr
import datetime




class BaseModel(object):
@declared_attr
def __tablename__(self):
return self.__name__.lower()




def to_dict(self):
intersection = set(self.__table__.columns.keys()) & set(self.FIELDS)
return dict(map(
lambda key:
(key,
(lambda value: self.FIELDS[key](value) if value else None)
(getattr(self, key))),
intersection))




FIELDS = {}


Base = declarative_base(cls=BaseModel)








class Task(Base):
id = Column(Integer, primary_key=True)
task_name = Column(String(50), nullable=False)
created = Column(DateTime, default=datetime.datetime.utcnow)
modified = Column(DateTime, default=datetime.datetime.utcnow)




def __repr__(self):
return "<Task(task_name='%s',is_finished='%s')>" % \
(self.task_name, self.is_finished)




FIELDS = {
'task_name': str,
}




FIELDS.update(Base.FIELDS)

Here we declare a base class that all schema objects will inherit from. Theto_dictfunction will manage our queries by returning results in dictionary form.

Ở chỗ này, chúng ta thanh minh sở hữu hình thức đối tượng đều đem kế thừa cơ loại.to_dictHàm số đem thông qua lấy từ điển hình thức phản hồi kết quả tới quản lý chúng ta tuần tra.

Thedeclarative_base()returns a new base class from which all mapped classes should inherit.

declarative_base()Phản hồi một cái tân cơ loại, sở hữu chiếu rọi loại đều đồng ý nên cơ loại kế thừa.

Inconfig.py,update the file to use our models. Here we use the base class from our models to declare metadata that will be used to issueCREATEstatements for all tables in our models.

config.py,Đổi mới văn kiện lấy sử dụng chúng ta mô hình. Ở chỗ này, chúng ta sử dụng mô hình trung cơ loại thanh minh nguyên số liệu, nên nguyên số liệu đem dùng cho vì mô hình trung sở hữu biểu phát raCREATECâu nói.

#app/config.py
.....
def init_session():
db_session.configure(bind=engine)
from app.models import Base
Base.metadata.create_all(engine)

Thỉnh cầu cùng đáp lại(Requests and responses)

Each responder in a resource receives a Request object that can be used to read the headers, query parameters, and body of the request.

Tài nguyên trung mỗi cái hưởng ứng giả đều sẽ thu được một cái Request đối tượng, nên đối tượng nhưng dùng cho đọc lấy tiêu đầu, tuần tra tham số cùng thỉnh cầu chính văn.

HTTP request and HTTP response are represented byreqandresp,respectively.

HTTP thỉnh cầu cùng HTTP hưởng ứng phân biệt từreqCùngrespTỏ vẻ.

Sáng tạo dùng cho quản lý thỉnh cầu cùng hưởng ứng trung gian kiện(Create middleware for managing requests and responses)

A middleware is a Python class that hooks into the request/response lifecycle.

Trung gian kiện là liên tiếp đến thỉnh cầu / hưởng ứng sinh mệnh chu kỳ Python loại.

Create a new filemiddleware.pyin the app directory and add the following middleware class:

Sáng tạo một cái tân văn kiệnmiddleware.pyỞ app mục lục trung, cũng tăng thêm dưới trung gian kiện loại:

# app/middleware.py


import json
class JSONTranslator(object):
def process_request(self, req, resp):
if req.content_length in (None, 0):
# Nothing to do
return


body = req.stream.read()


if not body:
raise falcon.HTTPBadRequest('Empty request body',
'A valid JSON is required.')




try:
req.context['doc'] = json.loads(body.decode('utf-8'))




except (ValueError, UnicodeDecodeError):
raise falcon.HTTPError(falcon.HTTP_753,
'Malformed JSON',
'Could not decode the request body.')




def process_response(self, req, resp, resource):
if 'result' not in resp.context:
return


resp.body = json.dumps(resp.context['result'])

The class above demonstrates how to read headers and query parameters, handle errors, and how to work with request and response bodies.

Mặt trên loại biểu thị như thế nào đọc lấy tiêu đầu cùng tuần tra tham số, như thế nào xử lý sai lầm cùng với như thế nào sử dụng thỉnh cầu cùng hưởng ứng chủ thể.

Phối trí WSGI server lấy đang download gian kiện cũng khởi động lại cơ sở dữ liệu(Configure WSGI server to load the middleware and initialize the database)

Edit themain.pyfile to include the middleware, and initialize the database as shown below.

Biên tậpmain.pyVăn kiện lấy bao hàm trung gian kiện, cũng như sau sở kỳ khởi động lại cơ sở dữ liệu.

import falcon
from app.config import db_session, init_session
from app.views import JSONTranslator


application = falcon.API(middleware=[
JSONTranslator()
])


init_session()
if __name__ == "__main__":
application.run(host= "127.0.0.1", debug=True)

Sáng tạo tài nguyên(Create resources)

As we mentioned at the beginning of this tutorial, Falcon uses the concept of a resource, and Python classes usually represent these resources. They convert the incoming response into an action and deliver a response back to the client.

Chính như chúng ta ở bổn giáo trình bắt đầu khi nhắc tới như vậy, Falcon sử dụng tài nguyên khái niệm, Python loại thông thường tỏ vẻ này đó tài nguyên. Bọn họ đem truyền vào hưởng ứng thay đổi vì thao tác, sau đó đem hưởng ứng truyền lại hồi bản cài đặt.

For a resource to provide support for any HTTP method, you add anon_*()method to the class, where*is any one of the common HTTP methods, in lowercase, i.e.,on_get(),on_put(),etc.

Vì sử tài nguyên duy trì bất luận cái gì HTTP phương pháp, thỉnh đemon_*()Phương pháp tăng thêm đến loại trung, trong đó*Là thường dùng HTTP phương pháp trung bất luận cái gì một loại, đều sử dụng viết thường hình thức, tứcon_get(),on_put()Chờ.

Although resources are just regular classes, we are going to create a custom base class,BaseResource,from which we will inherit when we start creating our resources.

Cứ việc tài nguyên chỉ là thường quy loại, nhưng chúng ta đem sáng tạo một cái tự định nghĩa cơ loạiBaseResource,Khi chúng ta bắt đầu sáng tạo tài nguyên khi, đem từ nên cơ loại kế thừa.

Let’s start by creating a tasksresource. Inapp/views.pyadd the following code to:

Làm chúng ta từ sáng tạo nhiệm vụ bắt đầuTài nguyên. Ởapp/views.pyĐem dưới số hiệu tăng thêm đến:

import falcon
from app.models import Task
from app.config import db_session


try:
from collections import OrderedDict
except ImportError:
OrderedDict = dict


class BaseResource(object):
def success(self, resp, data=None):
resp.status = falcon.HTTP_200
obj = OrderedDict()
obj['status'] = 200
obj['data'] = data
obj['message'] = 'OK'
resp.body = json.dumps(obj)




class TaskResource(BaseResource):


def on_get(self, req, resp):
tasks = db_session.query(Task).all()
obj = [task.to_dict() for task in tasks]
self.success(resp, obj)


def on_post(self, req, resp):
task_details = req.context['doc']
task = Task(task_name=task_details['task_name'])
db_session.add(task)
self.success(resp, "Task created successfullly" )

TheTaskResourcedefines two methods,on_get()for obtaining all the recorded tasks andon_post()for adding a new task.

TaskResourceĐịnh nghĩa hai loại phương pháp,on_get()Dùng cho thu hoạch sở hữu ký lục nhiệm vụ, cùng vớion_post()Dùng cho tăng thêm tân nhiệm vụ.

Thành lập địa chỉ web(Create URLs)

URLs provide a way for the client to identify resources uniquely.

URL vì bản cài đặt cung cấp một loại duy nhất đánh dấu tài nguyên phương pháp.

Edit themain.pyfile to include the URL for theTaskResourceas follows:

Biên tậpmain.pyVăn kiện lấy bao gồm địa chỉ webTaskResourceNhư sau:

from app import views
application.add_route(‘/tasks/’, views.TaskResource())

Now, when a request comes in for/tasks,Falcon will call the responder on the task’s resource that corresponds to the requested HTTP method.

Hiện tại, đương thỉnh cầu/tasks,Falcon đem ở cùng thỉnh cầu HTTP phương pháp tương đối ứng nhiệm vụ tài nguyên thượng thuyên chuyển hưởng ứng giả.

The project’s structure should now look like this:

Nên hạng mục kết cấu hiện tại ứng như sau sở kỳ:

Image for post

Navigate tohttp://localhost:8000/tasksand see your resource in action.

Hướng dẫn đếnhttp://localhost:8000/tasksCũng xem xét đang ở sử dụng tài nguyên.

Tăng thêm nhiệm vụ(Add a task)

Image for post

Xem xét nhiệm vụ(View tasks)

Image for post

Móc(Hooks)

Hooks in Falcon are similar to Python decorators.

Falcon trung móc cùng loại với Python trang trí khí.

Suppose our application required the user to be logged in before they could add or view tasks. We would implement this with abeforehook.

Giả thiết chúng ta ứng dụng trình tự yêu cầu người dùng giành trước lục, sau đó mới có thể tăng thêm hoặc xem xét nhiệm vụ. Chúng ta đem sử dụng một cáibeforeMóc thực hiện nó.

Let’s create a hook that will run before each request to view or add a task.

Làm chúng ta sáng tạo một cái móc nối, nên móc nối đem ở mỗi cái xem xét hoặc tăng thêm nhiệm vụ thỉnh cầu phía trước vận hành.

Next, we attach the hook to theon_post()responder andon_get()responders, as shown below.

Kế tiếp, chúng ta đem móc phụ gia đếnon_post()Hưởng ứng trình tự cùngon_get()Hưởng ứng giả, như sau sở kỳ.

class TaskResource(BaseResource):
@falcon.before(login_required)
def on_get(self, req, resp):...




@falcon.before(login_required)
def on_post(self, req, resp):...

Now, before every call to that responder, Falcon will first invokelogin_required,giving the following response.

Hiện tại, ở mỗi lần thuyên chuyển nên hưởng ứng giả phía trước, Falcon đem đầu tiên thuyên chuyểnlogin_required,Cũng cấp ra dưới hưởng ứng.

{
“title”: “401 Unauthorized”
}

Sai lầm xử lý(Error handling)

Falcon provides a set of error classes you can raise when something goes wrong, hence making it easier to detect and log errors.

Falcon cung cấp một tổ sai lầm phân loại, ngài có thể ở xuất hiện vấn đề khi dẫn phát này đó sai lầm phân loại, do đó làm này càng dễ dàng kiểm tra đo lường cùng ký lục sai lầm.

These error classes include:

Này đó sai lầm phân loại bao gồm:

  • falcon.HTTPBadRequest

    falcon.HTTPBadRequest

  • falcon.HTTPInvalidHeader

    falcon.HTTPInvalidHeader

  • HTTPMissingHeader

    HTTPMissingHeader

  • HTTPInvalidParam

    HTTPInvalidParam

We have already been able to use thefalcon.HTTPUnauthorizederror in thelogin_requiredhook.

Chúng ta đã có thể ởlogin_requiredMóc nối trung sử dụngfalcon.HTTPUnauthorizedSai lầm.

Kết luận(Conclusion)

This tutorial has covered most of what is required to be able to build a REST API with Falcon successfully. For more information, seeFalcon docs.

Bổn giáo trình giới thiệu thành công sử dụng Falcon xây dựng REST API sở cần đại bộ phận nội dung. Có quan hệ càng nhiều tin tức, thỉnh xem thêmFalcon docs.

Phiên dịch tự:https://medium /better-programming/an-introduction-to-the-falcon-framework-a787ceea098

Bình luận
Tăng thêm bao lì xì

Thỉnh điền bao lì xì chúc phúc ngữ hoặc tiêu đề

Cái

Bao lì xì cái số nhỏ nhất vì 10 cái

Nguyên

Bao lì xì kim ngạch thấp nhất 5 nguyên

Trước mặt ngạch trống3.43Nguyên Đi trước nạp phí >
Cần chi trả:10.00Nguyên
Thành tựu một trăm triệu kỹ thuật người!
Lĩnh sau ngươi sẽ tự động trở thành bác chủ cùng bao lì xì chủ fans Quy tắc
hope_wisdom
Phát ra bao lì xì
Thật phóNguyên
Sử dụng ngạch trống chi trả
Điểm đánh một lần nữa thu hoạch
Quét mã chi trả
Tiền bao ngạch trống 0

Để khấu thuyết minh:

1. Ngạch trống là tiền bao nạp phí giả thuyết tiền, dựa theo 1:1 tỉ lệ tiến hành chi trả kim ngạch để khấu.
2. Ngạch trống vô pháp trực tiếp mua sắm download, có thể mua sắm VIP, trả phí chuyên mục cập chương trình học.

Ngạch trống nạp phí