【问题标题】:Why flask session didn't store the user info when making different posts to it from react?为什么烧瓶会话在从反应中发布不同的帖子时没有存储用户信息?
【发布时间】:2019-08-08 19:35:30
【问题描述】:

我使用 Flask-RESTful 和几个反应模块编写了几个 API 用于测试目的。理想情况下,如果我通过请求在会话中存储了一些信息,python 应该能够检测是否存在这样的会话,即使在其他带有代码的 API 条目中,例如

if session:
    return jsonify({'user': session['username'], 'status': 2000})
return jsonify({'user': None, 'status': 3000})

但是,我遇到的问题是在单个请求中,比如说登录请求,会话确实被正确使用了,username 也被存储在会话中——例如,

from flask import session
...

# login API

class UserLoginResource(Resource):
    @staticmethod
    def post():
        ...
        ... # a user object (model) is defined
        session['username'] = user.username
        return jsonify({'status': 2000, 'user': session['username']})

使用此代码,它会从会话中返回准确的用户名,这意味着信息已被存储。但是,当我从反应端向索引 API 发出另一个获取请求时,例如

from flask import session
...

# index API (without any practical use)

class IndexResource(Resource):
    @staticmethod
    def get():
        if session:
            return jsonify({'username': session['username']})

在这种情况下,响应为 None,因为 API 没有检测到任何会话。

// makePostRequest Function

makePostRequest = (e: any) => {
        e.preventDefault()
        const payload = {
            'email': this.state.email,
            'password': this.state.password
        }

        fetch('http://127.0.0.1:5000/api/login', {
            method: 'POST',
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        }).then(res => res.json())
        .then(res => {this.setState({
            status: res['status'],
            username: res['user']
        })})
        .catch(err => console.log(err))
    }

这是我发出登录帖子请求的方式。登录成功返回状态码2000;如果状态码为2000,则表示程序已通过代码session['username']=_the_username_。访问索引页面时,我应该能够从会话存储中提取用户名数据。

componentDidMount = () => {
        fetch('http://127.0.0.1:5000/api')
        .then(res => res.json())
        .then(res => this.setState({
            user: res['user'],
            status: res['status']
        }))
    }

这就是我在主页模块上发出获取请求的方式。但是,user 始终为 Nonestatus 始终为 3000

这可能只是会话使用不当,但我不知道如何在flask中实际正确使用会话。那么,这里的错误是什么?


更新: 所以,我像这样在class UserLoginResource(Resource) 中添加了一个 GET 请求

class UserLoginResource(Resource):
    @staticmethod
    def post():
        ... # identical to the previous code

    @staticmethod():
    def get():      # url: http://127.0.0.1:5000/api/login
        session['username'] = 'user_a'
        return jsonify({'message': 'session set'})

我在反应方面向http://127.0.0.1:5000/api/login 提出了一个获取请求,并得到了message: session set。但是,当 react 访问 http://127.0.0.1:5000/api 时,结果仍然是 status 3000 和无用户名。 然后,我直接访问了网址http://127.0.0.1:5000/api/login,然后访问了http://127.0.0.1:5000/api,然后我们就得到了用户名user_a 和状态2000。 所以,我认为这里的问题可能是后端没有识别出正在访问它的浏览器是同一个人,或者可能是其他人。 另外,我检查了componentDidMount是否有问题,但不幸的是componentDidMount不是错误的来源——在我把它变成onClick触发的正常功能后,它仍然不起作用。 如何解决这个问题?

【问题讨论】:

  • 你用什么来调用api?将该代码添加到您的问题中。
  • @waynetech 是的。我刚刚添加了反应代码。

标签: python-3.x session web flask flask-restful


【解决方案1】:

fetch默认不支持cookie,需要使用credentials: 'include'开启

makePostRequest = (e: any) => {
        e.preventDefault()
        const payload = {
            'email': this.state.email,
            'password': this.state.password
        }

        fetch('http://127.0.0.1:5000/api/login', {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        }).then(res => res.json())
        .then(res => {this.setState({
            status: res['status'],
            username: res['user']
        })})
        .catch(err => console.log(err))
    }

使用pip install flask-cors在服务器上启用cors

然后将其添加到 app.py,您将在其中初始化您的应用

from flask_cors import CORS 
app = Flask(__name__) 
CORS(app)

【讨论】:

  • 获取和发布请求?
  • 好吧,console.log 告诉我,如果添加了 credentials: 'include',console.log 告诉我在标题中也将“Access-Control-Allow-Credentials”设置为 true,因为 CORs
  • 并澄清一下,将标头“Access-Control-Allow-Credentials”设置为响应,这是服务器端而不是反应端。
  • 检查答案,我已经添加了启用cors的步骤
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-27
相关资源
最近更新 更多