使用Flask从URL获取多个参数

2 投票
1 回答
3306 浏览
提问于 2025-04-18 04:03
import config
from flask import Flask, jsonify, request
## app and db is defined on model.py
from model import db, app, PLAY_STORE
@app.route('/app-api', methods=['GET'])
def listapp():
    if request.method == 'GET':
        store=request.args.get('store')
        category=request.args.get('category')
        results = PLAY_STORE.query.filter_by(Store=store,Category=category).all()
        json_results = []
        for result in results:
          d = {'rank': result.Rank,
           'store': result.Store,
           'category': result.Category,
           'type': result.Type,
           'title': result.Title}
          json_results.append(d)

    return jsonify(items=json_results)

if __name__ == '__main__':
    app.run(debug=True)

我正在尝试在 MySQL 数据库上使用 Flask 构建一个 REST API。在这个程序中,我想从网址中获取商店和类别的信息。尽管我使用了 request.args.get,但是商店的值是空的,也就是说 json_results 是空的。如果我直接写死,比如 PLAY_STORE.query.filter_by(Store="Play Store"),我能得到预期的结果。但是当我输入 127.0.0.1/app-api?store="Play Store" 时,json_results 还是空的。

我还有一个问题。如何在 filter_by 中添加多个条件,比如 PLAY_STORE.query.filter_by(Store="Play Store" and Category="Games") 这样?

1 个回答

1

问题出在你的GET请求的URL参数上。

试试这个网址:

  127.0.0.1:5000/app-api?store=Play Store&category=Games

在查询字符串的值中,你不需要加单引号,也就是说:

 <your-host>/?store=XXXXXX not like this <your-host>/?store='XXXXXX'

另外,filter_by是用来处理简单查询的。如果你想进行复杂的查询,可以使用filter,想了解更多信息可以看看这个StackOverflow的问题

撰写回答