我在使用Channel API时遇到了困难,但仅限生产环境。在开发服务器上可以运行,但是在生产环境中,我的javascript中出现了Invalid + token错误,而我的Python中出现了空白错误。
这是我的服务器端代码。“ channel_test”是我的控制器,“ do_send_message”是一个延迟的函数,“ send_message”是一个带有try-except块的包装器。基本上是创建通道,将令牌设置为cookie,然后调用延迟的任务直到计数器达到100。每次运行任务时,它都会在通道上发送消息。
def channel_test(self, key):
if not users.is_current_user_admin(): return 403
client_id = self.user.email()+key
token = channel.create_channel(client_id, duration_minutes=10)
print 'token: %s' % token
self.response.set_cookie('token', urllib.quote(token))
deferred.defer(do_send_message, client_id, _queue='retry')
# channel communication
def send_message(client_id, msg):
"""
msg is a dict
"""
if client_id:
print 'client_id: ', client_id
try:
channel.send_message(client_id, json.dumps(msg))
print 'sent message %s' % msg
except Exception as e:
print 'something went wrong with msg, %s: %s, %s' % (msg, e, e.__str__())
else:
print 'not sending message; no client id'
def do_send_message(client_id, x=10):
time.sleep(1)
text = "here's a message! %s" % x
if x >= 100:
text = "Done!"
msg = {"text":text, "percent":x}
send_message(client_id, msg)
if x < 100:
deferred.defer(do_send_message, client_id, x+10, _queue='retry')
每次调用“ send_message”时,都会失败,但是“ e”不会输出任何内容。这是日志中的输出:
something went wrong with msg, {'text': "here's a message! 10", 'percent': 10}: ,
此外,我的客户端javascript无法打开连接。它只是收到错误“ Invalide + token”。这基本上是从cookie中读取令牌,打开连接,并且每次传递消息时,都会将消息写入通知托盘,直到消息==“完成!”。然后重新加载页面。但是,可以这样说,它立即失败,并且onError打印'Object {description:“ Invalid + token。”,代码:“ 401”}'。
// globals
var channel, socket, hide;
var $msg = $('#channel-message');
var $bar = $('#notification-tray .progress-bar');
onMessage = function(obj){
var message = JSON.parse(obj.data);
if (message.percent !== undefined){
$bar.css('width', message.percent+'%');
}
switchMsg(message.text);
};
onOpen = function(){
$('#notification-tray').fadeIn();
$bar.css('width', '10%');
};
onClose = function(){
$('#notification-tray').fadeOut();
};
onError = function(err){
$('#notification-tray').fadeOut();
console.log(err);
};
function closeAndReload(){
socket.close();
$.removeCookie('token', {path:'/'});
$.removeCookie('hide', {path:'/'});
location.reload();
}
function switchMsg(msg){
$msg.fadeOut(function(){
$msg.html(msg);
$msg.fadeIn(function(){
if (msg == 'Done!'){
closeAndReload();
}
});
});
}
function initializeChannel(){
channel = new goog.appengine.Channel(token);
socket = channel.open();
socket.onmessage = onMessage;
socket.onopen = onOpen;
socket.onclose = onClose;
socket.onerror = onError;
}
$(function(){
token = $.cookie('token');
if (token !== undefined && token != ""){
initializeChannel();
}
});
即使我在生产环境中遇到此问题,这也可以在我的开发服务器上完美运行。
提前致谢。
好的,这令人沮丧,但是我想我已经知道该令牌具有一定的未证明最大长度。我将client_id设置为
client_id = self.user.email()+key[0:10]
代替
client_id = self.user.email()+key
现在就可以了。当然,令人讨厌的是(1)它可以在dev服务器上运行,而不是在生产环境上运行;(2)该错误不是很有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句