<commit_before>"""Main application entrypoint for the TinyLog API"""

import functools
import logging
import os

import envpy
from flask import Flask, abort, jsonify, request

from tinylog_server import recaptcha
from tinylog_server.db import models as tiny_models

# This doesn't conform to PEP-8 but it is idiomatic for Flask
app = Flask(__name__) #pylint: disable=C0103

CONFIG = envpy.get_config({
    "ENV": envpy.Schema(
        value_type=str,
        default="PROD",
    ),
    "CAPTCHA_CHALLENGE": envpy.Schema(
        value_type=str,
    ),
    "DATABASE_DSN": envpy.Schema(
        value_type=str,
    ),
})

SECRETS = envpy.get_config({
    "CAPTCHA_SECRET": envpy.Schema(
        value_type=str,
    ),
})


def init():
    """Initialise app"""
    # Init logging
    logging_handler = logging.StreamHandler()
    logging_formatter = logging.Formatter(\
        "%(asctime)s - %(levelname)s - %(name)s: %(message)s")
    logging_handler.setFormatter(logging_formatter)
    app.logger.addHandler(logging_handler)
    app.logger.setLevel(logging.INFO)

    # Log current config
    app.logger.info('Config loaded: %s', CONFIG)

    # Configure Flask App
    app.config['SQLALCHEMY_DATABASE_URI'] = CONFIG['DATABASE_DSN']

    # Register app with SQLAlchemy
    tiny_models.DB.init_app(app)
init()


# Decorators

def authorized(view):
    @functools.wraps(view)
    def wrapper(*args, **kwargs):
        auth_header = request.headers.get('Authorization')

        # Check auth header is provided
        if auth_header is None:
            return jsonify('Authorization header is required'), 400

        # Check auth header is valid
        auth_parts = auth_header.split(' ')
        if len(auth_parts) != 2:
            return jsonify('Invalid Authorization header'), 400

        auth_type, access_token = auth_parts
        if auth_type != 'tinylog':
            return jsonify('Unsupported auth type'), 400

        # Check session exists
        session = tiny_models.Session.query.filter_by(
            access_token=access_token).first()
        if (
            session is None:
            or not session.is_valid
        ):
            return jsonify('Invalid access token'), 403

        return view(session, *args, **kwargs)

    return wrapper


# Views

@app.route('/')
def index():
    """Return API Index"""
    return jsonify({<commit_msg>Small bug fix<commit_after>"""Main application entrypoint for the TinyLog API"""

import functools
import logging
import os

import envpy
from flask import Flask, abort, jsonify, request

from tinylog_server import recaptcha
from tinylog_server.db import models as tiny_models

# This doesn't conform to PEP-8 but it is idiomatic for Flask
app = Flask(__name__) #pylint: disable=C0103

CONFIG = envpy.get_config({
    "ENV": envpy.Schema(
        value_type=str,
        default="PROD",
    ),
    "CAPTCHA_CHALLENGE": envpy.Schema(
        value_type=str,
    ),
    "DATABASE_DSN": envpy.Schema(
        value_type=str,
    ),
})

SECRETS = envpy.get_config({
    "CAPTCHA_SECRET": envpy.Schema(
        value_type=str,
    ),
})


def init():
    """Initialise app"""
    # Init logging
    logging_handler = logging.StreamHandler()
    logging_formatter = logging.Formatter(\
        "%(asctime)s - %(levelname)s - %(name)s: %(message)s")
    logging_handler.setFormatter(logging_formatter)
    app.logger.addHandler(logging_handler)
    app.logger.setLevel(logging.INFO)

    # Log current config
    app.logger.info('Config loaded: %s', CONFIG)

    # Configure Flask App
    app.config['SQLALCHEMY_DATABASE_URI'] = CONFIG['DATABASE_DSN']

    # Register app with SQLAlchemy
    tiny_models.DB.init_app(app)
init()


# Decorators

def authorized(view):
    @functools.wraps(view)
    def wrapper(*args, **kwargs):
        auth_header = request.headers.get('Authorization')

        # Check auth header is provided
        if auth_header is None:
            return jsonify('Authorization header is required'), 400

        # Check auth header is valid
        auth_parts = auth_header.split(' ')
        if len(auth_parts) != 2:
            return jsonify('Invalid Authorization header'), 400

        auth_type, access_token = auth_parts
        if auth_type != 'tinylog':
            return jsonify('Unsupported auth type'), 400

        # Check session exists
        session = tiny_models.Session.query.filter_by(
            access_token=access_token).first()
        if (
            session is None
            or not session.is_valid
        ):
            return jsonify('Invalid access token'), 403

        return view(session, *args, **kwargs)

    return wrapper


# Views

@app.route('/')
def index():
    """Return API Index"""
    return jsonify({
{'fraction_non_alphanumeric': 0.1074066258704368, 'fraction_numerical': 0.007596539354294155, 'mean_word_length': 2.863080684596577, 'pattern_counts': {'":': 8, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5497950', 'n_tokens_mistral': 1496, 'n_tokens_neox': 1433, 'n_words': 365}