2017-09-23 145 views
1

使用Flask構建PWA有可能嗎?更具體地說,是否可以使用Flask模板渲染註冊服務工作人員?如果是這樣,任何人都可以提供一些關於如何去做或指向某些資源的信息?因爲我無法找到任何東西。謝謝。使用Python Flask構建漸進式Web應用程序

回答

1

應用結構

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> 

希望這有助於。