在 Django 中存储 MongoClient 的位置 [英] Where to store MongoClient in Django

查看:33
本文介绍了在 Django 中存储 MongoClient 的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 pymongo 来允许我的 Django 站点将数据保存到 MongoDB.显然 MongoClient() 类内置了连接池,它应该只在 Django 启动时实例化一次.因此,与我的 Django 站点的每个连接基本上都会重用该单个 MongoClient.我在网络上看到很多信息都说这是应该完成的方式.但是,我找不到任何关于在 Django 中放置 MongoClient 的单个实例的确切位置的任何建议.大多数 Django 文献明确指出不要保留所有用户会话中使用的全局变量.

I'm using pymongo to allow my Django site to save data to MongoDB. Apparently the MongoClient() class has connection pooling built in, and it should only be instantiated once when Django starts up. So each connection to my Django site will basically reuse that single MongoClient. I see lots of information on the web that states that this is the way it should be done.However, I cannot find any suggestions on where exactly in Django to put this single instance of MongoClient. Most Django literature says explicitly not to persist global variables used across all user sessions.

那么我究竟应该在哪里创建和存储这个 MongoClient 的实例?在views.py中?在models.py中?别的地方?如果只有一个 MongoClient 实例,内部的连接池究竟有什么帮助?

So where exactly do I create and store this single instance of MongoClient? In views.py? In models.py? Somewhere else? And if there is just a single instance of MongoClient, how exactly does the connection pooling inside help?

推荐答案

回答这个问题有点晚,但未来的搜索者可能会发现它很有用.

It's a bit late answering this question, but future searchers may find it useful.

如果您只将 MongoDB 用于少数操作(因此不想使用完整的 MongoEngine 架构),您可以这样设置您的架构:

If you're only using MongoDB for a few operations (and thus don't want to use the full MongoEngine architecture), you can set up your architecture like this:

# project/settings.py
  (place Mongo connection info here)

# project/__init__.py
  (declare a global MongoClient here, it will be throughout the app)

# project/all apps
  import project.MY_MONGO_CLIENT_NAME
  (use MongoClient as needed)

可以在此处找到更完整的细分:https://gist.github.com/josephmosby/4497f8a4f675170180ab

A more full breakdown may be found here: https://gist.github.com/josephmosby/4497f8a4f675170180ab

这篇关于在 Django 中存储 MongoClient 的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