Started writing data and server

This commit is contained in:
2022-08-24 15:55:53 +01:00
parent 2ec5c97c73
commit 2d04ae5bd8
17 changed files with 1255 additions and 0 deletions

27
server/app/__init__.py Normal file
View File

@ -0,0 +1,27 @@
from .config import Development as Config
from .models import *
from .extensions import db
from flask import Flask
from werkzeug.middleware.proxy_fix import ProxyFix
def create_app():
app = Flask(__name__)
app.config.from_object(Config())
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto = 1, x_host = 1)
db.init_app(app=app)
from .views import views
app.register_blueprint(
blueprint = views,
url_prefix = '/api'
)
"""Create database before first request"""
@app.before_first_request
def _create_database_tables():
with app.app_context(): db.create_all()
return app

38
server/app/config.py Normal file
View File

@ -0,0 +1,38 @@
import os
from pathlib import Path
from dotenv import load_dotenv
load_dotenv('../.env')
class Config(object):
"""Basic App Configuration"""
APP_HOST = '0.0.0.0'
DATA = './data/'
DEBUG = False
TESTING = False
SECRET_KEY = os.getenv('SECRET_KEY')
SERVER_NAME = os.getenv('SERVER_NAME')
SESSION_COOKIE_SECURE = True
"""Database Driver Configuration"""
DATABASE_TYPE = os.getenv('DATABASE_TYPE') or 'SQLite'
SQLALCHEMY_TRACK_MODIFICATIONS = False
if DATABASE_TYPE.lower() == 'mysql' and os.getenv('MYSQL_DATABASE') and os.getenv('MYSQL_USER') and os.getenv('MYSQL_PASSWORD'):
DATABASE_HOST = os.getenv('DATABASE_HOST') or 'localhost'
DATABASE_PORT = int(os.getenv('DATABASE_PORT') or 3306)
MYSQL_DATABASE = os.getenv('MYSQL_DATABASE')
MYSQL_USER = os.getenv('MYSQL_USER')
MYSQL_PASSWORD = os.getenv('MYSQL_PASSWORD')
SQLALCHEMY_DATABASE_URI = f'mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{DATABASE_HOST}:{DATABASE_PORT}/{MYSQL_DATABASE}'
else: SQLALCHEMY_DATABASE_URI = f'sqlite:///{Path(os.path.abspath(f"{DATA}/database.db"))}'
class Production(Config): pass
class Development(Config):
APP_HOST = '127.0.0.1'
DEBUG = True
SERVER_NAME = '127.0.0.1:5000'
SESSION_COOKIE_SECURE = False
class Testing(Development):
TESTING = True

2
server/app/extensions.py Normal file
View File

@ -0,0 +1,2 @@
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

View File

@ -0,0 +1 @@
from .entry import Entry

View File

@ -0,0 +1,27 @@
from ..extensions import db
from sqlalchemy_json import MutableJson
from datetime import datetime
from uuid import uuid4
class Entry():
id = db.Column(db.String(36), primary_key=True)
timestamp = db.Column(db.DateTime, nullable=False)
answers = db.Column(MutableJson, nullable=False)
result = db.Column(MutableJson, nullable=False)
def __repr__(self) -> str: return f'Entry with <id {self.id}>.'
@property
def generate_id(self): raise AttributeError('generate_id is not a readable attribute.')
generate_id.setter
def generate_id(self): self.id = uuid4().hex
@property
def set_timestamp(self): raise AttributeError('set_timestamp is not a readable attribute.')
set_timestamp.setter
def set_timestamp(self): self.timestamp = datetime.utcnow()

View File

22
server/app/tools/data.py Normal file
View File

@ -0,0 +1,22 @@
from flask import current_app as app
import json
from os.path import isfile
from pathlib import Path
def check_file(filename:str):
data_dir = Path(app.config.get('DATA'))
if isfile(f'./{data_dir}/{filename}'): return True
return False
def load(filename:str):
data_dir = Path(app.config.get('DATA'))
with open(f'./{data_dir}/{filename}') as file: return json.load(file)
def render_questions():
data = load('questions.json')
for question in data:
_answers = [ answer['text'] for answer in question['answers'] ]
question['answers'] = _answers
return data

23
server/app/views.py Normal file
View File

@ -0,0 +1,23 @@
from .tools.data import check_file, load, render_questions
from flask import Blueprint
from flask.helpers import abort
views = Blueprint(
name='views',
import_name=__name__
)
@views.route('/fetch/<string:data_type>/')
def _fetch(data_type):
if not check_file(f'{data_type}.json'): return abort(404)
if data_type == 'questions': return render_questions()
return load(f'{data_type}.json')
@views.route('/submit', methods=['POST'])
def _submit():
pass
@views.route('/results')
def _results():
pass