Skip to content
Advertisement

function object has no attribute ‘connect’

Seems there’s a problem with my sql alchemy connection, don’t get why? it works sometimes and then doesn’t the next. Also vs code isn’t auto recommending sql alchemy methods, maybe I’ve set it up wrong?

–database.py file

from sqlalchemy import create_engine, engine_from_config
from sqlalchemy.ext.declarative import declarative_base 
from sqlalchemy.orm import sessionmaker 


sqlalchemy_conn= 'postgresql://postgres:naija4life@localhost/fastapi database'
ormengine= create_engine(sqlalchemy_conn)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind= ormengine )
Base = declarative_base()


# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

main file

from logging import exception
from random import randrange
from tkinter.tix import STATUS
from typing import Optional
from urllib import response
from fastapi import Body, FastAPI, Query, Response ,status, HTTPException , Depends
from pydantic import BaseModel
import psycopg2
from psycopg2.extras import RealDictCursor
import time
import sqlalchemy
from sqlalchemy import create_engine, engine_from_config 
from sqlalchemy.ext.declarative import declarative_base 
from sqlalchemy.orm import sessionmaker,session , query
import models 
from database import ormengine , SessionLocal , get_db




app= FastAPI()

models.Base.metadata.create_all(bind=ormengine)



while True:
    try:   
        conn = psycopg2.connect(dbname= 'fastapi database', 
        host= 'localhost' , port= 5432 , 
        user = 'postgres', password= 'naija4life' )
        cur = conn.cursor()
        print('database connection succesful')
        break 
    except Exception as error :
        print("connection failed")
        print("error explanation:", error)
        time.sleep(2)

class Post(BaseModel):
    title: str
    content: str
    Published: bool = True
    rating: Optional[int] = None

@app.get("/sqlalchemy")
def test_post(db: session= Depends(get_db)):
    post= db.query(models.Post).all()
    return {"data":post} 

ERROR I GET:

   return await future
  File "C:UsersaobinOneDriveDocumentsAPI projfastlibsite-packagesanyio_backends_asyncio.py", line 754, in run
    result = context.run(func, *args)
  File "C:UsersaobinOneDriveDocumentsAPI projapp.main.py", line 78, in test_post
    post= db.query(models.Post).all()
  File "C:UsersaobinOneDriveDocumentsAPI projfastlibsite-packagessqlalchemyormquery.py", line 
2759, in all
    return self._iter().all()
  File "C:UsersaobinOneDriveDocumentsAPI projfastlibsite-packagessqlalchemyormquery.py", line 
2894, in _iter
    result = self.session.execute(
  File "C:UsersaobinOneDriveDocumentsAPI projfastlibsite-packagessqlalchemyormsession.py", line 1691, in execute
    conn = self._connection_for_bind(bind)
  File "C:UsersaobinOneDriveDocumentsAPI projfastlibsite-packagessqlalchemyormsession.py", line 1532, in _connection_for_bind
    return self._transaction._connection_for_bind(
  File "C:UsersaobinOneDriveDocumentsAPI projfastlibsite-packagessqlalchemyormsession.py", line 747, in _connection_for_bind
    conn = bind.connect()
AttributeError: 'function' object has no attribute 'connect'

It seems to me that the query method from sql alchemy isnt working for some reason. It doesn’t autocomplete on vs code either.I’ve tried the other variants: sql_expresson ,

Advertisement

Answer

I was looking through the SQL alchemy documentation. The engine connection url was in double-quotes there….so I changed that in my document…..it worked.

sqlalchemy_conn= 'postgresql://postgres:naija4life@localhost/fastapi database'

became

sqlalchemy_conn= "postgresql://postgres:naija4life@localhost/fastapi database"
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement