browsertrix/backend/db.py
Ilya Kreymer d05f04be9f
Crawl Config Editing Support (#141)
* support inactive configs in same collection, configs with `inactive` set to true (#137)
- add `inactive`, `newId`, `oldId` to crawlconfigs
- filter out inactive configs by default for most operations
- add index for aid + inactive field for faster querying
- delete returns status: 'deactivated' or 'deleted'
- if no crawls ran, config can be deleted, otherwise it is deactivated

* update crawl endpoint: add general PATCH crawl config endpoint, support updating schedule and name
2022-02-17 16:04:07 -08:00

60 lines
1.4 KiB
Python

"""
Browsertrix API Mongo DB initialization
"""
import os
from typing import Optional
import motor.motor_asyncio
from pydantic import BaseModel, UUID4
DATABASE_URL = (
f"mongodb://root:example@{os.environ.get('MONGO_HOST', 'localhost')}:27017"
)
# ============================================================================
def init_db():
"""initializde the mongodb connector"""
client = motor.motor_asyncio.AsyncIOMotorClient(
DATABASE_URL, uuidRepresentation="standard"
)
mdb = client["browsertrixcloud"]
return client, mdb
# ============================================================================
class BaseMongoModel(BaseModel):
"""Base pydantic model that is also a mongo doc"""
id: Optional[UUID4]
@property
def id_str(self):
""" Return id as str """
return str(self.id)
@classmethod
def from_dict(cls, data):
"""convert dict from mongo to an Archive"""
if not data:
return None
data["id"] = data.pop("_id")
return cls(**data)
def serialize(self, **opts):
"""convert Archive to dict"""
return self.dict(
exclude_unset=True, exclude_defaults=True, exclude_none=True, **opts
)
def to_dict(self, **opts):
"""convert to dict for mongo"""
res = self.dict(**opts)
res["_id"] = res.pop("id", "")
return res