2019年7月4日 星期四

My first PWA Progressive Web Application Google Part 02 with Python Flask

主要參考:https://codelabs.developers.google.com/codelabs/your-first-pwapp/#1

Google網頁裏面强烈建議使用Glitch作爲全雲端開發工具,另外一個方法是使用Node.js在自己的電腦運行,然而實際開發中需要使用Python+Flask,於是下載your-first-pwapp-master.zip后,將public文件夾改名成templates,將server.js改寫成main.py及config.json,然後輸入python main.py就會見到Chrome運行網頁

config.json

{
  "Web": [
    {
      "name": "Web01",
      "host": "0.0.0.0",
      "port": 80
    }
  ]
}

main.py

from flask import Flask, request, send_from_directory, render_template, url_for, redirect
import datetime, os, json, logging, webbrowser, requests

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')
    
@app.route('/forecast/<location>')
def forecast(location):
    try:
        BASE_URL = 'https://api.darksky.net/forecast'
        API_KEY = '7cfcae53bb33928e9a7d9a85df825bce'
        url = '/'.join([BASE_URL, API_KEY, location])
        r = requests.get(url)
        return json.dumps(r.json())
    except Exception as e:
        logging.error(e)
        
        fakeForecast = {
          fakeData: True,
          latitude: 0,
          longitude: 0,
          timezone: 'America/New_York',
          currently: {
            time: 0,
            summary: 'Clear',
            icon: 'clear-day',
            temperature: 43.4,
            humidity: 0.62,
            windSpeed: 3.74,
            windBearing: 208,
          },
          daily: {
            data: [
              {
                time: 0,
                icon: 'partly-cloudy-night',
                sunriseTime: 1553079633,
                sunsetTime: 1553123320,
                temperatureHigh: 52.91,
                temperatureLow: 41.35,
              },
              {
                time: 86400,
                icon: 'rain',
                sunriseTime: 1553165933,
                sunsetTime: 1553209784,
                temperatureHigh: 48.01,
                temperatureLow: 44.17,
              },
              {
                time: 172800,
                icon: 'rain',
                sunriseTime: 1553252232,
                sunsetTime: 1553296247,
                temperatureHigh: 50.31,
                temperatureLow: 33.61,
              },
              {
                time: 259200,
                icon: 'partly-cloudy-night',
                sunriseTime: 1553338532,
                sunsetTime: 1553382710,
                temperatureHigh: 46.44,
                temperatureLow: 33.82,
              },
              {
                time: 345600,
                icon: 'partly-cloudy-night',
                sunriseTime: 1553424831,
                sunsetTime: 1553469172,
                temperatureHigh: 60.5,
                temperatureLow: 43.82,
              },
              {
                time: 432000,
                icon: 'rain',
                sunriseTime: 1553511130,
                sunsetTime: 1553555635,
                temperatureHigh: 61.79,
                temperatureLow: 32.8,
              },
              {
                time: 518400,
                icon: 'rain',
                sunriseTime: 1553597430,
                sunsetTime: 1553642098,
                temperatureHigh: 48.28,
                temperatureLow: 33.49,
              },
              {
                time: 604800,
                icon: 'snow',
                sunriseTime: 1553683730,
                sunsetTime: 1553728560,
                temperatureHigh: 43.58,
                temperatureLow: 33.68,
              }
            ]
          }
        }
        
        if location.split(',')==2:
            result['latitude'] = location.split(',')[0]
            result['longitude'] = location.split(',')[1]
        
        return json.dumps(fakeForecast)

@app.route('/<path:path>')
def path(path):
    if path.endswith(('.js', '.css', '.png', '.ico', 'manifest.json', '.svg')):
        return send_from_directory("templates", path)
    return redirect(url_for('index'))
    
def init(name):
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    now = datetime.datetime.utcnow().strftime("%Y%m%d.%H%M%S")
    fileName = '.'.join([name, now, str(os.getpid()), 'log'])
    logPath = 'logs'
    os.makedirs(logPath, exist_ok=True)
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s",
        handlers=[
            logging.FileHandler("{0}/{1}".format('logs', fileName)),
            logging.StreamHandler()
    ])
    
def run_flask():
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    host='127.0.0.1'
    port=80
    with open('config.json', 'r') as infile:
        data = json.load(infile)
        print(data)
        web = data["Web"][0]
        host = web["host"]
        port = web["port"]
    webbrowser.open('http://{}:{}'.format('127.0.0.1' if host=='0.0.0.0' else host, port))
    app.secret_key = os.urandom(12)
    app.run(host=host, port=port)

    
if __name__ == "__main__":
    init('flask')
    run_flask()









End

沒有留言:

張貼留言

2007 to 2023 HP and Dell Servers Comparison

  HP Gen5 to Gen11  using ChatGPT HP ProLiant Gen Active Years CPU Socket Popular HP CPUs Cores Base Clock Max RAM Capacity Comparable Dell ...