|
| 1 | +from datetime import date, datetime |
| 2 | +import os |
| 3 | + |
| 4 | +from astral import Astral |
| 5 | +import cherrypy |
| 6 | +from cherrypy.process.plugins import Daemonizer, PIDFile |
| 7 | +import pytz |
| 8 | + |
| 9 | + |
| 10 | +class Root: |
| 11 | + @cherrypy.expose |
| 12 | + @cherrypy.tools.json_in() |
| 13 | + @cherrypy.tools.json_out() |
| 14 | + def index(self) -> str: |
| 15 | + """ |
| 16 | + Compute sunrise and sunset for the given city. |
| 17 | + """ |
| 18 | + a = Astral() |
| 19 | + a.solar_depression = 'civil' |
| 20 | + |
| 21 | + params = cherrypy.request.json |
| 22 | + city_name = params["city"] or "" |
| 23 | + try: |
| 24 | + city = a[city_name] |
| 25 | + except KeyError: |
| 26 | + return {"error": "unknown city"} |
| 27 | + |
| 28 | + tz = pytz.timezone(city.timezone) |
| 29 | + |
| 30 | + sun = city.sun(date=date.today(), local=False) |
| 31 | + result = {} |
| 32 | + for k, v in sun.items(): |
| 33 | + if isinstance(v, datetime): |
| 34 | + result[k] = v.astimezone(tz).isoformat() |
| 35 | + else: |
| 36 | + result[k] = v |
| 37 | + return result |
| 38 | + |
| 39 | + |
| 40 | +def run(): |
| 41 | + cur_dir = os.path.abspath(os.path.dirname(__file__)) |
| 42 | + |
| 43 | + cherrypy.config.update({ |
| 44 | + "environment": "production", |
| 45 | + "log.screen": True, |
| 46 | + "server.socket_port": 8444, |
| 47 | + "server.ssl_module": "builtin", |
| 48 | + "server.ssl_private_key": os.path.join(cur_dir, "../../key.pem"), |
| 49 | + "server.ssl_certificate": os.path.join(cur_dir, "../../cert.pem") |
| 50 | + }) |
| 51 | + Daemonizer(cherrypy.engine).subscribe() |
| 52 | + PIDFile(cherrypy.engine, 'astre.pid').subscribe() |
| 53 | + cherrypy.quickstart(Root()) |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == '__main__': |
| 57 | + run() |
0 commit comments