【问题标题】:Unable to set cookies using Falcon API and Python无法使用 Falcon API 和 Python 设置 cookie
【发布时间】:2019-02-18 20:25:05
【问题描述】:

我正在尝试使用以下内容为我的项目开发用户管理界面:

  • Python 2.7
  • 猎鹰 1.4.1
  • falcon-cors 1.1.7
  • gunicorn 19.9.0

我正在 Google Chrome 中测试由 Pycharm Professional 中的run 命令启动的登录页面。

操作系统: Ubuntu 18.04 LTS

import falcon
from falcon_cors import CORS
cors = CORS(allow_all_origins=True,allow_all_headers=True,allow_all_methods=True)

class User:
    def __init__(self):
        self.name = 'Users API'

    def on_post(self, req, resp):
        try:
            data = urlparse.parse_qs(req.stream.read())
            if "loginEmail" in data.keys() and "loginPassword" in data.keys():
                email = data['loginEmail'][0]
                password = data['loginPassword'][0]
                result = self.authenticate(email, password)
                if result["status"]=="Success":
                    resp.set_cookie('session', result["session"],path="/",domain="192.168.32.17:5000",secure=False)
            else:
                raise Exception, "Email or Password not provided"

            if len(result) <= 0:
                raise Exception, 'Empty Response'
            resp.body = json.dumps(result)

        except Exception as e:
            resp.body = json.dumps({'status': 'Error', 'message': e.message, 'details': str(e)})

    def on_get(self, req, resp):
        try:
            data = req.params
            cookies = req.cookies
            if "session" in cookies.keys():
                session = cookies['session']
                result=self.get(session,data)
                if len(result) <= 0:
                    raise Exception, 'Empty Response'
            else:
                raise Exception, "Session Terminated"

            resp.body = json.dumps(result)
        except Exception as e:
            resp.body = json.dumps({'status': 'Error','message': e.message,'details': str(e)})

api = falcon.API(middleware=[cors.middleware])
api.add_route('/user', User())

基本网页如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Project</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body onload="refresh()">
<form method="post" action="http://192.168.32.17:5000/user" accept-charset="UTF-8" id="login-nav">
    <input type="email" name="loginEmail" placeholder="Email address" required>
    <input type="password" name="loginPassword" placeholder="Password" required>
    <button type="submit" id="btnLogin">Sign in</button>
 </form>
<script>
    $(document).ready(function() {
        $('#login-nav').submit(function(){
            $.post($(this).attr('action'), $(this).serialize(), function(json) {
                refresh()
            }, 'json');
            return false;
       });
    });

   function refresh(){
            $.get("http://192.168.32.17:5000/user",  { 'fields': [ "name", "dp" ] }, function(json) {
                if (json["status"]=="Error"){
                    alert(json["message"])
                }
               else {
                $('#dd-username').text(json["data"]["name"])
                $("#dd-photo").attr("src",json["data"]["dp"])
                }
            }, 'json');
    }

    function getCookie(cname) {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for(var i = 0; i <ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

    function checkCookie() {
        var session = getCookie("session");
        if (session ==null || session==""){
            return false
        }
        else{
            return true
        }
</script>
</body>
</html>

在登录请求时,我收到如下所需的响应:

{"status": "Success", "message": "Session has been created successfully", "session": "F26F75C27942DE27"}

但在refresh(),我收到以下回复:

{"status": "Error", "message": "Session Terminated"}

我还尝试使用上述chechCookie() 方法检查cookie,它也返回false

我还尝试使用“Right Click> Inspect Element > Network”和“Right Click> Inspect Element > EditThisCookie”检查 cookie,但无处可寻。

然后我尝试通过修改上面的脚本,使用 javascript 在浏览器中设置 cookie,如下所示:

 $('#login-nav').submit(function(){
    $.post($(this).attr('action'), $(this).serialize(), function(json) {
        setCookie("session",json["session"])
        refresh()
    }, 'json');
    return false;
  });

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

使用这种方法,我可以在浏览器中设置 cookie。 checkCookie() 返回True。 我还能够在 Google ChromeEditThisCookie 插件中找到 session cookie。

但是

当调用refresh() 时,它返回相同的响应Session Terminated。 这意味着在服务器端的req.cookies 中找不到session

我也在 GitHub 上重新打开了这个问题。 https://github.com/falconry/falcon/issues/947#issuecomment-422652126

【问题讨论】:

  • 首先你应该使用你的浏览器调试器来查看Cookie 标头是否在响应中正确设置。
  • 我该怎么做?我的设置:gunicorn 运行服务器端应用程序一个简单的 HTML 表单,在 chrome 中向我的 API 路由发送一个发布请求我在 chrome 中使用这个 EditThisCookie 插件或通过检查功能检查 cookie。
  • 我得到了完美的响应体,但在任何地方都找不到 cookie。甚至使用 javascript 签入document.cookies
  • 谷歌:&lt;name of your browser&gt; debugger
  • 我添加了一个屏幕截图

标签: python rest wsgi


【解决方案1】:

你可以试试把cookie设置成

def handler_app(environ, start_response):
    response_body = b'Works fine'
    status = '200 OK'

    response_headers = [
       ('Content-type', 'text/html'),
       ('Set-Cookie', 'theme=light'),
       ('Set-Cookie': 'sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT')
    ]

    start_response(status, response_headers)

    return [response_body]

from gunicorn documentation ,希望对你有帮助!!!

【讨论】:

    【解决方案2】:

    你可以像这样在 falcon 中设置 cookie...

    class Resource(object):
        def on_get(self, req, resp):
            # Set the 'max-age' of the cookie to 10 minutes (600 seconds)
            # and the cookies domain to "example.com"
            resp.set_cookie("my_cookie", "my cookie value",
                            max_age=600, domain="example.com")
    

    然后得到这样的cookie...

    class Resource(object):
        def on_get(self, req, resp):
    
            cookies = req.cookies
    
            if "my_cookie" in cookies:
                my_cookie_value = cookies["my_cookie"]
            # ....
    

    更多信息请阅读 falcon 文档 --> https://falcon.readthedocs.io/en/0.3.0.1/api/cookies.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 2019-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多