Day 8 of the Anvil Advent Calendar

Build a web app every day until Christmas, with nothing but Python!

Counting Down the Days (again!)

It’s December 8th and boy have we got a treat for you.

For those of you who prefer your Christmas cheer in JSON format, we’ve re-rendered the Christmas countdown for your viewing pleasure.

Say hello to the Days to Christmas API:

https://christmas-days.anvil.app/_/api/get_days

Read on to hear how I built it. Or, you can open the source code for yourself:

Do the calculation

Create a new Anvil app and add a Server Module. We’ll define a get_days function that returns the number of days to Christmas:

from datetime import date

def get_days():
  christmas_year = date.today().year
  christmas = date(christmas_year,12,25)
  # Adjust the Christmas year if we're in late December
  if date.today() > christmas:
    christmas_year += 1
    christmas = date(christmas_year,12,25)
  days = (christmas-date.today()).days
  if days == 0:
    return {'Days to Christmas': days, 'Special Christmas Message': "It's Christmas Day!!!"}
  else:
    return {'Days to Christmas': days}

Turn it into an HTTP API endpoint (in one line of Python!)

We define a HTTP API endpoint using @anvil.server.http_endpoint('/<your-path-here>')

So, all you need to do is add the decorator to your get_days function:

@anvil.server.http_endpoint('/get_days')
def get_days():
  christmas_year = date.today().year
  christmas = date(christmas_year,12,25)
  # Adjust the Christmas year if we're in late December
  if date.today() > christmas:
    christmas_year += 1
    christmas = date(christmas_year,12,25)
  days = (christmas-date.today()).days
  if days == 0:
    return {'Days to Christmas': days, 'Special Christmas Message': "It's Christmas Day!!!"}
  else:
    return {'Days to Christmas': days}

Your endpoint will be available at <your-app-id>.anvil.app/_/api/get_days

Or, you can use mine, which is here https://christmas-days.anvil.app/_/api/get_days

Time for a mince pie

That’s all there is to it. Happy counting!

View the source code:


Give the Gift of Python

Share this post: