Skip to content
Snippets Groups Projects
Unverified Commit 77ebd6d5 authored by Sandro Lutz's avatar Sandro Lutz
Browse files

Initial commit

parents
No related branches found
No related tags found
No related merge requests found
.cache/
.data/
__pycache__/
.gitlab-ci.yml
.gitignore
Dockerfile.development
Dockerfile
README.md
.data/
.cache/
instance/
__pycache__/
.ash_history
FROM python:3.7-alpine
# Create user with home directory and no password and change workdir
RUN adduser -Dh /bastlibouncer bastlibouncer
WORKDIR /bastlibouncer
# Webinterface will run on port 8080
EXPOSE 8080
# Install bjoern and dependencies for install (we need to keep libev)
RUN apk add --no-cache --virtual .deps \
musl-dev python-dev gcc git && \
apk add --no-cache libev-dev && \
apk add --no-cache libffi-dev libressl-dev && \
pip install bjoern
# Copy files to /bastlibouncer directory, install requirements
COPY ./ /bastlibouncer
RUN pip install -r /bastlibouncer/requirements.txt
# Cleanup dependencies
RUN apk del .deps
# Update permissions for entrypoint
RUN chmod 755 entrypoint.sh
# Switch user
USER bastlibouncer
# Start application
CMD [ "./entrypoint.sh" ]
FROM python:3.7-alpine
# Create user with home directory and no password and change workdir
RUN adduser -Dh /bastlibouncer bastlibouncer
WORKDIR /bastlibouncer
# Webinterface will run on port 8080
EXPOSE 5000
# Copy files to /bastlibouncer directory, install requirements
COPY . /bastlibouncer
RUN pip install pip-tools && \
pip install -r /bastlibouncer/requirements.txt
# Switch user
USER bastlibouncer
ENV FLASK_DEBUG=1 \
FLASK_CONFIG="development" \
FLASK_APP="run_dev.py"
# Start application
CMD [ "flask run" ]
# Bastli Bouncer
This is an attendance manager/tracker to ensure COVID-19 restrictions.
## Development
Use the script `manage.sh` for local development.
```shell
$ ./manage.sh help
Managment Script Usage:
manage.sh [COMMAND]
COMMAND:
build Build docker image for local development.
db [start|restart|stop] Start/stop local database.
makemigrations Create new migration files.
migrate Apply migrations to local database.
update_dependencies Update dependencies based in requirements.in.
```
Build local development image with:
```shell
./manage.sh build
```
Run development server with:
```shell
docker run --rm -it --name bastlibouncer \
-p 5000:5000 \
-v ${PWD}:/bastlibouncer \
-v ${PWD}/instance/config.dev.py:/bastlibouncer/instance/config.py \
bastlibouncer-dev
```
## Upgrade dependencies
Run the command:
```shell
docker run -it \
-v ${PWD}:/bastlibouncer \
-v ${PWD}/instance/config.dev.py:/bastlibouncer/instance/config.py \
bastlibouncer-dev \
pip-compile --output-file requirements.txt requirements.in
```
## How to handle database changes
TODO
\ No newline at end of file
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
# db variable initialization
db = SQLAlchemy()
# initialize flask app and configure
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile('config.py')
# initialize ORM
db.init_app(app)
# add database migration from flask-migrate
Migrate(app, db)
@app.route('/')
def hello_world():
return 'Hello, World!'
version: "3"
services:
db:
image: mariadb:10.5
restart: always
ports:
- 3306:3306
environment:
- MYSQL_DATABASE=bastlibouncer
- MYSQL_USER=bastlibouncer
- MYSQL_PASSWORD=bastlibouncer
- MYSQL_RANDOM_ROOT_PASSWORD=yes
volumes:
- ./.data/:/var/lib/mysql
#!/bin/sh
export FLASK_APP="run_dev.py"
while true; do
flask db upgrade
if [[ "$?" == "0" ]]; then
break
fi
echo "Upgrade command failed, retrying in 5 seconds..."
sleep 5
done
unset FLASK_APP
python3 run_prod.py
# Local Development Configuration File
DEBUG = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://bastlibouncer:bastlibouncer@db/bastlibouncer'
SECRET_KEY = 'f08d502a04cfc9d945184f12f577f3ad'
# Example Configuration File
DEBUG = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://<username>:<password>@<host>/<db-name>'
SECRET_KEY = 'replace me (24 random bytes)'
#!/bin/bash
if [[ $EUID -eq 0 || $(groups | grep "\bdocker\b") ]]; then
SUDO_COMMAND=""
else
SUDO_COMMAND="sudo"
fi
BASE_DOCKER_RUN_COMMAND="${SUDO_COMMAND} docker run -it \
-p 5000:5000 \
-v ${PWD}:/bastlibouncer \
-v ${PWD}/instance/config.dev.py:/bastlibouncer/instance/config.py \
bastlibouncer-dev"
case $1 in
build)
$SUDO_COMMAND docker build -t bastlibouncer-dev -f Dockerfile.development .
;;
run)
$BASE_DOCKER_RUN_COMMAND flask run --host=0.0.0.0
;;
db)
case $2 in
start)
$SUDO_COMMAND docker-compose up -d
;;
restart)
$SUDO_COMMAND docker-compose restart db
;;
stop)
$SUDO_COMMAND docker-compose stop
;;
*)
echo "Unknown sub-command for command \"db\"."
exit 1
;;
esac
;;
makemigrations)
$BASE_DOCKER_RUN_COMMAND flask db migrate
;;
migrate)
$BASE_DOCKER_RUN_COMMAND flask db upgrade
;;
update_dependencies)
$BASE_DOCKER_RUN_COMMAND pip-compile --output-file requirements.txt requirements.in
;;
*)
echo "Managment Script Usage:"
echo ""
echo " manage.sh [COMMAND]"
echo ""
echo "COMMAND:"
echo " build Build docker image for local development."
echo " db [start|restart|stop] Start/stop local database."
echo " makemigrations Create new migration files."
echo " migrate Apply migrations to local database."
echo " update_dependencies Update dependencies based in requirements.in."
;;
esac
Generic single-database configuration.
\ No newline at end of file
# A generic, single database configuration.
[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
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
from __future__ import with_statement
import logging
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# 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.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from flask import current_app
config.set_main_option(
'sqlalchemy.url',
str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%'))
target_metadata = current_app.extensions['migrate'].db.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():
"""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
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')
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,
process_revision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}
# list all your hard requirements here
# Flask: the main web framework
flask
flask-bootstrap
flask-migrate
flask-sqlalchemy
# database connector
pymysql
# telegram bot
#
# This file is autogenerated by pip-compile
# To update, run:
#
# pip-compile --output-file=requirements.txt requirements.in
#
alembic==1.4.2 # via flask-migrate
click==7.1.2 # via flask
dominate==2.5.1 # via flask-bootstrap
flask-bootstrap==3.3.7.1 # via -r requirements.in
flask-migrate==2.5.3 # via -r requirements.in
flask-sqlalchemy==2.4.3 # via -r requirements.in, flask-migrate
flask==1.1.2 # via -r requirements.in, flask-bootstrap, flask-migrate, flask-sqlalchemy
itsdangerous==1.1.0 # via flask
jinja2==2.11.2 # via flask
mako==1.1.3 # via alembic
markupsafe==1.1.1 # via jinja2, mako
pymysql==0.9.3 # via -r requirements.in
python-dateutil==2.8.1 # via alembic
python-editor==1.0.4 # via alembic
six==1.15.0 # via python-dateutil
sqlalchemy==1.3.18 # via alembic, flask-sqlalchemy
visitor==0.1.3 # via flask-bootstrap
werkzeug==1.0.1 # via flask
from app import app
if __name__ == '__main__':
app.run(host='0.0.0.0')
# wsgi server (used in docker container)
# [bjoern](https://github.com/jonashaag/bjoern) required.
from app import app
import bjoern
if __name__ == '__main__':
print('Starting bjoern on port 8080...', flush=True)
bjoern.run(app, '0.0.0.0', 8080)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment