Skip to content

Instantly share code, notes, and snippets.

@blinkinglight
Last active October 19, 2024 17:49
Show Gist options
  • Save blinkinglight/17ceba65b2b608a50c56adddbf9a30b7 to your computer and use it in GitHub Desktop.
Save blinkinglight/17ceba65b2b608a50c56adddbf9a30b7 to your computer and use it in GitHub Desktop.

Revisions

  1. blinkinglight revised this gist Oct 19, 2024. 1 changed file with 7 additions and 3 deletions.
    10 changes: 7 additions & 3 deletions main.py
    Original file line number Diff line number Diff line change
    @@ -7,6 +7,10 @@
    def root_dir(): # pragma: no cover
    return os.path.abspath(os.path.dirname(__file__))


    def get_time():
    return '<div id="time">{}</div>'.format(time.strftime('%H:%M:%S'))

    @app.route('/')
    def index():
    return """
    @@ -18,18 +22,18 @@ def index():
    <body>
    <div data-on-load="$$get('/events')">
    <h1>Clock</h1>
    <p id="time"></p>
    {}
    </div>
    </body>
    </html>
    """
    """.format(get_time())

    @app.route('/events')
    def events():
    def generate():
    while True:
    yield 'event: datastar-fragment\n'
    yield 'data: fragment <div id="time">{}</div>\n\n'.format(time.strftime('%H:%M:%S'))
    yield 'data: fragment {}\n\n'.format(get_time())
    time.sleep(1)

    return Response(generate(), content_type='text/event-stream')
  2. blinkinglight created this gist Oct 19, 2024.
    38 changes: 38 additions & 0 deletions main.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    from flask import Flask, Response
    import time

    app = Flask(__name__)


    def root_dir(): # pragma: no cover
    return os.path.abspath(os.path.dirname(__file__))

    @app.route('/')
    def index():
    return """
    <!DOCTYPE html>
    <html>
    <head>
    <script type="module" defer src="https://cdn.jsdelivr.net/npm/@sudodevnull/datastar"></script>
    </head>
    <body>
    <div data-on-load="$$get('/events')">
    <h1>Clock</h1>
    <p id="time"></p>
    </div>
    </body>
    </html>
    """

    @app.route('/events')
    def events():
    def generate():
    while True:
    yield 'event: datastar-fragment\n'
    yield 'data: fragment <div id="time">{}</div>\n\n'.format(time.strftime('%H:%M:%S'))
    time.sleep(1)

    return Response(generate(), content_type='text/event-stream')

    if __name__ == '__main__':
    app.run(debug=True)