具有由url定义的可变输出的Flask API

时间:2015-06-30 21:23:42

标签: python json api flask

我正在使用烧瓶编写API。

我希望API根据网址返回列类别或我的表类别的列子类别中的元素。

例如http:... / categories / subcategory或http:... / categories / category

我尝试创建变量category_type并将其分配给输出d,但它不起作用。

 class Categories(db.Model):
      __tablename__ = 'categories'
      category = db.Column(db.Text)
      subcategory = db.Column(db.Text, primary_key = True)

 @app.route('/categories/<string:category_type>', methods=['GET'])
 def categories(category_type):
     if request.method == 'GET':
         results = Categories.query.all()

         json_results = []
         for result in results:
             d = {'Category': result.category_type}
             json_results.append(d)

         return jsonify(items=json_results)

1 个答案:

答案 0 :(得分:1)

更改类别方法类似如下:

@app.route('/categories/<string:category_type>', methods=['GET'])
def categories(category_type):
    if category_type.lower() not in ('category', 'subcagory'):
        flask.abort(404)

    if request.method == 'GET':
        results = Categories.query.all()

        json_results = []
        for result in results:
            d = {'Category': getattr(result, category_type.lower())}
            json_results.append(d)

        return jsonify(items=json_results)

更新:如果您要删除重复项,请将json_results变量类型更改为set,类似如下:

@app.route('/categories/<string:category_type>', methods=['GET'])
def categories(category_type):
    if category_type.lower() not in ('category', 'subcagory'):
        flask.abort(404)

    if request.method == 'GET':
        results = Categories.query.all()

        json_results = set()
        for result in results:
            d = {'Category': getattr(result, category_type.lower())}
            json_results.add(d)

        return jsonify(items=json_results)