Created
July 1, 2011 19:29
-
-
Save EntityReborn/1059220 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy import Column, Integer, String, create_engine | |
from sqlalchemy.orm import sessionmaker | |
Base = declarative_base() | |
class Info(Base): | |
__tablename__ = 'infos' | |
id = Column(Integer, primary_key=True) | |
keyword = Column(String, unique=True) | |
response = Column(String) | |
def __init__(self, key, response): | |
self.keyword = key | |
self.response = response | |
def __repr__(self): | |
return "<Info('%s', '%s', '%s')>" % (self.keyword, self.response) | |
class InfoExists(Exception): pass | |
class NoSuchData(Exception): pass | |
class InfoManager(object): | |
def __init__(self, db="/:memory:"): | |
self.engine = create_engine('sqlite://%s' % db, echo=True) | |
Base.metadata.create_all(self.engine) | |
Session = sessionmaker(bind=self.engine) | |
self.session = Session() | |
def addInfo(self, key, response, replace=False): | |
key = key.lower() | |
exists = self.session.query(Info).filter_by(keyword=key) | |
if exists.count(): | |
if not replace: | |
raise InfoExists, key | |
if exists.count(): | |
info = exists | |
info.response = response | |
else: | |
info = Info(key, response) | |
self.session.add(info) | |
self.session.commit() | |
return info | |
def getInfo(self, key): | |
key = key.lower() | |
exists = self.session.query(Info).filter_by(keyword=key) | |
if not exists.count(): | |
return NoSuchData, key | |
return exists.first().response | |
if __name__ == "__main__": | |
m = InfoManager() | |
print "Adding bot" | |
m.addInfo("bot", "I am a bot") | |
print "Adding EntityReborn" | |
m.addInfo("EntityReborn", "He's my owner") | |
try: | |
print "Trying to redefine bot, without replacing" | |
m.addInfo("bot", "should make an error") | |
except InfoExists, key: | |
print "Passed, InfoExists raised for %s" % key | |
try: | |
print "Trying to replace bot" | |
info = m.addInfo("bot", "Updated!", True) | |
print "Passed, bot is now '%s'" % info.response | |
except InfoExists, key: | |
print "Got infoexists, %s" % key | |
except Exception, err: | |
print "Got error: %s" % err | |
print "EntityReborn is '%s'" % m.getInfo("EntityReborn") # All good. | |
print "bot is '%s'" % m.getInfo("bot") # Should be "Updated!", returns "I am a bot" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment