#encoding: utf-8

from sqlalchemy import create_engine,Column,Integer,String,Float,func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from random import randint HOSTNAME = '127.0.0.1' PORT = 3306 DATABASE = 'first_sqlalchemy' USERNAME = 'root' PASSWORD = '' #dialect+driver://username:password@host:port/database
DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/" \
"{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE) engine = create_engine(DB_URI) Base = declarative_base(engine) # Session = sessionmaker(engine)
# session = Session() session = sessionmaker(engine)() #Session(**local_kw) class Article(Base):
__tablename__ = 'article' id = Column(Integer,primary_key=True,autoincrement=True) title = Column(String(50),nullable=False) price = Column(Float,nullable=False) def __repr__(self):
return '<Article(title:%s)>'%self.title # Base.metadata.drop_all()
#
# Base.metadata.create_all() # for x in range(6):
# article = Article(title='title%s'%x,price=randint(x,x+1))
# session.add(article)
#
# session.commit() #模型对象
# articles = session.query(Article).all() #查出所有的数据
#
# s = [article for article in articles]
#
# print(s) #模型属性
article = session.query(Article.title,Article.price).all()#根据类的属性查出相应得数据
print(article) #[('title0', 1.0), ('title1', 2.0), ('title2', 3.0), ('title3', 3.0), ('title4', 4.0), ('title5', 5.0)]
#里面是()元祖 #聚合函数
#func是个类,调用count方法
article_count = session.query(func.count(Article.id)).first()
print(article_count)#(6,)返回得结果是元祖 price_avg = session.query(func.avg(Article.price)).first()
print(price_avg)#(3.0,) price_max = session.query(func.max(Article.price)).first()
print(price_max)#(5.0,) price_min = session.query(func.min(Article.price)).all()
print(price_min)#[(1.0,)] price_sum = session.query(func.sum(Article.price)).first()
print(price_sum)#(18.0,)
#来看下源码func是什么鬼
func = _FunctionGenerator()是这个实例化出来的对象
class _FunctionGenerator(object):
"""Generate :class:`.Function` objects based on getattr calls.""" def __init__(self, **opts):
self.__names = []
self.opts = opts
构造没有func.min这些属性,怎搞出来的,如果对象.__dict__没有这个属性就会执行__getattr__这个方法,所以func.min =_FunctionGenerator(**self.opts)
 
def __getattr__(self, name):
# passthru __ attributes; fixes pydoc
if name.startswith('__'):
try:
return self.__dict__[name]
except KeyError:
raise AttributeError(name) elif name.endswith('_'):
name = name[0:-1]
f = _FunctionGenerator(**self.opts)
f.__names = list(self.__names) + [name]
return f

print(func.sum)

#func.sum()就是调用 __call__方法
def __call__(self, *c, **kwargs):
o = self.opts.copy()
o.update(kwargs) tokens = len(self.__names) if tokens == 2:
package, fname = self.__names
elif tokens == 1:
package, fname = "_default", self.__names[0]
else:
package = None if package is not None:
func = _registry[package].get(fname)
if func is not None:
return func(*c, **o) return Function(self.__names[-1],
packagenames=self.__names[0:-1], *c, **o) #func.sum(Article.price) 相当于 select sum(price) from article

 
 

最新文章

  1. C#-和时间有关的计算代码、时间相减 得到天数、小时、分钟、秒差
  2. PL/Cool
  3. CentOS7下安装FTP服务
  4. Node初学者入门,一本全面的NodeJS教程(转载)
  5. MongoDB的基本使用
  6. Ubuntu上安装zsh
  7. c基础补充
  8. Mysql线程池优化笔记
  9. C# winForm里窗体嵌套
  10. bzoj 2298: [HAOI2011]problem a
  11. bzoj4195(并查集+离散化)
  12. Django基础和基本使用
  13. 简单整理关于C#和Java的区别
  14. SQL Server 2012/2016/2017 新增函数
  15. pyspider入门
  16. Android开发颜色大全
  17. 【Python学习笔记】-冒泡排序、插入排序、二分法查找
  18. 怎样更新PE内的工具
  19. Python 3 学习笔记(2)
  20. Django 2.0.1 官方文档翻译: 编写你的第一个 Django app,第五部分(Page 10)

热门文章

  1. java常见问题 ——编辑报错1
  2. HGOI 20190830 题解
  3. flask框架(十一): 蓝图
  4. 顺序表应用5:有序顺序表归并(SDUT 3329)
  5. AcWing:142. 前缀统计(字典树)
  6. selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  7. HDU 5810 Balls and Boxes ——(数学,概率,方差)
  8. [洛谷P3942]:将军令(贪心)
  9. 当 springboot 部署war包,tomcat报一堆无法解决的问题时
  10. JS基础_使用工厂方法创建对象