简体   繁体   中英

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.

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.

MongoDB, by default, creates a unix socket at /tmp/mongodb-27017.sock . As of pymongo 2.4 you can make a connection like this:

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>

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 .

Update for 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. You will receive permission denied error's when you connect using 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.

Example /etc/mongod.conf in YAML format:

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. So that, you can still use pymongo

Either netcat or socat can do this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM