Our Start-Up is 25% Pregnant 🎊 So Naturally I Made an Emoji-Powered Python Web App
Tags: python, pregnancy, emoji, webdev
Published: 2020-11-13 14:27:41


Anvil is expanding. Well, I’ve gained a [lot](https://anvil.works/forum/t/hello-im-anvils-new-developer-advocate/6610) of [new](https://anvil.works/forum/t/so-its-official/6679) [colleagues](https://anvil.works/forum/t/yet-another-developer-advocate/6733) lately, but that's not what I mean! Bridget and I are both pregnant, and our newest teammate Stu is expecting a baby too – with all three babies due in the new year :tada:

![](https://anvil.works/blog/img/fruitmoji/fruitmoji-mobile-format-screenshot.png)

Naturally, this has meant a lot of nerdy tracking of how the pregnancies are going. For some reason, baby sites seem obsessed with the idea of [comparing the size of your baby to fruit and veg](https://www.babycenter.com/pregnancy/your-body/how-big-is-my-baby-week-by-week-fruit-and-veggie-comparisons_5223185). So I decided to make my own fruit-based pregnancy app - with a twist.

[Try out my app!](https://howpregnantami.com)

# We love Emoji 😂

Emoji are taking over the world! They’re everywhere you look, adding a dash of colour to texts, tweets and chats with friends and colleagues.

Emoji were initially invented for Japanese email and phone programs. They proved so popular [the Unicode Consortium officially adopted them](http://www.unicode.org/reports/tr51/#Introduction) back in 2007 and has reserved a set of code points to represent emoji. Since then emoji have increased in number and spread around the world, replacing older ways of conveying emotion in text like `:-)`. They’ve become a fun way to express ourselves [that can cross language barriers](https://www.wired.com/story/academic-emoji-conference/).

Even Oxford Dictionaries joined in. They explained:

> That’s right – for the first time ever, the Oxford Dictionaries Word of the Year is a pictograph: 😂, officially called the ‘Face with Tears of Joy’ emoji, though you may know it by other names. There were other strong contenders from a range of fields but 😂 was chosen as the ‘word’ that best reflected the ethos, mood, and preoccupations of 2015.

So why not represent pregnancy with emoji too?

## Python & Emoji 🐍

I built my web app with [Anvil](https://anvil.works/docs), which means I could write everything in Python! This made emoji-wrangling particularly easy - Python 3 is [great with Unicode](https://docs.python.org/3/howto/unicode.html), and [most web browsers](http://caniemoji.com/) now support emoji display too. I previewed [how they would look](https://unicode.org/emoji/charts/full-emoji-list.html) for different browsers using the Unicode site.

![Now it's easy to get your 5 emoji fruit and veg a day!](https://anvil.works/blog/img/fruitmoji/fruit-emoji-table.png) <figcaption>
                <p>Now it’s easy to get your 5 emoji fruit and veg a day!</p>
            </figcaption>

And with Anvil, that’s all we need to worry about! This is great news for those of us who like to express ourselves with the power of 😎.

# Building the app 🏠

Anvil’s online interface made it easy to start building my pregnancy tracker. I wanted a splash of colour so I chose the ‘Hello San Francisco’ theme and replaced the header image with a cute photo of a fruit-stall I found on [pexels.com](https://www.pexels.com/search/fruits%20market/).

![Adding labels to my Form. I chose the font &lsquo;Pacifico&rsquo;.](https://anvil.works/blog/img/fruitmoji/What-size-is-bb.gif) <figcaption>
                <p>Adding labels to my Form. I chose the font ‘Pacifico’.</p>
            </figcaption>

## Font fun ✍

The best part was [finding appropriate emoji](https://unicode.org/emoji/charts/full-emoji-list.html#food_&_drink) for each week of pregnancy. There are quite a few fruits and veggies available as emoji but some creative choices had to be made!

I found it harder to pick emoji for the final weeks and really stretched the definition of “fruit or vegetable”! For example, for 37 weeks I resorted to 🥗, and any time after the due date (40+ weeks) I just display ‘👶’. I’d started to run out of large vegetables 🎃 and most babies will make an appearance before this point.

To display all the emoji, you’ll need [a fairly recent browser](https://caniemoji.com/). I didn’t have any issues on Windows and Mac, but if you’re using Linux you might need to [update your system fonts](https://askubuntu.com/questions/1029661/18-04-color-emoji-not-showing-up-at-all-in-chrome-only-partially-in-firefox). Otherwise you’ll see funky-looking black-and-white emoji!

## Data tables 📑

I decided to use Anvil’s [built in database](/docs/data-tables) to store the emoji I chose for each week. This was easier than trying to keep track of it all in my code.

![The table of emoji aliases vs weeks of pregnancy I made. 1 to 4 weeks have the same emoji, sparkles ✨ because things are so tiny at that point.](https://anvil.works/blog/img/fruitmoji/fruitmoji-fruit-table.png) <figcaption>
                <p>The table of emoji aliases vs weeks of pregnancy I made. 1 to 4 weeks have the same emoji, sparkles ✨ because things are so tiny at that point.</p>
            </figcaption>

You can store emoji directly in an Anvil Data Table - all Unicode is fully supported. But for convenience I stored [emoji aliases](https://www.webfx.com/tools/emoji-cheat-sheet/) in my Data Table instead, and made a little `dict` to translate between the aliases and emoji to display. This made it easier to play around with which emoji corresponded to which week. And it made it easier to see what I was doing regardless of what browser I was using, as some don’t render all emoji.

```
EMOJI_LOOKUP = {'sparkles': '✨', 'salt': '\U0001f9c2', 'cherries': '🍒', 'strawberry': '🍓', 'mushroom': '🍄', 'chestnut': '🌰', 'peanuts': '🥜', 'kiwi': ':kiwi:', 'tangerine': '🍊', 'peach': '🍑', 'lemon': '🍋', 'apple': ':apple:', 'avocado': '🥑', 'onion': '\U0001f9c5', 'potato': '🥔', 'mango': '\U0001f96d', 'banana': '🍌', 'carrot': '🥕', 'hot_pepper': '🌶', 'pear': '🍐', 'ear_of_corn': '🌽', 'broccoli': '\U0001f966', 'leafy_green': '\U0001f96c', 'burrito': '🌯', 'eggplant': '🍆', 'grapes': '🍇', 'cucumber': '🥒', 'pineapple': '🍍', 'bread': '🍞', 'sunflower': '🌻', 'bouquet': '💐', 'coconut': '\U0001f965', 'melon': '🍈', 'green_salad': '🥗', 'jack-o-lantern': '🎃', 'watermelon': '🍉', 'baby': '👶'}
```

I generated `EMOJI_LOOKUP` using Python’s `emoji.emojize` module. Just `pip install emoji` locally to give it a try yourself. Here’s what I did:

```
import emoji

# exported from table in Anvil with Server function
alias_list = ['sparkles', 'sparkles', 'sparkles', 'sparkles', 'salt', 'cherries', 'strawberry', 'mushroom', 'chestnut', 'peanuts', 'kiwi', 'tangerine', 'peach', 'lemon', 'apple', 'avocado', 'onion', 'potato', 'mango', 'banana', 'carrot', 'hot_pepper', 'pear', 'ear_of_corn', 'broccoli', 'leafy_green', 'burrito', 'eggplant', 'grapes', 'cucumber', 'pineapple', 'bread', 'sunflower', 'bouquet', 'coconut', 'melon', 'green_salad', 'jack-o-lantern', 'watermelon', 'baby', 'baby']

if __name__ == " __main__":

    EMOJI_LOOKUP = {alias: emoji.emojize(":{}:".format(alias)) for alias in alias_list}

    print(EMOJI_LOOKUP)
```

I only needed to run it once. Then I popped `EMOJI_LOOKUP` into my app code. Notice that it doesn’t matter that some code points are represented long-form (like `'\U0001f9c2'`) because I didn’t have the full emoji supporting fonts available in my local terminal. The Python interpreter in Anvil knows how to deal with that format, too.

# Returning users 🤩

Using the [User Service](https://anvil.works/docs/users) I created a login flow for return users, so they can keep tracking their pregnancy throughout its duration without needing to redo their due date calculation each time they visit.

## Emails 📧

Users of the app can optionally sign up for weekly update emails. I did this by adding the [Email Service](/docs/email) and customised it with an unsubscribe option.

Each day, my app runs a [Scheduled Task](/docs/background-tasks/scheduled-tasks) to send an email to those users who signed up for emails and have reached their next gestation week that day. Users get dropped from the table and email list after 43 weeks (at which point the baby should hopefully have made an appearance!)

## Unsubscribing 🔔

For obvious reasons, I wanted to make it as easy as possible for users to unsubscribe from the weekly emails. They shouldn’t need to log in to the app to do it.

But I had to make sure that people could only unsubscribe themselves, not other users. If I just set up a generic “Unsubscribe” API, it would be too easy for someone to accidentally (or maliciously) remove other people from the mailing list.

The solution: generate a secret token for each user. If we get a request with the right token, it must be from that user, and we can unsubscribe them immediately. I used `token_urlsafe()` from [the secrets module](https://docs.python.org/3/library/secrets.html) to generate a unique token for each user that is safe to use as part of a URL.

When the app emails a user, the message contains an unsubscribe url customised with their secret token:

```
"To unsubscribe, click here: {app}/_/api/unsubscribe/{unsub}".format(app=anvil.server.get_app_origin(), unsub=user['unsubscribe_token'])
```

I set up a [custom HTTP API endpoint](/blog/http-api-endpoints) to handle clicks on those unsubscription links:

```
@anvil.server.http_endpoint("/unsubscribe/:id")
def unsubscribe_user(id):
  """
  Enable users to unsubscribe from email updates by clicking this API link.
  Check the id matches the unique unsubscribe token stored in the table against them 
  and if it does, remove that user's email subscription.
  """
  ip = anvil.server.request.remote_address
  user_to_unsubscribe = app_tables.users.search(unsubscribe_token=id)
  
  for user in user_to_unsubscribe:
    unsub_email = user['email']
    user.update(signed_up_for_emails=False)
    # Redirect user to app after unsubscribing them.
    redirect = anvil.server.HttpResponse(302, f"Unsubscribed user {unsub_email} from IP {ip}, now trying to redirect")
    redirect.headers['Location'] = "{}#unsubscribed".format(anvil.server.get_app_origin())
    return redirect

  return "Could not unsubscribe you - please check link is correct."
```

The corresponding code in the ` __init__ ` of the Form uses [`get_url_hash()`](https://anvil.works/docs/client/navigation#using-the-url-hash):

```
    # If user got here by clicking unsubscribe link in their email
    if get_url_hash() == "unsubscribed":
      alert("You have been unsubscribed from Fruitmoji emails.")
```

Users just click the link that appears in their email, leading them to a popup in the app which confirms they’ve been removed from the mailing list.

# Learn more 🍓

If you’re interested in discovering more about how the ‘Fruitmoji’ app works, take a look at the clone link below. It might be a helpful template for collecting a mailing list of your users with an unsubscribe mechanism:

[ Clone the finished app _<svg width="41" height="24" viewbox="0 0 180.7 81.4" xmlns="http://www.w3.org/2000/svg" version="1.1" preserveaspectratio="xMinYMin">
                <use xlink:href="#img-anvil-icon"></use>
            </svg>_](https://anvil.works/build#clone:2OFAQTEZR3JVKA42%3dDXAXNWONAZUQNBS6W5ASEOVG)

* * *

### Build your own app!

[Anvil](https://anvil.works/) is a platform for building full-stack web apps with nothing but Python. No need to wrestle with JS, HTML, CSS, Python, SQL and all their frameworks – just *build it all in Python* :heart: