🎉 First commit, from couchbase generator, basic changes

not tested / updated yet
This commit is contained in:
Sebastián Ramírez
2019-02-09 19:42:36 +04:00
commit 7f8bfc8faa
198 changed files with 21022 additions and 0 deletions
@@ -0,0 +1,5 @@
# Import all the models, so that Base has them before being
# imported by Alembic
from app.db.base_class import Base # noqa
from app.models.role import Role # noqa
from app.models.user import User # noqa
@@ -0,0 +1,11 @@
from sqlalchemy.ext.declarative import declarative_base, declared_attr
class CustomBase(object):
# Generate __tablename__ automatically
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
Base = declarative_base(cls=CustomBase)
@@ -0,0 +1,8 @@
from app.core import config
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine(config.SQLALCHEMY_DATABASE_URI, convert_unicode=True)
db_session = scoped_session(
sessionmaker(autocommit=False, autoflush=False, bind=engine)
)
@@ -0,0 +1,106 @@
import json
from pathlib import Path, PurePath
from typing import Any, Dict
import requests
from requests.auth import HTTPBasicAuth
from app.core.config import (
COUCHBASE_FULL_TEXT_INDEX_DEFINITIONS_DIR,
COUCHBASE_PASSWORD,
COUCHBASE_USER,
)
def get_index(
index_name: str,
*,
username: str = COUCHBASE_USER,
password: str = COUCHBASE_PASSWORD,
host="couchbase",
port="8094",
):
full_text_url = f"http://{host}:{port}"
index_url = f"{full_text_url}/api/index/{index_name}"
auth = HTTPBasicAuth(username, password)
response = requests.get(index_url, auth=auth)
if response.status_code == 400:
content = response.json()
error = content.get("error")
if error == "rest_auth: preparePerms, err: index not found":
return None
raise ValueError(error)
elif response.status_code == 200:
content = response.json()
assert (
content.get("status") == "ok"
), "Expected a status OK communicating with Full Text Search"
index_def = content.get("indexDef")
return index_def
raise ValueError(response.text)
def create_index(
index_definition: Dict[str, Any],
*,
reset_uuids=True,
username: str = COUCHBASE_USER,
password: str = COUCHBASE_PASSWORD,
host="couchbase",
port="8094",
):
index_name = index_definition.get("name")
assert index_name, "An index name is required as key in an index definition"
if reset_uuids:
index_definition.update({"uuid": "", "sourceUUID": ""})
full_text_url = f"http://{host}:{port}"
index_url = f"{full_text_url}/api/index/{index_name}"
auth = HTTPBasicAuth(username, password)
response = requests.put(index_url, auth=auth, json=index_definition)
content = response.json()
if response.status_code == 400:
error = content.get("error")
if (
"cannot create index because an index with the same name already exists:"
in error
):
raise ValueError(error)
else:
raise ValueError(error)
elif response.status_code == 200:
assert (
content.get("status") == "ok"
), "Expected a status OK communicating with Full Text Search"
return True
raise ValueError(response.text)
def ensure_create_full_text_indexes(
index_dir=COUCHBASE_FULL_TEXT_INDEX_DEFINITIONS_DIR,
username: str = COUCHBASE_USER,
password: str = COUCHBASE_PASSWORD,
host="couchbase",
port="8094",
):
file_path: PurePath
for file_path in Path(index_dir).iterdir():
if file_path.name.endswith(".json"):
with open(file_path) as f:
index_definition = json.load(f)
name = index_definition.get("name")
assert name, "A full text search index definition must have a name field"
current_index = get_index(
index_name=name,
username=username,
password=password,
host=host,
port=port,
)
if not current_index:
assert create_index(
index_definition=index_definition,
username=username,
password=password,
host=host,
port=port,
), "Full Text Search index could not be created"
@@ -0,0 +1,29 @@
from app.core import config
from app.db.utils import (
assign_role_to_user,
create_role,
create_user,
get_role_by_name,
get_user_by_username,
)
def init_db(db_session):
# Tables should be created with Alembic migrations
# But if you don't want to use migrations, create
# the tables uncommenting the next line
# Base.metadata.create_all(bind=engine)
role = get_role_by_name("default", db_session)
if not role:
role = create_role("default", db_session)
user = get_user_by_username(config.FIRST_SUPERUSER, db_session)
if not user:
user = create_user(
db_session,
config.FIRST_SUPERUSER,
config.FIRST_SUPERUSER_PASSWORD,
is_superuser=True,
)
assign_role_to_user(role, user, db_session)