内容简介:最近在研究SQLAlchemy源码,自己造个轮子先(当然,SQLAlchemy远比这里复杂)运行结果:
最近在研究SQLAlchemy源码,自己造个轮子先(当然,SQLAlchemy远比这里复杂)
import logging
logging.basicConfig(level=logging.DEBUG)
class Column:
def __init__(self, type, default=None):
self.col_name = None
self.col_type = type
self.col_default = default
def __eq__(self, value):
logging.debug("__eq__ of {} && {}".format(self, value))
return "{} = {}".format(self.col_name, value)
class Base(type):
def __new__(cls, *args, **kwargs):
logging.debug("creating class {}, args {}, kwargs {}".format(
cls, args, kwargs
))
if len(args) > 2:
for k, v in args[2].items():
if k.startswith("_"):
continue
v.col_name = k
return type.__new__(cls, *args, **kwargs)
class User(metaclass=Base):
__tablename__ = "user"
id = Column(int)
name = Column(str)
passwd = Column(str)
class Queryable:
def __init__(self, table):
self.table = table
def filter(self, text):
return "select * from {} where {}".format(
self.table.__tablename__,
text,
)
class Session:
def query(self, table):
logging.debug("returning Queryable({})".format(table))
return Queryable(table)
session = Session()
print(session.query(User).filter(User.id == 1))
运行结果:
jiajun@debian test: python3 orm.py
DEBUG:root:creating class <class '__main__.Base'>, args ('User', (), {'__qualname__': 'User', '__tablename__': 'user', 'id': <__main__.Column object at 0x7f8174b107b8>, 'passwd': <__main__.Column object at 0x7f8174b10940>, 'name': <__main__.Column object at 0x7f8174b10828>, '__module__': '__main__'}), kwargs {}
DEBUG:root:returning Queryable(<class '__main__.User'>)
DEBUG:root:__eq__ of <__main__.Column object at 0x7f8174b107b8> && 1
select * from user where id = 1
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
年入10万,17岁草根少年的网赚实战
陶秋丰 / 重庆出版集团 / 2009-3 / 28.00元
《年入10万:17岁草根少年的网赚实战》以一个17岁的在校大学生的真实故事为大家讲述草根少年的网络赚钱之旅。随着网络的普及以及网上应用的日益增多,要在网络上谋生并不难,比如网上写稿、网上兼职、威客赚钱、网上开店等,然而要利用互联网赚大钱,并成就一番事业,那么创建并运营一个独立的网站就是一个绝佳的选择。本书的作者正是经历了“网上写稿一网上各类兼职一策划并创建网站一网站推广与运营一年入10万”这一过程......一起来看看 《年入10万,17岁草根少年的网赚实战》 这本书的介绍吧!
JS 压缩/解压工具
在线压缩/解压 JS 代码
正则表达式在线测试
正则表达式在线测试