0

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_base
from sqlalchemy import *
from sqlalchemy.orm import *

Base = declarative_base()

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    street = Column(String, nullable=False)
    city = Column(String, nullable=False)
    user = relationship('User', back_populates="address")

class Main():
    def __init__(self):
        engine = create_engine('mysql://test:test@localhost:3306/test', echo=False)
        Session = sessionmaker(bind=engine)
        session = Session()

    def insert(self):
        #   INSERT
        a1 = Address()
        a1.street = "Str 123"
        a1.city = "City WTF"

        session.add(a1) # Unresolved reference
        session.commit()

if __name__ == '__main__':
    Main().run()

I understand it. session is local object in constructor (__init__).

But how can I put object "directly to class"? In Java I do something like:

public class Main {
    Engine engine;
    Session session;
    public Main() {}
        engine = create_engine('mysql://test:test@localhost:3306/test', echo=False)
        session = sessionmaker(bind=engine)
    }
    private insert() {
        //...
        session.commit();
    }
}

How can I do it in python? Sorry for stupid question, I am python newbie.

--------------------- EDIT:

class Main():
    engine = None # What I write here? How declare uninitialized object?
    session = None # What I write here?
    def __init__(self):
        engine = create_engine('mysql://test:test@localhost:3306/test', echo=False)
        Session = sessionmaker(bind=engine)
        session = Session()

    def insert(self):
        #   INSERT
        a1 = Address()
        a1.street = "Str 123"
        a1.city = "City WTF"
        self.session.add(a1) # Is possible to call session without "self"?
        self.session.commit()
4
  • I don't know if this is the direct cause of your problem, but you appear to be mixing tabs and spaces in your indentation. This can cause surprising and unusual errors, because a tab is not interpreted by the parser as four spaces even if that's what it looks like in your text editor. Please use only spaces. Commented May 28, 2015 at 12:08
  • 2
    Just so you know OOP doesn't mean "stick everything in classes." A class should be a digital representation of a real world object. Classes shouldn't (in a perfect world) just be a collection of functions. Commented May 28, 2015 at 12:17
  • I using PyCharm auto code format - it fix space/tabs. Commented May 28, 2015 at 12:19
  • What is your solution? Put content of cosntructor to if __name__ == '__main__':? Commented May 28, 2015 at 12:19

4 Answers 4

4

In Java you'd do this.session = ...; in Python that's self.session = ....

Sign up to request clarification or add additional context in comments.

Comments

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)

class Address(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

    def insert(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, Address
addr = Address('123 Test St.', 'Sometown', 'NY', '12345', some_user)
addr.insert(session)

Comments

1

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

Comments

1

use self.session
to save variables in session

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.