Python/Docker - Unknown server host 'db' when migrating - python

I am trying to migrate a program using python manage.py db migrate in my Visual Studio terminal but when I run it I am getting an error named (2005, "Unknown server host 'db' (11001)"). I am also using the SQLAlchemy library as well to use it alongside flask to create my app. I have found some solutions on StackOverflow and GitHub like trying to recreate my network https://github.com/docker-library/mysql/issues/644 and trying to import MySQLdb and using MySQLdb.connect() "Unknown MySQL server host" when using Flask in Python, but when I try both of these solutions on my program using Visual Studio they don't work.
Here is the error that I am getting in it's full form:
Traceback (most recent call last):
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\engine\base.py", line 2336, in _wrap_pool_connect
return fn()
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 304, in unique_connection
return _ConnectionFairy._checkout(self)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 778, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 495, in checkout
rec = pool._do_get()
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\impl.py", line 241, in _do_get
return self._create_connection()
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 309, in _create_connection
return _ConnectionRecord(self)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 440, in __init__
self.__connect(first_connect_check=True)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 661, in __connect
pool.logger.debug("Error on connect(): %s", e)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\util\langhelpers.py", line 68, in __exit__
compat.raise_(
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\util\compat.py", line 182, in raise_
raise exception
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\pool\base.py", line 656, in __connect
connection = pool._invoke_creator(self)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\engine\strategies.py", line 114, in connect
return dialect.connect(*cargs, **cparams)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\engine\default.py", line 493, in connect
return self.dbapi.connect(*cargs, **cparams)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\__init__.py", line 123, in Connect
return Connection(*args, **kwargs)
File "C:\Users\trevo\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\connections.py", line 185, in __init__
super().__init__(*args, **kwargs2)
MySQLdb._exceptions.OperationalError: (2005, "Unknown server host 'db' (11001)")
Here are my required files respectivly:
Dockerfile:
FROM python:3.9
ENV PYTHONUNBUFFERED 1
WORKDIR /app
COPY requirements.txt /app/requirements.txt
RUN pip install -r requirements.txt
COPY . /app
CMD python main.py
requirements.txt:
Flask==1.1.2
Flask-SQLAlchemy==2.4.4
SQLAlchemy==1.3.20
Flask-Migrate==2.6.0
Flask-Script==2.0.6
Flask-Cors==3.0.9
requests==2.25.0
werkzeug==1.0.1
mysqlclient==2.1.0
pika==1.1.0
itsdangerous==2.0.1
wolframalpha==5.0.0
docker-compose.yml:
version: '3.8'
services:
backend:
build:
context: .
dockerfile: Dockerfile
command: 'python main.py'
ports:
- 8001:5000
volumes:
- .:/app
depends_on:
- db
queue:
build:
context: .
dockerfile: Dockerfile
command: 'python -u consumer.py'
depends_on:
- db
db:
image: mysql:5.7.22
restart: always
environment:
MYSQL_DATABASE: veganetworkscript
MYSQL_USER: root
MYSQL_PASSWORD: root
MYSQL_ROOT_PASSWORD: root
volumes:
- .dbdata:/var/lib/mysql
ports:
- 33068:3306
And finally my manage.py file:
from main import app, db
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
main.py:
from flask_cors import CORS
from sqlalchemy import UniqueConstraint
from vegaaimain.vegamain import main
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
from dataclasses import dataclass
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://root:root#db/veganetworkscript'
CORS(app)
db = SQLAlchemy(app)
class Product(db.Model):
id: int
title: str
image: str
id = db.Column(db.Integer, primary_key=True, autoincrement=False)
title = db.Column(db.String(200))
image = db.Column(db.String(200))
class VegaScriptRun(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=False)
title = db.Column(db.String(200))
description = db.Column(db.String(400))
image = db.Column(db.String(200))
main()
class ProductUser(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer)
product_id = db.Column(db.Integer)
UniqueConstraint('product_id', 'user_id', name='user_product_unique')
#app.route('/api/products')
def index():
return jsonify(Product.query.all())
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
What exactly am I missing or potentially doing wrong here, thank you!

Make changes as follow and it should work:
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://root:root#127.0.0.1:33068/veganetworkscript'
But this will only work for migration when your docker container is not running. You can reach the host machine within the container on ip address 172.17.0.1. So your database URI should be
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql://root:root#172.17.0.1:33068/veganetworkscript'
Also checkout this link
https://www.digitalocean.com/community/tutorials/how-to-use-flask-sqlalchemy-to-interact-with-databases-in-a-flask-application

Related

Can't connect my app with postgres inside a docker container

app_dockerfile
FROM python:latest
WORKDIR /app
COPY requirements.txt /app
RUN pip3 install -r /app/requirements.txt
ADD sqlalch.py /app/sqlalch.py
CMD [ "python3", "sqlalch.py" ]
my_compose.yml
version: '3.3'
services:
postgres_db:
image: postgres:14.2
container_name: postgres_db
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
- POSTGRES_DB=mydb
- POSTGRES_HOST_AUTH_METHOD=trust
expose:
- "5432"
#ports:
# - "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- mynet
app:
build:
context: .
dockerfile: app_dockerfile
depends_on:
- postgres_db
restart: always
links:
- postgres_db:postgres_db
networks:
- mynet
volumes:
postgres_data:
networks:
mynet:
driver: bridge
Python script sqlalch.py
from sqlalchemy import (create_engine, Column, Integer,
String, Date, desc, ForeignKey)
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
DATABASE_URI = 'postgresql+psycopg2://postgres:postgres#postgres_db:5432/mydb'
engine = create_engine(DATABASE_URI)
Session = sessionmaker(engine)
session = Session()
Base = declarative_base()
class Book(Base):
__tablename__ = 'books'
id = Column(Integer, primary_key=True)
title = Column(String(30))
author = Column(String(30))
pages = Column(Integer)
published = Column(Date)
def __repr__(self):
return f'{self.title}, {self.author}, {self.pages},{self.published}\n'
class Library(Base):
__tablename__ = 'library'
id = Column(Integer, primary_key=True)
city = Column(String(50))
street = Column(String(80))
state = Column(String(50))
book_id = Column(Integer, ForeignKey('books.id'))
book_rel = relationship('Book')
def __repr__(self):
return f'{self.id}, {self.city} - {self.book_rel}\n'
Base.metadata.create_all(engine)
def instert_books():
title = str(input('Book title name: '))
author = str(input('Book author name: '))
pages = int(input('Book pages: '))
published = str(input('Book published data (M/D/YYY): '))
book = Book(title=title, author=author, pages=pages, published=published)
session.add(book)
session.commit()
def instert_library():
city = str(input('City: '))
street = str(input('Street: '))
state = str(input('State: '))
book_id = str(input('Book id: '))
libr = Library(city=city, street=street, state=state, book_id=book_id)
session.add(libr)
session.commit()
def view_the_table():
books = session.query(Book).order_by(desc(Book.published)).all()
print(books)
def view_library():
library = session.query(Library).order_by(Library.book_id).all()
print(library)
# instert_books()
# instert_library()
# view_the_table()
view_the_table()
view_library()
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2cfe63663c36 app_app "python3 sqlalch.py" 16 minutes ago Restarting (1) 36 seconds ago app_app_1
5f4936a55286 postgres:14.2 "docker-entrypoint.s…" 16 minutes ago Up 16 minutes 5432/tcp postgres_db
$ docker run -ti app_app /bin/bash
root#f52dc749e0ed:/app# ls
requirements.txt sqlalch.py
root#f52dc749e0ed:/app# python3 sqlalch.py
RESULT
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
raise exception
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/impl.py", line 143, in _do_get
return self._create_connection()
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 256, in _create_connection
return _ConnectionRecord(self)
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 371, in __init__
self.__connect()
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 665, in __connect
with util.safe_reraise():
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/util/langhelpers.py", line 70, in __exit__
compat.raise_(
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
raise exception
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 661, in __connect
self.dbapi_connection = connection = pool._invoke_creator(self)
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/create.py", line 590, in connect
return dialect.connect(*cargs, **cparams)
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 597, in connect
return self.dbapi.connect(*cargs, **cparams)
File "/usr/local/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
Is the server running on host "postgres_db" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
Is the server running on host "podtgres_db" (::1) and accepting
TCP/IP connections on port 5432?
(Background on this error at: https://sqlalche.me/e/14/e3q8)
I do not make sense :(
I tried everything and it's not working but quickly works when I set the ports: 5432:5432 and set localhost:5432 in python script with my host machine but not with docker host.
What can I do wrong, does anyone have any idea;

Need help accessing a virtual server using Flask

So for our last coding projects we've set up a web API that runs on local host. But now he has set up a virtual server for us to use along with usernames and passwords to use as well as which ports we are alllowed to use. I have my current code here. On the last line it used to be localhost and the port was 8080 but I changed it to reflect the new server we were given. However, it doesn't work and I couldn't seem to find a solution online. I also have the IP address and it didn't work either. I wasn't sure how to add my username and password to the mix as well as I am sure it is needed to access the server.
from flask_cors import CORS
import os
from flask import Flask, jsonify, make_response, Blueprint
from flask_swagger_ui import get_swaggerui_blueprint
from routes import request_api
import ssl
context = ssl.SSLContext()
context.load_cert_chain('certificate.pem', 'key.pem')
APP = Flask(__name__)
SWAGGER_URL = '/swagger'
API_URL = '/static/swagger.json'
SWAGGERUI_BLUEPRINT = get_swaggerui_blueprint(
SWAGGER_URL,
API_URL,
config={
'app_name': "Kales Flask Project"
}
)
APP.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL)
APP.register_blueprint(request_api.get_blueprint())
#APP.errorhandler(400)
def handle_400_error(_error):
return make_response(jsonify({'error': 'Misunderstood'}), 400)
#APP.errorhandler(404)
def handle_404_error(_error):
return make_response(jsonify({'error': 'Not found'}), 404)
#APP.errorhandler(401)
def handle_401_error(_error):
return make_response(jsonify({'error': 'Invalid Key Provided'}), 401)
if __name__ == '__main__':
CORS = CORS(APP)
APP.run(host='easel4.cs.utsarr.net', port=int(os.environ.get('PORT', 12145)), ssl_context=context)
Here is the output when I attempt to run this code
C:\Users\kingk\PycharmProjects\AdvanceSoft>python webapi.py
* Serving Flask app "webapi" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
Traceback (most recent call last):
File "webapi.py", line 44, in <module>
APP.run(host='10.100.201.3', port=12145, ssl_context=context)
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\flask\app.py", line 943, in run
run_simple(host, port, self, **options)
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\werkzeug\serving.py", line 1009, in run_simple
inner()
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\werkzeug\serving.py", line 962, in inner
fd=fd,
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\werkzeug\serving.py", line 805, in make_server
host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
File "C:\Users\kingk\PycharmProjects\AdvanceSoft\yes\lib\site-packages\werkzeug\serving.py", line 698, in __init__
HTTPServer.__init__(self, server_address, handler)
File "C:\Users\kingk\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 452, in __init__
self.server_bind()
File "C:\Users\kingk\AppData\Local\Programs\Python\Python37\lib\http\server.py", line 137, in server_bind
socketserver.TCPServer.server_bind(self)
File "C:\Users\kingk\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 466, in server_bind
self.socket.bind(self.server_address)
OSError: [WinError 10049] The requested address is not valid in its context
I assume the host='easel4.cs.utsarr.net' is the problem. The Flask documentation of the run method of the Application object recommends:
host – the hostname to listen on. Set this to '0.0.0.0' to have the server available externally as well. Defaults to '127.0.0.1' or the host in the SERVER_NAME config variable if present.

PeeWee PostgreSQL Database creation: does not exist

I'm attempting to create a PostgreSQL database using PeeWee. Upon connecting I get the following error:
File "peewee_test.py", line 44, in
psql_db.connect()
File "c:\python27\lib\site-packages\peewee.py", line 3602, in connect
self.initialize_connection(self._local.conn)
File "c:\python27\lib\site-packages\peewee.py", line 3514, in exit
reraise(new_type, new_type(*exc_args), traceback)
File "c:\python27\lib\site-packages\peewee.py", line 3600, in connect
**self.connect_kwargs)
File "c:\python27\lib\site-packages\playhouse\postgres_ext.py", line 385, in _connect
conn = super(PostgresqlExtDatabase, self)._connect(database, **kwargs)
File "c:\python27\lib\site-packages\peewee.py", line 3990, in _connect
conn = psycopg2.connect(database=database, **kwargs)
File "c:\python27\lib\site-packages\psycopg2__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
peewee.OperationalError: FATAL: database "test" does not exist
Any idea what I am doing wrong?
from peewee import *
from playhouse.postgres_ext import PostgresqlExtDatabase
psql_db = PostgresqlExtDatabase(
'test', # Required by Peewee.
user='xxxxx', # Will be passed directly to psycopg2.
password='xxxxx', # Ditto.
host='', # Ditto.
port='5432'
)
psql_db.connect() # error occurs here
psql_db.create_tables([Person, Pet])
Peewee wont create the database for you, you need to first connect to the database with psql shell for example and admin user access psql --host HOST --port 5432 --username YOUR_USER -W -d postgres and run CREATE DATABASE test;
Postgres has also a helper createdb executable:
createdb my_db

Flask-Migrate Error: 'ConfigParser.NoSectionError: No section: 'alembic''

For the last few weeks I've been building a website mostly based on Miguel Grinberg's book 'Flask Web Development'. This is my 'manage.py' file for reference:
import os
from app import create_app, db
from app.models import User, Role, Permission, Post
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
return dict(app=app, db=db, User=User, Follow=Follow, Role=Role,
Permission=Permission, Post=Post)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
And this is my app/__init.py file:
from flask import Flask #session, flash, url_for
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from config import config
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
mail = Mail()
moment = Moment()
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
login_manager.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
from main import main as main_blueprint
from .auth import auth as auth_blueprint
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix = '/auth')
return app
As you can see it's a relatively bare-bones project, but it was going well until a few days ago when I accidentally deleted my migrations folder, which up until that point was working without perfectly fine. When I attempted to set up the migrations folder again, I got this error:
(website1)joshua#joshua-ThinkPad-Edge-E430 ~/website/website1 $ python manage.py db migrate
Traceback (most recent call last):
File "manage.py", line 29, in <module>
manager.run()
File "/home/joshua/.virtualenvs/website1/lib/python2.7/site-packages/flask_script/__init__.py", line 412, in run
result = self.handle(sys.argv[0], sys.argv[1:])
File "/home/joshua/.virtualenvs/website1/lib/python2.7/site-packages/flask_script/__init__.py", line 383, in handle
res = handle(*args, **config)
File "/home/joshua/.virtualenvs/website1/lib/python2.7/site-packages/flask_script/commands.py", line 216, in __call__
return self.run(*args, **kwargs)
File "/home/joshua/.virtualenvs/website1/lib/python2.7/site-packages/flask_migrate/__init__.py", line 153, in migrate
config = _get_config(directory, opts=['autogenerate'])
File "/home/joshua/.virtualenvs/website1/lib/python2.7/site-packages/flask_migrate/__init__.py", line 51, in _get_config
config.set_main_option('script_location', directory)
File "/home/joshua/.virtualenvs/website1/lib/python2.7/site-packages/alembic/config.py", line 201, in set_main_option
self.file_config.set(self.config_ini_section, name, value)
File "/home/joshua/anaconda/lib/python2.7/ConfigParser.py", line 753, in set
ConfigParser.set(self, section, option, value)
File "/home/joshua/anaconda/lib/python2.7/ConfigParser.py", line 396, in set
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'alembic'
I'm not really sure what to do about this, I've tried dropping then re-creating my database and running db migrate again but I got the same error as before. I also tried uninstalling and reinstalling alembic but with no luck.
I'm not really sure what do do at this point, up until now whenever I've had an issue with the tutorial I took the time to figure it out on my own since I want to understand how everything works, but I'm totally stumped on this one.
Courtesy Dauros: I neglected to run python manage.py db init.

OperationalError: (OperationalError) (2003, "Can't connect to MySQL server on '192.168.129.139' (111)") None None

I am trying to create a remote database using mysql on an Ubuntu machine running 12.04.
It has a root user with remote login enabled and no password.I have started the server.
output of
sudo netstat -tap | grep mysql
shows
tcp 0 0 localhost:mysql *:* LISTEN 13246/mysqld
I have created a database called nwtopology using (as mentioned root doesn't have a password yet.)
create database nwtopology
grant all privileges on *.* to root#192.168.129.221
FLUSH PRIVILEGES;
From the client machine that also runs Ubuntu 12.04 I use a python script to connect to the remote mysql database using sqlalchemy.
from pox.core import core
import pox.openflow.libopenflow_01 as of
import re
import datetime
import time
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.expression import exists
log = core.getLogger()
engine = create_engine('mysql://root#192.168.129.139/nwtopology', echo=False)
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()
class SourcetoPort(Base):
""""""
__tablename__ = 'source_to_port'
id = Column(Integer, primary_key=True)
port_no = Column(Integer)
src_address = Column(String,index=True)
#-----------------------------------------
def __init__(self, src_address,port_no):
""""""
self.src_address = src_address
self.port_no = port_no
The create_engine() call is failing with the following error.
POX 0.1.0 (betta) / Copyright 2011-2013 James McCauley, et al.
Traceback (most recent call last):
File "/home/karthik/ms_thesis/pox/pox/boot.py", line 89, in do_import2
__import__(name, globals(), locals())
File "/home/karthik/ms_thesis/pox/custom/tutorial.py", line 39, in <module>
Base.metadata.create_all(engine)
File "/usr/lib/python2.7/dist-packages/sqlalchemy/schema.py", line 2515, in create_all
tables=tables)
File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2230, in _run_visitor
conn = self.contextual_connect(close_with_result=False)
File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2340, in contextual_connect
self.pool.connect(),
File "/usr/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 210, in connect
return _ConnectionFairy(self).checkout()
File "/usr/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 371, in __init__
rec = self._connection_record = pool._do_get()
File "/usr/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 697, in _do_get
con = self._create_connection()
File "/usr/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 174, in _create_connection
return _ConnectionRecord(self)
File "/usr/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 256, in __init__
self.connection = self.__connect()
File "/usr/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 316, in __connect
connection = self.__pool._creator()
File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/strategies.py", line 80, in connect
return dialect.connect(*cargs, **cparams)
File "/usr/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 280, in connect
return self.dbapi.connect(*cargs, **cparams)
File "/usr/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (OperationalError) (2003, "Can't connect to MySQL server on '192.168.129.139' (111)") None None
I cannot figure out why this is happening?Any help is greatly appreciated?
Looks like the mysql server is configured to listen only on localhost.
You can test this by running telnet 192.168.129.139 3306 from your client machine.
Most probable reason - mysqld (=MySQL daemon) is configured to do so.
Please try to follow Configuration step described here:
Edit the /etc/mysql/my.cnf file to configure MySQL to listen for connections from network hosts, change the bind-address directive to the server's IP address. For example, in your case, replace 192.168.0.5 with 192.168.129.139.
From:
bind-address = 192.168.0.5
to:
bind-address = 192.168.129.139
If there is no such entry and you cannot connect, create a new line.
You may also try commenting out the line instead.
After making a change to /etc/mysql/my.cnf the MySQL daemon will need to be restarted:
sudo systemctl restart mysql.service
Then test with telnet or by running your application once again. Also netstat would have second entry for mysqld.

Categories