sqlalchemy核心构建动态查询

时间:2016-02-25 11:05:32

标签: python curl sqlalchemy

我需要使用flask框架基于请求表单输入构建搜索表单。应使用sqlalchemy CORE ONLY基于参数的各种输入值动态构建查询。某些值可以为null。同样需要curl命令。我使用过滤器遇到了基于sqlalchemy orm的方法。我该怎么办?我尝试了以下方法: 表:

docs = Table("docs", metadata,   
                      Column("id", Integer, primary_key=True),
                      Column("file_name", String),
                      Column("custom_tag", String, nullable=True),
                      Column("description", String, nullable=True),
                      Column("up_date", DateTime(timezone=True),
                             default=datetime.datetime.utcnow),
                      Column("category_id", Integer, 
                             ForeignKey("categories.id"), nullable=True),
                      Column("sub_category_id", Integer,
                             ForeignKey("sub_categories.id"), nullable=True),
                      Column("alert_date", DateTime(timezone=True)))

卷曲:

curl -b cookies.txt -X POST http://localhost:5000/api/v1.0/docs -d "category_id=1&sub_category_id=None&alert_date=None"

此处任何参数值都是可选的。

查看:

@app.route('/api/v1.0/docs', methods=['POST'])
def search_docs():
        if request.method == 'POST':
            doc_list = []
            category_id = request.form['category_id']
            sub_category_id = request.form['sub_category_id']
            custom_tag = request.form['custom_tag']
            alert_date = request.form['alert_date']

            f_dict = {
                'category_id': category_id,
                'sub_category_id': sub_category_id, 
                'alert_date': alert_date
                }
            for f in f_dict:
                if f_dict[f] == "None":
                    f_dict[f] = None

            s = select([docs]).\
                where(
                and_(
                     docs.c.category_id == category_id,
                     docs.c.sub_category_id == sub_category_id,
                     docs.c.alert_date == alert_date
                     )
                )
            print str(s)
            rs = conn.execute(s)
            for r in rs:
                doc_list.append(dict(r))

            return jsonify({'doc_list': doc_list}), 200

我刚刚尝试删除了一些属性。请回复一下如何生成查询。我在查询中要考虑很多属性值。使用烧瓶0.10,sqlalchemy core,python 2.7

执行上述操作时,数据不会始终存储在表格中。有时它会存储记录,但很多时候它会抛出http 400状态代码。如何将sub_category_id与Null值进行比较?这是可选的?

1 个答案:

答案 0 :(得分:2)

听起来您希望根据为任何过滤器指定的值是None来有条件地构建您的where子句。这样的事情对你有用吗?:

conditions = []
if category_id is not None:
    conditions.append(docs.c.category_id == category_id)
if sub_category_id is not None:
    conditions.append(docs.c.sub_category_id == sub_category_id)
if alert_date is not None:
    conditions.append(docs.c.alert_date == alert_date)

s = select([docs]).where(and_(*conditions))

为确保您希望排除的过滤器具有None值,您可以将其从curl命令行中排除:

-d "category_id=1&sub_category_id=None&alert_date=None"

变为:

-d "category_id=1"

然后在Python脚本中,您可以使用get,其默认返回值为None

category_id = request.form.get('category_id')
sub_category_id = request.form.get('sub_category_id')
...

另一种方法是使用空字符串来表示排除过滤器,这可能更容易传递。