sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) with PostgreSQL - python
I searched for this error a lot, but I only find some with more information behind that like "FATAL: ...". Mine has none. It only says
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError)
I have a postgres database inside a docker container that has set his port to the standard 5432.
I've created the container with the following command:
docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -p 5432:5432 -d postgres
It is clean so no database created. The API should automatically create them.
I'm using Pycharm IDE, maybe it has something todo with that.
Traceback (most recent call last):
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 373, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\uvicorn\middleware\debug.py", line 96, in __call__
raise exc from None
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\uvicorn\middleware\debug.py", line 93, in __call__
await self.app(scope, receive, inner_send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\fastapi\applications.py", line 208, in __call__
await super().__call__(scope, receive, send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\middleware\errors.py", line 181, in __call__
raise exc from None
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\middleware\errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\exceptions.py", line 82, in __call__
raise exc from None
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\routing.py", line 580, in __call__
await route.handle(scope, receive, send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\routing.py", line 241, in handle
await self.app(scope, receive, send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\routing.py", line 52, in app
response = await func(request)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\fastapi\routing.py", line 226, in app
raw_response = await run_endpoint_function(
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\fastapi\routing.py", line 159, in run_endpoint_function
return await dependant.call(**values)
File "C:\Users\Veril\PycharmProjects\partyapp-python\app\routers\v1\users.py", line 31, in create_user
session.commit()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1428, in commit
self._transaction.commit(_to_root=self.future)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 829, in commit
self._prepare_impl()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
self.session.flush()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3339, in flush
self._flush(objects)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3479, in _flush
transaction.rollback(_capture_exception=True)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
compat.raise_(
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
raise exception
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3439, in _flush
flush_context.execute()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 456, in execute
rec.execute(self)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 630, in execute
util.preloaded.orm_persistence.save_obj(
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 209, in save_obj
for (
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 370, in _organize_states_for_save
for state, dict_, mapper, connection in _connections_for_states(
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 1709, in _connections_for_states
connection = uowtransaction.transaction.connection(base_mapper)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 626, in connection
return self._connection_for_bind(bind, execution_options)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 735, in _connection_for_bind
conn = self._parent._connection_for_bind(bind, execution_options)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 747, in _connection_for_bind
conn = bind.connect()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\future\engine.py", line 419, in connect
return super(Engine, self).connect()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\engine\base.py", line 3194, in connect
return self._connection_cls(self, close_with_result=close_with_result)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\engine\base.py", line 96, in __init__
else engine.raw_connection()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\engine\base.py", line 3273, in raw_connection
return self._wrap_pool_connect(self.pool.connect, _connection)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\engine\base.py", line 3243, in _wrap_pool_connect
Connection._handle_dbapi_exception_noconnection(
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2097, in _handle_dbapi_exception_noconnection
util.raise_(
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
raise exception
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\engine\base.py", line 3240, in _wrap_pool_connect
return fn()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\base.py", line 310, in connect
return _ConnectionFairy._checkout(self)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\base.py", line 868, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\base.py", line 476, in checkout
rec = pool._do_get()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 146, in _do_get
self._dec_overflow()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
compat.raise_(
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
raise exception
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 143, in _do_get
return self._create_connection()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\base.py", line 256, in _create_connection
return _ConnectionRecord(self)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\base.py", line 371, in __init__
self.__connect()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\base.py", line 666, in __connect
pool.logger.debug("Error on connect(): %s", e)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
compat.raise_(
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
raise exception
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\base.py", line 661, in __connect
self.dbapi_connection = connection = pool._invoke_creator(self)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\engine\create.py", line 590, in connect
return dialect.connect(*cargs, **cparams)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\engine\default.py", line 584, in connect
return self.dbapi.connect(*cargs, **cparams)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\psycopg2\__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError)
(Background on this error at: https://sqlalche.me/e/14/e3q8)
This is my error that i get. My code looks like this:
main.py:
import os
import uvicorn
if __name__ == '__main__':
port = int(os.getenv("PORT"))
uvicorn.run("main:app", host='0.0.0.0', port=port, reload=True, debug=True, workers=3)
app/main.py:
import os
from fastapi import FastAPI
from .database import engine
from .routers import v1
engine.init_db()
port = int(os.getenv("PORT")) #Port is 8000
app = FastAPI()
app.include_router(v1.router, prefix="/v1")
app/database/engine.py: (referenced in the file above)
import os
from fastapi.security import HTTPBearer
from sqlmodel import create_engine, SQLModel, Session
DATABASE_URL = "postgresql+psycopg2://postgres:mysecretpassword#localhost:5432"
engine = create_engine(DATABASE_URL, echo=True)
token_auth_scheme = HTTPBearer()
async def init_db():
async with engine.begin() as conn:
# await conn.run_sync(SQLModel.metadata.drop_all)
await conn.run_sync(SQLModel.metadata.create_all)
async def get_session():
session = Session(engine)
try:
yield session
finally:
session.close()
The route "users" inside routers/v1/users.py:
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Path, Response, status
from pydantic import ValidationError
from sqlalchemy.exc import IntegrityError
from sqlalchemy.sql.functions import concat
from sqlalchemy import func
from sqlmodel import Session, select, col
from starlette import status
from app.database import models
from app.database.authentication import VerifyToken
from app.database.engine import get_session, token_auth_scheme
router = APIRouter()
#router.post("", status_code=status.HTTP_201_CREATED, response_model=models.UserRead,
response_model_exclude_none=True, name="Create User", tags=["users"])
async def create_user(user_data: models.UserCreate,
session: Session = Depends(get_session)):
try:
new_user = models.User(**dict(user_data))
session.add(new_user)
session.commit()
session.refresh(new_user)
return new_user
except IntegrityError:
session.rollback()
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, detail="IntegrityError")
except ValidationError:
session.rollback()
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail="ValidationError")
The models.User:
class UserBase(SQLModel):
id: str
username: Optional[str]
country_code: Optional[str]
phone: Optional[str]
class Config:
allow_population_by_field_name = True
class User(UserBase, table=True):
__tablename__ = 'users'
id: str = Field(primary_key=True)
username: Optional[str] = Field(sa_column=Column('username', VARCHAR(length=50), unique=True, default=None))
phone: Optional[str] = Field(sa_column=Column('phone', VARCHAR(length=20), unique=True, default=None))
I hope that this is everything you guys need to find something. If you need something else contact me.
Best regards
Colin
EDIT:
After I changed the link from `postgresql+psycopg2` to `postgresql+asyncpg` I get a new error:
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 373, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\uvicorn\middleware\debug.py", line 96, in __call__
raise exc from None
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\uvicorn\middleware\debug.py", line 93, in __call__
await self.app(scope, receive, inner_send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\fastapi\applications.py", line 208, in __call__
await super().__call__(scope, receive, send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\middleware\errors.py", line 181, in __call__
raise exc from None
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\middleware\errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\exceptions.py", line 82, in __call__
raise exc from None
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\routing.py", line 580, in __call__
await route.handle(scope, receive, send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\routing.py", line 241, in handle
await self.app(scope, receive, send)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\starlette\routing.py", line 52, in app
response = await func(request)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\fastapi\routing.py", line 226, in app
raw_response = await run_endpoint_function(
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\fastapi\routing.py", line 159, in run_endpoint_function
return await dependant.call(**values)
File "C:\Users\Veril\PycharmProjects\partyapp-python\app\routers\v1\users.py", line 26, in create_user
session.commit()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1428, in commit
self._transaction.commit(_to_root=self.future)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 829, in commit
self._prepare_impl()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
self.session.flush()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3339, in flush
self._flush(objects)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3479, in _flush
transaction.rollback(_capture_exception=True)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
compat.raise_(
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
raise exception
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3439, in _flush
flush_context.execute()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 456, in execute
rec.execute(self)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 630, in execute
util.preloaded.orm_persistence.save_obj(
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 209, in save_obj
for (
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 370, in _organize_states_for_save
for state, dict_, mapper, connection in _connections_for_states(
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 1709, in _connections_for_states
connection = uowtransaction.transaction.connection(base_mapper)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 626, in connection
return self._connection_for_bind(bind, execution_options)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 735, in _connection_for_bind
conn = self._parent._connection_for_bind(bind, execution_options)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\orm\session.py", line 747, in _connection_for_bind
conn = bind.connect()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\future\engine.py", line 419, in connect
return super(Engine, self).connect()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\engine\base.py", line 3194, in connect
return self._connection_cls(self, close_with_result=close_with_result)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\engine\base.py", line 96, in __init__
else engine.raw_connection()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\engine\base.py", line 3273, in raw_connection
return self._wrap_pool_connect(self.pool.connect, _connection)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\engine\base.py", line 3240, in _wrap_pool_connect
return fn()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\base.py", line 310, in connect
return _ConnectionFairy._checkout(self)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\base.py", line 868, in _checkout
fairy = _ConnectionRecord.checkout(pool)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\base.py", line 476, in checkout
rec = pool._do_get()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 146, in _do_get
self._dec_overflow()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
compat.raise_(
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
raise exception
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 143, in _do_get
return self._create_connection()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\base.py", line 256, in _create_connection
return _ConnectionRecord(self)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\base.py", line 371, in __init__
self.__connect()
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\base.py", line 666, in __connect
pool.logger.debug("Error on connect(): %s", e)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
compat.raise_(
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
raise exception
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\pool\base.py", line 661, in __connect
self.dbapi_connection = connection = pool._invoke_creator(self)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\engine\create.py", line 590, in connect
return dialect.connect(*cargs, **cparams)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\engine\default.py", line 584, in connect
return self.dbapi.connect(*cargs, **cparams)
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py", line 748, in connect
await_only(self.asyncpg.connect(*arg, **kw)),
File "C:\Users\Veril\PycharmProjects\partyapp-python\venv\lib\site-packages\sqlalchemy\util\_concurrency_py3k.py", line 61, in await_only
raise exc.MissingGreenlet(
sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/14/xd2s)
EDIT 2:
If I use my local postgres database in docker i get this error. If I use my extern database from Heroku it works perfectly fine!
EDIT 3:
So apparently it won't work with my local docker postgres database. Now I am using my production database over heroku (so externally) and everything works with psycopg2. I didn't found the error why it won't let me use my local db but whatever.
Even though I can see that you are using default port, maybe this can help to somebody with the same problem.
For me the problem was in explicit port definition - as I'm running two different postgres DB and (both from containers), one of them I set to listen to 5433 port - and this gives me exact same problem, so instead
SQLALCHEMY_DATABASE_URL = "postgresql://postgres:password#localhost/fastapi"
I just put:
SQLALCHEMY_DATABASE_URL = "postgresql://postgres:password#localhost:5433/fastapi"
Problem solved right away.
Related
"KeyError: 0" when connecting to MySQL (get_default_isolation_level)
Currently developing for python 3.9.6 with sqlalchemy version 1.4.23 and whenever I use sqlalchemy to connect to a database, I get an error with this stack trace: Traceback (most recent call last): File "/mnt/c/Importer/common/db.py", line 106, in db_cur with engine.connect() as con: File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3166, in connect return self._connection_cls(self, close_with_result=close_with_result) File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 96, in __init__ else engine.raw_connection() File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3245, in raw_connection return self._wrap_pool_connect(self.pool.connect, _connection) File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 3212, in _wrap_pool_connect return fn() File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 307, in connect return _ConnectionFairy._checkout(self) File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 767, in _checkout fairy = _ConnectionRecord.checkout(pool) File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 425, in checkout rec = pool._do_get() File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/pool/impl.py", line 146, in _do_get self._dec_overflow() File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 70, in __exit__ compat.raise_( File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 207, in raise_ raise exception File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/pool/impl.py", line 143, in _do_get return self._create_connection() File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 253, in _create_connection return _ConnectionRecord(self) File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 368, in __init__ self.__connect() File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 622, in __connect pool.dispatch.connect.for_modify( File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/event/attr.py", line 329, in _exec_w_sync_on_first_run self(*args, **kw) File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/event/attr.py", line 343, in __call__ fn(*args, **kw) File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 1691, in go return once_fn(*arg, **kw) File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/engine/create.py", line 674, in first_connect dialect.initialize(c) File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/dialects/mysql/base.py", line 2961, in initialize default.DefaultDialect.initialize(self, connection) File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 407, in initialize self.default_isolation_level = self.get_default_isolation_level( File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 473, in get_default_isolation_level return self.get_isolation_level(dbapi_conn) File "/home/jimmy/.local/share/virtualenvs/Importer-0-6a4YAh/lib/python3.9/site-packages/sqlalchemy/dialects/mysql/base.py", line 2720, in get_isolation_level val = row[0] KeyError: 0 I can fix the issue by manually changing the file from val = row[0] to val = row['##transaction_isolation'] but I don't want to have to manually change dependency files after installing them. I have tried manually setting the transaction isolation when creating the engine, but that doesn't prevent get_isolation_level() from being called so the error persists. Is sqlalchemy not compatible with python 3.9.6? Does this have anything to do with the mysql server version?
Problem was with the DictCursor being used in the connection. Changing _fetch_type for SELECT ##transaction_isolation to be a tuple instead of a dictionary solved the issue.
Why my Cloud Run got an Broken Pipe error?
I got an error on my Cloud Run, in my log it said Broken Pipe error, and when I check it which line that got an error on my Code, it on my db2.comit(). My cloud run always run well from 6 month ago without any error, but now got this error. So here are the detail from the log. Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 385, in run_asgi result = await app(self.scope, self.receive, self.send) File "/usr/local/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__ return await self.app(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/fastapi/applications.py", line 190, in __call__ await super().__call__(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__ await self.middleware_stack(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__ raise exc from None File "/usr/local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__ await self.app(scope, receive, _send) File "/usr/local/lib/python3.8/site-packages/starlette/middleware/cors.py", line 78, in __call__ await self.app(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__ raise exc from None File "/usr/local/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__ await self.app(scope, receive, sender) File "/usr/local/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__ await route.handle(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle await self.app(scope, receive, send) File "/usr/local/lib/python3.8/site-packages/starlette/routing.py", line 41, in app response = await func(request) File "/usr/local/lib/python3.8/site-packages/fastapi/routing.py", line 188, in app raw_response = await run_endpoint_function( File "/usr/local/lib/python3.8/site-packages/fastapi/routing.py", line 135, in run_endpoint_function return await dependant.call(**values) File "/app/api/endpoints.py", line 48, in detect db2.commit() File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 1042, in commit self.transaction.commit() File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 504, in commit self._prepare_impl() File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 483, in _prepare_impl self.session.flush() File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 2523, in flush self._flush(objects) File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 2664, in _flush transaction.rollback(_capture_exception=True) File "/usr/local/lib/python3.8/site-packages/sqlalchemy/util/langhelpers.py", line 68, in __exit__ compat.raise_( File "/usr/local/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 182, in raise_ raise exception File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 2624, in _flush flush_context.execute() File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/unitofwork.py", line 422, in execute rec.execute(self) File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/unitofwork.py", line 586, in execute persistence.save_obj( File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/persistence.py", line 205, in save_obj for ( File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/persistence.py", line 373, in _organize_states_for_save for state, dict_, mapper, connection in _connections_for_states( File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/persistence.py", line 1602, in _connections_for_states connection = uowtransaction.transaction.connection(base_mapper) File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 314, in connection return self._connection_for_bind(bind, execution_options) File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 421, in _connection_for_bind conn = self._parent._connection_for_bind(bind, execution_options) File "/usr/local/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 433, in _connection_for_bind conn = bind._contextual_connect() File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 2304, in _contextual_connect self._wrap_pool_connect(self.pool.connect, None), File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/base.py", line 2338, in _wrap_pool_connect return fn() File "/usr/local/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 364, in connect return _ConnectionFairy._checkout(self) File "/usr/local/lib/python3.8/site-packages/sqlalchemy/pool/base.py", line 809, in _checkout result = pool._dialect.do_ping(fairy.connection) File "/usr/local/lib/python3.8/site-packages/sqlalchemy/engine/default.py", line 560, in do_ping cursor.execute(self._dialect_specific_select_one) File "/usr/local/lib/python3.8/site-packages/pg8000/core.py", line 340, in execute self._c.execute_unnamed(self, "begin transaction") File "/usr/local/lib/python3.8/site-packages/pg8000/core.py", line 1214, in execute_unnamed self.handle_messages(cursor) File "/usr/local/lib/python3.8/site-packages/pg8000/core.py", line 1377, in handle_messages code, data_len = ci_unpack(self._read(5)) struct.error: unpack_from requires a buffer of at least 5 bytes for unpacking 5 bytes at offset 0 (actual buffer size is 0) And this is my line of code that occurs the error. except Exception as e: # noqa log = orm.LogPredictStatus(customer_id=customer_id, status_code=500, car_attribute=car.dict(), price=None, source='TEST', created_at=time_zone_jakarta) db2.add(log) db2.commit() raise HTTPException( status_code=500, detail=str(e), )
Connecting to Google Cloud SQL Server from App Engine in the same project - Login timeout
I am using the sample code that google has provided on github: https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/cloud-sql/sql-server/sqlalchemy I have created a Cloud SQL server on the project and when I run the main.py file from my local machine, the database gets updated OK. However, when I deploy the same code on Google App Engine, I get the following timeout error: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/gunicorn/workers/gthread.py", line 271, in handle keepalive = self.handle_request(req, conn) File "/usr/local/lib/python3.9/site-packages/gunicorn/workers/gthread.py", line 320, in handle_request respiter = self.wsgi(environ, resp.start_response) File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 2464, in __call__ return self.wsgi_app(environ, start_response) File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 2450, in wsgi_app response = self.handle_exception(e) File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1867, in handle_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python3.9/site-packages/flask/_compat.py", line 39, in reraise raise value File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1945, in full_dispatch_request self.try_trigger_before_first_request_functions() File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1993, in try_trigger_before_first_request_functions func() File "/app/main.py", line 116, in create_tables if not db.has_table("votes"): File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 2331, in has_table return self.run_callable(self.dialect.has_table, table_name, schema) File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 2211, in run_callable with self._contextual_connect() as conn: File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 2302, in _contextual_connect self._wrap_pool_connect(self.pool.connect, None), File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 2339, in _wrap_pool_connect Connection._handle_dbapi_exception_noconnection( File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 1583, in _handle_dbapi_exception_noconnection util.raise_( File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 182, in raise_ raise exception File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/base.py", line 2336, in _wrap_pool_connect return fn() File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 364, in connect return _ConnectionFairy._checkout(self) File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 778, in _checkout fairy = _ConnectionRecord.checkout(pool) File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 495, in checkout rec = pool._do_get() File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/impl.py", line 140, in _do_get self._dec_overflow() File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 68, in __exit__ compat.raise_( File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 182, in raise_ raise exception File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/impl.py", line 137, in _do_get return self._create_connection() File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 309, in _create_connection return _ConnectionRecord(self) File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 440, in __init__ self.__connect(first_connect_check=True) File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 661, in __connect pool.logger.debug("Error on connect(): %s", e) File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.py", line 68, in __exit__ compat.raise_( File "/usr/local/lib/python3.9/site-packages/sqlalchemy/util/compat.py", line 182, in raise_ raise exception File "/usr/local/lib/python3.9/site-packages/sqlalchemy/pool/base.py", line 656, in __connect connection = pool._invoke_creator(self) File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect return dialect.connect(*cargs, **cparams) File "/usr/local/lib/python3.9/site-packages/sqlalchemy/engine/default.py", line 493, in connect return self.dbapi.connect(*cargs, **cparams) sqlalchemy.exc.OperationalError: (pyodbc.OperationalError) ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
You need to configure your App Engine Flex service to connect to a Cloud SQL instance. In your app.yaml you need to set: beta_settings: cloud_sql_instances: INSTANCE_CONNECTION_NAME=tcp:PORT Where the INSTANCE_CONNECTION_NAME has the following structure: <project-name>:<region-name>:<instance-name> And when you connect, you should connect to 172.17.0.1:PORT where PORT is the port you specified in the app.yaml file
Connecting Flask To AWS RDS using Flask-SQLAlchemy
I have been trying to connect my aws RDS database instance to a flask application I have downloaded. I have been following https://medium.com/#rodkey/deploying-a-flask-application-on-aws-a72daba6bb80 and using the flask app on this github to connect to the database https://github.com/inkjet/flask-aws-tutorial. I have set the permissions on my RDS server correctly and have been using the following code to connect to the DB. # edit the URI below to add your RDS password and your AWS URL # The other elements are the same as used in the tutorial # format: (user):(password)#(db_identifier).amazonaws.com:3306/(db_name) SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{userName}:{password}#{endpoint}:3306/{dbName}' # Uncomment the line below if you want to work with a local DB #SQLALCHEMY_DATABASE_URI = 'sqlite:///test.db' SQLALCHEMY_POOL_RECYCLE = 3600 WTF_CSRF_ENABLED = True I am still receiving a timeout error: {path_to_virt_env}/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py:834: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True or False to suppress this warning. 'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and ' Traceback (most recent call last): File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 583, in connect **kwargs) File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 728, in create_connection raise err File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 716, in create_connection sock.connect(sa) socket.timeout: timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2345, in _wrap_pool_connect return fn() File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 364, in connect return _ConnectionFairy._checkout(self) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 778, in _checkout fairy = _ConnectionRecord.checkout(pool) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 495, in checkout rec = pool._do_get() File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 140, in _do_get self._dec_overflow() File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__ exc_value, with_traceback=exc_tb, File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_ raise exception File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 137, in _do_get return self._create_connection() File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 309, in _create_connection return _ConnectionRecord(self) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 440, in __init__ self.__connect(first_connect_check=True) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 661, in __connect pool.logger.debug("Error on connect(): %s", e) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__ exc_value, with_traceback=exc_tb, File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_ raise exception File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 656, in __connect connection = pool._invoke_creator(self) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect return dialect.connect(*cargs, **cparams) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 490, in connect return self.dbapi.connect(*cargs, **cparams) File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 325, in __init__ self.connect() File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 630, in connect raise exc pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '{endpoint}' (timed out)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "db_create.py", line 4, in <module> db.create_all() File "{path_to_virt_env}/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 1039, in create_all self._execute_for_all_tables(app, bind, 'create_all') File "{path_to_virt_env}/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 1031, in _execute_for_all_tables op(bind=self.get_engine(app, bind), **extra) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/sql/schema.py", line 4465, in create_all ddl.SchemaGenerator, self, checkfirst=checkfirst, tables=tables File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2103, in _run_visitor with self._optional_conn_ctx_manager(connection) as conn: File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py", line 112, in __enter__ return next(self.gen) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2095, in _optional_conn_ctx_manager with self._contextual_connect() as conn: File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2311, in _contextual_connect self._wrap_pool_connect(self.pool.connect, None), File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2349, in _wrap_pool_connect e, dialect, self File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1591, in _handle_dbapi_exception_noconnection sqlalchemy_exception, with_traceback=exc_info[2], from_=e File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_ raise exception File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2345, in _wrap_pool_connect return fn() File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 364, in connect return _ConnectionFairy._checkout(self) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 778, in _checkout fairy = _ConnectionRecord.checkout(pool) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 495, in checkout rec = pool._do_get() File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 140, in _do_get self._dec_overflow() File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__ exc_value, with_traceback=exc_tb, File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_ raise exception File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 137, in _do_get return self._create_connection() File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 309, in _create_connection return _ConnectionRecord(self) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 440, in __init__ self.__connect(first_connect_check=True) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 661, in __connect pool.logger.debug("Error on connect(): %s", e) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__ exc_value, with_traceback=exc_tb, File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_ raise exception File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 656, in __connect connection = pool._invoke_creator(self) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect return dialect.connect(*cargs, **cparams) File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 490, in connect return self.dbapi.connect(*cargs, **cparams) File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 325, in __init__ self.connect() File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 630, in connect raise exc sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '{endpoint}' (timed out)") (Background on this error at: http://sqlalche.me/e/e3q8 If any more information is needed, please let me know!
Based on the comments, the issue was that RDS's public accessibility setting was not enabled. The solution was to enable it.
Error while trying to connect MySQL with sqlalchemy (Flask)
I have been looking for this error for a while but nothing seems to solve my problem, the thing is.. I was using sqlite3 with flask, but it seems like sqlite3 does not support migrations, so I decided to change to Mysql. I have installed LAMPP, and I created a symbolik link from: /opt/lampp/var/mysql/mysql.sock to: /var/run/mysqld/mysql.sock but still I get this error (it is a little long but the trouble relapse on the last line): Traceback (most recent call last): File "db_create.py", line 5, in <module> db.create_all() File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 895, in create_all self._execute_for_all_tables(app, bind, 'create_all') File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/flask_sqlalchemy/__init__.py", line 887, in _execute_for_all_tables op(bind=self.get_engine(app, bind), **extra) File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/sql/schema.py", line 3634, in create_all tables=tables) File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1851, in _run_visitor with self._optional_conn_ctx_manager(connection) as conn: File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__ return self.gen.next() File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1844, in _optional_conn_ctx_manager with self.contextual_connect() as conn: File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 2035, in contextual_connect self._wrap_pool_connect(self.pool.connect, None), File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 2074, in _wrap_pool_connect e, dialect, self) File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1405, in _handle_dbapi_exception_noconnection exc_info File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 199, in raise_from_cause reraise(type(exception), exception, tb=exc_tb) File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 2070, in _wrap_pool_connect return fn() File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 376, in connect return _ConnectionFairy._checkout(self) File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 708, in _checkout fairy = _ConnectionRecord.checkout(pool) File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 480, in checkout rec = pool._do_get() File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 1055, in _do_get self._dec_overflow() File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 60, in __exit__ compat.reraise(exc_type, exc_value, exc_tb) File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 1052, in _do_get return self._create_connection() File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 323, in _create_connection return _ConnectionRecord(self) File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 449, in __init__ self.connection = self.__connect() File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/pool.py", line 602, in __connect connection = self.__pool._invoke_creator(self) File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/strategies.py", line 97, in connect return dialect.connect(*cargs, **cparams) File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 385, in connect return self.dbapi.connect(*cargs, **cparams) File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/MySQLdb/__init__.py", line 81, in Connect return Connection(*args, **kwargs) File "/home/gerardo/Documentos/python_web_dev/flask-intro/venv/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 193, in __init__ super(Connection, self).__init__(*args, **kwargs2) sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") On my research, I found that I have to change the line: socket = /var/run/mysqld/mysqld.sock placed on /etc/mysql/my.cnf to: socket = /opt/lampp/var/mysql/mysql.sock (The path were "mysql.sock" is located), but still it does not solve my problem. Thank you!
In the database configuration. Replace localhost with 127.0.0.1: environ.get('APP_DATABASE_HOST', 'localhost') to environ.get('APP_DATABASE_HOST', '127.0.0.1')