S
S
Spoon in the brain2020-04-17 01:01:35
JavaScript
Spoon in the brain, 2020-04-17 01:01:35

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)

data.txt
Привет!
And so, the essence of this code is that if changes occur in the data.txt file , then the client receives information about this, in turn, the client asks the server
Changes in data.txt
Привет!
Как дела?

Клиент: Есть чёт новое?
...
...
...
...
...
Сервер: Да! Держи - {'date':'2020/04/17 00:57:53', 'content':'Привет! Как дела?'}

The problem is that the code works, but at first, after a few minutes, the client simply stops asking the server what and how.
Can you please suggest what is the problem here?
I will be very happy with your answers! :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rasschitai, 2020-04-17
@rasschitai

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 question

Ask a Question

731 491 924 answers to any question