class Employees(Base): __tablename__ = 'employees' emp_id = Column(Integer, primary_key=True) emp_name = Column(String(20)) birth_date = Column(Date) email = Column(String(50)) dep_id = Column(Integer, ForeignKey('departments.dep_id'))
class Server_info(Base): __tablename__ = 'server_info' id = Column(Integer, primary_key=True) server_ip = Column(String(64)) server_port = Column(Integer) user_name = Column(String(64)) server_pwd = Column(String(128)) server_key = Column(String(128))
class Users(Base): __tablename__ = 'users' user_id = Column(Integer, primary_key=True) email = Column(String(50), unique=True) password = Column(String(50), unique=True) nickname = Column(String(50), unique=True) c_time = Column(TIMESTAMP, default=datetime.now) def __init__(self, id=None, email=None, password=None, nickname=None, c_time=None): self.id = id self.email = email self.password = password self.nickname = nickname self.c_time = c_time
class User(Base): __tablename__ = "user" id = Column(Integer, primary_key=True, autoincrement=True) username = Column(String(50), nullable=False) def __repr__(self): return self.username
class Author(db.Model): id = Column(Integer, primary_key=True) name = Column(String(255), nullable=False) books = relationship('Book') @staticmethod def search(name): author = Author.query.filter_by(name=name).first() if author is not None: return author return None # staticn method to return instance of unknown author - TOTO optimize to singleton @staticmethod def unknown_author(): return Author.default('Unknown Author') # Check if author exists, if not create a new author @staticmethod def default(name): author = Author.search(name) if author is None: # Author is not known author = Author(name=name) db.session.add(author) db.session.commit() return author def as_dict(self): return {col.name: getattr(self, col.name) for col in self.__table__.columns}
def __init__(self): self.bridge = cv_bridge.CvBridge() self.image_sub = rospy.Subscriber('cropTag', Image, self.image_callback) self.cmd_vel_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1) self.pose_pub = rospy.Publisher('2Dpose', String, queue_size=1) self.twist=Twist() self.string=String() self.rate = rospy.Rate(1)
class Series(db.Model): id = Column(Integer, primary_key=True) name = Column(String(255), nullable=False) sequence = Column(Integer, default=0) books = relationship('Book') def as_dict(self): return {col.name: getattr(self, col.name) for col in self.__table__.columns}
class State(BaseModel): """ Initialize class State with attribute name: (str) name of the state """ __tablename__ = "states" name = Column(String(128), nullable="False") @property def cities(self):
def build(self): # Makefile self['mk']/(self['log'].str() + String(' : ') + self['exe']) self['mk']/(String('\t./')+self['exe']+String(' > $@')) # hpp/cpp self.build_cpp() # bat.bat self['bat']/( String('@gvim -p ') + (self['files']/String(' ')).str() ) # .gitignore self['git']/String('*~')/String('*.swp')/self['exe']/self['log'] return self
def __init__(self, V): Object.__init__(self, V) self['dir'] = Dir(self.val) self['files'] = Vector() self['exe' ] = self['dir']/String(self.val+'.exe') ; self['exe'].rm() self['log' ] = self['dir']/String(self.val+'.log') ; self['files'] += self['log'] self['hpp'] = self['dir']/String('hpp.hpp') ; self['files'] += self['hpp'] self['cpp'] = self['dir']/String('cpp.cpp') ; self['files'] += self['cpp'] self['mk' ] = self['dir']/String('Makefile') ; self['files'] += self['mk'] self['bat'] = self['dir']/String('bat.bat') ; self['files'] += self['bat'] self['git'] = self['dir']/String('.gitignore') ; self['files'] += self['git']
class Article(Base): __tablename__ = "article" id = Column(Integer, primary_key=True, autoincrement=True) title = Column(String(50), nullable=False) create_time = Column(DateTime, nullable=False, default=datetime.now) uid = Column(Integer, ForeignKey("user.id")) user = relationship("User", backref=backref('articles', order_by=create_time.desc())) # __mapper_args__ = { # "order_by": create_time.desc() # } def __repr__(self): return self.title
class Book(db.Model): id = Column(Integer, primary_key=True) title = Column(String(255), nullable=False) # primary information description = Column(Text, nullable=True) isbn13 = Column(String(255), nullable=True) isbn10 = Column(String(255), nullable=True) publisher = Column(String(255), nullable=True) # secondary inputs release_date = Column(String, nullable=True) pagecount = Column(Integer, nullable=True) bindingtype = Column(String, nullable=True) genre = Column(String(255), nullable=True) image_path = Column(String(255), default='no_image_available.gif') # links to other fields author_id = Column(Integer, ForeignKey('author.id')) author = relationship('Author') series_id = Column(Integer, ForeignKey('series.id'), nullable=True) series_nr = Column(Integer, default=0) series = relationship('Series') # includes user scoring libraries = relationship('AssociationBookLibrary') # link to genre tags tags = relationship('AssociationBookTags', back_populates='book') def as_dict(self): return {col.name: getattr(self, col.name) for col in self.__table__.columns} def as_dict_verbose(self): d = self.as_dict() d.pop('author_id') d['author'] = self.author.as_dict() return d def parse(self, d): self.isbn13 = d.get('isbn13') self.isbn10 = d.get('isbn10') self.description = d.get('description') self.publisher = d.get('publisher') def __str__(self): return self.title
class Tag(db.Model): id = Column(Integer, primary_key=True) tag = Column(String(255), nullable=False) @staticmethod def search(label): tag = Tag.query.filter_by(tag=label).first() if tag is not None: return tag return None # Check if tag exists, if not create a new author @staticmethod def default(label): tag = Tag.search(name) if tag is None: # Author is not known tag = Tag(tag=label) db.session.add(tag) db.session.commit() return tag
class User_info(Base): __tablename__ = 'user_info' id = Column(Integer, primary_key=True) user_name = Column(String(64)) user_pwd = Column(String(128))
In [20]: class User(Base): ...: __tablename__ = 'user' ...: id = Column(Integer, primary_key=True) ...: name = Column(String) ...: email = Column(String) ...: def __repr__(self): ...: return "<User(name=%s)>" % self.name ...: In [21]: 以上代码执行以后就成功定义了 User 类,注意 __repr__ 前后各有两个下划线,这种前后有两个下划线的函数表示一个特殊的函数,称为 Python 类的魔法方法,__init__ 也是一个魔法方法,这里 __repr__ 方法会在直接调用实例对象的时候被调用。 此时 User 有一个 __table__ 属性,记录了定义的表信息,该属性如下所示: In [27]: User.__table__ Out[27]: Table('user', MetaData(bind=None), Column('id', Integer(), table=<user>, primary_key=True, nullable=False), Column('name', String(), table=<user>), Column('email', String(), table=<user>), schema=None) 如果想通过 User 查询数据库该怎么办呢?需要先引入 Session。Session 是映射类和数据库沟通的桥梁,包含事务管理功能。通过以下代码创建 Session: In [30]: from sqlalchemy.orm import sessionmaker In [31]: Session = sessionmaker(bind=engine) In [32]: session = Session() 这里的代码先从 sqlalchemy.orm 中导入 sessionmaker,然后创建了 sessionmaker 对象 Session,其中 Session 对象中有一个魔法方法(__call__),这个魔法方法让 Session 对象可以像函数那样调用,从而使用 Session() 获得了 session 对象。 Session 创建成功以后,就可以查询用户了,主要通过 session.query 方法: In [63]: session.query(User).all() Out[63]: [<User(name=aiden)>, <User(name=lxttx)>] In [65]: session.query(User).filter(User.name=='aiden').first()
class Group_info(Base): __tablename__ = 'group_info' id = Column(Integer, primary_key=True) group_name = Column(String(64))
class Departments(Base): __tablename__ = 'departments' # 设置与库中的哪张表关联 dep_id = Column(Integer, primary_key=True) dep_name = Column(String(20), unique=True)
from {{ cookiecutter.tool_name_slug }} import SharedConfig, String class {{ cookiecutter.tool_name_camel_case }}DefaultModel(SharedConfig): target = String() __all__ = ("{{ cookiecutter.tool_name_camel_case }}DefaultModel", )
def str(self): S = '' for i in self.nest: S += i.str().val return String(S)
def build_cpp(self): # hpp.hpp self['hpp']/String('#ifndef _H_HPP')/String('#define _H_HPP') self['hpp']/String('#endif // _H_HPP') # cpp.cpp self['cpp']/(String('#include "')+self['hpp']+String('"')) self['cpp']/String('int main(int argc, char *argv[]) { return 0; }') # Makefile self['mk']/(String('C = ')+self['cpp']) self['mk']/(String('H = ')+self['hpp']) self['mk']/(String('')+self['exe'] + String(' : $(C) $(H)')) self['mk']/(String('\t$(CXX) $(CXXFLAGS) -o $@ $(C) $(L)'))
def str(self): return String(self.val)
def execInput(self, execCtX): text = input() return RTResult().success(String(text))
def execPrintRet(self, execCtX): return RTResult().success(String(str(execCtX.symbTable.get('value'))))