Skip to content

Instantly share code, notes, and snippets.

@paul121
Last active May 5, 2020 02:32
Show Gist options
  • Save paul121/05cace7f09e13e7d2185897c226ecef7 to your computer and use it in GitHub Desktop.
Save paul121/05cace7f09e13e7d2185897c226ecef7 to your computer and use it in GitHub Desktop.
farmOS client caching

Just realized I'm doing something similar for the CSV Importer. I found myself querying for a taxonomy term by the term'sname multiple times. This required me to also look up the taxonomy_vocabulary vid multiple times... but rather than querying the farmOS server for the taxonomy vid each time, I maintain a copy of the resources from /farm.json. This makes it easy to get a taxonomy vocabulary vid from the vocabularyname without a request to the server.

With the vid, I then make a request for any term that matches the vocabulary name and term name.

Some preliminary helper code that handles getting a taxonomy term from a name specified in a CSV file:

    def _get_farmos_taxonomy_term(self, name, taxonomy_name, create=False):
        taxonomy_vid = self.farm_client_info.get('resources').get('taxonomy_term').get(taxonomy_name).get('vid')
        taxonomy_vid = int(taxonomy_vid)

        terms = self.farm_client.term.get(filters={'vocabulary': taxonomy_vid, 'name': name})['list']
        if len(terms) > 0:
            return terms[0]

        if create:
            return self._create_farmos_taxonomy_term(name=name, taxonomy_name=taxonomy_name)

        return None

    def _get_farmos_material(self, material_name, create=False):
        return self._get_farmos_taxonomy_term(name=material_name, taxonomy_name='farm_materials', create=create)

    def _get_farmos_unit(self, unit_name, create=False):
        return self._get_farmos_taxonomy_term(name=unit_name, taxonomy_name='farm_quantity_units', create=create)

    def _get_farmos_log_category(self, category_name, create=False):
        return self._get_farmos_taxonomy_term(name=category_name, taxonomy_name='farm_log_categories', create=create)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment