Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect to mongodb via unix socket in python

Tags:

python

mongodb

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.

like image 360
Felix Yan Avatar asked Dec 07 '11 05:12

Felix Yan


3 Answers

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.

like image 157
Tyler Brock Avatar answered Sep 30 '22 17:09

Tyler Brock


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
like image 42
Shane Davies Avatar answered Sep 30 '22 18:09

Shane Davies


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

like image 37
ukessi Avatar answered Sep 30 '22 17:09

ukessi