Day 14 of the Anvil Advent Calendar

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

Making a list and checking it twice…offline!

Did you know that Anvil apps are progressive web apps? This means they can be installed to your mobile phone and work offline. Today’s app is a shopping list that you can install to your phone and update while offline!

https://offline-shopping-list.anvil.app/

Adding to the list

Adding to the shopping list is done through an alert where the user can add what they need to buy and choose a category for the item.

Adding an item to the list updates the list_item dictionary then displays the items in a RepeatingPanel:

if alert(AddAlert(item=list_item), buttons=[('Add', True), ('Cancel', False)], large=True, title="Add to the Shopping List"):
    if not list_item.get('text'):
        # ignore empty entries
        return         
    self.todo_panel.items = self.todo_panel.items + [{'text': list_item['text'], 'category': list_item['category'], 'complete': False}]

If the user is online, the dictionary is added to a DataTable:

@anvil.server.callable
def save(todos):
    row = get_row()
    row['todos'] = todos
    row['last_updated'] = datetime.now()

Working offline

If the user is offline, the dictionary is stored in the browser’s localStorage object. localStorage is a dictionary-like javascript object that persists between browser sessions and works offline. It can be used to store JSON data and can be accessed using anvil.js.

def call_or_queue_save(to_save):
    """save todos in the server or store in local_storage['unsaved']"""
    try:
        anvil.server.call_s('save', to_save)
    except anvil.server.AppOfflineError:
        print('app is offline - storing unsaved changes')
        local_storage['unsaved'] = {"when": datetime.now().astimezone().isoformat(), "to_save": to_save}
    finally:
        local_storage['todos'] = to_save

Check out the source code in more detail by cloning app:


Give the Gift of Python

Share this post: