I am trying to connect to a database on Cloud SQL, but I keep getting the same error. Not sure what it is, and tried several approaches.
Input:
import pymysql
connection = pymysql.connect(host='127.0.0.1',
user='',
password='XXXX',
db='cmcsql')
output:
C:\Users\Ejer\anaconda3\envs\pythonProject\python.exe C:/Users/Ejer/PycharmProjects/pythonProject/CloudSQL_test.py
Traceback (most recent call last):
File "C:\Users\Ejer\anaconda3\envs\pythonProject\lib\site-packages\pymysql\connections.py", line 569, in connect
sock = socket.create_connection(
File "C:\Users\Ejer\anaconda3\envs\pythonProject\lib\socket.py", line 808, in create_connection
raise err
File "C:\Users\Ejer\anaconda3\envs\pythonProject\lib\socket.py", line 796, in create_connection
sock.connect(sa)
ConnectionRefusedError: [WinError 10061] Der kunne ikke oprettes forbindelse, fordi destinationscomputeren aktivt nægtede det
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/Ejer/PycharmProjects/pythonProject/CloudSQL_test.py", line 2, in <module>
connection = pymysql.connect(host='127.0.0.1',
File "C:\Users\Ejer\anaconda3\envs\pythonProject\lib\site-packages\pymysql\__init__.py", line 94, in Connect
return Connection(*args, **kwargs)
File "C:\Users\Ejer\anaconda3\envs\pythonProject\lib\site-packages\pymysql\connections.py", line 327, in __init__
self.connect()
File "C:\Users\Ejer\anaconda3\envs\pythonProject\lib\site-packages\pymysql\connections.py", line 619, in connect
raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' ([WinError 10061] Der kunne ikke oprettes forbindelse, fordi destinationscomputeren aktivt nægtede det)")
Process finished with exit code 1
You should not be using 127.0.0.1 to connect to cloud sql instance.
127.0.0.1 is (in most cases) for localhost connection (when you run the db server locally on the same machine as where the client is). Instead you should be using the ip address given to your cloud sql instance. You can find it on the overview tab of the sql instance under Connect to this instance.
You should also create your user on the users tab and then use it in your code.
Don't forget about authentication, check out connections tab and read more about it here
Making sure that you have proper ip, user, existing db and connecting from authorized network should do the trick.
PyMysql connects to port 3306 by default, if your process is running on a different port it won't be able to connect.
Apart from the host, user, password parameters you also have to provide the port on which the sql process is running.
Related
I'm having trouble connecting to a db I set up in Atlas MongoDB.
I have already read multiple other questions but no answer made my connection work.
I want to point out that I am trying to access it behind a company's proxy (if that has anything to do with it).
My code is this and fails only on the last line where I try to count the documents:
from pymongo import MongoClient
client = MongoClient(
"mongodb+srv://name:pass#iliastrialcluster-1tl2y.azure.mongodb.net/test?retryWrites=true&w=majority&ssl=true&ssl_cert_reqs=CERT_NONE"
)
db = client.get_database('sample_airbnb')
print(db)
listings_and_reviews = db.listingAndReviews
print(listings_and_reviews)
listings_and_reviews.count_documents({})
The error I get is:
Traceback (most recent call last):
File "C:~/mongo_connection1.py", line 11, in <module>
listings_and_reviews.count_documents({})
File "C:~\lib\site-packages\pymongo\collection.py", line 1721, in count_documents
_cmd, self._read_preference_for(session), session)
File "C:~\lib\site-packages\pymongo\mongo_client.py", line 1454, in _retryable_read
read_pref, session, address=address)
File "C:~\lib\site-packages\pymongo\mongo_client.py", line 1253, in _select_server
server = topology.select_server(server_selector)
File "C:~\lib\site-packages\pymongo\topology.py", line 235, in select_server
address))
File "C:~\lib\site-packages\pymongo\topology.py", line 193, in select_servers
selector, server_timeout, address)
File "C:~\lib\site-packages\pymongo\topology.py", line 209, in _select_servers_loop
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: iliastrialcluster-shard-00-00-1tl2y.azure.mongodb.net:27017: timed out,iliastrialcluster-shard-00-02-1tl2y.azure.mongodb.net:27017: timed out,iliastrialcluster-shard-00-01-1tl2y.azure.mongodb.net:27017: timed out
ServerSelectionTimeout error is the client's way of telling you you can't connect to the server. The primary cause of these errors when using MongoDB Atlas is the failure to enable access for the IP address of the node the client is running on.
To verify try connecting using the MongoDB shell mongo using the same connection string. if you get a connection failed then you know it's not a Python problem. Your client code looks OK BTW so I am pretty sure this is what it is.
The connection to the server is lazily evaluated so we don't try to initiate a connection until you make an actual request. In this case the count_documents call. This is why this is the call that generates the error.
#JoeDrumgoole Thanks for your answer. The problem was the proxy after all, after deactivating it the connection works fine. Good to know that the connection to the server is lazily evaluated.
I am coming across an issue with mysql connector.
I have an environment that i can't connect from my local machine.
I use simple command for connection:
from mysql.connector import connect
connection = mysql.connector.connect(user='dbuser', database='dbname',
host='amazon_link', password='dbpassword')
This works for all environment except one. And this also works in the server as well where the database lives.
I can access the database using my MySqlWorkbench from local machine. But when i try from my script, i get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/__init__.py", line 179, in connect
return MySQLConnection(*args, **kwargs)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 95, in __init__
self.connect(**kwargs)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/abstracts.py", line 719, in connect
self._open_connection()
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 210, in _open_connection
self._ssl)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 144, in _do_auth
self._auth_switch_request(username, password)
File "/Users/rajatvij/Development/env/lib/python2.7/site-packages/mysql/connector/connection.py", line 177, in _auth_switch_request
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'dbuser'#'10.0.1.72' (using password: YES)
And the ip address that i get for the host link is different from what mysql connector is showing here as well.
Is there a way to avoid mysql connector to change link to url here, as when i use the link instead of ip address in my Workbench i am able to connect. So i doubt it is an issue related to vpn or security groups. Otherwise i wouldn't be able to connect to database via work bench at all.
Any help would be appreciated. Thanks.
And sorry in case i missed something basic here.
Try to use the global IP address of your server instead of the domain name.
Refer the stackoverflow link for more details:
Remotely connect to MySQL with Python mysql.connector
Im trying to connect to an ftp server that is behind ftp proxy.
The proxy server does not require username and password, the ftp server does.
I have searched through several posts:
Proxies in python
How to use urllib2 to access ftp/http server using proxy with authentification
How to connect to ftp server via proxy using ftplib
How to specify an authenticated proxy for a python http connection?
Here is the last version of my code. So far I've figured out that to open the ftp server behind an ftp proxy, the notation ftp://username:password#server can be used. I'm using the urllib2 library to define the proxy server.
import urllib2
proxy_host = '101.11.44.84:8021' # only host name, no scheme (http/ftp)
proxy_handler = urllib2.ProxyHandler({'ftp': proxy_host})
auth = urllib2.FTPHandler()
try:
opener_thru_proxy = urllib2.build_opener(proxy_handler, auth)
except:
logger.exception('build_opener error')
raise
print opener_thru_proxy
try:
conn = opener_thru_proxy.open('ftp://user:password#100.159.66.113')
except:
logger.exception('opener thru proxy error')
raise
print conn.read()
conn.close()
The output of this code yields:
2016-05-23 16:15:28,286 - root - ERROR - opener thru proxy error
Traceback (most recent call last):
File "<string>", line 293, in <module>
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 431, in open
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 449, in _open
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 409, in _call_chain
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 1412, in ftp_open
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib2.py", line 1434, in connect_ftp
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib.py", line 875, in __init__
File "C:\_Studna\Python\python-2.7.10.amd64\lib\urllib.py", line 884, in init
File "C:\_Studna\Python\python-2.7.10.amd64\lib\ftplib.py", line 135, in connect
File "C:\_Studna\Python\python-2.7.10.amd64\lib\socket.py", line 575, in create_connection
URLError: <urlopen error ftp error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
It seems that I'm unable to establish the ftp connection with the ftp server.
However, when I use the same set of connection data and use it in Total Commander, the connection works correctly. See the image enclosed Total Commander ftp connection window.
I am trying to connect to a MySQL database using python but I am getting a strange error. It is compounded by the fact that I can use the same connection values from the mysql console command and it connects with no problems.
Here is the exact code I am using:
import pymysql
from checks import AgentCheck
class DelayedJobCheck(AgentCheck):
def check(self, instance):
self.log.info("testing connection")
self.log.info(instance)
connection = pymysql.connect(**instance)
cur = cnx.cursor(buffered=True)
cur.execute("SHOW STATUS LIKE 'Ssl_cipher'")
print(cur.fetchone())
cur.close()
cnx.close()
self.gauge('hello.world', 1)
This is the error that I am getting:
Traceback (most recent call last):
File "/opt/datadog-agent/agent/checks/__init__.py", line 661, in run
self.check(copy.deepcopy(instance))
File "/opt/datadog-agent/agent/checks.d/delayed_job.py", line 10, in check
connection = pymysql.connect(**instance)
File "/opt/datadog-agent/embedded/lib/python2.7/site-packages/pymysql/__init__.py", line 88, in Connect
return Connection(*args, **kwargs)
File "/opt/datadog-agent/embedded/lib/python2.7/site-packages/pymysql/connections.py", line 644, in __init__
self._connect()
File "/opt/datadog-agent/embedded/lib/python2.7/site-packages/pymysql/connections.py", line 869, in _connect
raise exc
OperationalError: (2003, u"Can't connect to MySQL server on '192.168.199.86' ([SSL: SSL_NEGATIVE_LENGTH] dh key too small (_ssl.c:590))")
I am running this code on a Ubuntu box and I though initially that it might be because the SSL CA is a self generated cert. So I followed the steps here But, it did not make any difference. Also I have verified that the process that is running this code has full access to the cert files
Any ideas what else might be causing this?
As the err info said dh key is too small, a larger one might help. Replace the default dh512.pem file with dh4096.pem
sudo wget "https://git.openssl.org/gitweb/?p=openssl.git;a=blob_plain;f=apps/dh4096.pem" -O dh4096.pem
Ref: http://www.alexrhino.net/jekyll/update/2015/07/14/dh-params-test-fail.html
I'm developing a Flask based python app using the peewee ORM. I was initially connecting to the database that was being stored locally on my machine and I'm now trying to transition to connecting to the db remotely. I've set up the database in phpmyadmin via my server's cpanel section.
The Issue
I've set up my IP address to be able to remotely access my databases but I am getting the following error when I attempt to connect to the database:
Traceback (most recent call last):
File "app.py", line 294, in <module>
models.initialize()
File "/Users/wyssuser/Desktop/dscraper/models.py", line 145, in initialize
DATABASE.connect()
File "/Library/Python/2.7/site-packages/peewee.py", line 2767, in connect
self.__local.closed = False
File "/Library/Python/2.7/site-packages/peewee.py", line 2688, in __exit__
reraise(new_type, new_type(*exc_value.args), traceback)
File "/Library/Python/2.7/site-packages/peewee.py", line 2766, in connect
**self.connect_kwargs)
File "/Library/Python/2.7/site-packages/peewee.py", line 3209, in _connect
return mysql.connect(db=database, **conn_kwargs)
File "/Library/Python/2.7/site-packages/pymysql/__init__.py", line 88, in Connect
return Connection(*args, **kwargs)
File "/Library/Python/2.7/site-packages/pymysql/connections.py", line 644, in __init__
self._connect()
File "/Library/Python/2.7/site-packages/pymysql/connections.py", line 869, in _connect
raise exc
peewee.OperationalError: (2003, "Can't connect to MySQL server on '142.157.25.22' ([Errno 61] Connection refused)")
This is the portion of my code that references the database connection:
app.py
if __name__ == '__main__':
models.initialize()
app.run(debug=DEBUG, port=PORT, host=HOST)
config.py
DATABASE = {
'db': 'my_dbname',
'host': '142.157.25.22',
'port': 3306,
'user': 'my_username',
'passwd': 'my_pswd',
}
models.py
from peewee import *
import config
DATABASE = MySQLDatabase(config.DATABASE['db'], host=config.DATABASE['host'], port=config.DATABASE['port'], user=config.DATABASE['user'], passwd=config.DATABASE['passwd'])
...all of my models related code
def initialize():
print 'starting db connection'
DATABASE.connect()
print 'connected'
DATABASE.create_tables([Batch, Company, User, Post],safe=True)
DATABASE.close()
I've also tried connecting to 'localhost' as the host but that doesn't seem to work here, is there a different host I should be connecting to?
Solution is bad default port:
the example from peewee doc is
# Connect to a MySQL database on network.
mysql_db = MySQLDatabase('my_app', user='app', password='db_password',
host='10.1.0.8', port=3316)
but defaul port is 3306