Example #1
0
    def get_collection(cls):
        """
        Get collection (create one if it doesn't exist yet).
        :return: collection reference object
        """
        collection = None

        if server_env == "localhost":
            # datetime serializer for TinyDB. Make sure to add tinydb-serialization in requirements.txt
            from datetime import datetime
            from tinydb_serialization import Serializer, SerializationMiddleware

            class DateTimeSerializer(Serializer):
                OBJ_CLASS = datetime  # The class this serializer handles

                def encode(self, obj):
                    return obj.strftime('%Y-%m-%dT%H:%M:%S')

                def decode(self, s):
                    return datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')

            serialization = SerializationMiddleware()
            serialization.register_serializer(DateTimeSerializer(), 'TinyDate')

            tiny_db_name = 'db.json'
            if os.getenv("TESTING"):
                tiny_db_name = 'test_db.json'

            db = TinyDB(tiny_db_name, storage=serialization)
            collection = db.table(cls.__name__)
        elif server_env == "gae":
            if gae_database == "datastore":
                db = datastore.Client()
                return db  # no collections in the Datastore
            else:
                db = firestore.client()
                collection = db.collection(cls.__name__)
        elif server_env == "azure":
            db = client["my-database"]
            # these two env vars should be created automatically when you launch Cosmos DB (with MongoDB API) on Azure
            # if not, add them manually
            db.authenticate(name=os.getenv("APPSETTING_MONGO_USERNAME"),
                            password=os.getenv("APPSETTING_MONGO_PASSWORD"))
            collection = db[cls.__name__]
        elif server_env == "heroku":
            db_name = os.getenv("MONGODB_URI").split(":")[1].replace(
                "//", "")  # get the username out, which is also the db name
            db = client[db_name]
            collection = db[cls.__name__]

        return collection