轻松创建在fastapi python框架之上构建的openfaas函数
faastapi的Python项目详细描述
faastapi
Easily create OpenFaas functions built on top of FastAPI Python framework
警告:
这个项目正处于早期阶段。它可能会受到很多更改,并且可能会添加/删除许多功能。
概述
FaastAPI
构建在FastAPI框架、pydantic库和jinja2库之上。
它允许开发人员快速生成OpenFaas函数。
可以使用几个插件来快速设置rest api。命令行接口可以与包一起安装,以便可以在本地测试函数。
安装
您可以使用pip安装软件包:
pip install faastapi
默认情况下,不安装命令行界面和插件。您可以选择使用附加的cli
安装cli:
pip install faastapi[cli]
示例
一个简单的faastapi函数文件(默认情况下,faastapi搜索文件名为faastapi.yml
)可以如下:
---apiversion:v1meta:name:hello-faastapiversion:0.3.4image:gcharbon/hello-fastapitags:-test-demodescription:A dummy function to demonstrate Faastapibuild:plugins:basic-auth:username:adminpassword:passwordmongodb:host:127.0.0.1port:27017database:demosqlite:uri:sqlite:///example.dbasync-sqlite:instrumentation:run:script:hello.pyfunction:say_hellomethod:postinput:name:type:strdefault:Worldoutput:message:strdate:datetimedrivers:Dict[str,str]
考虑到文件hello.py
位于faastapi.yml
旁边,内容如下:
importdatetimedefsay_hello(context,name):return{"message":f"Hello {name}","date":datetime.datetime.now(),"drivers":{"mongodb":str(context.mongodb),"sqlite":str(context.sql),"async-sqlite":str(context.async_sql),},}
Note: As you can see function must always accept an argument named
context
. In this case, sincesqlite
,async-sqlite
andmongodb
plugins where specified, clients are available in the context.
当用户运行faastapi function new -f faastapi.yml openfaas
时,将在openfaas
目录中生成openfaas函数。
然后可以使用faas-cli
:
cd openfaas/ faas-cli up -f function.yml
然后您可以在openfaas portal上尝试该函数(http://<OPENFAAS_URL>
):
您还可以在http://<OPENFAAS_URL>/function/hello-faastapi/docs
:
可用插件列表
安全插件:
basic-auth
:在应用程序中启用基本身份验证。
Note: Username and password can be configured as in the above example
oauth2-password
:使用密码和承载启用简单的oauth2。
Note: At this moment, configuration of user database is not possible, thus usage is limited to default values (username:
admin
, password:secret
)
数据库插件:
sqlite
:默认情况下,将带有sqlite3
引擎的sqlalchemySession
注入到上下文中。postgres
:默认情况下,将带有psycopg2
引擎的sqlachemySession
注入到上下文中。mysql
:默认情况下,将带有mysqlclient
引擎的sqlalchemySession
注入到上下文中。async-sqlite
:默认情况下,将带有aiosqlite
引擎的databases.Database
实例注入到上下文中。async-postgres
:默认情况下,将带有asyncpg
引擎的databases.Database
实例注入到上下文中。async-mysql
:默认情况下,将带有aiomysql
引擎的databases.Database
实例注入到上下文中。
Note: All those plugins accept a single configuration variable:
uri
mongodb
:向上下文中注入一个pymongo.Database
实例。
Note: MongoDB plugin can be configured using the variables:
host
(default to127.0.0.1
),port
(default to27017
) anddatabase
(default totest
)
redis
:向上下文中注入一个Redis
实例。
Note: Redis plugin can be configured using the variables:
host
(default to127.0.0.1
),port
(default to6379
) anddb
(default to0
)