Python Websockets handles one time use only - python

I want to make a python code that browsers can connect to get a video stream.
Problem is that my python code handles only one time use, meaning if you open the browser it will connect to that websocket correctly, but if you refresh the page, or another client want to access a stream from in parallel it doesn't work
My code:
import asyncio
import websockets
import cv2
import os
import signal
async def time1(websocket, path):
while True:
vid = cv2.VideoCapture('V_DRONE_097.mp4')
vid.set(cv2.CAP_PROP_FPS,24)
try:
#v = VideoStreamWidget()
#v.ops()
while(vid.isOpened()):
img, frame = vid.read()
#frame = cv2.resize(frame, (640, 480))
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 65]
man = cv2.imencode('.jpg', frame, encode_param)[1]
#sender(man)
#print(len(man.tobytes()))
#cv2.imshow('img',man)
await websocket.send(man.tobytes())
except :
pass
async def main():
loop = asyncio.get_running_loop()
stop = loop.create_future()
#loop.add_signal_handler(signal.SIGTERM, stop.set_result, None)
port = int(os.environ.get("PORT", "8585"))
global stop1
async with websockets.serve(time1, "", port):
await stop
stop1 = False
'''
async def main():
async with websockets.serve(time1, "localhost", 8585):
await asyncio.Future() # run forever
asyncio.run(main())
'''
if __name__ == "__main__":
while True:
asyncio.run(main())
I want the server to keep working even if the client (browser) refreshes the page or close it and comeback later.
This is the code of javascript running in the browser if that will help:
openSocket = () => {
socket = new WebSocket("ws://127.0.0.1:8585/");
let msg = document.getElementById("msg");
socket.addEventListener('open', (e) => {
document.getElementById("status").innerHTML = "Opened";
});
socket.addEventListener('message', (e) => {
let ctx = msg.getContext("2d");
let image = new Image();
image.src = URL.createObjectURL(e.data);
image.addEventListener("load", (e) => {
ctx.drawImage(image, 0, 0, msg.width, msg.height);
});
});
}
and this is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Python_Websocket_Live_Streaming</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js" ></script>
</head>
<body onload="openSocket()">
<div id="status">
Connection failed. Somebody may be using the socket.
</div>
<div style="text-align: center">
<canvas id="msg" width="960" height="720" style="display:inline-block" />
</div>
</body>
</html>
I've searched and tried many solutions but non worked.
My final goal is to integrate this with flask API
Update 1:
yes it is stuck in the time1 function
I've known from wrapping the "send" function in a try catch:
try:
await websocket.send(man.tobytes())
except websockets.exceptions.ConnectionClosedError:
print("clean up")
break
when the browser closes/refresh the page, clean up is printed infinitely
Edit 2
It was stuck in the outer loop, that while true loop. Solved now Thanks

There are a few culprits, but ultimately I think that while(vid.isOpened()) prevents the async from ever being free
edit
or stuck in the outer while loop

Related

How can I send data though socket-io without the client requesting first with python and flask

