在Flask"POST"中发送JSON响应路线 [英] Sending JSON response in Flask "POST" Route

查看:63
本文介绍了在Flask"POST"中发送JSON响应路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为参考,我研究了以下三个问题:

For reference, I've looked at these three questions:

从Flask视图返回JSON响应

发送带有Flask响应的JSON和状态代码

返回请求.从Flask响应对象

正如标题所述,我正在尝试从flask post方法返回JSON响应.烧瓶路径如下:

As the title states, I am trying to return a JSON response from a flask post method. The flask route is as follows:

@app.route('/login', methods=['POST'])
def login_route():
    content = request.json
    jwt = get_authorization(content['username'], content['password'])
    return {'session-token': jwt} , 200

我想在Web应用程序中的 session-token 中存储cookie(目前).

Where in my web application I would like to store the session-token in cookies (for now).

目前在网络端,我有以下代码:

Currently on the web side I have the following code:

static postWithJSONResponse(url, body, onFetchComplete, onFetchFailure) {
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(body)
        })
        .then((data) => onFetchComplete(data))
        .catch(error => onFetchFailure(error));
    }

componentDidMount() {
        NetworkUtils.postWithJSONResponse('/login', this.state.userObject,
        (data) => {
             console.log(data);
        },
        (error) => {

        });
    }

其中 userObject username password 属性组成.鉴于上面列出的以前的搜索,我已经尝试了一些烧瓶路线的变体:

Where userObject consists of username and password attributes. I've tried a few variations of my flask route given the previous searches listed above:

基于此问题的变化

from flask import jsonify

@app.route('/login', post)
def login_route():
    content = request.json
    d = {}
    d['session-token'] = get_authorization(content['username'], content['password'])
    return jsonify(d)

与同一篇文章不同:

@app.route('/login', post)
def login_route():
    content = request.json
    jwt = get_authorization(content['username'], content['password'])
    app.response_class(
        response=json.dumps({'session-token': jwt}),
        status=200,
        mimetype='application/json'
    )

最后,尝试尝试创建新的响应对象:

from flask import Flask, request, make_response

@app.route('/login', methods=['POST'])
def login_route():
    content = request.json
    jwt = get_authorization(content['username'], content['password'])
    resp = make_response(json.dumps({'session-token': jwt}), 200)
    resp.headers['Content-Type'] = 'application/json'
    return resp

所有这3种尝试都会将以下json响应对象返回给我的chrome控制台:

All 3 of these attempts return the following json response objects to my chrome console:

Response {type: "basic", url: "http://localhost:3000/login", redirected: false, status: 200, ok: true, …}
body: ReadableStream
locked: false
__proto__: ReadableStream
bodyUsed: false
headers: Headers
__proto__: Headers
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:3000/login"
__proto__: Response

如您所见,响应对象不包含 session-token 的单个条目.我真的不确定这里可能出什么问题,也不确定问题出在烧瓶路径还是JavaScript.不用说我可以使用一些帮助,任何建议将不胜感激.我正在使用Flask版本1.1.2.

As you can see, the response object doesn't contain a single entry for session-token. I'm really not sure what could be going wrong here and I'm not certain if the issue is with the flask route or the javascript anymore. Needless to say I could use some help and any recommendations would be appreciated. I am using Flask version 1.1.2.

推荐答案

Javascript中的 fetch API很不错,因为它为您提供了登录时可以看到的选项,例如潜在的访问权限机体作为流(现在是TC 39的任何一天……),但对于90%的机壳来说,它完全是过度设计的.要记住的魔咒如下:

The fetch API in Javascript is nice in the sense that it gives you options you're seeing when you log it like potentially accessing the body as stream (any day now TC 39...), but it's totally over-engineered for the 90% case. The magic incantation to remember is as follows:

// can only do this inside an async function
const resp = await fetch(someURL);
const jsonData = await resp.json();
// step 3, profit

(非常轻微)老式Javascript

fetch(someURL)
  .then(resp => resp.json())
  .then(jsonData => /* profit! */);

它们在功能上是等效的.如果您总是想在学校午餐时间坐在凉爽的孩子的桌子旁,请使用较新的桌子.如果您像我一样是个笨拙的老婆婆,请使用另一个,这几天他们抱怨孩子们的餐桌和午餐时间很长.

They are functionally equivalent. Use the newer one if you always wanted to sit at the cool kid's table at lunchtime in school. Use the other if you're a stodgy old curmudgeon like myself who complains about the kids these days with their cool tables and lunchtimes.

这篇关于在Flask"POST"中发送JSON响应路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