FastAPI+React全栈开发04 FastAPI概述

Chapter01 Web Development and the FARM Stack

04 Introducing FastAPI

FastAPI+React全栈开发04 FastAPI概述

Now we will look at a brief introducion to the Python REST-API framework of choice - FastAPI. Additionally, we will go over a high-level overview of the features that make it a protagonist in our FARM stack. I will try to compare FastAPI with Python and JavaScript alternatives and explain why it can be a great fit for a modern and flexible stack.

现在我们将简要介绍所选择的Python REST-API框架—FastAPI。此外,我们将对使其成为FARM堆栈中的主角的特性进行高级概述。我将尝试比较FastAPI与Python和JavaScript的替代品,并解释为什么它可以非常适合现代和灵活的堆栈。

REST APIs

What is an API? Technically, API stands for Application Programming Interface. APIs are used to enable some kind of interaction between different pieces of software and different systems, and they communicate using HTTP (short for Hypertext Transfer Protocol) through a cycle of requests and responses. In the last couple of decades, APIs have become the standard protocol for communication between various servers and heterogeneous clients, and they can be seen as a sort of vascular system that is fundamental to information exchange on the web.

什么是API?从技术上讲,API代表应用程序编程接口。api用于支持不同软件和不同系统之间的某种交互,它们通过请求和响应的循环使用HTTP(超文本传输协议的缩写)进行通信。在过去的几十年里,api已经成为各种服务器和异构客户端之间通信的标准协议,它们可以被视为一种血管系统,是web上信息交换的基础。

There are many definitions, more or less formal ones, and application programming interfaces can mean many things, but I like to view them as wirings that expose the business logic through a uniform interface, allowing us to use them from another realm.

有许多定义,或多或少是正式的定义,应用程序编程接口可以意味着许多东西,但我喜欢将它们视为通过统一接口公开业务逻辑的连接,允许我们从另一个领域使用它们。

An API is, as its name suggests, an interface. It is a way for a human or a machine to interact with an application or a service through an interface. Every API provider will provide an interface that is well-suited for the type of data that they provide, for instance, a weather forecasting station will provide an API that lists the temperatures and humidity levels for a certain period and a certain location. Some sports sites will provide statistical data about the games that are being played and a pizza delivery API will provide you with the selected ingredients, the price, and the estimated time of arrival. APIs are everywhere, inside your TV, your wallet, and heck, your favorite news site probably uses at least a dozen of them. With the adoption of the Internet of Things, APIs will enter even more aspects of our lives, transmitting biometric and medical data, enabling fast communications between factory machines, tractors in the fields, traffic frequencies, traffic light control systems, and more. APIs are what makes today’s web turn, what generates traffic, and ultimately, what generates revenue. Put simply, we can think of an API as a standardized way of information exchange, with usability, performance, and scalability in mind.

顾名思义,API是一个接口。它是人或机器通过接口与应用程序或服务交互的一种方式。每个API提供者都将提供一个非常适合其提供的数据类型的接口,例如,天气预报站将提供一个API,列出特定时间段和特定位置的温度和湿度水平。一些体育网站将提供有关正在进行的比赛的统计数据,而比萨饼配送API将为您提供所选的配料、价格和预计到达时间。api无处不在,在你的电视里,在你的钱包里,见鬼,你最喜欢的新闻网站可能至少使用了一打api。随着物联网的采用,api将进入我们生活的更多方面,传输生物识别和医疗数据,实现工厂机器,田间拖拉机,交通频率,交通灯控制系统等之间的快速通信。api使今天的网络转向,产生流量,最终产生收益。简单地说,我们可以把API看作是一种标准化的信息交换方式,考虑到可用性、性能和可伸缩性。