My goal is for my Flask server to send the client data either every three seconds, or when a function is called. To do this I am using SocketIO. However based on some example code I am working with, it seems that I can only send data after a client requests something. I don't want the client to have to 'poll' to find if there is new data, so I want the server to push it when it is ready.
Here is what I tried so far. (some of the code is unnecessary since it is based off an example) This should use socketio to push the time to the client every few seconds.
HTML
<!DOCTYPE HTML>
<html>
<head>
<title>Socket-Test</title>
<script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
namespace = '/test';
var socket = io(namespace);
socket.on('my_response', function(msg, cb) {
$('#log').text( $('<div/>').text(msg.data).html());
if (cb)
cb();
});
});
</script>
</head>
<body style="background-color:white;">
<h1 style="background-color:white;">Socket</h1>
<div id="time" ></div>
</body>
</html>
Python
import threading
from flask import Flask, render_template, session, copy_current_request_context,request
from flask_socketio import SocketIO, emit, disconnect
from threading import Lock
import time
async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socket_ = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()
clients = []
def update():
time.sleep(1)
emit('my_response',
{'data': time.time},
room=clients[0])
t=threading.Thread(target=update)
#socket_.on('connect')
def handle_connect():
print('Client connected')
clients.append(request.sid)
t.start()
#app.route('/')
def index():
return render_template('index.html', async_mode=socket_.async_mode)
#socket_.on('my_event', namespace='/test')
def test_message(message):
session['receive_count'] = session.get('receive_count', 0) + 1
emit('my_response',
{'data': message['data'], 'count': session['receive_count']})
#socket_.on('my_broadcast_event', namespace='/test')
def test_broadcast_message(message):
session['receive_count'] = session.get('receive_count', 0) + 1
emit('my_response',
{'data': time.time},
broadcast=True)
socket_.run(app,port=8050)
I try to run it but it gives me the error RuntimeError: Working outside of request context.
I fixed my code by following this tutorial: https://www.shanelynn.ie/asynchronous-updates-to-a-webpage-with-flask-and-socket-io/
import threading
from flask import Flask, render_template, session, copy_current_request_context,request
from flask_socketio import SocketIO, emit, disconnect
from threading import Lock
import time
async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socket_ = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()
def update():
time.sleep(1)
socket_.emit('my_response',
{'data': time.time()},
namespace='/test')
print("emitted")
update()
t=threading.Thread(target=update)
#socket_.on('connect', namespace='/test')
def handle_connect():
print('Client connected')
if not t.isAlive():
t.start()
#app.route('/')
def index():
return render_template('index.html', async_mode=socket_.async_mode)
socket_.run(app,port=8070)
HTML
<!DOCTYPE HTML>
<html>
<head>
<title>Socket-Test</title>
<script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
namespace = '/test';
var socket = io(namespace);
console.log(("test"));
socket.on('my_response', function(msg) {
$('#time').text( $('<div/>').text(msg.data).html());
console.log(msg);
});
});
</script>
</head>
<body style="background-color:white;">
<h1 style="background-color:white;">Socket</h1>
<div id="time" ></div>
</body>
</html>
I would like to point out that using recursion in this case is not the best choice.
you call the update function inside the update and do not have the completion of this process.
the best option would be to use a loop(as done in the link you attached)
def update():
while True:
time.sleep(1)
socket_.emit('my_response', {'data': time.time()}, namespace='/test')
print("emitted")
t=threading.Thread(target=update)
also, it would be better to write "while is_work_var" instead of "while True"

how to get connected clients in flask

