90 lines
2.5 KiB
Python
90 lines
2.5 KiB
Python
|
|
import ast
|
||
|
|
import csv
|
||
|
|
import json
|
||
|
|
import logging
|
||
|
|
|
||
|
|
from playhouse.sqlite_ext import JSONField
|
||
|
|
|
||
|
|
from .models import Archive, Autotests, Log, Recipes, Session, Users, db
|
||
|
|
|
||
|
|
models_reference = {
|
||
|
|
"archive": Archive,
|
||
|
|
"autotests": Autotests,
|
||
|
|
"log": Log,
|
||
|
|
"recipes": Recipes,
|
||
|
|
"users": Users,
|
||
|
|
}
|
||
|
|
|
||
|
|
db.connect()
|
||
|
|
db.create_tables(list(models_reference.values()))
|
||
|
|
|
||
|
|
log = logging.getLogger("db")
|
||
|
|
|
||
|
|
|
||
|
|
def init_db():
|
||
|
|
tables = db.get_tables()
|
||
|
|
tables.sort()
|
||
|
|
for table in tables:
|
||
|
|
count = 0
|
||
|
|
try:
|
||
|
|
with open("src/lib/db/imports/{}.csv".format(table), "r") as f:
|
||
|
|
table = models_reference[table]
|
||
|
|
fields = list(table._meta.fields)
|
||
|
|
log.info(f"importing {table._meta.table_name}")
|
||
|
|
reader = csv.DictReader(f)
|
||
|
|
for row in reader:
|
||
|
|
obj = {}
|
||
|
|
for field in fields:
|
||
|
|
if type(table._meta.fields[field]) is JSONField:
|
||
|
|
obj[field] = json.loads(row[field])
|
||
|
|
else:
|
||
|
|
try:
|
||
|
|
obj[field] = ast.literal_eval(row[field])
|
||
|
|
except (SyntaxError, ValueError):
|
||
|
|
obj[field] = row[field]
|
||
|
|
table.insert(**obj).on_conflict_replace().execute()
|
||
|
|
count += 1
|
||
|
|
log.info(f"{table._meta.table_name}: imported {count} rows.")
|
||
|
|
except FileNotFoundError:
|
||
|
|
pass
|
||
|
|
|
||
|
|
|
||
|
|
init_db()
|
||
|
|
|
||
|
|
|
||
|
|
# register or reset admin
|
||
|
|
admin = Users.get_user("ADMIN")
|
||
|
|
if admin is None or not admin.is_admin:
|
||
|
|
Users.register(username="ADMIN", password="123123", roles=["admin"])
|
||
|
|
# register or reset user
|
||
|
|
Users.register(username="USER", password="user")
|
||
|
|
# register test recipe
|
||
|
|
Recipes.replace(id=0, name="TEST", spec={
|
||
|
|
# recipe
|
||
|
|
"client": "TEST_CLIENT",
|
||
|
|
"part_number": "TEST_PART_NUMBER",
|
||
|
|
"station": "TEST_STATION",
|
||
|
|
# pressure
|
||
|
|
"pressure_min": 0,
|
||
|
|
"pressure_test": 1,
|
||
|
|
"pressure_max": 2,
|
||
|
|
"pressure_ramp": 3,
|
||
|
|
# test
|
||
|
|
"cleaning_time": 4,
|
||
|
|
"tolerance": 5,
|
||
|
|
"test_duration": 6,
|
||
|
|
"flush_duration": 7,
|
||
|
|
# stabilizarion
|
||
|
|
"stabilization_time": 8,
|
||
|
|
"stabilization_level_min": 9,
|
||
|
|
"stabilization_level_max": 10,
|
||
|
|
"stabilization_settling_time": 11,
|
||
|
|
"stabilization_cycles": 12,
|
||
|
|
# description
|
||
|
|
"description": "TEST_DESCRIPTION",
|
||
|
|
}, archived=False).execute()
|
||
|
|
|
||
|
|
if True:
|
||
|
|
# crud_db must be imported after db and models_reference are available
|
||
|
|
from .crud_db import Crud_DB
|