โ† Integrations

Backend ยท Python

Planetary hours (hora) in a Flask blueprint

Hora - the planetary hour - divides daylight and night into twelve parts each, so the windows stretch and shrink with the seasons. This Flask example serves them for any date and city: a client module using only the standard library, a blueprint route, and a zoneinfo lookup so the offset is right on both sides of a clock change.

Updated

How this page was checked: astronode_client.py was executed with Python 3.9 (standard library only) against the in-memory API: the winter and summer windows and the 400 below are its output. Flask is not installed on the build machine, so the blueprint route itself was not served.

A client with no dependencies

astronode_client.py:

python
"""Stdlib-only AstroNode client: no requests, no SDK."""
import json
import os
import urllib.error
import urllib.request
from datetime import datetime, time, timedelta, timezone
from zoneinfo import ZoneInfo

BASE_URL = os.environ.get("ASTRONODE_BASE_URL", "https://api.astronode.dev")


class AstroNodeError(Exception):
    def __init__(self, status, code, message):
        super().__init__(f"{status} {code}: {message}")
        self.status = status
        self.code = code


def _post(path, body):
    req = urllib.request.Request(
        BASE_URL + path,
        data=json.dumps(body).encode(),
        method="POST",
        headers={
            "Authorization": "Bearer " + os.environ["ASTRONODE_API_KEY"],
            "Content-Type": "application/json",
        },
    )
    try:
        with urllib.request.urlopen(req, timeout=15) as res:
            return json.load(res)["data"]
    except urllib.error.HTTPError as e:
        # urlopen raises on 4xx/5xx; the API's error envelope is in the body.
        err = json.load(e).get("error", {})
        raise AstroNodeError(e.code, err.get("code"), err.get("message")) from None


def offset_minutes(day, tz_name):
    """UTC offset of tz_name at local noon on `day` - DST-aware."""
    noon = datetime.combine(day, time(12), tzinfo=ZoneInfo(tz_name))
    return int(noon.utcoffset().total_seconds() // 60)


def horas(day, lat, lng, tz_name):
    """The 24 planetary hours for `day`, start/end converted to local time."""
    offset = offset_minutes(day, tz_name)
    data = _post("/v1/muhurta/hora", {
        "date": day.isoformat(),
        "tz_offset_minutes": offset,
        "lat": lat,
        "lng": lng,
    })
    local = timezone(timedelta(minutes=offset))
    return [
        {
            "lord": w["lord"],
            "start": datetime.fromisoformat(w["start"].replace("Z", "+00:00")).astimezone(local),
            "end": datetime.fromisoformat(w["end"].replace("Z", "+00:00")).astimezone(local),
        }
        for w in data["windows"]
    ]
  • urlopen raises HTTPError for any 4xx or 5xx. The exception is also a readable response, so json.load(e) recovers the API's error.code and message instead of a bare "HTTP Error 400".
  • .replace("Z", "+00:00") is there for Python 3.9 and 3.10, whose fromisoformat does not accept a trailing Z; from 3.11 it is unnecessary but harmless.
  • offset_minutes asks zoneinfo for the offset on *that* date, so London is 0 in December and 60 in June without a table of DST dates in your code.

The blueprint

hora.py - register with app.register_blueprint(bp):

python
from datetime import date

from flask import Blueprint, abort, jsonify, request

import astronode_client as an

bp = Blueprint("hora", __name__, url_prefix="/hora")


@bp.get("/<iso_date>")
def hora(iso_date):
    # /hora/2026-12-07?lat=51.5074&lng=-0.1278&tz=Europe/London
    try:
        day = date.fromisoformat(iso_date)
        lat = float(request.args["lat"])
        lng = float(request.args["lng"])
        windows = an.horas(day, lat, lng, request.args.get("tz", "UTC"))
    except (KeyError, ValueError):  # missing/bad arg, bad date, unknown zone
        abort(400)
    except an.AstroNodeError as e:
        return jsonify(error=e.code, message=str(e)), (400 if e.status < 500 else 502)
    return jsonify([
        {"lord": w["lord"], "start": w["start"].isoformat(), "end": w["end"].isoformat()}
        for w in windows
    ])

An unknown tz raises ZoneInfoNotFoundError, which subclasses KeyError, so it lands in the same 400 as a missing lat. The responses are the same for every visitor asking about the same date and place, so a cache in front of this route (Flask-Caching, or an HTTP cache honouring Cache-Control) removes most of the API calls.

Winter and summer in London

First hora and lengths, from the client run
DateOffset sentFirst hora (local)Day horaNight hora
Mon 7 Dec 20260Moon 07:51-08:3140 min80 min
Mon 7 Jun 202760Moon 04:45-06:0782 min38 min

Each day starts at sunrise with the hora of the weekday's lord - the Moon on a Monday - and the thirteenth hora begins at sunset (Venus at 15:52 in December). The last of the 24 ends at the next sunrise, so a page listing "today's" horas runs past midnight. See muhurta time windows for how the API places sunrise.

Sending 0 for the June date returned the same UTC instants, since sunrise does not depend on your clock - the offset tells the API which local day you mean and what your times will be shown in. If the code then formats with that wrong offset, the Moon hora is printed at 03:45, an hour early. Use the zone, not a constant.

The mistake that bites first: the .env that gunicorn never reads

With python-dotenv installed, flask run loads .env and .flaskenv automatically, so ASTRONODE_API_KEY in .env works in development. That loading is a feature of the flask command. Under gunicorn or uWSGI in production nothing reads the file, os.environ["ASTRONODE_API_KEY"] raises KeyError, and the first hora request is a 500.

  • Set the variable in the process manager or host (systemd Environment=, the container's env, your platform's settings), or call load_dotenv() yourself in the app factory.
  • Check for the key when the app is created so a missing value fails the deploy, not the first visitor.
  • Keep the key out of .flaskenv: that file is meant for committed, non-secret CLI settings such as FLASK_APP. .env is the git-ignored one.
  • The birth and date inputs are strict: adding a time field to the hora body returned 400 VALIDATION_ERROR. POST /v1/muhurta/hora needs the Hobby plan or above.

Questions

Which AstroNode endpoints does the Flask example call?
1 endpoint: Hora (Planetary Hours) (POST /v1/muhurta/hora).
Was the Flask code on this page actually run?
astronode_client.py was executed with Python 3.9 (standard library only) against the in-memory API: the winter and summer windows and the 400 below are its output. Flask is not installed on the build machine, so the blueprint route itself was not served.