【问题标题】:Python Flask app on Heroku not updating variables instantly [duplicate]Heroku上的Python Flask应用程序不会立即更新变量[重复]
【发布时间】:2020-08-25 21:24:27
【问题描述】:

我有一个 Python Flask 应用程序在 Heroku 上成功运行。

  1. 用户被重定向到 spotify Oauth 的登录页面
@bp.route('/api/spotify_auth_request')
@limiter.limit("2 per day")
def api_spotify_auth_request():
    """
    Requests authorisation from the Spotify API.
    """
    from uuid import uuid4

    base_url = "https://accounts.spotify.com/authorize/?"

    params = {
        "client_id": os.environ.get('SPOTIFY_CLIENT_ID'),
        "response_type": "code",
        "redirect_uri": "https://[REMOVED]/api/spotify_auth",
        "state": str(uuid4())
    }

    Spotify.valid_states.append(params["state"])
    url = base_url + urlencode(params)

    return redirect(url, 302)

注意:状态被添加到 Spotify.valid_states

class Spotify:
    valid_states = []
  1. 登录后,Spotify 将用户重定向到路由 /api/spotify_auth 上的我的应用程序
@bp.route('/api/spotify_auth')
@limiter.exempt
def api_spotify_auth():
    """
    Redirect endpoint from Spotify after authentication attempt.
    """
    code = request.args.get("code", None)
    error = request.args.get("error", None)
    state = request.args.get("state")

    if error:
        return error

    if state not in Spotify.valid_states:
        return jsonify({
            "error": "State returned was not valid",
            "state": state,
            "valid_states": Spotify.valid_states
        }), 500

    Spotify.valid_states.remove(state)

    # ... some more code

问题在于,当 Spotify 重定向到 /api/spotify_auth 时,Spotify.valid_states 没有更新为原始请求。几次刷新后,变量将更新,用户将被允许继续。

我尝试在检查 Spotify.valid_states 之前添加 20 秒超时,但似乎必须刷新选项卡才能更新变量。

我真的不想忽略状态,是否有任何其他解决方案可以确保在添加新状态后立即更新 valid_states 变量?

【问题讨论】:

    标签: python flask heroku


    【解决方案1】:

    像这样存储状态不是线程安全的:

    class Spotify:
        valid_states = []
    

    如果与多个同步工作人员一起启动,每个工作人员都有自己的记忆,可以解释您所看到的行为(“几次刷新后,变量将更新,用户将被允许继续。”)。

    我在 Heroku 上的 discussed previously gunicorn 默认为 2 个同步工作人员,如果没有指定工作人员类型或计数。一个快速的解决方法是指定 1 个(同步)worker,尽管这可能无法很好地应对负载。

    更好的解决方案是实现不同的存储后端,以允许您保持独立于工作人员的状态。 Redis,即 Heroku 的 offically supported,可能值得对此进行调查。

    【讨论】:

      猜你喜欢
      • 2016-08-16
      • 2016-01-17
      • 2021-01-15
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 2020-02-20
      • 1970-01-01
      相关资源
      最近更新 更多