简体   繁体   中英

Circular Import Error while importing create_engine in Sqlalchemy

I am trying the CS50 Web Development with Python Course, and in the sql section, while importing create_engine from sqlalchemy I got this error

ImportError: cannot import name 'create_engine' from partially initialized module 'sqlalchemy' (most likely due to a circular import)

Here is the snippet:

DATABASE_URL = "postgres://usrname:password@YourHost:5432/flights"


from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine(DATABASE_URL)
db = scoped_session(sessionmaker(bind=engine))   

flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall() 

for flight in flights:
    print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes.")

Timestamp for the Video:

https://video.cs50.net/web/2018/spring/lectures/3?t=1h9m52s

This can result from a namespace collision - ie naming the file you are executing sqlalchemy.py . To fix this, change the name of the script you are executing to something else.

I dont see a circular import here, but a possible work-around is to

import sqlalchemy as sqlalchemy_package
engine = sqlalchemy_package.create_engine(DATABASE_URL)

, replacing the line engine = create_engine(DATABASE_URL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM