new way thinking. python data-star

Susan Sarandon
Release: 2024-10-20 06:12:02
Original
697 people have browsed it

new way thinking. python   data-star

Tiny example in python what https://data-star.dev does.

Realtime clock example in python:

from flask import Flask, Response
import time

app = Flask(__name__)

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

@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>
                {}    
            </div>
        </body>
    </html>
    """.format(get_time())

@app.route('/events')
def events():
    def generate():
        while True:
            yield 'event: datastar-fragment\n'
            yield 'data:  fragment {}\n\n'.format(get_time())
            time.sleep(1)

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

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

The above is the detailed content of new way thinking. python data-star. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!