修改Flask不宁的JSON响应

2024-06-25 06:40:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着用不安的烧瓶余烬不是很好。是GET的反应让我绊倒了。例如,当我对/api/people执行GET请求时余烬期望:

{ 
    people: [
        { id: 1, name: "Yehuda Katz" }
    ] 
}

但“不安烧瓶”的反应是:

^{pr2}$

我怎样改变烧瓶不安的反应来符合什么余烬想要?我有这种感觉,它可能在一个后处理器函数中,但我不确定如何实现它。在


Tags: 函数nameapiidget烧瓶处理器people
2条回答

当时公认的答案是正确的。然而,post和preprocessor在Flask untillet中的工作方式发生了变化。According to the documentation

The preprocessors and postprocessors for each type of request accept different arguments, but none of them has a return value (more specifically, any returned value is ignored). Preprocessors and postprocessors modify their arguments in-place.

所以现在在我的后处理器中,我只删除我不想要的任何键。例如:

def api_post_get_many(result=None, **kw):
    for key in result.keys():
        if key != 'objects':
            del result[key]

烧瓶延伸部分有pretty readable source code。您可以制作GET_MANY后处理器:

def pagination_remover(results):
    return {'people': results['objects']} if 'page' in results else results

manager.create_api(
    ...,
    postprocessors={
        'GET_MANY': [pagination_remover]
    }
)

我还没有测试过,但应该可以用。在

相关问题 更多 >