我正在尝试使用以下方法为我的项目开发用户管理界面:
我正在测试 Pycharm Professional 中的run
命令启动的 Google Chrome 中的登录页面。
操作系统::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
。
我还尝试使用“ 右键单击>检查元素>网络”和“ 右键单击>检查元素> EditThisCookie ”来检查cookie,但是找不到它。 / p>
然后我尝试通过修改上面的脚本,使用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 Chrome 的 EditThisCookie 插件中找到session
cookie。
但是
调用refresh()
时,它返回相同的响应Session Terminated
。
这意味着在服务器端的session
中找不到req.cookies
。
我也已经在GitHub上重新打开了这个问题。 https://github.com/falconry/falcon/issues/947#issuecomment-422652126
答案 0 :(得分:0)
您可以尝试将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 希望对您有所帮助!
答案 1 :(得分:0)
您可以像这样在猎鹰中设置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"]
# ....
有关更多信息,请参阅猎鹰文档-> https://falcon.readthedocs.io/en/0.3.0.1/api/cookies.html