Skip to main content
 首页 » 编程设计

python之使用 flask 从url获取多个参数

2025年05月04日8soundcode

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) 

我正在尝试使用 flask 在 mysql 数据库之上构建一个 rest api。 在上面的程序中,我试图从 url 中获取商店和类别。即使我使用 request.args.get,Store 值为空,即 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")。

请您参考如下方法:

问题出在您的 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 question