views:

57

answers:

2

I keep receiving the error, "TypeError: 'Shard' object is unsubscriptable."

#Establish an on-demand connection to the central database
def connectCentral():
    engine = engine_from_config(config, 'sqlalchemy.central.')
    central.engine = engine
    central.Session.configure(bind=engine)

#Establish an on-demand connection to a shard that contains
#data for the supplied id
def connectShard(id):

    #If no connection has been made to the central database
    #make one to determine the shard info
    if central.engine == None:
        print 'Connecting to central database'
        connectCentral()

    shard_info = central.Session.query(Shard).filter_by(id=id).first()

    #If no shard exists for the given id, return false
    if shard_info == None:
        return 'None'

    shard.engine = shard_info['sqlite']
    shard.Session.configure(bind=shard.engine)

c_shard = sa.Table("Shard", central.metadata,
sa.Column("id", sa.types.Integer, primary_key=True),
sa.Column("ip",sa.types.String(100), nullable=False),
sa.Column("username",sa.types.String(100), nullable=False),
sa.Column("password",sa.types.String(100), nullable=False),
sa.Column("port",sa.types.String(100), nullable=False),
sa.Column("active",sa.types.String(100), nullable=False),
sa.Column("sqlite",sa.types.String(100), nullable=True)
)

The error output is:

connectShard(232)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/project/project/model/__init__.py", line 39, in connectShard
    shard.Session.configure(bind=shard.engine)
TypeError: 'Shard' object is unsubscriptable
A: 

Given the incomplete snippet of code you've given, the only relevant line is:

shard.Session.configure(bind=shard.engine)

The error indication is a base Python type error, a scalar (or None) needed to be subscripted inside SQLAlchemy. This almost certainly is the result of an incompletely or erroneously constructed session in part of the code that you haven't shown.

msw
A: 

My guess is that the error is in this line:

    shard.engine = shard_info['sqlite']

because shard_info is the only object of Shard class that I can see, and it's the only subscription operation in the code pasted. The traceback shows a different line, so perhaps you edited the source after it was imported?

Back to the error: SQLAlchemy objects aren't dictionaries, so what you want is

    shard.engine = shard_info.sqlite

but that would assign a string (filename? sqlalchemy url?) to engine, which is not what you should be passing to Session.configure(). I'm guessing you want something like

    dbname = shard_info.sqlite
    shard.engine = create_engine('sqlite:///' + dbname)
    shard.Session.configure(bind=shard.engine)
Marius Gedminas