Implement Algolia Search

What I’m trying to do:
Hello Community! I’m trying to implement AlgoliaSearch in my application

What I’ve tried and what’s not working:
I’ve tried a few variations of this:

from ._anvil_designer import Form1Template
from anvil import *

from anvil.js import import_from

AlgoliaSearchModule = import_from("https://cdn.jsdelivr.net/npm/algoliasearch/dist/algoliasearch.umd.min.js")
algolisearch = AlgoliaSearchModule.algoliasearch

I’ve tried to mimic the documentation:

import anvil.js
uuid_module = anvil.js.import_from('https://jspm.dev/uuid')
uuid4 = uuid_module.v4

I keep getting a variation of the following error:

AttributeError: 'Module' object has no attribute 'algoliasearch'

  • at Form1, line 7

Hoping someone else has successfully implemented this library!

Thanks!

Without looking into the details, my guess is that, because you’re using umd it will attach the global to the window object.

But you can also print the return value from your import_from line to see what you’re getting.

Typically a umd file would be put in native libraries and then you would use a window import in JavaScript.

from anvil.js.window import algoliasearch

If I wanted to use a module approach I would look at getting the JavaScript url from jspm.io or esm.sh. This would be my preference.

If those pointers don’t help I can take a look at it. But not at a computer right now.

2 Likes

Thanks for educating me! I had to have a bit of a conversation with gpt to fully grasp everything.

For completeness,

I installed jspm to my local device. With this I could then create the javascript url that could be used in my module with the import_from method, this was in the importmap.json file created by jspm. I then used the print(dir(<imported module><imported_module>)) to find the callable function I wanted.

In the end the form looked like this

from ._anvil_designer import Form1_copyTemplate
from anvil import *

import anvil.js

AlgoliaSearch = anvil.js.import_from("https://ga.jspm.io/npm:algoliasearch@5.0.0/dist/algoliasearch.esm.browser.js")

print(dir(AlgoliaSearch))


class Form1_copy(Form1_copyTemplate):
  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)

    # Any code you write here will run before the form opens.
    self.client = AlgoliaSearch.algoliasearch(<YourKeysHere>,<YourKeysHERE>)
    print(dir(self.client))


  def text_box_search_pressed_enter(self, **event_args):
    """This method is called when the user presses Enter in this text box"""
    hits = self.client.searchSingleIndex(
        {
          'indexName':"Locations",
          "searchParams":{'query': self.text_box_search.text}
        }
      )
    print(hits)

I think I prefer this method as well. Keeps every library in the file its being used, along with other benefits I’m not knowledgeable enough to speak on.

Thank you!

1 Like