Skip to content

Instantly share code, notes, and snippets.

@duhaime
Created June 20, 2019 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duhaime/cf786152ff80be4ae42de192265d7b7d to your computer and use it in GitHub Desktop.
Save duhaime/cf786152ff80be4ae42de192265d7b7d to your computer and use it in GitHub Desktop.
Flask + Redis + background process in while loop
from flask import Flask, jsonify, request, send_from_directory
import redis, celery, sys, socket, os, json
# config
port = 6000 # port on which data streams
# app
app = Flask(__name__, static_url_path='')
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'
celery = celery.Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
@app.route('/frames')
def get_frames():
return jsonify(frames)
@celery.task
def update_frames():
# data streaming socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((socket.gethostbyname('127.0.0.1'), port)) # host, port
frame = [] # initialize the container obj that will hold all frame data
while True:
data = client.recv(1024).decode('utf8')
for l in data.split('\n'):
if 'end_frame' in l:
d = {i.split(':')[0]: i.split(':')[1] for i in frame if ':' in i}
redis.lpush('frames', json.dumps(d))
frame = []
elif l.rstrip('\n'):
frame.append(l.rstrip('\n'))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5050)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment