Python: Define Object Variable Without Initialization
I am trying to rewrite my code from one big function to oop. If I have this, it crash on session.add(a1) # Unresolved reference: from sqlalchemy.ext.declarative import declarative_
Solution 1:
In Java you'd do this.session = ...
; in Python that's self.session = ...
.
Solution 2:
The methods on your Main
class look like they belong in the Address
class.
engine = create_engine('mysql://test:test@localhost:3306/test', echo=False)
session = sessionmaker(bind=engine)
classAddress(Base):
__tablename__ = 'address'id = Column(Integer, primary_key=True)
street = Column(String, nullable=False)
city = Column(String, nullable=False)
# you are missing some fields you'll need eventually
state = Column(String, nullable=False)
zip_code = Column(String, nullable=False) # this can be an int if you don't have to worry about Canadian zips which have letters in them
user = relationship('User', back_populates="address")
def__init__(self, street, city, state, zip_code, user):
self.street = street
self.city = city
self.state = state
self.zip_code = zip_code
self.user = user
definsert(self, session):
# INSERT
session.add(self)
session.commit()
You shouldn't create the session as part of a class because then you will be creating a new one every time you instantiate a class. Keep the session in the global space and pass it in to your methods/functions that need it as a parameter (don't use global
).
Now with everything in right place you can use it like this:
from models import session, Addressaddr= Address('123 Test St.', 'Sometown', 'NY', '12345', some_user)
addr.insert(session)
Solution 3:
You are initializing local variable session
in the __init__
method and calling for it in a method this variable is unknown to.
use self.varialbe
in both cases instead
Solution 4:
use self.session to save variables in session
Post a Comment for "Python: Define Object Variable Without Initialization"