hi i need to display total number of connected clients on my flask app i write this code for checking connected and disconnected connections.
app = Flask(__name__)
socketio = SocketIO(app)
clients = []
#socketio.on('connect', namespace='/')
def connect():
clients.append(request.namespace)
#socketio.on('disconnect', namespace='/')
def disconnect():
clients.remove(request.namespace)
then i render template like this
return render_template_string(TABLE_TEMPLATE, data=data, clients=len(clients))
In html part i call like this
<h1>{{ clients }} </h1>
but on webpage it keep showing 0 even client is connect i get output from client and it is connected it should print 1 2 depends how many clients are connected. even if i print this print(len(clients)) it return 0. even my client is connect and i get output.
this is my updated code
from flask import Flask, request, render_template_string
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app, logge=True)
clients = 0
#socketio.on("connect", namespace="/")
def connect():
# global variable as it needs to be shared
global clients
clients += 1
# emits a message with the user count anytime someone connects
emit("users", {"user_count": clients}, broadcast=True)
#socketio.on("disconnect", namespace="/")
def disconnect():
global clients
clients -= 1
emit("users", {"user_count": clients}, broadcast=True)
TABLE_TEMPLATE = """
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var namespace = '/';
var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
// Update the counter when a new user connects
socket.on('users', function(users) {
userCount = document.getElementById('user_counter');
userCount.innerHTML = users.user_count;
});
});
</script>
<h1 id='user_counter'></h1>
<style>
table, th, td {
border: 1px solid black;
}
</style>
<table style="width: 100%">
<thead>
<th>Client</th>
<th>IP</th>
<th>Status</th>
</thead>
<tbody>
{% for row in data %}
<tr>
<td><center>{{ row.client }}</td></center>
<td><center>{{ row.ip }}</td></center>
<td><center>{{ row.status }}</td></center>
</tr>
{% endfor %}
</tbody>
</table>
"""
#app.route("/device_add", methods=['POST'])
def device_add():
name = request.args.get('name')
with open('logs.log', 'a') as f:
f.write(f'{name} Connected USB from IP: {request.remote_addr} \n')
return 'ok'
#app.route("/device_remove", methods=['POST'])
def device_remove():
name = request.args.get('name')
with open('logs.log', 'a') as f:
f.write(f'{name} Disconnected USB from IP: {request.remote_addr}\n')
return 'ok'
#app.route("/", methods=['GET'])
def device_list():
keys = ['client', 'ip', 'status']
data = []
with open('logs.log', 'r') as f:
for line in f:
row = line.split()
data.append(dict(zip(keys, [row[0], row[-1], row[1]])))
return render_template_string(TABLE_TEMPLATE, data=data)
if __name__ == "__main__":
socketio.run(app)
Client Side :
import requests
import subprocess, string, time
import os
url = 'http://127.0.0.1:5000/'
name = os.uname()[1]
def on_device_add():
requests.post(f'{url}/device_add?name={name}')
def on_device_remove():
requests.post(f'{url}/device_remove?name={name}')
def detect_device(previous):
total = subprocess.run('lsblk | grep disk | wc -l', shell=True, stdout=subprocess.PIPE).stdout
time.sleep(3)
# if condition if new device add
if total > previous:
on_device_add()
# if no new device add or remove
elif total == previous:
detect_device(previous)
# if device remove
else:
on_device_remove()
# Infinite loop to keep client running.
while True:
detect_device(subprocess.run(' lsblk | grep disk | wc -l', shell=True , stdout=subprocess.PIPE).stdout)
After reading a bit of socket.io documentation I've managed to spot the problems in your code.
Not a problem per-se, but incrementing/decrementing an int counter is more than enough for this use case. Secondly, you don't have to pass that counter to the render_template call as you're basically passing the user count before the conenct event has had the opportunity to fire. You should emit a message (in this example with a users topic) that will inform your page that something has changed:
from flask import Flask, request, render_template_string
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app, logge=True)
clients = 0
#socketio.on("connect", namespace="/")
def connect():
# global variable as it needs to be shared
global clients
clients += 1
# emits a message with the user count anytime someone connects
emit("users", {"user_count": clients}, broadcast=True)
#socketio.on("disconnect", namespace="/")
def disconnect():
global clients
clients -= 1
emit("users", {"user_count": clients}, broadcast=True)
Moreover, you didn't open a connection to the socket in your template, this allows you to listen to the messages emitted by your socketio decorators and update all connected clients. You will also need to write a bit of javascript to specify that the counter needs to be updated anytime a user connects/disconnects.
<!-- Remember to import socketio library -->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var namespace = '/';
var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
// Update the counter when a new user connects
socket.on('users', function(users) {
userCount = document.getElementById('user_counter');
userCount.innerHTML = users.user_count;
});
});
</script>
<h1 id='user_counter'></h1>
<!-- the rest of your template -->
This being said, you don't need to pass the counter value in your render_template call.
Also, from flask-socketio docs, it seems to be good practice to start your app in the following way:
if __name__ == "__main__":
socketio.run(app)
Here a link to an edited version of your example.

Ajax with flask for real time esque updates of sensor data on webpage

I've been trying to get this flask server to update itself with data generated from a loop that runs on a a .py script when called for by the user via push button on webpage. I've been looking into recommended solutions and have seen websockets (sockets.io), ajax, nodejs come up. I understand that i need to implement some form of js in my project, and ajax looked to be the most simple (so i thought). I only have about 3 weeks of experience programming in python. Mainly i look for examples close to what i want, and then try to modify it to suit my needs, but haven't found any examples for what i'm looking for. Even then, my general newness to programming means that the more examples i "tack on" the more likely i am to degrade the overall structure of what i've already accomplished.
Goal
The goal is to update a value displayed on the page without a reload but instead have js update the value every second. The value is generated from a x=x+1 counter in my .py file. This will be replaced by sensor inputs gathered from my Rpi later.
Actual results
When i run the current code,
my html elements get double posted so i see what i've put into the index.html file twice although the second button elements don't actually respond to clicking,
I also get an endless stream of Posts in my terminal window.
Clicking on the button elements no longer execute my loop in the .py file and instead displays "Method not allowed"
What i've tried
I've tried to implement setTmeout in my html file as a way to call back to the python app and get an updated value (the x=x+1) every second. I've read posts around using setTimeout as a way to deal with issues using setInterval. Due to the variety of ways i've seen ajax calls employed and learning resources being primarily structured towards forms, databases, and chat apps, most of my searches aren't bringing up anything new for me to learn from that might help. I'm currently doing ajax tutorials hoping to come accross something i can use, any help would be greatly appreciated.
ajaxTest.py My python flask file
import threading
import time
from flask import Flask, render_template, jsonify, request
import RPi.GPIO as GPIO
import datetime
from datetime import datetime
from datetime import timedelta
app = Flask(__name__)
bioR_on = False
ledGrnSts = 0
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
air = 21
light = 20
waste = 16
feed = 12
water = 26
pinList = [21,20,16,12,26]
def pump(pin):
GPIO.output(pin, GPIO.LOW)
print(pin,'on')
time.sleep(1)
GPIO.output(pin, GPIO.HIGH)
print(pin, 'off')
time.sleep(1)
def on(pin):
GPIO.output(pin, GPIO.LOW)
#app.route("/")
def index():
templateData = {
'title' : 'Bioreactor output Status!',
'ledGrn' : ledGrnSts,
}
return render_template('index.html', **templateData)
#app.route('/<deviceName>/<action>', methods = ["POST"])
def start(deviceName, action):
# script for Pi Relays
def run():
if action == "on":
alarm = datetime.now() + timedelta(seconds =10)
global bioR_on
bioR_on = True
while bioR_on:
tday = datetime.now()
time.sleep(1)
#feed(tday, alarm)
x=x+1
return jsonify(x)
GPIO.setmode(GPIO.BCM)
for i in pinList:
GPIO.setup (i, GPIO.OUT)
GPIO.output(i, GPIO.HIGH)
on(air)
on(light)
print(tday)
if tday >= alarm:
print('alarm activated')
# run = False
pump(waste)
print('waste activated')
pump(feed)
print('feed on')
GPIO.cleanup()
alarm = datetime.now() + timedelta(seconds =10)
print('next feeding time ', alarm)
time.sleep(1)
if action == 'off':
bioR_on = False
#return "off"
GPIO.cleanup()
thread = threading.Thread(target=run)
thread.start()
templateData = {
'ledGrn' : ledGrnSts,
}
return render_template('index.html', **templateData)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True, threaded=True)
My index.html file
<!DOCTYPE html>
<head>
<title>BioReactor Control</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href='../static/style.css'/>
</head>
<body>
<h1>Actuators</h1>
<h2> Status </h2>
<h3> GRN LED ==> {{ ledGrn }}</h3>
<br>
<h2> Commands </h2>
<h3>
Activate Bioreactor Ctrl ==>
TURN ON
TURN OFF
</h3>
<h3>
Current Count
</h3>
<p id="demo"></p>
<script>
setTimeout($.ajax({
url: '/<deviceName>/<action>',
type: 'POST',
success: function(response) {
console.log(response);
$("#num").html(response);
},
error: function(error) {
console.log(error);
}
}), 1000);
</script>
<h1>Output</h1>
<h1 id="num"></h1>
</body>
</html>
Picture of results
I created minimal code which uses AJAX to get new value every 1 second.
I use setInterval to repeate it every 1 second. I also uses function(){ $.ajax ... } to create function which is not executed at once but setInterval will call it every 1 second. Without function(){...} code $.ajax was executed at start and its result was used as function executed every 1 second - but it returns nothing - so finally it updated value only once (at start) and later setInterval was running nothing.
I added current time to see if it is still running.
buttons run function '/<device>/<action>' which start and stop thread but AJAX uses /update to get current value.
I use render_template_string to have all code in one file - so other people can easily copy and test it.
I reduced HTML to minimal. To make sure I put <h1> before script which needs these tags.
I didn't tested it with global=True which may run it in new threads and it can make problem.
from flask import Flask, request, render_template_string, jsonify
import datetime
import time
import threading
app = Flask(__name__)
running = False # to control loop in thread
value = 0
def rpi_function():
global value
print('start of thread')
while running: # global variable to stop loop
value += 1
time.sleep(1)
print('stop of thread')
#app.route('/')
#app.route('/<device>/<action>')
def index(device=None, action=None):
global running
global value
if device:
if action == 'on':
if not running:
print('start')
running = True
threading.Thread(target=rpi_function).start()
else:
print('already running')
elif action == 'off':
if running:
print('stop')
running = False # it should stop thread
else:
print('not running')
return render_template_string('''<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
TURN ON
TURN OFF
<h1 id="num"></h1>
<h1 id="time"></h1>
<script>
setInterval(function(){$.ajax({
url: '/update',
type: 'POST',
success: function(response) {
console.log(response);
$("#num").html(response["value"]);
$("#time").html(response["time"]);
},
error: function(error) {
console.log(error);
}
})}, 1000);
</script>
</body>
</html>
''')
#app.route('/update', methods=['POST'])
def update():
return jsonify({
'value': value,
'time': datetime.datetime.now().strftime("%H:%M:%S"),
})
app.run() #debug=True

Try to broadcast video to multiple clients using cheroot flask and opencv

I am trying to create a video streaming from my Raspberry Pi to multiple clients. Flask does not support WSGI server so i use the cheroot.wsgi Server. i have created a ddns server using noip in order to broadcast the video stream over the internet. Till now i manage to serve the video only to one client even if i use a wsgi server.
Here is the video feeder
from flask import Flask, render_template, Response
from camera import VideoCamera
import RPi.GPIO as gpio
gpio.setmode(gpio.BCM)
gpio.setup(21, gpio.OUT)
app = Flask(__name__)
def gen(camera):
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
#app.route('/')
def index():
return render_template('index.html')
#app.route('/video_feed')
def video_feed():
return Response(gen(VideoCamera()),mimetype='multipart/x-mixed-replace; boundary=frame')
#app.route('/background_process_test')
def background_process_test():
gpio.output(21, gpio.HIGH)
print ("Hello")
return ("nothing")
#app.route('/background_process_test2')
def background_process_test2():
gpio.output(21, gpio.LOW)
print ("Hello")
return ("nothing")
if __name__ == '__main__':
app.run()
here is the wsgi server using cheroot
try:
from cheroot.wsgi import Server as WSGIServer, PathInfoDispatcher
except ImportError:
print("OK")
from cherrypy.wsgiserver import CherryPyWSGIServer as WSGIServer, WSGIPathInfoDispatcher as PathInfoDispatcher
from main import app
d = PathInfoDispatcher({'/': app})
server = WSGIServer(('0.0.0.0', 5000), d)
if __name__ == '__main__':
try:
server.start()
except KeyboardInterrupt:
server.stop()
The opencv module that captures the camera frames
import cv2
class VideoCamera(object):
def __init__(self):
# Using OpenCV to capture from device 0. If you have trouble capturing
# from a webcam, comment the line below out and use a video file
# instead.
self.video = cv2.VideoCapture(0)
self.video.set(cv2.CAP_PROP_FRAME_WIDTH, 160)
self.video.set(cv2.CAP_PROP_FRAME_HEIGHT, 200)
# If you decide to use video.mp4, you must have this file in the folder
# as the main.py.
# self.video = cv2.VideoCapture('video.mp4')
def __del__(self):
self.video.release()
def get_frame(self):
success, image = self.video.read()
# We are using Motion JPEG, but OpenCV defaults to capture raw images,
# so we must encode it into JPEG in order to correctly display the
# video stream.
ret, jpeg = cv2.imencode('.jpg', image)
return jpeg.tobytes()
finally the web page that serves the video feed
<!doctype html>
<html>
<head>
<!-- <link rel="shortcut icon" href="1.ico" type="image/x-icon" />-->
<title>jindeath</title>
</head>
<body>
hello
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('a#test').bind('click', function() {
$.getJSON('/background_process_test',
function(data) {
//do nothing
});
return false;
});
});
$(function() {
$('a#test2').bind('click', function() {
$.getJSON('/background_process_test2',
function(data) {
//do nothing
});
return false;
});
});
</script>
<div class='container'>
<h3>Test</h3>
<form>
<img id="bg" src="{{ url_for('video_feed') }}">
<a href=# id=test><button class='btn btn-default'>Test</button></a>
<a href=# id=test2><button class='btn btn-default'>Test</button></a>
</form>
</body>
</html>
Further more when more than one devices connect to the page my rpi uses 100% of its cpu. any suggestions

