Answer the question
In order to leave comments, you need to log in
What is the problem here?
I started using long polling in my application, in general, here is the code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="{{ url_for("static", filename="poll.js") }}"></script>
</head>
<body>
<h1>Файл</h1>
<p id="date"></p>
<pre id="content"></pre>
</body>
</html>
function update() {
$.ajax({
url: '/data-update',
success: function(data) {
$('#date').text(data.date);
$('#content').text(data.content);
update();
},
timeout: 50000
});
}
function load() {
$.ajax({
url: '/data',
success: function(data) {
$('#content').text(data.content);
update();
}
});
}
$(document).ready(function() {
load();
});
from flask import Flask
from flask import render_template
import os
import time
from datetime import datetime
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/data-update', methods=['GET'])
def update():
request_time = time.time()
while not os.stat('data.txt').st_mtime > request_time:
time.sleep(0.5)
content = ''
with open('data.txt') as data:
content = data.read()
return {'content': content,
'date': datetime.now().strftime('%Y/%m/%d %H:%M:%S')}
@app.route('/data', methods=['GET'])
def get():
content = ''
with open('data.txt') as data:
content = data.read()
return {'content': content}
if __name__ == '__main__':
app.run(port=5000, debug=True, threaded=True)
Привет!
Привет!
Как дела?
Клиент: Есть чёт новое?
...
...
...
...
...
Сервер: Да! Держи - {'date':'2020/04/17 00:57:53', 'content':'Привет! Как дела?'}
Answer the question
In order to leave comments, you need to log in
it would be nice to handle $.ajax errors, through the error method you may have something happening there and you don’t see it (don’t call the update function after that)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question