Playing with AWS Lamba

With all the buzz about serverless, I wanted to have quick play with AWS Lambda.

A few years ago, I developed a Python module to calculate tide predictions. Thanks to Chalice (Python Serverless Microframework for AWS), it was super quick to deploy an API endpoint with few lines of code.

from chalice import Chalice
from chalicelib import tmgpm
from chalice import CORSConfig
import datetime

cors_config = CORSConfig(
    allow_origin='https://www.hleroy.com'
)

app = Chalice(app_name='aws-tides')


@app.route('/predictions/daily/{station}/{year}/{month}/{day}', cors=cors_config)
def predictions_daily(station, year, month, day):
    """Returns tide heights for the specified station and specified day"""

    # Initialize a tide object
    tide = tmgpm.Tmgpm(station, int(year), int(month), int(day))

    # Initialize an empty list. Each list item will be a dictionnary with
    # datetime as x key and height as y key
    # e.g. { "x": "2019-03-07T11:00:00+01:00", "y": "1.41" }
    heights = []

    # ... except the first element of the list which is the time zone info
    heights.append(tide.get_station_tz())

    # Loop from 0 hour to 23 hours
    for t in range(24):

        # Calculate tide height
        h = tide.height(t)

        # Convert to meters (/ 1000) and round to centimeters (2 digits)
        h = round(h / 1000, 2)

        # Create a date object with date and time
        date = datetime.datetime(int(year), int(month), int(day), t, 0, 0, 0)

        # Format datetime as isoformat without microsecond e.g. "2019-08-08T12:00:00"
        date_iso = date.replace(microsecond=0).isoformat()

        # Append datetime and tide height as a dictionnary
        heights.append({"x": date_iso, "y": h})

    return heights



It exposes a very simple REST API which returns a JSON list of hourly tide heights for the given location and date. Then the tide chart is rendered with ChartJS. Et voila 🙂

Retour haut de page