How to connect to mongodb via unix socket in python

Is there a way to connect to mongodb through a unix socket in python, while the official pymongo module does not yet support a unix socket.

I would like to use third-party alternatives or patches while I searched for them and not found.

I don't like the ORM style library, since mongodb => python dicts are natural and user-friendly, so I didn’t take into account something like MongoEngine.

+6
source share
3 answers

MongoDB by default creates a unix socket in /tmp/mongodb-27017.sock . Starting with pymongo 2.4, you can establish a connection as follows:

 from pymongo import MongoClient CONNECTION = MongoClient('/tmp/mongodb-27017.sock') 

Alternatively, you can disable this behavior by running mongod with --nounixsocket or specify an alternative location with --unixSocketPrefix <path>

MongoDB always creates and listens for a UNIX socket if --bind_ip not installed, --bind_ip not installed, or --bind_ip indicates 127.0.0.1 .

+7
source

Update for MongoDB v3.x

If you upgrade to MongoDB 3.x on Linux, group and other permissions on / tmp / mongodb -27017.sock have been removed. When connecting using MongoClient (host = '/tmp/mongodb-27017.sock) you will get permission rejected

To fix this, update the MongoDB configuration file in YAML format, which includes the filePermissions parameter to set permissions.

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 
+6
source

Outside the Python domain, you can create a proxy between a TCP / IP socket and a domain unix socket. So 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

+1
source

Source: https://habr.com/ru/post/903255/


All Articles