I previously wrote my app using local development servers, and now that I have moved it onto an openshift small gear almost all works except for mysql connections.

In my code I have the line:

self.db = MySQLdb.connect(host, username, password, dbname)

When I review the openshift error log, the following error is reported:

_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")

I think that python is trying to connect using a UNIX socket as opposed to an INET one, but I'm not sure how to change this behavior. Any help is much appreciated.

没有正确的解决方案

其他提示

Not specific to MySQLdb: if you use localhost as hostname, a MySQL client using the MySQL C libraries will try to connect using UNIX socket (or named pipe on Windows). There are 2 ways around this, but you'll need to grant extra permissions to make it work for both:

Use IP address 127.0.0.1

Use IP address 127.0.0.1 instead of the localhost hostname. This will make MySQL client connect using TCP/IP.

Use option files

The other way is to force the protocol using using option files. For example, in your ~/.my.cnf (or any file you want), add the following:

[python]
protocol=tcp

Now use the connection arguments to read the option file and group:

import MySQLdb
cnx = MySQLdb.connect(host='localhost', user='scott', passwd='tiger',
                      read_default_file='~/.my.cnf',
                      read_default_group='python')

The group name does not need to be python, but it is good not to use mysql or client as it might interfere with other MySQL tools (unless you want that of course).

For setting up permissions, you'll need to use the IP address of localhost, something like:

mysql> GRANT SELECT TO yourdb.* TO 'scott'@'127.0.0.1' IDENTIFIED BY ...;

(Site note: MySQL database drivers such as MySQL Connector/Python do not consider localhost to be special and connect through TCP/IP right away and you have to explicitly use the unix_socket.)

As I later discovered, while the database server runs on localhost, it runs on a very specific localhost bind address. In my case it was an address that I would never have though to try if I hadn't noticed how phpmyadmin was connecting.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top