简体   繁体   English

MongoDb 与 FastAPI

[英]MongoDb with FastAPI

I am playing around with FastAPI a bit and wanted to connect it to a MongoDB database.我正在玩FastAPI ,想将它连接到 MongoDB 数据库。 I however am confused which ODM to choose between motor which is async and mongoengine.然而,我很困惑在异步电机和 mongoengine 电机之间选择哪个 ODM。 Also, in the NoSQL example here they have created a new bucket and also the called the code to connect to db every time it is used.此外,在此处的 NoSQL 示例中,他们创建了一个新存储桶,并且还调用了每次使用时连接到数据库的代码。 However, both motor and mongoengine seem to prefer a global connection.但是,motor 和 mongoengine 似乎都更喜欢全局连接。 So what would be a good way to connect to mongodb?那么连接到 mongodb 的好方法是什么?

I believe you already got your answers in the issue forums of the Fastapi project on Github: Issue 452 (closed) .我相信您已经在 Github 上 Fastapi 项目的问题论坛中得到了答案:问题 452 (关闭) But I'll recap the solutions here for future reference:但我会在这里回顾一下解决方案以供将来参考:

In short, you can use either motor or mongoengine , Fastapi supports both and you can reuse a global client object that's started and ended with your app process.简而言之,您可以使用motormongoengine ,Fastapi 两者都支持,并且您可以重用在您的应用程序进程中启动和结束的全局客户端对象。

Some context details to (hopefully) clarify these technologies and their relationships:一些上下文细节(希望)阐明这些技术及其关系:

The official MongoDB driver for Python is pymongo . Python 的官方 MongoDB 驱动程序是pymongo Under the hoods, both MongoEngine and Motor use Pymongo.在引擎盖下,MongoEngine 和 Motor 都使用 Pymongo。 Pymongo implements a direct client for MongoDB (daemons) and offers a Python API to make requests. Pymongo 为 MongoDB(守护进程)实现了一个直接客户端,并提供了一个 Python API 来发出请求。

If you wanted to, you could use pymongo with Fastapi directly.如果您愿意,可以直接将 pymongo 与 Fastapi 一起使用。 (On th SQL side of things, this would be equivalent to using psycopg2 in Flask directly without going through something like SQLAlchemy.) (在 SQL 方面,这相当于直接在 Flask 中使用 psycopg2 而无需通过 SQLAlchemy 之类的东西。)

MongoEngine is an ODM (Object-Document Mapper). MongoEngine 是一个 ODM(对象文档映射器)。 It offers a Python object-oriented API that you can use in your application to work more comfortably and when it comes to the actual DB requests, MongoEngine will use pymongo.它提供了一个 Python 面向对象的 API,你可以在你的应用程序中使用它来更舒适地工作,当涉及到实际的数据库请求时,MongoEngine 将使用 pymongo。

Motor is a wrapper for pymongo that makes it non-blocking (allowing async/await). Motor 是 pymongo 的包装器,使其成为非阻塞(允许 async/await)。 It uses an event-loop, either through Tornado or through asyncio.它使用事件循环,通过 Tornado 或通过 asyncio。 If you are using Fastapi with uvicorn, uvicorn will implement async functionality with uvloop.如果您将 Fastapi 与 uvicorn 一起使用,则 uvicorn 将使用 uvloop 实现异步功能。 In short, using Motor with FastAPI, async should "just work".简而言之,将 Motor 与 FastAPI 一起使用,异步应该“正常工作”。 Unfortunately, Motor does not implement an ODM.不幸的是,Motor 没有实施 ODM。 In this sense it is more similar to pymongo.从这个意义上说,它更类似于 pymongo。

Fastapi handles the requests from clients (using Starlette), but it will let you implement your own connection to MongoDB. Fastapi 处理来自客户端的请求(使用 Starlette),但它可以让您实现自己的 MongoDB 连接。 So you are not restricted to any particular choice, but you are mostly on your own (a la Flask).因此,您不受任何特定选择的限制,但您主要依靠自己(a la Flask)。

You can use the startup/shutdown hooks of your FastAPI app to start/stop your Motor/MongoEngine client.您可以使用 FastAPI 应用程序的启动/关闭挂钩来启动/停止您的 Motor/MongoEngine 客户端。 You don't need to worry about your client object not persisting due to multiprocess issues, because Fastapi is single-threaded.由于多进程问题,您无需担心客户端对象不会持久化,因为 Fastapi 是单线程的。

@app.on_event("startup")
async def create_db_client():
    # start client here and reuse in future requests


@app.on_event("shutdown")
async def shutdown_db_client():
    # stop your client here

An example implementation of motor with Fastapi can be found here .可以在此处找到带有 Fastapi 的电机的示例实现。

I recently created an Async Mongo ODM well suited for FastAPI: ODMantic .我最近创建了一个非常适合 FastAPI 的 Async Mongo ODM: ODMantic

app = FastAPI()
engine = AIOEngine()

class Tree(Model):
    """This model can be used either as a Pydantic model or 
       saved to the database"""
    name: str
    average_size: float
    discovery_year: int

@app.get("/trees/", response_model=List[Tree])
async def get_trees():
    trees = await engine.find(Tree)
    return trees

@app.put("/trees/", response_model=Tree)
async def create_tree(tree: Tree):
    await engine.save(tree)
    return tree

You can have a look to the FastAPI example for a more detailed example.您可以查看FastAPI 示例以获取更详细的示例。

I disagree with accepted answer saying fastapi is single threaded.我不同意接受的答案说 fastapi 是单线程的。 As far as I can tell fastapi is only single threaded if you handle the requestions using an async function. So if you dont use async under the hood starlette should use mutliple threads from a threadpool to handle multiple requests.据我所知,如果您使用异步 function 处理请求,fastapi 只是单线程的。因此,如果您不在引擎盖下使用异步,starlette 应该使用线程池中的多个线程来处理多个请求。

For more information on threading model and async in fastapi/starlette this is a good intro https://fastapi.tiangolo.com/async/有关 fastapi/starlette 中线程 model 和异步的更多信息,这是一个很好的介绍https://fastapi.tiangolo.com/async/

https://stackoverflow.com/questions/70446584/how-does-fastapi-uvicorn-parallelize-requests#:~:text=For%20endpoints%20defined%20with%20def%20%28not%20async%20def%29%2C,can%20be%20controlled.%20This%20question%20is%20addressed%20here . https://stackoverflow.com/questions/70446584/how-does-fastapi-uvicorn-parallelize-requests#:~:text=For%20endpoints%20defined%20with%20def%20%28not%20async%20def%29%2C ,%20be%20controlled.%20This%20question%20is%20addressed%20here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 FastAPI 路由器与 FastAPI 用户和 MongoDB 一起使用? - How can I use FastAPI Routers with FastAPI-Users and MongoDB? 更新当前用户数据(FastAPI + MongoDB) - Update current user data (FastAPI + MongoDB) MongoDB 模型为 FASTAPI python 生成类似于 sqlacodegen - MongoDB model generate for FASTAPI python similar to sqlacodegen 如何使用 MongoDB(Motor) 为 FastAPI 实现 pytest - How to implement pytest for FastAPI with MongoDB(Motor) 在 FASTAPI 上使用 PyMongo 将元素插入到嵌套模型 Mongodb 的数组中 - Insert an element into an array of nested model Mongodb with PyMongo on FASTAPI 从mongodb数据库中获取数据时Fastapi显示空列表 - Fastapi showing empty list when fetching data from mongodb database 使用fastAPI从MongoDb获取数据时出错 - Getting Error while fetching data from MongoDb using fastAPI 如何使用 FastAPI 从 MongoDB 上的集合中获取结果? - How to get a result from a collection on MongoDB using FastAPI? FastAPI - 如何设置正确的 response_model 以从 MongoDB 返回 n 个文档? - FastAPI - How to set correct response_model to return n documents from MongoDB? FastAPI + MongoDB: bson.errors.InvalidId: '2021-01-01_2021-12-31' 不是有效的 ObjectId,它必须是 12 字节的输入或 24 字符的十六进制字符串 - FastAPI + MongoDB: bson.errors.InvalidId: '2021-01-01_2021-12-31' is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM