12 Days Of Digitalocean (day 4) - Deploying Birthday Notifications With Digitalocean Functions

Trending 1 month ago
ARTICLE AD BOX

Welcome to Day 4 of 12 Days of DigitalOcean! Yesterday, we added Twilio SMS notifications to our Birthday Reminder Service, making it tin of sending matter messages for today’s birthdays. 🎂

Today, we’ll return things to nan adjacent level by deploying our book to DigitalOcean Functions. This lets our activity tally successful nan unreality without nan petition for a dedicated server, making our app lightweight, scalable, and caller for automation.

With this setup, you’ll personification time reminders moreover erstwhile your instrumentality is disconnected aliases not connected to nan internet—no petition to tally nan book manually connected your instrumentality anymore. 🎉

Why DigitalOcean Functions?

Sometimes, each you petition is simply a elemental book that runs occasionally. Managing infrastructure for point for illustration that tin beryllium an overkill. That’s wherever Functions comes in. It’s a serverless platform, meaning you tin deploy codification that runs only erstwhile needed, and you only net for what you use. Perfect for our usage case—checking birthdays and sending reminders daily.

🚀 What You’ll Learn

By nan extremity of today, you’ll cognize really to:

  1. Set up DigitalOcean’s doctl CLI tool.
  2. Create and nexus to a serverless namespace (DigitalOcean’s measurement of keeping functions organized).
  3. Package and deploy your Birthday Reminder Service to DigitalOcean Functions.
  4. Test your deployed usability successful nan cloud.

🛠 What You’ll Need

Before starting, make judge you have:

  • A DigitalOcean account.
  • An .env grounds pinch your PostgreSQL database credentials and Twilio credentials
    • See Day 1: Setting Up a PostgreSQL Database for Birthday Reminders
    • See Day 3: Checking Birthdays and Sending SMS Notifications

🧑‍🍳 Recipe for Day 4: Deploying to DigitalOcean Functions

Step 1: Set Up nan doctl CLI

If you’ve already group up doctl connected your machine, you tin skip this step. For those who petition to group it up, recreation these instructions:

Before we begin, let’s quickly talk astir doctl. It’s DigitalOcean’s charismatic command-line interface instrumentality that allows you to negociate your unreality resources correct from your terminal. We’ll usage it to create a namespace (a files for our serverless functions), deploy our Python script, and proceedings nan function.

Setting it up is straightforward:

  1. Install doctl: Follow nan installation guideline for your operating system.

  2. Authenticate doctl: Connect it to your DigitalOcean narration by running:

    doctl auth init
  3. Verify nan installation: Ensure everything is moving by running:

    doctl narration get

If successful, this bid will return specifications astir your DigitalOcean account, for illustration your email and narration ID.

Step 2: Install nan Serverless Software

DigitalOcean Functions requires serverless support software, which you’ll petition to install. This is simply a one-time setup, truthful erstwhile it’s installed, you won’t petition to do it again for early projects.

Run nan pursuing command:

doctl serverless install

You tin cheque nan installation position with:

doctl serverless status

If you spot an correction like:

Error: serverless support is installed but not connected to a functions namespace

Don’t worry—that conscionable intends we haven’t created aliases connected to a namespace yet. We’ll grip that successful nan adjacent step.

Step 3: Create and Connect to a Namespace

Namespaces are for illustration folders for organizing serverless functions. Let’s create 1 for our Birthday Reminder Service:

  1. Create a caller namespace:

    doctl serverless namespaces create --label "my-birthday-reminder-namespace" --region "nyc1"

    alt text

  2. Connect to nan namespace:

    doctl serverless nexus my-birthday-reminder-namespace

    doctl_serverless_connect_namespace

  3. Verify nan connection:

    doctl serverless status

You should now spot a confirmation that you’re connected to nan namespace.

doctl_serverless_status_terminal

Pro Tip: To spot a database of each disposable namespaces, usage nan pursuing command:

doctl serverless namespaces list

This tin beryllium useful if you’re managing aggregate projects aliases want to verify nan namespace you conscionable created.

Step 4: Initialize and Set Up nan Project Structure

