V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
U87
V2EX  ›  问与答

flask 有个小问题堵了半天没弄明白

  •  
  •   U87 · 2018-07-26 17:31:08 +08:00 · 1237 次点击
    这是一个创建于 2094 天前的主题,其中的信息可能已经有所发展或是发生改变。

    from flask import Flask, abort, request, jsonify

    app = Flask(name)

    测试数据暂时存放

    tasks = []

    @app.route('/add_task/', methods=['POST']) def add_task(): if not request.json or 'id' not in request.json or 'info' not in request.json: abort(400) task = { 'id': request.json['id'], 'info': request.json['info'] } tasks.append(task) return jsonify({'result': 'success'})

    @app.route('/get_task/', methods=['GET']) def get_task(): if not request.args or 'id' not in request.args: # 没有指定 id 则返回全部 return jsonify(tasks) else: task_id = request.args['id'] task = filter(lambda t: t['id'] == int(task_id), tasks) return jsonify(task) if task else jsonify({'result': 'not found'})

    if name == "main": app.run(debug=True)

    当 tasks 是[{"id":123, "info": "测试"},{"id":456, "info":"测试 2"}] 我 get 请求是 http://127.0.0.1:5000/get_task/?id=123 为什么报错 TypeError: Object of type 'filter' is not JSON serializable

    4 条回复    2018-07-26 17:54:50 +08:00
    yxcxx
        1
    yxcxx  
       2018-07-26 17:46:39 +08:00
    task = filter(lambda t: t['id'] == int(task_id), tasks)

    这里 task 是一个 filter,并不是一个可以序列化的 列表,字典 之类的
    U87
        2
    U87  
    OP
       2018-07-26 17:49:40 +08:00
    @yxcxx 那我怎么改呀
    yxcxx
        3
    yxcxx  
       2018-07-26 17:51:27 +08:00
    @U87 另外,在 python 中建议尽量使用列表推导来替代 map reduce filter 等, 你可以这样写

    task = [t for t in tasks if t.get('id') == int(task_id) ]
    U87
        4
    U87  
    OP
       2018-07-26 17:54:50 +08:00
    @yxcxx 明白了谢谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1463 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 17:16 · PVG 01:16 · LAX 10:16 · JFK 13:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.