[英]How to connect to mongodb via unix socket in python
Is there any way to connect to mongodb via unix socket in python, while the official pymongo module does not support unix socket yet. 有没有办法通过python中的unix socket连接到mongodb,而官方的pymongo模块还不支持unix socket。
I'd like any third-party alternatives, or patches, while I've searched around and did not find one. 我喜欢任何第三方替代品或补丁,而我一直在搜索并找不到。
I do not like an ORM-style library since the mongodb => python dicts are natural and easy to use, so I did not take something like MongoEngine into account. 我不喜欢ORM风格的库,因为mongodb => python dicts是自然且易于使用的,所以我没有考虑像MongoEngine这样的东西。
MongoDB, by default, creates a unix socket at /tmp/mongodb-27017.sock
. 默认情况下,MongoDB在
/tmp/mongodb-27017.sock
创建一个unix套接字。 As of pymongo 2.4 you can make a connection like this: 从pymongo 2.4开始,您可以建立如下连接:
from pymongo import MongoClient
CONNECTION = MongoClient('/tmp/mongodb-27017.sock')
Additionally you can disable this behavior by starting mongod with --nounixsocket
or specify an alternate location with --unixSocketPrefix <path>
此外,您可以通过使用
--nounixsocket
启动mongod或使用--unixSocketPrefix <path>
指定备用位置来禁用此行为
MongoDB will always create and listen on a UNIX socket, unless --nounixsocket
is set, --bind_ip
is not set, or --bind_ip
specifies 127.0.0.1
. MongoDB的总会创造和监听UNIX套接字,除非
--nounixsocket
设置, --bind_ip
未设置,或--bind_ip
指定127.0.0.1
。
Update for MongoDB v3.x MongoDB v3.x的更新
If you upgrade to MongoDB 3.x on linux, the group and other permissions on /tmp/mongodb-27017.sock have been removed. 如果您在Linux上升级到MongoDB 3.x,则已删除/tmp/mongodb-27017.sock上的组和其他权限。 You will receive permission denied error's when you connect using MongoClient(host='/tmp/mongodb-27017.sock')
使用MongoClient连接时,您将收到权限被拒绝错误(host ='/ tmp / mongodb-27017.sock')
To fix this, upgrade your MongoDB configuration file to YAML format, which includes the filePermissions option so you set the permissions back. 要解决此问题,请将MongoDB配置文件升级为YAML格式,其中包括filePermissions选项,以便您重新设置权限。
Example /etc/mongod.conf in YAML format: YAML格式的/etc/mongod.conf示例:
storage:
dbPath: "/var/lib/mongodb"
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true
net:
unixDomainSocket:
filePermissions: 0777
Outside the scope of Python, you can build a proxy between TCP/IP socket and unix domain socket. 在Python的范围之外,您可以在TCP / IP套接字和unix域套接字之间构建代理。 So that, you can still use pymongo
所以,你仍然可以使用pymongo
Either netcat or socat can do this. netcat或socat都可以做到这一点。
nc -l 1234 | nc -U /tmp/foo
or 要么
socat TCP-LISTEN:1234,reuseaddr,fork UNIX-CLIENT:/tmp/foo
See also: 也可以看看:
Redirecting TCP-traffic to a UNIX domain socket under Linux 在Linux下将TCP流量重定向到UNIX域套接字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.