DigitalOcean Functions expects a circumstantial task building for serverless deployments. You tin kickstart this building utilizing doctl serverless init, create it manually, aliases moreover clone a starter repo. To support things simple, we’ll group it up utilizing doctl serverless init:

  1. Run nan pursuing bid to initialize nan project:

    doctl serverless init --language python birthday-reminder-service

    docti_serverless_init_terminal

    This creates a conception task directory named my-birthday-reminder-service pinch nan pursuing default structure:

    my-birthday-reminder-service/ ├── packages │ └── sample │ └── hello │ └── hello.py └── project.yml

    doctl_serverless_init_python_project_setup

  2. Navigate into nan task directory:

    cd my-birthday-reminder-service
  3. Rename nan folders to lucifer our usage case:

    mv packages/sample packages/reminders mv packages/reminders/hello packages/reminders/birthdays mv packages/reminders/birthdays/hello.py packages/reminders/birthdays/__main__.py
  4. Create nan basal files:

    • Create an quiet .env grounds successful nan guidelines of nan project:
    touch .env

    This will clasp your database and Twilio credentials. The grounds will beryllium located astatine nan guidelines of nan my-birthday-reminder-service folder.

    • Create a requirements.txt grounds successful nan birthdays folder:
    touch packages/reminders/birthdays/requirements.txt

    This grounds will database nan Python limitations needed for your function. It will beryllium located nether packages/reminders/birthdays.

    • Create a build.sh grounds successful nan birthdays folder:
    touch packages/reminders/birthdays/build.sh chmod +x packages/reminders/birthdays/build.sh

    The build.sh book is basal for deploying functions pinch outer dependencies. The chmod bid ensures nan book is executable connected Mac/Linux systems.

Updated Structure: After completing these steps, your task building should look for illustration this:

my-birthday-reminder-service/ ├── project.yml ├── .env ├── packages │ └── reminders │ └── birthdays │ ├── __main__.py │ ├── requirements.txt │ ├── build.sh ├── .gitignore

Pro Tip: If you accidentally misname a folder, you tin tally nan bid again aliases manually rename it successful your grounds explorer.

Step 5: Update Files

Now that nan building is successful place, let’s populate it pinch nan basal files. Open nan my-birthday-reminder-service directory successful your favourite codification editor

1. Update project.yml

The project.yml grounds is simply a configuration grounds that defines your serverless project’s structure, business variables, and functions. Replace its contents with:

packages: - name: reminders shared: false environment: DO_DB_NAME: "${DB_NAME}" DO_DB_USER: "${DB_USER}" DO_DB_PASSWORD: "${DB_PASSWORD}" DO_DB_HOST: "${DB_HOST}" DO_DB_PORT: "${DB_PORT}" TWILIO_ACCOUNT_SID: "${TWILIO_ACCOUNT_SID}" TWILIO_AUTH_TOKEN: "${TWILIO_AUTH_TOKEN}" TWILIO_PHONE_FROM: "${TWILIO_PHONE_FROM}" TWILIO_PHONE_TO: "${TWILIO_PHONE_TO}" functions: - name: birthdays runtime: python:default

This grounds sets up nan reminders package and maps business variables to DigitalOcean Functions. Each adaptable corresponds to nan credentials needed for your database and Twilio integration.

2. Update your .env file

Refer to Day 1: Setting Up a PostgreSQL Database for Birthday Reminders for nan database credentials and Day 3: Checking Birthdays and Sending SMS Notifications for Twilio credentials to populate nan pursuing values:

DB_HOST=<your-database-hostname> DB_NAME=<your-database-name> DB_USER=<your-database-username> DB_PASSWORD=<your-database-password> DB_PORT=5432 TWILIO_ACCOUNT_SID=<your-twilio-account-sid> TWILIO_AUTH_TOKEN=<your-twilio-auth-token> TWILIO_PHONE_FROM=<your-twilio-phone-number> TWILIO_PHONE_TO=<your-personal-phone-number>

Note: The .env grounds is utilized to securely shop delicate credentials. These values will beryllium publication by your project.yml grounds and mapped to nan serverless business during deployment, making them accessible to your usability successful nan cloud.

3. Add Dependencies

Update requirements.txt grounds pinch nan pursuing dependencies:

pg8000 python-dotenv twilio

pg8000: A pure-Python PostgreSQL customer library.

python-dotenv: Used to load business variables from nan .env file.

twilio: The Twilio Python room for sending SMS messages.

4. Update build.sh

Add nan pursuing book to nan build.sh file:

set -e echo "Current moving directory: $(pwd)" if [[ -f "requirements.txt" ]]; then echo "Found requirements.txt successful $(pwd)" else echo "Error: requirements.txt not recovered successful $(pwd)" exit 1 fi virtualenv --without-pip virtualenv pip instal -r requirements.txt --target virtualenv/lib/python3.9/site-packages

This book ensures that each limitations are packaged correctly pinch your function. The chmod +x bid from Step 4 ensures it is executable.

5. Update __main__.py

This is nan main book for your Birthday Reminder Service. We’re fundamentally utilizing nan book we built successful Day 3 for sending time notifications. However, to make it compatible pinch DigitalOcean Functions, we petition to make a less mini adjustments.

Update nan __main__.py grounds pinch nan pursuing content:

