Browse Source

Several cleanup's to get the full stack running

backend_DiskStation_Sep-29-1817-2021_TypeConflict
Andreas Berthoud 4 years ago
parent
commit
fe40b4d64f
  1. 28
      README.md
  2. 38
      backend/docker-compose-prod.yml
  3. 27
      backend/monsun_backend/__init__.py
  4. 5
      backend/monsun_backend/defaults/config.yml
  5. 2
      backend/monsun_backend/endpoints/admin.py
  6. 7
      backend/monsun_backend/endpoints/command.py
  7. 4
      backend/nginx.conf
  8. 1
      backend/requirements.txt

28
README.md

@ -39,4 +39,30 @@ GATT concepts: https://learn.adafruit.com/introduction-to-bluetooth-low-energy/g
### Client
[ble-client-seq.puml](ble-client-seq.puml)
[ble-client-seq.puml](ble-client-seq.puml)
## Backend
### DEBUG config
VS Code:
```json
"configurations": [
{
"name": "Python: Flask",
"type": "python",
"request": "launch",
"module": "flask",
"env": {
"FLASK_APP": "backend/wsgi.py",
"FLASK_ENV": "development",
"FLASK_DEBUG": "0",
"SECRET": "\\\x10#\xd9\x89,2|hBN\xe4\xdf\xe0\xf7W"
},
"args": [
"run",
],
"jinja": true
}
]
```

38
backend/docker-compose-prod.yml

@ -1,38 +0,0 @@
version: "3"
services:
monsun_postgres:
image: postgres
container_name: monsun_postgres
restart: always
logging:
driver: json-file
options:
max-size: "200k"
max-file: "10"
volumes:
- ./db-data:/var/lib/postgresql/data
env_file: prod.env
monsun_backend:
image: registry.berthoud.dev/monsun_backend
container_name: monsun_backend
restart: always
logging:
driver: json-file
options:
max-size: "200k"
max-file: "10"
ports:
- 30010:80
volumes:
- ./config:/var/config/
depends_on:
- monsun_postgres
environment:
POSTGRES_HOST: monsun_postgres
env_file: prod.env
devices:
- "/dev/ttyACM0:/dev/tty.client"
command: ["bash", "./wait-for-it.sh", "monsun_postgres:5432", "-t", "60", "--", "./docker-entrypoint.sh"]

27
backend/monsun_backend/__init__.py

@ -1,12 +1,10 @@
import logging
import os
from logging.config import dictConfig
from flask_api import FlaskAPI
from flask_cors import CORS
from flask_marshmallow import Marshmallow
"""https://blog.miguelgrinberg.com/post/how-to-add-flask-migrate-to-an-existing-project""" # noqa
import os
from flask_migrate import Migrate
from flask_security import Security
from sqlalchemy import create_engine
@ -18,6 +16,7 @@ from . import command_execution
from . import database
from . import error
from . import models
from .container import get_initialize_container
from .endpoints import admin
from .endpoints import command
from .endpoints import login
@ -47,6 +46,9 @@ migrate = Migrate()
def create_app() -> FlaskAPI:
app = FlaskAPI(__name__)
container_ = get_initialize_container()
app.register_blueprint(command.bp)
app.register_blueprint(login.bp)
app.register_blueprint(logout.bp)
@ -86,10 +88,25 @@ def create_app() -> FlaskAPI:
logger = logging.getLogger("monsun_backend.init")
_exception_logger = logging.getLogger("monsun_backend.exception")
app.secret_key = os.getenv("SECRET")
if os.getenv("MONSUN_DEBUG"):
logger.debug("=== MONSUN DEBUG MODE ===")
CORS(
app,
origins=["http://localhost:4200"],
supports_credentials=True,
)
app.config.update(
SECRET_KEY=os.getenv("SECRET"),
SQLALCHEMY_TRACK_MODIFICATIONS=False,
SQLALCHEMY_DATABASE_URI=os.getenv("DATABASE_URI"),
SESSION_COOKIE_SECURE=container_.config.session_cookie_secure(required=True),
SESSION_COOKIE_HTTPONLY=container_.config.session_cookie_httponly(
required=True,
),
SESSION_COOKIE_SAMESITE=container_.config.session_cookie_samesite(
required=True,
),
)
logger.info(f"DATABASE_URI: {os.getenv('DATABASE_URI')}")

5
backend/monsun_backend/defaults/config.yml

@ -5,3 +5,8 @@ serial_reconnection_wait_timeout: 1
admin_user_email: andreasberthoud@gmail.com
admin_user_password: password
roles: []
session_cookie_secure: False
session_cookie_httponly: False
session_cookie_samesite: Lax
session_cookie_domain: None

2
backend/monsun_backend/endpoints/admin.py

@ -10,6 +10,6 @@ bp = blueprints.Blueprint("admin", __name__)
rule="/admin",
methods=["GET"],
)
@access.admin_permission.require(http_exception=status.HTTP_403_FORBIDDEN)
@access.admin_permission.require(http_exception=status.HTTP_401_UNAUTHORIZED)
def admin():
return "success", 200

7
backend/monsun_backend/endpoints/command.py

@ -21,7 +21,7 @@ bp = blueprints.Blueprint("command", __name__)
@bp.route("/<role>/command", methods=["POST", "GET"])
@access.admin_permission.require(http_exception=status.HTTP_403_FORBIDDEN)
@access.admin_permission.require(http_exception=status.HTTP_401_UNAUTHORIZED)
def command(role: str):
logger = _logger.getChild(f"{role}/command")
@ -50,7 +50,10 @@ def command(role: str):
)
except KeyError:
logger.error(f"role {role} does not exist")
return Response(status=status.HTTP_400_BAD_REQUEST)
return Response(
f"role '{role}' does not exist",
status=status.HTTP_400_BAD_REQUEST,
)
if response is None:
return Response(status=status.HTTP_408_REQUEST_TIMEOUT)

4
backend/nginx.conf

@ -26,8 +26,8 @@ http {
index index.html index.htm;
server {
listen 80 default_server;
listen [::]:80 default_server;
listen 5000 default_server;
listen [::]:5000 default_server;
server_name localhost;
root /var/www/html;

1
backend/requirements.txt

@ -1,6 +1,7 @@
dependency-injector[yaml]>=4.34.0,<5
email_validator
flask-api>=3.0.post1,<4
flask-cors
flask-migrate
flask-script
flask-sqlalchemy

Loading…
Cancel
Save