与Flask和SqlAlchemy一样的Django式基于日期的存档

时间:2013-07-20 13:44:37

标签: sqlalchemy flask

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

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

1 个答案:

答案 0 :(得分:2)

使用extract按日期组件过滤对我来说似乎很奇怪。我会创建一个辅助函数,从yearmonthday参数返回一系列日期:

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()