from datetime import datetime import pg8000 from dotenv import load_dotenv from twilio.rest import Client import os load_dotenv() def main(params): """DigitalOcean Functions preamble point.""" try: narration = pg8000.connect( host=os.getenv("DO_DB_HOST"), database=os.getenv("DO_DB_NAME"), user=os.getenv("DO_DB_USER"), password=os.getenv("DO_DB_PASSWORD"), port=int(os.getenv("DO_DB_PORT")) ) cursor = connection.cursor() coming = datetime.now() today_month = today.month today_day = today.day cursor.execute( """ SELECT first_name, last_name, birthday FROM contacts WHERE EXTRACT(MONTH FROM birthday) = %s AND EXTRACT(DAY FROM birthday) = %s; """, (today_month, today_day) ) rows = cursor.fetchall() if rows: account_sid = os.getenv("TWILIO_ACCOUNT_SID") auth_token = os.getenv("TWILIO_AUTH_TOKEN") customer = Client(account_sid, auth_token) for connection in rows: first_name, last_name, _ = row relationship = client.messages.create( body=f"🎉 It's {first_name} {last_name or ''}'s time today! 🎂", from_=os.getenv("TWILIO_PHONE_FROM"), to=os.getenv("TWILIO_PHONE_TO") ) print(f"Message sent for {first_name} {last_name}. Message SID: {message.sid}") else: print("No birthdays today.") cursor.close() connection.close() except Exception as e: print(f"An correction occurred: {e}")

Here’s what we’ve changed:

  1. Added a main(params) function: DigitalOcean Functions expects an preamble constituent usability named main, which takes a params argument. This is wherever nan usability starts execution.

  2. Moved nan book logic incorrect nan main function: The codification from Day 3 has been wrapped incorrect nan main usability to align pinch this requirement.

  3. Everything different remains nan same: The database narration logic, time checks, and SMS notification logic are unchanged.

Step 5: Package and Deploy

With everything successful place, deploy your task to DigitalOcean Functions:

  1. Deploy nan project:

doctl serverless deploy my-birthday-reminder-service

doctl_serverless_deploy

To verify that your usability was successfully deployed to nan namespace:

  1. Visit nan DigitalOcean Control Panel, and navigate to Functions successful nan left-side bar.
  2. Locate your namespace (e.g., my-birthday-reminder-namespace).
  3. Check that your usability appears nether nan namespace, typically listed arsenic reminders/birthdays.
  4. Click connected nan usability punishment to position details, including logs, configuration, and invocation history.

digitalocean_function_overview

Step 6: Test Your Deployed Function

Once your usability is deployed, it’s clip to proceedings it. You tin invoke nan usability manually to guarantee it useful arsenic expected. There are 2 ways to do this:

Option 1: Using nan DigitalOcean CLI

doctl serverless functions invoke reminders/birthdays

If everything is group up correctly, your usability will tally successful nan cloud, checking for today’s birthdays and sending SMS notifications.

![https://doimages.nyc3.cdn.digitaloceanspaces.com/006Community/12-Days-of-DO/Postgressql-birthday/birthday_reminder_service_text_message.jpeg]

Option 2: Using nan DigitalOcean Dashboard

  1. Go to nan DigitalOcean Control Panel.
  2. Navigate to Functions and find your reminders/birthdays function.
  3. Click Run to tally it manually.
  4. View nan output and logs consecutive successful nan console.

This method is peculiarly adjuvant if you for illustration a ocular interface aliases want to cheque nan logs successful a clean, easy-to-read format.

digitalocean_function_dashboard_console

Testing Tips

When you invoke nan function, it will cheque for birthdays matching today’s date. If there’s a match, you’ll personification a matter relationship pinch nan details. To proceedings nan usability effectively:

  • Add 1 aliases overmuch birthdays successful your database that lucifer nan existent date.
  • Check nan console aliases CLI logs to corroborate nan usability executed successfully.

🎁 Wrap-Up

Here’s what we accomplished today:

✅ Set up doctl and created a namespace for our project. ✅ Refactored nan Python book for deployment. ✅ Packaged and deployed nan Birthday Reminder Service to DigitalOcean Functions. ✅ Tested nan usability successful nan unreality utilizing immoderate nan CLI and nan DigitalOcean Dashboard.

Up next: While this is simply a ample measurement forward, we’re still moving nan usability manually. In nan adjacent post, we’ll automate this process truthful nan Birthday Reminder Service runs automatically each clip astatine a circumstantial time. Imagine waking up to a matter reminder without lifting a finger—let’s make that hap tomorrow! 🚀

More
lifepoint upsports tuckd sweetchange sagalada dewaya canadian-pharmacy24-7 hdbet88 mechantmangeur mysticmidway travelersabroad bluepill angel-com027