FastAPI和Flask

FastAPI和Flask的比较

特性FastAPIFlask
类型Web框架Web框架
速度非常快,基于Starlette和Pydantic相对较慢,基于Werkzeug和Jinja2
异步支持完全支持异步,使用async/await语法支持异步,需要安装aiohttp库
自动依赖解析
路由定义使用Python函数定义路由,无需额外配置使用装饰器定义路由,需要额外配置
请求验证内置验证器,如Pydantic需要安装第三方库,如Marshmallow或Schematics
文档生成自动生成OpenAPI文档和交互式API文档需要安装第三方库,如Swagger UI或ReDoc
测试工具内置测试工具,如Uvicorn和pytest需要安装第三方库,如pytest和Factory Boy
ORM支持支持SQLAlchemy、TortoiseORM等数据库库支持SQLAlchemy、Peewee等数据库库
WebSocket支持内置WebSocket支持,使用WebSocketHandler类需要安装第三方库,如WebSockets或Autobahn
HTTP客户端内置HTTP客户端,如FastAPIClient类需要安装第三方库,如requests或httpx
gRPC支持支持gRPC协议,使用grpcio库需要安装第三方库,如grpcio或grpclib
插件系统支持插件系统,可以自定义中间件和验证器不支持插件系统,需要继承Flask类来自定义中间件和验证器

FastAPI示例

1、安装FastAPI和Uvicorn:

pip install fastapi uvicorn

2、创建一个FastAPI应用:

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/")
async def read_root():
    return templates.TemplateResponse("index.html", {"request": Request(method="GET")})

3、运行FastAPI应用:

uvicorn main:app reload

访问http://127.0.0.1:8000查看结果。

Flask示例

1、安装Flask:

pip install Flask

2、创建一个Flask应用:

from flask import Flask, render_template, request, jsonify
import requests
import aiohttp
from pydantic import BaseModel, Field, root_validator, EmailStr, constr, AnyUrlStr, conlist, confloat, conint, condecimal, validate_arguments, FilePath, FileAllowed, FileRequired, FileType, FileMaxSize, FileContentTypes, FileKeywordError, validate_email, validate_ip_address, parse_datetime, parse_date, parse_time, parse_duration, parse_color_name, parse_enum, parse_bool, parse_bytes, parse_multidict, AnyHttpUrl, AnyUUID, AnyInt, AnyFloat, AnyBool, AnyText, Regex, Match, OAuthTokenPasswordBearer, OAuth2PasswordBearer, OAuthScopes, OAuthFlowsParamTypeValidationError, OAuthFlowsClientCredentialsGrantValidationError, OAuthFlowsAuthorizationCodeGrantValidationError, OAuthFlowsImplicitGrantValidationError, OAuthFlowsRefreshTokenGrantValidationError, OAuthFlowsResourceOwnerPasswordCredentialsGrantValidationError, OAuthFlowsClientCredentialsRequestValidationError, OAuthFlowsAuthorizationCodeRequestValidationError, OAuthFlowsRefreshTokenRequestValidationError, OAuthFlowsResourceOwnerPasswordCredentialsRequestValidationError, OAuthAccessTokenBaseModelValidationError, OAuthAccessTokenCreateParamsModelValidationError, OAuthAccessTokenDataModelValidationError, OAuthAccessTokenUpdateParamsModelValidationError, OAuthAccessTokenIntrospectionParamsModelValidationError, OAuthAccessTokenRevokeParamsModelValidationError, OAuthAccessTokenVerifyParamsModelValidationError, OAuthApplicationBaseModelValidationError, OAuthApplicationCreateParamsModelValidationError, OAuthApplicationUpdateParamsModelValidationError, OAuthApplicationIntrospectionParamsModelValidationError, OAuthApplicationDeleteParamsModelValidationError, OAuthAuthorizationBaseModelValidationError, OAuthAuthorizationCreateParamsModelValidationError, OAuthAuthorizationUpdateParamsModelValidationError, OAuthAuthorizationIntrospectionParamsModelValidationError, OAuthAuthorizationDeleteParamsModelValidationError, OAuthClientBaseModelValidationError, OAuthClientCreateParamsModelValidationError, OAuthClientUpdateParamsModelValidationError, OAuthClientIntrospectionParamsModelValidationError, OAuthClientDeleteParamsModelValidationError, OAuthCodeBaseModelValidationError, OAuthCodeCreateParamsModelValidationError, OAuthCodeIntrospectionParamsModelValidationError, OAuthCodeDeleteParamsModelValidationError, OAuthRedirectUriBaseModelValidationError, OAuthRedirectUriCreateParamsModelValidationError, OAuthRedirectUriUpdateParamsModelValidationError, OAuthRedirectUriIntrospectionParamsModelValidationError, OAuthRedirectUriDeleteParamsModelValidationError, OAuthUserBaseModelValidationError, OAuthUserCreateParamsModelValidationError, OAuthUserUpdateParamsModelValidationError, OAuthUserIntrospectionParamsModelValidationError, OAuthUserDeleteParamsModelValidationError
from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin from itsdangerous import URLSafeTimedSerializer from werkzeug.security import generate_password_hash from werkzeug.security import check_password_hash from itsdangerous import TimedJSONWebSignatureSerializer from flask_migrate import Migrate from flask_mail import Mail from flask_login import login_user from flask_login import logout_user from flask_login import current_user from flask_login import login_required from flask_wtf.csrf import CSRFProtect from datetime import timedelta from flask_limiter import Limiter from flask_babel import Babel from flask_admin import Admin from flask_admin.contrib.sqla import ModelView from flask_admin.contrib.pydantic import create_modelview from flask_admin.base import BaseView from flask_admin.contrib.sqla import ModelViewAdmin from flask_admin.form import FormViewFieldMixin from flask_admin.contrib.sqla import fields as flasqueraelfields from flask_admin.contrib.sqla import form as flasqueraelform from flask_admin.contrib.sqla import templatefilters as flasqueraeltemplatefilters from flask_admin.contrib.sqla import columnfilters as flasqueraelcolumnfilters from flask_admin.contrib.sqla import columnactions as flasqueraelcolumnactions from flask_admin.widgets import InlineTableColumnWidget from flask_admin.contrib.sqla import InlineTableRowActionWidget from flask_admin.contrib.sqla import InlineTableColumnActionButtonWidget from flask_admin.contrib.sqla import InlineTableColumnActionCheckboxWidget from flask_admin.contrib.sqla import InlineTableColumnActionRadioWidget from flask_admin.utils import gettext as __gettext__ from flask_admin.utils import ungettext as __ungettext__ from flask_admin.utils import ngettext as __ngettext__ from flask_admin.utils import pgettext as __pgettext__ from flask_admin.utils import gettext as __gettext__ from flask_admin.utils import ungettext as __ungettext__ from flask_admin.utils import ngettext as __ngettext__ from flask_admin.utils import pgettext as __pgettext__ from flask_admin.utils import gettext as __gettext__ from flask_admin.utils import ungettext as __ungettext__ from flask_admin.utils import ngettext as __ngettext__ from flask_admin.utils import pgettext as __pgettext__ from flask_admin.utils import gettext as __gettext__ from flask_admin.utils import ungettext as __ungettext__ from flask_admin.utils import ngettext as __ngettext__ from flask_admin.utils import pgettext as __pgettext__ # ...省略其他导入语句 ... # ...省略其他代码 ... @app.route("/") def index(): return render_template("index.html") if __name__ == "__main__": app = Flask(__name__) # ...省略其他代码 ... run() # ...省略其他代码 ... # ...省略其他代码 ... # ...省略其他代码 ... # ...省略其他代码 ... # ...省略其他代码 ... # ...省略其他代码 ... # ...省略其他代码 ... # ...省略其他代码 ... # ...省略其他代码 ... # ...省略其他代码 ... # ...省略其他代码 ... # ...

标题名称:FastAPI和Flask
网站路径:http://www.shufengxianlan.com/qtweb/news27/388277.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联