Featured image of post Playing with AWS Lamba

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(

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

    # 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 :)

Licensed under CC BY-NC-SA 4.0
Dernière mise à jour le Sep 03, 2022 15:11 +0200
Généré avec Hugo
Thème Stack conçu par Jimmy