Python Bottle SSE

I'm trying to get Server Sent Events to work from Python, so I found a little demo code and to my surprise, it only partly works and I can't figure out why. I got the code from here and put in just a couple little changes so I could see what was working (I included a print statement, an import statement which they clearly forgot, and cleaned up their HTML to something I could read a little easier). It now looks like this:
# Bottle requires gevent.monkey.patch_all() even if you don't like it.
from gevent import monkey; monkey.patch_all()
from gevent import sleep
from bottle import get, post, request, response
from bottle import GeventServer, run
import time
sse_test_page = """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js "></script>
<script>
var es = new EventSource("/stream");
es.onmessage = function(e) {
document.getElementById("log").innerHTML = e.data;
}
</script>
</head>
<body>
<h1>Server Sent Events Demo</h1>
<p id="log">Response Area</p>
</body>
</html>
"""
#get('/')
def index():
return sse_test_page
#get('/stream')
def stream():
# "Using server-sent events"
# https://developer.mozilla.org/en-US/docs/Server-sent_events/Using_server-sent_events
# "Stream updates with server-sent events"
# http://www.html5rocks.com/en/tutorials/eventsource/basics/
response.content_type = 'text/event-stream'
response.cache_control = 'no-cache'
# Set client-side auto-reconnect timeout, ms.
yield 'retry: 100\n\n'
n = 1
# Keep connection alive no more then... (s)
end = time.time() + 60
while time.time() < end:
yield 'data: %i\n\n' % n
print n
n += 1
sleep(1)
if __name__ == '__main__':
run(server=GeventServer, port = 21000)
So here's what ends up happening: I can see the original header and paragraph on the website, but response area never changes. On the python side, it prints n once per second, but I never see that change on the web page. I get the feeling that I just lack a fundamental understanding of what I'm trying to do but I can't find anything missing.
I'm running Python 2.7, windows 7, chrome 43.0.2357.81 m.
EDIT: I got rid of the extra quotation mark. Now it only seems to update when it gets to 60 (which I guess is better than not at all...)
Why would it wait until the end of the function to send the event?
You've got 2 sets of quotes after p id="log""

Categories

Resources