Compare commits

...
10 Commits
20 changed files with 727 additions and 182 deletions
+48 -10
View File
@@ -1,13 +1,51 @@
__pycache__/
*.log
<<<<<<< Updated upstream
=======
*.env
>>>>>>> Stashed changes
.env
start.sh
update.sh
# OS
.DS_Store
Thumbs.db
Desktop.ini
# Editors / IDEs
.vscode/
.idea/
*.swp
*.swo
*~
# Logs
*.log
logs/
# Env / secrets
.env
.env.*
!.env.example
# Dependencies
node_modules/
vendor/
venv/
update.ps1
venv/pyvenv.cfg
venv/*
.venv/
__pycache__/
*.pyc
# Build output
dist/
build/
out/
*.egg-info/
target/
bin/
obj/
# Testing / coverage
coverage/
.nyc_output/
.pytest_cache/
# Misc
*.tmp
*.bak
*.old
.cache/
migration_status.flag
+152
View File
@@ -0,0 +1,152 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/migration
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# the special token `%(here)s` is available which indicates the absolute path
# to this configuration file.
#
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
# path_separator (New in Alembic 1.16.0, supersedes version_path_separator);
# This indicates what character is used to
# split lists of file paths, including version_locations and prepend_sys_path
# within configparser files such as alembic.ini.
#
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
# See notes in "escaping characters in ini files" for guidelines on
# passwords
sqlalchemy.url = driver://user:pass@localhost/dbname
# [post_write_hooks]
# This section defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner,
# against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
+1 -1
View File
@@ -1,7 +1,7 @@
from fastapi import APIRouter, HTTPException, Depends, Header
import logging
import db
import api_security as auth
import auth.api_security as auth
from pydantic import BaseModel
from api import tokens
+1 -1
View File
@@ -1,7 +1,7 @@
from fastapi import APIRouter, HTTPException, Depends, Header
import logging
import db
import api_security as auth
import auth.api_security as auth
from pydantic import BaseModel
+16 -34
View File
@@ -7,6 +7,7 @@ import logging
from argon2 import PasswordHasher
import random
import string
from models import Tokens
#Logging
@@ -23,17 +24,7 @@ try:
except Exception as e:
logging.exception('An error occurred')
load_dotenv()
db_name = os.getenv("DB_NAME")
db_psswd = os.getenv("DB_PASSWORD")
db_user = os.getenv("DB_USER")
db_port = os.getenv("DB_PORT") or "3306"
db_host = os.getenv("DB_HOST")
if db_host == None:
logging.error("no hostname provided")
os._exit(1)
db.connect(db_user, db_psswd, db_host, int(db_port), db_name)
session = db.session
def generate_token(duration):
@@ -43,11 +34,9 @@ def generate_token(duration):
hash = ph.hash(token)
end_date = enddate(duration)
time = datetime.now()
cursor = db.connection.cursor()
executed = "INSERT INTO tokens (tokens, time, end_date) VALUES (?, ?, ?)"
executed_data = (hash, time, end_date)
cursor.execute(executed, executed_data)
db.connection.commit()
new_item = Tokens(tokens=hash, time=time, end_date=end_date)
session.add(new_item)
session.commit()
logging.info(f"Token till {end_date} created")
return token
@@ -68,10 +57,8 @@ def enddate(duration):
def check_token(token):
ph = PasswordHasher()
cursor = db.connection.cursor()
valid = False
cursor.execute("SELECT tokens FROM tokens")
hashes = [row[0] for row in cursor.fetchall()]
hashes = [row[0] for row in session.query(Tokens.tokens).all()]
for hash in hashes:
try:
valid = ph.verify(hash, token)
@@ -80,16 +67,16 @@ def check_token(token):
except Exception as e:
logging.error("Token not the same")
logging.error(e)
return valid
def check_validaty():
cursor = db.connection.cursor()
cursor.execute("SELECT end_date FROM tokens")
end_dates = [row[0] for row in cursor.fetchall()]
end_dates = [row[0] for row in session.query(Tokens.end_date).all()]
for end_date in end_dates:
end_date_dt = datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")
if datetime.now() > end_date_dt:
cursor.execute("DELETE FROM tokens WHERE end_date = ?", (end_date,))
session.query(Tokens).filter_by(end_date=end_date).delete()
session.commit()
def admin_token():
@@ -98,11 +85,9 @@ def admin_token():
hash = ph.hash(token)
time = datetime.now()
end_date = enddate("forever")
cursor = db.connection.cursor()
executed = "INSERT INTO tokens (tokens, time, end_date) VALUES (?, ?, ?)"
executed_data = (hash, time, end_date)
cursor.execute(executed, executed_data)
db.connection.commit()
new_item = Tokens(tokens=hash, time=time, end_date=end_date)
session.add(new_item)
session.commit()
logging.info(f"Token till {end_date} created")
return token
@@ -112,8 +97,7 @@ def check_admin_token(token):
if len(token) == 64:
ph = PasswordHasher()
cursor = db.connection.cursor()
cursor.execute("SELECT tokens FROM tokens")
hashes = [row[0] for row in cursor.fetchall()]
hashes = [row[0] for row in session.query(Tokens.tokens).all()]
for hash in hashes:
try:
valid = ph.verify(hash, token)
@@ -126,14 +110,12 @@ def check_admin_token(token):
def delete_token(token):
if not len(token) == 64:
ph = PasswordHasher()
cursor = db.connection.cursor()
cursor.execute("SELECT tokens FROM tokens")
hashes = [row[0] for row in cursor.fetchall()]
hashes = [row[0] for row in session.query(Tokens.tokens).all()]
for hash in hashes:
try:
valid = ph.verify(hash, token)
if valid == True:
cursor.execute("DELETE FROM tokens WHERE tokens = ?", (hash,))
session.query(Tokens).filter_by(tokens=hash).delete()
db.connection.commit()
logging.critical("token deleted")
except Exception as e:
+65
View File
@@ -0,0 +1,65 @@
from argon2 import PasswordHasher
import db
from models import User
import logging
#Logging
logging.basicConfig(
filename='auth/user.log', # Log to a file
level=logging.DEBUG, # Log everything (DEBUG and above)
format='%(asctime)s %(levelname)s %(message)s'
)
logging.info('Application started')
try:
logging.debug('Debug info here')
except Exception as e:
logging.exception('An error occurred')
session = db.session
def create_user(username, password, role):
user = username
passwd = PasswordHasher().hash(password)
new_item = User(username=user, password=passwd, role=role)
def check_login(username, password):
result = session.query(User.password).filter_by(username=username).first()
hash_passwd = result[0] if result else None
valid = False
try:
valid = PasswordHasher().verify(hash_passwd, password)
if valid == True:
return valid
except Exception as e:
logging.error(e)
return False
def delete_user(username, password):
result = session.query(User.password).filter_by(username=username).first()
hash_password = result[0] if result else None
valid = False
try:
valid = PasswordHasher().verify(hash_password, password)
except Exception as e:
logging.error(e)
if valid == True:
try:
session.query(User).filter_by(username=username).delete()
session.commit()
logging.info(f"User {username} was successfully deleted")
except Exception as e:
logging.error(e)
def check_username(username):
try:
exists = session.query(User).filter_by(username=username).first() is not None
return exists # True if taken, False if available
except db.IntegrityError as e:
if e.errno == 1062:
logging.error("Username taken")
return True #If the username is not available it returns True
def get_role(username):
result = session.query(User.role).filter_by(username=username).first()
return result[0] if result else None
+4 -1
View File
@@ -3,6 +3,7 @@ import logging
import time
import os
import sys
from flags import status
print("loading")
@@ -177,7 +178,7 @@ def menu():
#The Terminal App Starts here
time.sleep(5)
time.sleep(2)
print(r"""
## ## ##########
### ### ## ##
@@ -186,6 +187,8 @@ print(r"""
## ## ## ## ##
## ## ## ##
""")
while not status.get_migration():
time.sleep(0.5)
logging.info("Menu is starting")
time.sleep(2.5)
menu()
+74 -98
View File
@@ -1,7 +1,10 @@
import mariadb
import logging
from dotenv import load_dotenv
import os
from models import Items
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from urllib.parse import quote_plus
#Logging
@@ -17,102 +20,6 @@ try:
except Exception as e:
logging.exception('An error occurred')
def connect(db_user, db_psswd, db_host, db_port, db_name):
try:
global connection
connection = mariadb.connect(user=db_user,
password=db_psswd,
host=db_host,
port=db_port,
database=db_name)
print("Connected to MariaDB successfully!")
logging.info("Connected to MariaDB successfully!")
except mariadb.Error as e:
print(f"Error connecting to DB: {e}")
logging.error("Error connecting")
logging.debug(f"Error connecting to DB: {e}")
def new_part(cloth_type, weight, pieces):
if type(pieces) is not int:
print("only ints allowed")
logging.error("only ints allowed")
else:
cursor = connection.cursor()
executed = "INSERT INTO luggage (clothes, weight, pieces) VALUES (?, ?, ?)"
executed_data = (cloth_type, weight, pieces)
cursor.execute(executed, executed_data)
connection.commit()
logging.info("new Insert is in DB")
def fetch_clothes():
cursor = connection.cursor()
cursor.execute("SELECT clothes FROM luggage")
clothes = [str(row[0]) for row in cursor.fetchall()]
logging.info("fetched clothes")
return clothes
def update_weight(cloth_type, weight):
cursor = connection.cursor()
executed = "UPDATE luggage SET weight = ? WHERE clothes = ?"
executed_data = (weight, cloth_type)
cursor.execute(executed, executed_data)
connection.commit()
logging.info("weight updated")
def update_pieces(cloth_type, pieces):
if type(pieces) is not int:
logging.error("only ints allowed")
else:
cursor = connection.cursor()
executed = "UPDATE luggage SET pieces = ? WHERE clothes = ?"
executed_data = (pieces, cloth_type)
cursor.execute(executed, executed_data)
connection.commit()
logging.info("pieces updated")
def fetch_weight(cloth_type):
cursor = connection.cursor()
cursor.execute("SELECT weight FROM luggage WHERE clothes = ?", (cloth_type,))
weight = cursor.fetchone()[0]
logging.info("fetched weight")
return weight
def fetch_luggage_weight():
cursor = connection.cursor()
cursor.execute("SELECT sum(weight) FROM luggage")
weight = cursor.fetchone()[0]
logging.info("fetched luggage weight")
return weight
def fetch_piece(cloth_type):
cursor = connection.cursor()
cursor.execute("SELECT pieces FROM luggage WHERE clothes = ?", (cloth_type,))
pieces = cursor.fetchone()[0]
logging.info("fetched luggage pieces")
return pieces
def fetch_all_pieces():
cursor = connection.cursor()
cursor.execute("SELECT sum(pieces) FROM luggage")
pieces = cursor.fetchone()[0]
logging.info("fetched all luggage pieces")
return pieces
def delete(cloth_type):
cursor = connection.cursor()
cursor.execute("DELETE FROM luggage WHERE clothes = ?;", (cloth_type,))
logging.critical(f"{cloth_type} was deleted")
connection.commit()
def check_clothe(clothe_type):
cursor = connection.cursor()
cursor.execute("SELECT (SELECT clothes FROM luggage WHERE clothes = ? LIMIT 1) AS clothes", (clothe_type,))
check = cursor.fetchone()[0]
return check
#using .env
load_dotenv()
db_name = os.getenv("DB_NAME")
@@ -123,4 +30,73 @@ db_host = os.getenv("DB_HOST")
if db_host == None:
logging.error("no hostname provided")
os._exit(1)
connect(db_user, db_psswd, db_host, int(db_port), db_name)
engine = create_engine(f"mariadb+mariadbconnector://{db_user}:{quote_plus(db_psswd)}@{db_host}:{db_port}/{db_name}")
Session = sessionmaker(bind=engine)
session = Session()
def new_part(cloth_type, weight, pieces):
existing = session.query(Items).filter_by(clothes=cloth_type).first()
if existing:
logging.debug("Item already inserted")
else:
if type(pieces) is not int:
print("only ints allowed")
logging.error("only ints allowed")
else:
new_item = Items(clothes=cloth_type, weight=weight, pieces=pieces)
session.add(new_item)
session.commit()
logging.info("new Insert is in DB")
def update_weight(cloth_type, weight):
item = session.query(Items).filter_by(clothes=cloth_type).first()
item.weight = weight
session.commit()
logging.info("weight updated")
def update_pieces(cloth_type, pieces):
if type(pieces) is not int:
logging.error("only ints allowed")
else:
item = session.query(Items).filter_by(clothes=cloth_type).first()
item.pieces = pieces
session.commit()
logging.info("pieces updated")
def delete(cloth_type):
logging.critical(f"{cloth_type} was deleted")
session.query(Items).filter_by(clothes=cloth_type).delete()
session.commit()
def fetch_clothes():
logging.info("fetched clothes")
return [row[0] for row in session.query(Items.clothes).all()]
def fetch_weight(cloth_type):
logging.info("fetched weight")
result = session.query(Items.weight).filter_by(clothes=cloth_type).first()
return result[0] if result else None
def fetch_luggage_weight():
logging.info("fetched whole weight")
result = session.query(func.sum(Items.weight)).scalar()
return result if result else None
def fetch_piece(cloth_type):
logging.info("fetched pieces")
result = session.query(Items.pieces).filter_by(clothes=cloth_type).first()
return result[0] if result else None
def fetch_all_pieces():
logging.info("fetched all pieces")
result = session.query(Items.pieces).all()
return [row[0] for row in session.query(Items.pieces).all()]
#Checks if clothe is in db
def check_clothe(clothe_type):
exists = session.query(Items.clothes).filter_by(clothes=clothe_type).first() is not None
return exists
View File
+50
View File
@@ -0,0 +1,50 @@
import threading
from watchdog.events import PatternMatchingEventHandler
from watchdog.observers import Observer
import os
import time
FLAGS_DIR = os.path.dirname(os.path.abspath(__file__))
class FlagHandler(PatternMatchingEventHandler):
def __init__(self, shared_state, lock):
super().__init__(patterns=["*.flag"], ignore_directories=True)
self.shared_state = shared_state
self.lock = lock
def on_created(self, event):
try:
with open(event.src_path, "r") as f:
content = f.read().strip()
except FileNotFoundError:
return
try:
os.remove(event.src_path)
except FileNotFoundError:
pass
with self.lock:
self.shared_state["current"] = content
time.sleep(2)
shared_state = {"current": None}
lock = threading.Lock()
observer = Observer()
observer.schedule(FlagHandler(shared_state, lock), path=FLAGS_DIR, recursive=False)
observer.start()
def get_status():
with lock:
current = shared_state["current"]
if current == "db_check_done":
return False
return current
def get_migration():
with lock:
current = shared_state["current"]
if current == "migration_done":
return True
return False
+42 -4
View File
@@ -2,8 +2,10 @@ import logging
import subprocess
import sys
import os
import api_security as auth
import auth.api_security as auth
import time
import threading
from tests import db_test
try:
os.remove("api.log")
@@ -28,17 +30,53 @@ except Exception as e:
env = os.environ.copy()
env["PYTHONIOENCODING"] = "utf-8"
try:
os.remove("migration_status.flag")
except Exception as e:
logging.info(e)
#migration
def run_migration():
global migration_done
process = subprocess.Popen(
["python", "migration/alembic_scipt.py"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
process.wait()
migration_done = (process.returncode == 0)
with open("flags/migration_status.flag", "w") as f:
f.write("migration_done" if migration_done else "failed")
#DB test
def run_db_test():
tokens = db_test.test_table("tokens", ["tokens", "time", "end_date"])
user = db_test.test_table("user", ["username", "password", "role"])
items = db_test.test_table("luggage", ["clothes", "weight", "pieces"])
time.sleep(5)
if tokens == True & user == True & items == True:
with open("flags/db.flag", "w") as f:
f.write("db_check_done")
else:
os._exit(1)
#cli and api
log_file = open("api_server.log", "w", encoding="utf-8")
api_process = subprocess.Popen(
["fastapi", "dev", "api_server.py"],
["fastapi", "dev", "api_server.py", "--reload-dir", "web", "--reload-dir", "api", "--reload-dir", "api_server.py",],
stdout=log_file,
stderr=log_file,
env=env
)
cli_process = subprocess.Popen([sys.executable, "cli.py"])
api_process.wait()
cli_process.wait()
db_thread = threading.Thread(target=run_db_test)
db_thread.start()
thread = threading.Thread(target=run_migration)
thread.start()
threading.Thread(target=api_process.wait, daemon=True).start()
threading.Thread(target=cli_process.wait, daemon=True).start()
# automatic durataion validation check
while True:
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration.
+67
View File
@@ -0,0 +1,67 @@
import os
from alembic.config import Config
from alembic.script import ScriptDirectory
from alembic.runtime.migration import MigrationContext
from alembic import command
from sqlalchemy import create_engine
from alembic import command
from dotenv import load_dotenv
import logging
#Logging
logging.basicConfig(
filename='app.log', # Log to a file
level=logging.DEBUG, # Log everything (DEBUG and above)
format='%(asctime)s %(levelname)s %(message)s'
)
logging.info('Application started')
try:
logging.debug('Debug info here')
except Exception as e:
logging.exception('An error occurred')
load_dotenv()
db_name = os.getenv("DB_NAME")
db_psswd = os.getenv("DB_PASSWORD")
db_user = os.getenv("DB_USER")
db_port = os.getenv("DB_PORT") or "3306"
db_host = os.getenv("DB_HOST")
if db_host == None:
os._exit(1)
engine_url = f"mariadb+mariadbconnector://{db_user}:{db_psswd}@{db_host}:{db_port}/{db_name}"
base_dir = os.path.dirname(__file__)
ini_path = os.path.join(base_dir, "..", "alembic.ini")
alembic_cfg = Config(ini_path)
alembic_cfg.set_section_option(alembic_cfg.config_ini_section, "sqlalchemy.url", engine_url)
script = ScriptDirectory.from_config(alembic_cfg)
engine = create_engine(engine_url)
def check_db():
with engine.connect() as conn:
context = MigrationContext.configure(conn)
current_rev = context.get_current_revision()
head_rev = script.get_current_head()
if current_rev != head_rev:
command.upgrade(alembic_cfg, "head")
return False
def auto_lookup():
command.revision(alembic_cfg, message="add tables and rows", autogenerate=True)
script = ScriptDirectory.from_config(alembic_cfg)
head_rev = script.get_revision(script.get_current_head())
with open(head_rev.path) as f:
content = f.read()
if "pass\n # ### end Alembic commands ###" in content:
os.remove(head_rev.path)
command.stamp(alembic_cfg, "head")
logging.info("No changes DB detected")
else:
command.upgrade(alembic_cfg, "head")
logging.info("New DB changes, upgrade table")
auto_lookup()
+84
View File
@@ -0,0 +1,84 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from models import Base
metadata = Base.metadata
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
if config.config_file_name is not None:
fileConfig(config.config_file_name)
+28
View File
@@ -0,0 +1,28 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
+1
View File
@@ -0,0 +1 @@
from .models import Items, Tokens, User, Base
+23
View File
@@ -0,0 +1,23 @@
from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, String, Numeric, Integer
Base = declarative_base()
class Tokens(Base):
__tablename__ = "tokens"
tokens = Column(String(255), primary_key=True)
time = Column(String(255))
end_date = Column(String(255))
class Items(Base):
__tablename__ = "luggage"
clothes = Column(String(50), primary_key=True)
weight = Column(Numeric(20, 2))
pieces = Column(Integer)
class User(Base):
__tablename__ = "user"
username = Column(String(50), primary_key=True)
password = Column(String(255))
role = Column(String(50))
+7 -1
View File
@@ -1,4 +1,10 @@
mariadb == 1.1.14
python-dotenv == 1.2.3
fastapi[standard] == 0.141.1
argon2-cffi == 25.1.0
Jinja2==3.1.6
MarkupSafe==3.0.3
itsdangerous==2.2.0
alembic==1.20.0
SQLAlchemy==2.0.54
watchdog==6.0.0
#watchfiles==1.2.0
+16 -31
View File
@@ -1,8 +1,8 @@
from dotenv import load_dotenv
import db
import os
from migration.alembic_scipt import auto_lookup
import time
import logging
import api_security as auth
import auth.api_security as auth
import os
#Logging
@@ -18,34 +18,19 @@ try:
except Exception as e:
logging.exception('An error occurred')
load_dotenv()
db_name = os.getenv("DB_NAME")
db_psswd = os.getenv("DB_PASSWORD")
db_user = os.getenv("DB_USER")
db_port = os.getenv("DB_PORT") or "3306"
db_host = os.getenv("DB_HOST")
if db_host == None:
logging.error("no hostname provided")
def new_table():
auto_lookup()
def admin():
token = auth.admin_token()
print(token)
logging.info(token)
time.sleep(300)
os.remove("app.log")
os._exit(1)
db.connect(db_user, db_psswd, db_host, int(db_port), db_name)
def new_table(name):
cursor = db.connection.cursor()
if name == "tokens":
executed = "CREATE TABLE tokens (tokens VARCHAR(255) PRIMARY KEY, `time` VARCHAR(255), end_date VARCHAR(255))"
cursor.execute(executed)
db.connection.commit()
logging.info("Table 'tokens' created")
if name == "luggage":
executed = "CREATE TABLE luggage (clothes VARCHAR(50) PRIMARY KEY, weight DECIMAL(20,2), pieces INT(11))"
cursor.execute(executed)
db.connection.commit()
logging.info("Table 'luggage' created")
new_table("tokens")
new_table("luggage")
print(auth.admin_token())
new_table()
admin()
+46
View File
@@ -0,0 +1,46 @@
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
import os
import db
import logging
import sys
from migration import alembic_scipt as alembic
from sqlalchemy import inspect
session = db.session
engine = db.engine
def test_column(engine, tablename, row):
try:
inspector = inspect(engine)
columns = [col["name"] for col in inspector.get_columns(tablename)]
return row in columns
except Exception as e:
logging.error(e)
def test_table(table, columns):
for column in columns:
try:
exists = test_column(engine, table, column)
if exists == False:
logging.error(f"DB has not all columns. {column} is missing")
print(f"Column {column} is missing")
sys.exit()
os._exit(1)
return False
else:
logging.info("Column fine")
except Exception as e:
logging.error(e)
return True
def migration_check():
if alembic.check_db() == False:
print("migrating")
logging.info("DB is migrating")