0

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-Cing the terminal, all of the comment IDs appear in the console, like this:

Comment IDs

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.

cass
  • 858
  • 1
  • 10
  • 17
  • Are you using one of the async frameworks (eventlet, gevent)? If yes, you need to monkey patch the standard library so that it is async compatible. – Miguel Grinberg Feb 17 '18 at 06:22
  • @Miguel As described [here](https://stackoverflow.com/questions/32458568/gevent-blocked-by-flask-even-use-monkey-patch)? I also saw a solution for asynchronous updating [here](https://www.shanelynn.ie/asynchronous-updates-to-a-webpage-with-flask-and-socket-io/) that used threading instead of monkey patching. – cass Feb 18 '18 at 14:20
  • Better look at the official docs on monkey patching for eventlet or gevent, whichever one you are using. The "threading" option is almost always not a good idea, as it does not support websocket, so I would not recommend that you do that. – Miguel Grinberg Feb 18 '18 at 19:06

0 Answers0