TL;DR: I'm working on an application using PRAW, Flask, Flask-SocketIO on the back end and the SocketIO JS library on the front end to live-stream reddit comments as they happen. I have a websocket configured to send an authorization code to the back-end, and then for the back-end to send data to the front-end once it has the code. The problem is that the front-end Javascript apparently doesn't receive any data until I Ctrl-C
in terminal.
Here's the relevant code
Front end:
// Open up the websocket
var codeSocket = io.connect('http://' + document.domain + ':' + location.port + '/code');
var commentsSocket = io.connect('http://' + document.domain + ':' + location.port + '/comments');
// Send the authorization code to Flask when you connect to the socket
codeSocket.on('connect', function() {
codeSocket.emit('authorization_code', {code: getUrlParameter('code')});
});
// Do something with the data stream
commentsSocket.on('comment', function(data){
console.log(JSON.parse(data).id);
});
Back end:
@socketio.on('authorization_code', namespace='/code')
def generate_comments(json):
code = json['code']
reddit = generate_reddit_instance()['instance']
reddit.auth.authorize(code)
def generate():
for comment in reddit.subreddit('all').stream.comments():
emit('comment', dumps({'id': str(comment)}), namespace='/comments')
return generate()
After Ctrl-C
ing the terminal, all of the comment IDs appear in the console, like this:
The full source code for this project is available on GitHub, here. I haven't been able to find anyone with this same problem, but maybe my Google-fu is weak today.