我正在重新研究python和Web开发。我过去使用Django,但是已经有一段时间了。Flask + SqlAlchemy对我来说都是新手,但是我喜欢它给我的控件。
开始 下面的代码在我的开发服务器上就像一个超级按钮。我仍然觉得它没有它应该的那么小和高效。我想知道是否有人建立了类似的解决方案。现在,我正在尝试找到一种使用单个查询并将关键字参数设置为格式的方法。此外,我认为围绕该函数构建一个类以使其更具可重用性可能对我很有用。
以下是根据日期构造查询的功能:
def live_post_filter(year=None, month=None, day=None):
""" Query to filter only published Posts exluding drafts
Takes additional arguments to filter by year, month and day
"""
live = Post.query.filter(Post.status == Post.LIVE_STATUS).order_by(Post.pub_date.desc())
if year and month and day:
queryset = live.filter(extract('year', Post.pub_date) == year,
extract('month', Post.pub_date) == month,
extract('day', Post.pub_date) == day).all()
elif year and month:
queryset = live.filter(extract('year', Post.pub_date) == year,
extract('month', Post.pub_date) == month).all()
elif year:
queryset = live.filter(extract('year', Post.pub_date) == year).all()
else:
queryset = live.all()
return queryset
这是我从视图中调用上述函数的方式:
@mod.route('/api/get_posts/', methods = ['GET'])
@mod.route('/api/get_posts/<year>/<month>/<day>/', methods = ['GET'])
@mod.route('/api/get_posts/<year>/<month>/', methods = ['GET'])
@mod.route('/api/get_posts/<year>/', methods = ['GET'])
def get_posts(year=None, month=None, day=None):
posts = live_post_filter(year=year, month=month, day=day)
postlist = []
if request.method == 'GET':
# do stuff
如上所述,所有这些都感觉很笨拙,任何建议我都将不胜感激。
对extract
日期组件进行筛选对我来说似乎很奇怪。我反而会创建一个返回范围从您的旅行日期的辅助功能year
,month
以及day
参数:
def get_date_range(year=None, month=None, day=None):
from_date = None
to_date = None
if year and month and day:
from_date = datetime(year, month, day)
to_date = from_date
elif year and month:
from_date = datetime(year, month, 1)
month += 1
if month > 12:
month = 1
year += 1
to_date = datetime(year, month, 1)
elif year:
from_date = datetime(year, 1, 1)
to_date = datetime(year + 1, 1, 1)
return from_date, to_date
然后查询功能变得简单得多:
def live_post_filter(year=None, month=None, day=None):
""" Query to filter only published Posts exluding drafts
Takes additional arguments to filter by year, month and day
"""
live = Post.query.filter(Post.status == Post.LIVE_STATUS).order_by(Post.pub_date.desc())
from_date, to_date = get_date_range(year, month, day)
if from_date and to_date:
live = live.filter(Post.pub_date >= from_date, Post.pub_date < to_date)
return live.all()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句