使用Python Flask构建渐进式Web应用程序。

11

是否可能使用Flask构建PWA?更具体地说,是否可以使用Flask模板渲染注册服务工作者?如果可以,是否有人可以提供有关如何进行操作或指向某些资源的信息?因为我找不到任何东西。谢谢。

1个回答

8

应用程序结构

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>

希望这能帮到你。

将 'navigator.serviceWorker.register("../sw.js")' 改为 'navigator.serviceWorker.register("/sw.js")'。如果使用前者,navigator 将在任何地方寻找新的 service worker(但找不到),而不是识别第一个注册的 service worker。 - Caleb Wright
1
我总是收到“ServiceWorker注册失败:DOMException:使用脚本('http://localhost:5000 / sw.js')为范围('http://localhost:5000 /')注册ServiceWorker失败:脚本有一个不受支持的MIME类型('text / plain')。 ” - Şansal Birbaş

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接