Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building Progressive Web Apps using Python Flask

Is it possible to build PWA's with Flask? More specifically, is it possible to register a service worker using Flask template rendering? If so, could anyone give some information on how to go about that or point to some resources? Because I was unable to find anything. Thank you.

like image 967
suplolx Avatar asked Sep 23 '17 15:09

suplolx


People also ask

Can flask be used for app development?

Flask is a small and lightweight Python web framework that provides useful tools and features that make creating web applications in Python easier. It gives developers flexibility and is a more accessible framework for new developers since you can build a web application quickly using only a single Python file.

Which language is best for PWA?

Angular JS is the most popular open source for Progressive web apps. Maintained by Google, developers can easily add functionality to PWA.


1 Answers

App structure

app
    static
        css
            page.css
        js
            app.js
        sw.js

    templates
        index.html

    app.py

app.py

from flask import Flask, render_template, url_for

app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
    return render_template('index.html')

@app.route('/sw.js', methods=['GET'])
def sw():
    return app.send_static_file('sw.js')

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

index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="../static/css/page.css">
</head>
<body>
    <h1>Hello World!</h1>
</body>
    <script type="text/javascript" src="../static/js/app.js"></script>
    <script type="text/javascript">
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', function() {
                navigator.serviceWorker.register("../sw.js").then(function(registration) {
                    // Registration was successful
                    console.log('ServiceWorker registration successful with scope: ', registration.scope);
                }, function(err) {
                    // registration failed :(
                    console.log('ServiceWorker registration failed: ', err);
                });
            });
        }
    </script>
</html>

Hope this helps.

like image 152
Stefan Piazza Avatar answered Oct 18 '22 07:10

Stefan Piazza