【问题标题】:value error if cookie value is a string but not if an int如果 cookie 值是字符串,则值错误,但如果是 int 则不会
【发布时间】:2015-11-03 01:51:33
【问题描述】:

在我的 make_session 函数中,如果表单中的密码与某些凭据不匹配,则它会返回一个字符串,该字符串最终被存储为名为 session 的 cookie。在我的索引文件中,我在 index.html 上设置了它,如果 cookie 值为 {},它会询问登录信息。如果我通过将“invalid”替换为任何整数来更改 make_session 函数返回的内容,代码将按预期工作。

我的问题的一个不好的解决方案是添加

except:
    data = {}

在返回到我的 get_saved_data 函数之前设置数据等于 {} 但这最终会得到相同的结果,就好像我的浏览器中根本没有 cookie,但它消除了我的错误:https://gist.github.com/anonymous/e101aa46f154a075b038

我怀疑 get_saved_data 函数可能有问题。

我的目录地图:

                         |---- layout.html
                         |---- index.html
         |--- templates -|
Project -|
         |--- test.py

test.py:

from flask import Flask, render_template, redirect, url_for, request, make_response
import json

def get_saved_data(key):
    try:
        data = json.loads(request.cookies.get(key))
    except TypeError:
        data = {}
    return data


def make_session(form_data):
    if form_data.get('username') == "username" and form_data.get('password') == "password":
        return "12345"
    else:
        return "invalid"


app = Flask(__name__)


@app.route('/')
def index():
    data = get_saved_data("session")
    return render_template('index.html', saves=data)


@app.route('/login', methods=['POST'])
def login():
    response = make_response(redirect(url_for('index')))
    response.set_cookie("session", make_session(dict(request.form.items())))
    return response

app.run(debug=True, host='0.0.0.0', port=8000)

index.html:

{% extends "layout.html" %}

{% block content %}
    {% if saves == {}: %}
        <p>Please log in.</p>
    {% else: %}
        <p>Your Session value is: {{ saves }}</p>
    {% endif %}
    {% if saves == {}: %}
        <form action="{{ url_for('login') }}" method="POST">
            <p>We take your private information very seriously. All data is encrypted not once but twice! in ROT13 to provide the best security.</p><br />
            <label for="username">Please enter your username:</label>
            <input type="text" name="username" /><br />
            <label for="password">Please enter your password:</label>
            <input type="text" name="password" /><br />
            <button class="btn">Log In</button>
        </form>
    {% endif %}
{% endblock %}

layout.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Character Generator</title>
    </head>
    <body>
        {% block content %}{% endblock %}
    </body>
</html>

【问题讨论】:

    标签: python json python-3.x cookies flask


    【解决方案1】:

    将您的get_saved_data 更改为以下内容会有什么不同吗?

    def get_saved_data(key):
        data = json.loads(request.cookies.get(key, '{}'))
        return data
    

    如果没有这样的key,返回'{}',确保json不会报错。

    【讨论】:

      【解决方案2】:

      虽然我还没有找到直接解决问题的方法,并且使用 lord63.j 的答案为我节省了几行代码,但间接解决问题的一种方法是通过修改将 cookie 值保存为字典登录功能:

      @app.route('/login', methods=['POST'])
      def login():
          response = make_response(redirect(url_for('index')))
          response.set_cookie("data", json.dumps({"session": make_session(dict(request.form.items()))}))
          return response
      

      从他们开始,为了访问我需要使用的会话值

      saves.get('session')
      

      as saves 等价于

      json.loads(request.cookies.get('data', '{}'))
      

      在索引函数中

      @app.route('/')
      def index():
          data = get_saved_data("data")
          return render_template('index.html', saves=data)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-29
        • 2019-01-17
        • 2018-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-12
        相关资源
        最近更新 更多