We will not go over the rigorous definitions of REST APIs, but just list some of the most important ones:

  • Statelessness: REST APIs are said to be stateless, which means that neither the client nor the server stores any states in-between. All the requests and responses are handled by the PAI server in isolation and without information about the session itself.
  • Layered structure: In order to keep the API scalable and understandable, a RESTful architecture implies a layered structure. The different layers form a hierarchy and communicate with each other but not with every component, thus improving overall security.
  • Client-server architecture: APIs should be able to connect different systems/pieces of software without limiting their own functionalities, the server (the system that provides the response) and the client (the system making the request) have to stay separate and independent from each other.

我们不会详细介绍REST api的严格定义,只列出一些最重要的定义:

  • 无状态:REST api被认为是无状态的,这意味着客户端和服务器之间都不存储任何状态。所有请求和响应都由PAI服务器单独处理,不包含会话本身的信息。
  • 分层结构:为了保持API的可扩展性和可理解性,RESTful架构意味着分层结构。不同的层形成一个层次结构,彼此通信,但不是与每个组件通信,从而提高了整体安全性。
  • 客户端-服务器架构:api应该能够连接不同的系统/软件,而不限制它们自己的功能,服务器(提供响应的系统)和客户端(发出请求的系统)必须保持彼此分离和独立。

We will be using FastAPI for our REST API layer, and we could say that it checks all the required boxes and then some more.

我们将使用FastAPI作为REST API层,我们可以说它检查了所有必需的框,然后还有更多。

What is FastAPI?

FastAPI is a modern and performant web framework for building APIs. Built by Sebastian Ramirez, it uses, to best avail, the newest features of the Python programming language, such as type hinting and annotations, the async-await syntax, Pydantic models, web socket support, and more.

FastAPI是一个用于构建api的现代高性能web框架。它由Sebastian Ramirez构建,充分利用了Python编程语言的最新特性,例如类型提示和注释、async-await语法、Pydantic模型、web套接字支持等等。

There are numerous reasons why FastAPI, though relatively new, will probably see a wider spread in the web development world in the future, so let’s list some of them:

  • High performance: FastAPI is able to achieve very high performance, especially compared to other Python-based solutions. By using Starlette under the hood, FastAPI’s performance reaches levels that are usually reserved for Node.js and Go.
  • Data validation and simplicity: Being heavily based on Python types and Pydantic brings numerous benefits. Since Pydantic structures are just instances of classes the developers define, we can perform complex data validations, deeply nested JSON objects, and hierarchical models (using Python lists and dictionaries), and this relates very well with the nature of MongoDB.
  • Faster development: Development becomes more intuitive, with strong integrated development environment(IDE) support, which leads to faster development time and fewer bugs.
  • Standards compliance: FastAPI is standard based and fully compatible with open standards for building APIs - OpenAPI and JSON schemas.
  • Logical structuring of apps: The framework allows for structuring of APIs and apps into multiple reouters and allows granular request and response customization. and easy access to every part of the HTTP cycle.
  • Async support: FastAPI uses an Asynchrounous Server Gateway Interface (ASGI) and, with the use of an ASGI compatible server, such as Uvicorn or Hypercorn, is able to provide a truly asynchronous workflow without actually having to import the Async.io module into Python.
  • Dependency injection: The dependency injection system in FastAPI is one of its biggest selling points. It enables us to create complex functionalities that are easily reusable across our API. This is a pretty big deal and probably the feature that makes FastAPI ideal for hybrid web apps, it gives developers the opportunity to easily attach different functionalities to the REST endpoints.
  • Great documentation: The documentation of the framework itself is excellent and second to none. It is both easy to follow and extensive.
  • Automatic documentation: Being based on OpenAPI, FastAPI enables automatic documentation creation, which essentially means that we get our API documented for free with Swagger.

FastAPI虽然相对较新,但在未来的web开发领域可能会有更广泛的应用,这里有很多原因,所以让我们列出一些原因:

  • 高性能:FastAPI能够实现非常高的性能,特别是与其他基于python的解决方案相比。通过在底层使用Starlette, FastAPI的性能达到了通常为Node.js和Go保留的水平。
  • 数据验证和简单性:基于Python类型和Pydantic带来了许多好处。由于Pydantic结构只是开发人员定义的类的实例,因此我们可以执行复杂的数据验证,深度嵌套的JSON对象和分层模型(使用Python列表和字典),这与MongoDB的性质非常相关。
  • 更快的开发:开发变得更加直观,强大的集成开发环境(IDE)支持,这导致更快的开发时间和更少的错误。
  • 符合标准:FastAPI是基于标准的,完全兼容开放的标准,用于构建api - OpenAPI和JSON模式。
  • 应用程序的逻辑结构:该框架允许将api和应用程序结构成多个路由器,并允许粒度请求和响应定制。并且可以轻松访问HTTP周期的每个部分。
  • 异步支持:FastAPI使用异步服务器网关接口(ASGI),并使用ASGI兼容服务器,如Uvicorn或Hypercorn,能够提供真正的异步工作流,而无需实际导入Async.io模块导入Python。
  • 依赖注入:依赖注入系统是FastAPI最大的卖点之一。它使我们能够创建复杂的功能,这些功能很容易在我们的API中重用。这是一个非常重要的功能,可能是使FastAPI成为混合web应用程序的理想特性,它使开发人员有机会轻松地将不同的功能附加到REST端点。
  • 出色的文档:框架本身的文档非常出色,首屈一指。它既容易遵循又广泛。
  • 自动文档:基于OpenAPI, FastAPI支持自动文档创建,这本质上意味着我们可以使用Swagger免费获取API文档。

In order to get at least a basic idea of what coding with FastAPI looks like, let’s take a look at a miniamal API:

为了至少对FastAPI的编码有一个基本的概念,让我们来看一个最小的API:

from fastapi import FastAPIapp = FastAPI()@app.get("/")
async def root():return {"Message": "Hello World"}

The preceding few lines of code define a minimal API with a single endpoint(/) that responds to a GET request with the message “Hello world”. We instantiate a FastAPI class and use decorators to tell the server which HTTP methods should trigger which function for a response, just like with the Flask microframework, for example.

前面的几行代码定义了一个带有单个端点(/)的最小API,它用消息“Hello world”响应GET请求。我们实例化一个FastAPI类,并使用装饰器告诉服务器哪个HTTP方法应该触发哪个函数来响应,就像Flask微框架一样。

Python and REST APIs

Python has been used to build REST APIs for a very long time. While there are many options and solutions, DRF and Flask seem to be the most popular ones, at least until recently. If you are feeling adventurous, you can Google less popular or older frameworks such as bottle.py and CherryPy. DRF is a plug-in system for the Django web framework and enables a Django system to create highly customized REST API responses and generate endpoints based on the defined models. DRF is a very mature and battle tested system. It is regularly updated, and its documentation is very detailed. Flask, Python’s lightweight microframework, is a real gem among the web-building Python tools and can create REST APIs in a lot of different ways. You can use pure Flask and just output the appropriate format (i.e., JSON instead of HTML) or use some of the extensions developed to make the creation of REST APIs as straightforward as possible. Both of these solutions are fundamentally sysnchronous, although there seems to be active development in the direction of enabling async support.

Python用于构建REST api已经有很长时间了。虽然有许多选择和解决方案,但DRF和Flask似乎是最受欢迎的,至少直到最近。如果您喜欢冒险,您可以Google不太流行或较老的框架,如bottle.py和CherryPy。DRF是Django web框架的一个插件系统,它使Django系统能够创建高度自定义的REST API响应,并根据定义的模型生成端点。DRF是一个非常成熟和经过实战测试的系统。它定期更新,其文档非常详细。Flask, Python的轻量级微框架,是构建web的Python工具中的一个真正的宝石,可以用很多不同的方式创建REST api。你可以使用纯Flask,只输出适当的格式(例如,JSON而不是HTML),或者使用一些开发的扩展,使REST api的创建尽可能简单。这两种解决方案基本上都是同步的,尽管似乎正在朝着启用异步支持的方向积极发展。

There are also some very robust and mature tools, such as Tonado, which is an asynchronous networking library(and a server) that is able to scale to tens of thousands of open connections. Finally, in the last couple of years, several new Python based solutions have been created.

还有一些非常健壮和成熟的工具,例如Tonado,它是一个异步网络库(和服务器),能够扩展到数万个打开的连接。最后,在过去几年中,已经创建了几个新的基于Python的解决方案。

One of these solutions, and arguably the fastest, is Starlette. Dubbed as a lightweight ASGI framework/toolkit, it is ideal for building high-performance async services.

其中一个解决方案,可以说是最快的,是Starlette。它被称为轻量级的ASGI框架/工具包,是构建高性能异步服务的理想选择。

Like Flask was built on top of a couple of solid Python libraries, Werkzeug and Jinja2, 10 or more years ago, Sebastian Ramirez built FastAPI on top of Starlette and Pydantic, while also adding numerous features and goodies by using the latest Python features, such as type hinting and async support. According to some recent surveys, FastAPI is quickly becomming one of the most popular and most loved web frameworks. Undeniably, it is gaining in popularity, and it looks like it is here to stay, at least for the foreseeble future.

就像10多年前Flask是在几个坚实的Python库Werkzeug和Jinja2上构建的一样,Sebastian Ramirez在Starlette和Pydantic上构建了FastAPI,同时通过使用最新的Python特性(如类型提示和异步支持)添加了许多功能和优点。根据最近的一些调查,FastAPI正迅速成为最流行和最受喜爱的web框架之一。不可否认的是,它越来越受欢迎,看起来至少在可预见的未来,它将继续存在。

In Chapter 3, Getting Started with FastAPI, of this book, we will go over the most important features of FastAPI, but at this point, I just want to stress the significance of having a truly async Python framework as the glue for the most diverse components of a system. In fact, besides doing the usual web framework stuff, such as communicating with a database or, in our case, a MongoDB store, spitting out data to a frontend, and managing authentication and authorization, this Python pipeline enables us to quickly integrate and easily achieve frequently required tasks such as background jobs, header and body manipulation, response and request validation, and more through the dependency injection system.

在本书的第3章,FastAPI入门中,我们将讨论FastAPI最重要的特性,但在这一点上,我只想强调拥有一个真正的异步Python框架作为系统中最多样化组件的粘合剂的重要性。事实上,除了做通常的web框架的事情,比如与数据库通信,或者在我们的例子中,与MongoDB存储通信,向前端输出数据,以及管理身份验证和授权,这个Python管道使我们能够快速集成并轻松实现经常需要的任务,如后台作业,头部和正文操作,响应和请求验证,以及更多通过依赖注入系统。

We will try to cover the absolute minimum necessary for you to be able to build a simple FastAPI system. I will make frequent trips to the official documentation site and try to find the simplest solutions. Lastly, we will consider various web server solutions and deployment options(such as Deta, Heroku, and Digitalocean) for our FastAPI Python-based backend, while trying to opt for free solutions.

我们将尝试涵盖您能够构建一个简单的FastAPI系统所需的绝对最低限度。我将经常访问官方文档站点,并尝试找到最简单的解决方案。最后,我们将为FastAPI基于python的后端考虑各种web服务器解决方案和部署选项(如Deta、Heroku和Digitalocean),同时尝试选择免费的解决方案。

So, to cut a long story short, we choose FastAPI because we ideally want the ability and speed to handle requests asynchronously as if we were using a Node.js server while having access to the Python ecosystem. Additionally, we want the simplicity and development speed of a framework that automatically generates documentation for us.

所以,长话短说,我们选择FastAPI,是因为我们理想地想要异步处理请求的能力和速度,就像我们使用Node.js服务器一样,同时可以访问Python生态系统。此外,我们希望框架的简单性和开发速度能够自动为我们生成文档。

After reviewing the backend components, it is time to finalize our stack and put a face on it. We will now look at a minimal introduction to React and discuss what distinguishes it from other(also valid) solutions.

在检查了后端组件之后,是时候完成我们的堆栈并对其进行处理了。现在,我们将简单介绍一下React,并讨论它与其他(同样有效的)解决方案的区别。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/778636.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

项目管理:项目进度管理的五大关键步骤

作为项目经理,要想做好项目进度管理,可以遵循以下五个关键步骤: 一、确定范围和分解目标 1、明确项目目标:首先,要清晰地定义项目的总体目标和预期成果。 2、范围界定:详细列出项目所需完成的所有任务和…

LDL^H分解求逆矩阵与MATLAB仿真(Right-Looking)

通过分解将对称正定厄米特矩阵分解成下三角矩阵L和对角矩阵D来求其逆矩阵 目录 前言 一、LDL^H基本算法 二、LDL^H Right-Looking算法 三、D矩阵求逆 四、L矩阵求逆 五、A矩阵求逆 六、计算量分析 七、MATLAB仿真 八、参考资料 总结 前言 在线性代数中,LDL…

HarmonyOS入门--配置环境 + IDE汉化

文章目录 下载安装DevEco Studio配置环境先认识DevEco Studio界面工程目录工程级目录模块级目录 app.json5module.json5main_pages.json通知栏预览区 运行模拟器IED汉化 下载安装DevEco Studio 去官网下载DevEco Studio完了安装 配置环境 打开已安装的DevEco Studio快捷方式…

Java中有哪些容器(集合类)?

Java中的集合类主要由Collection和Map这两个接口派生而出,其中Collection接口又派生出三个子接 口,分别是Set、List、Queue。所有的Java集合类,都是Set、List、Queue、Map这四个接口的实现 类,这四个接口将集合分成了四大类&#…

蓝桥杯 - 小明的背包1(01背包)

解题思路: 本题属于01背包问题,使用动态规划 dp[ j ]表示容量为 j 的背包的最大价值 注意: 需要时刻提醒自己dp[ j ]代表的含义,不然容易晕头转向 注意越界问题,且 j 需要倒序遍历 如果正序遍历 dp[1] dp[1 - vo…

Android应用程序的概念性描述

1.概述 Android 应用程序包含了工程文件、代码和各种资源,主要由 Java 语言编写,每一个应用程序将被编译成Android 的一个 Java 应用程序包(*.apk)。 由于 Android 系统本身是基于 Linux 操作系统运行的,因此 …

SpringBoot Redis 之Lettuce 驱动

一、前言 一直以为SpringBoot中 spring-boot-starter-data-redis使用的是Jredis连接池,直到昨天在部署报价系统生产环境时,因为端口配置错误造成无法连接,发现报错信息如下: 一了解才知道在SpringBoot2.X以后默认是使用Lettuce作…

蓝桥杯 2022 省A 选数异或

一种比较无脑暴力点的方法&#xff0c;时间复杂度是(nm)。 (注意的优先级比^高&#xff0c;记得加括号(a[i]^a[j])x&#xff09; #include <iostream> #include <vector> #include <bits/stdc.h> // 包含一些 C 标准库中未包含的特定实现的函数的头文件 usi…

使用脚本进行编译安装nginx和安装mysql

1. 编译安装nginx # 先看有没有安装nginx&#xff0c;然后安装&#xff0c;创建用户&#xff0c;启动cat <<EOF 功能&#xff1a; 1、编译安装nginx 2、初始化功能 3、清理安装环境 4、选择是否启动nginx EOF# 检查是否安装nginx nginx_pathfind / -name *nginx if [ -n…

成都市酷客焕学新媒体科技有限公司:实现品牌的更大价值!

成都市酷客焕学新媒体科技有限公司专注于短视频营销&#xff0c;深知短视频在社交媒体中的巨大影响力。该公司巧妙地将品牌信息融入富有创意和趣味性的内容中&#xff0c;使观众在轻松愉悦的氛围中接受并传播这些信息。凭借独特的创意和精准的营销策略&#xff0c;成都市酷客焕…

第二证券|打新股有风险吗?

打新股有危险&#xff0c;其主要危险是破发&#xff0c;其间呈现以下状况&#xff0c;新股可能会破发&#xff1a; 1、估值过高 新股的估值过高&#xff0c;与其价值不相契合&#xff0c;其泡沫性较大&#xff0c;然后导致个股在上市之后&#xff0c;稳健投资者以及主力大量地…

maven3.8.1开始不支持http私有库

问题 since maven 3.8.1 http repositories are blocked. 意思是从maven3.8.1版本开始&#xff0c;maven不在认http的私有库&#xff0c;它觉得http私有库不安全。 解决 我直接回退到maven3.8.1之前一个版本&#xff0c;maven3.6.3。我不想去研究settings.xml怎么去配置放心…

10个替代Sketch的软件大盘点!第一款震撼来袭!

Sketch是Mac平台上专门为用户界面设计的矢量图形绘制工具。Sketch简单的界面背后有优秀的矢量绘制能力和丰富的插件库。但遗憾的是&#xff0c;Sketch只能在Mac平台上使用和浏览&#xff0c;而且是本地化的工具&#xff0c;云共享功能并不完善。在本文中&#xff0c;我们评估了…

金三银四面试题(一):JVM类加载与垃圾回收

面试过程中最经典的一题&#xff1a; 请你讲讲在JVM中类的加载过程以及垃圾回收&#xff1f; 加载过程 当Java虚拟机&#xff08;JVM&#xff09;启动时&#xff0c;它会通过类加载器&#xff08;ClassLoader&#xff09;加载Java类到内存中。类加载是Java程序运行的重要组成…

最佳矢量绘图设计软件Sketch for Mac v99.5 最新中文激活版

Sketch for Mac是一款功能强大的矢量绘图软件&#xff0c;它提供了简单易用的界面和丰富的工具&#xff0c;让用户能够轻松创建精美的设计作品。 软件下载&#xff1a;Sketch for Mac v99.5 最新中文激活版 Sketch具有直观的布局和智能的工具&#xff0c;使得设计师能够快速实现…

python(一)网络爬取

在爬取网页信息时&#xff0c;需要注意网页爬虫规范文件robots.txt eg:csdn的爬虫规范文件 csdn.net/robots.txt User-agent: 下面的Disallow规则适用于所有爬虫&#xff08;即所有用户代理&#xff09;。星号*是一个通配符&#xff0c;表示“所有”。 Disallow&…

Scikit-Learn K近邻分类

Scikit-Learn K近邻分类 1、K近邻分类1.1、K近邻分类及原理1.2、超参数K1.3、K近邻分类的优缺点2、Scikit-Learn K近邻分类2.1、Scikit-Learn K近邻分类API2.2、K近邻分类实践(鸢尾花分类)2.3、交叉验证寻找最佳K2.4、K近邻分类与Pipeline1、K近邻分类 K近邻是一种常用的分类…

JSP基础

一、JSP JSP&#xff08;全称&#xff1a;Java Server Pages&#xff09;&#xff1a;Java 服务端页面。是一种动态的网页技术&#xff0c;其中既可以定义 HTML、JS、CSS等静态内容&#xff0c;还可以定义 Java代码的动态内容&#xff0c;也就是 JSP HTML Java 。如下就是js…

SHELL(01)

Shell基础 Shell : [ 解释器 ] 在Linux内核与用户之间的解释器程序通常指 /bin/bash , 这是系统默认解释器负责向内核翻译及传达用户/程序指令相当于操作系统的 “外壳” Shell的使用方式 交互式指令---------------命令行 人工干预智能化程度高逐条解析执行 , 效率低 非交互…

【NOI】树的初步认识

文章目录 前言一、树1.什么是树&#xff1f;2.树的基本概念3.树的基本术语3.1 节点3.1.1 根节点3.1.2 父节点、子节点3.1.3 兄弟节点、堂兄弟节点3.1.4 祖先节点、子孙节点3.1.5 叶子节点/终端节点3.1.6 分支节点/非终端节点 3.2 边3.3 度3.3.1 树的度 3.4 层次3.4.1 树的深度3…