3

我正在重新审视 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 

如上所述,所有这些都感觉很笨拙,任何建议我都会非常感激。

4

1 回答 1

2

按日期组件过滤的使用extract对我来说似乎很奇怪。year相反,我将创建一个辅助函数,该函数从您的,monthday参数返回一系列日期:

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()
于 2013-07-20T18:32:59.330 回答