Exemplo n.º 1
0
from lib import CustomLogger
from quart.logging import default_handler
from quart import Blueprint, render_template

from AXL import *

applog = CustomLogger.getCustomLogger('rest_axl_phone', 'quartapp')

rest_axl_phone = Blueprint('rest_axl_phone', __name__)


@rest_axl_phone.route('/api/v1/axl_phone/', methods=['GET'])
async def rest_axl_phone_get():
    applog.info('Request method')
    return await render_template('index.html',
                                 name='Blueprint - AXL Phone - GET')


@rest_axl_phone.route('/api/v1/axl_phone/', methods=['DELETE'])
async def rest_axl_phone_delete():
    return await render_template('index.html',
                                 name='Blueprint - AXL Phone - DELETE')


@rest_axl_phone.route('/api/v1/axl_phone/', methods=['PUT'])
async def rest_axl_phone_put():
    return await render_template('index.html',
                                 name='Blueprint - AXL Phone - PUT')
Exemplo n.º 2
0
from quart import render_template
from quart import request
from quart import session
from quart import send_file

from constants import regexes
from objects import glob
from objects import utils
from objects.privileges import Privileges
from objects.utils import flash
from objects.utils import flash_with_customizations

VALID_MODES = frozenset({'std', 'taiko', 'catch', 'mania'})
VALID_MODS = frozenset({'vn', 'rx', 'ap'})

frontend = Blueprint('frontend', __name__)

def login_required(func):
    @wraps(func)
    async def wrapper(*args, **kwargs):
        if not session:
            return await flash('error', 'You must be logged in to access that page.', 'login')
        return await func(*args, **kwargs)
    return wrapper

@frontend.route('/home')
@frontend.route('/')
async def home():
    return await render_template('home.html')

@frontend.route('/home/account/edit')
Exemplo n.º 3
0
from quart import Blueprint, session

user = Blueprint('user', __name__)


@user.route('/login', methods=['Post'])
async def login():
    session['logged_in'] = True


@user.route('/logout')
async def logout():
    session.pop('logged_in', None)
    return None
Exemplo n.º 4
0
from quart import (flash, redirect, render_template, request, send_file,
                   url_for, websocket)
from quart_auth import current_user, login_required, login_user, logout_user

from tsundoku import __version__ as version
from tsundoku.blueprints.api import APIResponse
from tsundoku.fluent import get_injector
from tsundoku.user import User
from tsundoku.webhooks import WebhookBase

from .issues import get_issue_url

ux_blueprint = Blueprint(
    'ux',
    __name__,
    template_folder="templates",
    static_folder="static",
    static_url_path="/ux/static"
)
hasher = PasswordHasher()


@ux_blueprint.context_processor
async def update_context() -> dict:
    async with app.acquire_db() as con:
        await con.execute("""
            SELECT
                COUNT(*)
            FROM
                shows;
        """)
Exemplo n.º 5
0
from quart import Blueprint, request, current_app as app, jsonify
from logbook import Logger

from ..auth import token_check
from ..schemas import validate, INVITE
from ..enums import ChannelType
from ..errors import BadRequest
from .guilds import create_guild_settings
from ..utils import async_map

from discord.blueprints.checks import (channel_check, channel_perm_check,
                                       guild_check, guild_perm_check)

log = Logger(__name__)
bp = Blueprint('invites', __name__)


# TODO: Ban handling
async def use_invite(user_id, invite_code):
    """Try using an invite"""
    inv = await app.db.fetchrow(
        """
            SELECT guild_id, created_at, max_age, uses, max_uses
            FROM invites
            WHERE code = $1
            """, invite_code)

    if inv is None:
        raise BadRequest('Unknown invite')
Exemplo n.º 6
0
# -*- coding: utf-8 -*-

__all__ = ()

import datetime

import timeago
from quart import Blueprint
from quart import render_template
from quart import session

from objects import glob
from objects.utils import flash

admin = Blueprint('admin', __name__)


@admin.route('/')
@admin.route('/home')
@admin.route('/dashboard')
async def home():
    """Render the homepage of guweb's admin panel."""
    if not 'authenticated' in session:
        return await flash('error', 'Please login first.', 'login')

    if not session['user_data']['is_staff']:
        return await flash('error', f'You have insufficient privileges.',
                           'home')

    # fetch data from database
    dash_data = await glob.db.fetchrow(
Exemplo n.º 7
0
from quart import Blueprint, request

from . import services as todo_service
from ...helpers.decorators import auth_required

todo_bp = Blueprint("todo_bp", __name__)


@todo_bp.route("/todos", methods=["POST"])
@auth_required()
async def create_todo():
    user = request.user

    payload = await request.json
    name = payload.get("name")
    await todo_service.create_todo(name, user)

    return {"data": {"name": name, "user": user}}, 201


@todo_bp.route("/todos", methods=["GET"])
@auth_required()
async def list_todo():
    data = await todo_service.get_all_todo(request.user)
    data = list(data)

    return {"data": [dict(i) for i in data]}


@todo_bp.route("/todos/<int:id>", methods=["PATCH"])
@auth_required()
Exemplo n.º 8
0
from quart import Blueprint, render_template, request, jsonify, abort
import time
import peewee
import os

from madt_lib.runtime_api import restart_lab, stop_lab, start_lab

from .lab_messenger import Messenger, msg_cache
from .config import prefix, lab_path
from .models import Host, Lab, Node, Network
from .net_control import routers_cache

lab_control_bp = Blueprint('lab_control', __name__)


try:
    runtime = os.environ['MADT_RUNTIME']
except KeyError:
    runtime = 'docker'

@lab_control_bp.route('/lab/<string:name>')
async def list_containers(name):
    # hosts = Host.select()
    if not os.path.exists(lab_path(name)):
        abort(404)

    containers = []

    show_containers = 'show_containers' in request.args and request.args['show_containers'] == 'True'

    if show_containers:
Exemplo n.º 9
0
from quart import Blueprint
from typing import Dict, List, Tuple, Union

import aiohttp
import spotify
import ujson
import util

log = util.setLogger(__name__)
player_route = Blueprint('player_route', __name__)


@player_route.route('/play/<string:uri>')
async def play(uri):
    pass


async def play_song(sp: spotify.Spotify,
                    context_uri: str = None,
                    uris: List[str] = None,
                    offset: Dict[str, Union[str, int]] = None,
                    position_ms=None,
                    session: aiohttp.ClientSession = None):
    """ Plays a song if uris is provided, otherwise plays context_uri if provided and then returns
     true. Otherwise returns false"""
    if uris is None and context_uri is None:
        return False
    if not session:
        session = aiohttp.ClientSession(json_serialize=ujson)

    if uris:
Exemplo n.º 10
0
from quart import Blueprint
from lnbits.db import Database

db = Database("ext_ngrok")

ngrok_ext: Blueprint = Blueprint("ngrok", __name__, template_folder="templates")

from .views import *  # noqa
Exemplo n.º 11
0
sv = Service('网页端',
             visible=True,
             enable_on_default=True,
             bundle='网页端',
             help_='''
- [#帮助] 帮助页面的网页端
- [手册] 打开会战手册
- [主页] 浏览主页
'''.strip())

work_env = Path(os.path.dirname(__file__))
homework_folder = work_env.joinpath('img')
static_folder = work_env.joinpath('static')
ma = Blueprint('ma',
               __name__,
               template_folder='templates',
               static_folder=static_folder)
hp = Blueprint('hp',
               __name__,
               template_folder='templates',
               static_folder=static_folder)
tk = Blueprint('tk',
               __name__,
               template_folder='templates',
               static_folder=static_folder)
ab = Blueprint('ab',
               __name__,
               template_folder='templates',
               static_folder=static_folder)
sc = Blueprint('sc',
               __name__,
Exemplo n.º 12
0
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

from quart import Blueprint, current_app, request, stream_with_context, jsonify
from .stream_results import stream_result_as_json
from .check_claims import check_geography_claims

blueprint = Blueprint("geography", __name__)


@blueprint.route("/geography/<aggregation_unit>")
@check_geography_claims()
async def get_geography(aggregation_unit):
    request.socket.send_json(
        {
            "request_id": request.request_id,
            "action": "get_geography",
            "params": {"aggregation_unit": aggregation_unit},
        }
    )
    #  Get the reply.
    message = await request.socket.recv_json()
    current_app.logger.debug(f"Got message: {message}")
    try:
        status = message["status"]
    except KeyError:
        return (
            jsonify({"status": "Error", "msg": "Server responded without status"}),
            500,
        )
Exemplo n.º 13
0
from quart import Blueprint, request, current_app
from utils import stringify, parse_datetime
from utils import HTTPCode
from auth import auth_needed, Auth
from objects import Student
from exceptions import DateTimeParserError

bp = Blueprint("task", __name__, url_prefix="/task")


@bp.route('/', methods=['GET'])
@auth_needed(Auth.ANY, provide_obj=True)
async def get_all_tasks(auth_obj):
    """Route that gets all the tasks in the database. Any authentication necessary.
    Teacher auth -> all tasks returned
    Student auth -> student's tasks returned
    No auth -> BADREQUEST"""
    tasks = current_app.config['task_manager']
    is_completed = request.args.get(
        "is_completed"
    )  # Should be set to True if client wants the "has_completed" attribute
    is_mine = request.args.get(
        "mine"
    ) == "True"  # Used when a teacher wants to get their own tasks TODO: Perhaps make this a default thing - make default teacher funcitonaity return only the teacher's tasks

    if type(auth_obj) == Student:
        # Get only student's tasks
        if is_completed == "True":
            data = await tasks.get(student_id=auth_obj.id, get_completed=True)
        else:
            data = await tasks.get(student_id=auth_obj.id)
Exemplo n.º 14
0
import uuid
import datetime
from collections import Counter
from typing import List, Dict, Any

from quart import Blueprint, request, jsonify, current_app as app

from rana.auth import token_check
from rana.utils import jsonify
from rana.models import validate, SUMMARIES_IN
from rana.database import timestamp_
from rana.errors import BadRequest

from rana.blueprints.durations import calc_durations, convert_tz

bp = Blueprint("summaries", __name__)


# modification of https://stackoverflow.com/a/1060330
def daterange(start_date, delta):
    """Yield dates, making a per-day iteration of the given start date until
    start_date + delta."""
    for day in range(int(delta.days) + 1):
        yield start_date + datetime.timedelta(days=day)


def _process_durations(durations: List[Dict[str, Any]], counter_key: str,
                       value_func) -> Counter:
    counter: Counter = Counter()

    for duration in durations:
Exemplo n.º 15
0
from quart import Blueprint

blog_api = Blueprint("blog",__name__)

from . import blog_controller
Exemplo n.º 16
0
from hoshino import Service, priv
from quart import request, Blueprint, jsonify, render_template

import string
import random
import nonebot
import hoshino

from datetime import *
from . import util
from .constant import config

auth = Blueprint('auth',
                 __name__,
                 url_prefix='/auth',
                 template_folder="./vue",
                 static_folder='./vue',
                 static_url_path='')
bot = nonebot.get_bot()
app = bot.server_app
manage_password = config.PASSWORD  # 管理密码请在authMS.py中修改


@auth.route('/')
async def index():
    return await render_template("index.html")


@auth.route('/api/login', methods=['POST'])
async def login_auth():
    password = request.args.get('password')
Exemplo n.º 17
0
from quart import Blueprint
from lnbits.db import Database

db = Database("ext_amilk")

amilk_ext: Blueprint = Blueprint("amilk",
                                 __name__,
                                 static_folder="static",
                                 template_folder="templates")

from .views_api import *  # noqa
from .views import *  # noqa
Exemplo n.º 18
0
from quart import Blueprint, jsonify

bp = Blueprint('science', __name__)


@bp.route('/science', methods=['POST'])
async def science():
    return '', 204


@bp.route('/applications', methods=['GET'])
async def applications():
    return jsonify([])


@bp.route('/experiments', methods=['GET'])
async def experiments():
    return jsonify({
        'assignments': []
    })
Exemplo n.º 19
0
import math
import moment
import src.utils.google as google
import asyncio
from quart import abort, Blueprint, jsonify, request
from src.utils.array_utils import get_nested_value

popularity = Blueprint('popularity', __name__)


@popularity.route('/popularity', methods=['GET'])
async def get_popularities():
    """Retrieve current popularity for an array of ids"""
    ids = await request.get_json()

    if len(ids) > 100:
        abort(400, description='You can send at most 100 ids at once.')

    loop = asyncio.get_event_loop()

    def parse_result(r):
        data = r['data']
        p = get_nested_value(data, 6, 84, 7, 1)
        time_zone = get_nested_value(data, 31, 1, 0, 0)
        timestamp = moment.utcnow().timezone(time_zone).replace(minutes=0,
                                                                seconds=0)

        return dict(id=r['id'],
                    data=dict(popularity=p, timestamp=str(timestamp)))

    futures = []
import nonebot
import json

from datetime import timedelta
from hoshino.service import Service
from quart import request, session, redirect, Blueprint
from .data_source import render_template, get_random_str

switcher = Blueprint('switcher', __name__)
bot = nonebot.get_bot()
app = bot.server_app
if not app.config.get('SECRET_KEY'):
    app.config['SECRET_KEY'] = get_random_str(10)

public_address = ''  #改为你服务器的公网ip,域名应该也可以,我没试过
port = bot.config.PORT
botname = bot.config.NICKNAME
passwd = ''  #登录密码


@switcher.before_request
async def _():
    user_ip = request.remote_addr
    if request.path == '/login':
        return
    if request.path == '/check':
        return
    if session.get('user_ip') == user_ip:
        return
    return redirect('/login')
Exemplo n.º 21
0
Use of this source code is governed by an MIT-style license that can be found in the LICENSE file.
"""

import json
import asyncio
import traceback
from base64 import b64decode
from datetime import datetime
from hashlib import sha256
from quart import Blueprint, websocket, abort, current_app, copy_current_app_context
from ..extensions import queue, logger, connected_websockets, redis
from ..storage import Client
from ..common.enums import Connection
from .WebsocketMessage import WebsocketMessage

websocket_connect = Blueprint('websocket_connect', __name__)


@websocket_connect.websocket('/connect/<client_uid>')
async def connect_client(client_uid: str):
    if not current_app.config['DEBUG'] and not websocket.headers.get('X-Forwarded-For'):
        abort(403)
    client = await Client.filter(uid=client_uid).first()
    if not client or not websocket.headers.get('Authorization'):
        abort(403)
    credentials = b64decode(websocket.headers.get('Authorization')[6:]).decode().split(':')
    if len(credentials) != 2:
        abort(403)
    if not client.basicauth_password or sha256(credentials[1].encode()).hexdigest() != client.basicauth_password:
        abort(403)
    client.ip = websocket.headers.get('X-Forwarded-For', None)
Exemplo n.º 22
0
import re

from quart import current_app as app
from quart import Blueprint, request

from .room import Room, RoomComponent

integrations_blueprint = Blueprint("integrations", __name__)


async def extract_content(content: str):
    """
    Extracts content from raw content.

    Returns [(type, content, content_extra), ...]
    """
    extracted = []
    seen_links = set()

    image_urls = re.finditer(r"\S+(?:\.png|\.jpeg|\.jpg|\.gif)", content)
    for match in image_urls:
        seen_links.add(match.group(0))
        extracted.append(("image", match.group(0), None))

    code_blocks = re.finditer(r"```[a-z]*\n([\s\S]*?)\n```", content)
    for match in code_blocks:
        extracted.append(("code", match.group(1), None))

    youtube_links = re.finditer(
        r"(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)",
        content)
Exemplo n.º 23
0
import os
import json
from datetime import datetime, timezone, timedelta

import asks
from quart import request, jsonify, Blueprint, abort
from .auth import simple_token
from .storage import Store

views = Blueprint("grafana", __name__)


def get_time_range(the_range):
    if not the_range:
        return None, None

    def parse_time(string):
        return datetime.strptime(string, "%Y-%m-%dT%H:%M:%S.%fZ").astimezone(
            timezone.utc
        )

    return parse_time(the_range["from"]), parse_time(the_range["to"])


def to_grafana_type(some_type):
    if isinstance(some_type, list):
        some_type = type(some_type[0])
    return {
        int: "number",
        float: "number",
        bool: "number",
Exemplo n.º 24
0
from __future__ import annotations

from dataclasses import dataclass
from sqlite3 import Connection

import quart
from ariadne import graphql
from ariadne.constants import PLAYGROUND_HTML
from quart import Blueprint, Request, Response

from src.graphql import error_formatter, schema
from src.library import user as libuser
from src.webserver.util import check_auth

bp = Blueprint("graphql", __name__, url_prefix="/graphql")


@dataclass
class GraphQLContext:
    user: libuser.T
    db: Connection
    request: Request


@bp.route("", methods=["GET"])
async def graphql_playground() -> tuple[str, int]:  # pragma: no cover
    """
    **Developer endpoint.**

    Return the GraphQL playground if we are in debug mode, otherwise
    raise a 404.
Exemplo n.º 25
0
import os
import jwt
from quart import Blueprint, request
from . import services as user_service
from ...helpers.decorators import auth_required

user_bp = Blueprint("user_bp", __name__)
SECRET = os.environ.get("SECRET_KEY")


@user_bp.route("/register", methods=["POST"])
async def register():
    payload = await request.json
    data = {
        "name": payload.get("name"),
        "email": payload.get("email"),
    }
    await user_service.register(**data)
    return {"data": data}, 201


@user_bp.route("/profile")
@auth_required()
async def profile():
    user_id = request.user.get("id")
    user = await user_service.detail_user(user_id)
    return {"data": dict(user)}


@user_bp.route("/auth", methods=["POST"])
async def auth():
Exemplo n.º 26
0
from goblin import Goblin
from app.config import Configuration
from app.utilities import prepare_event_date_time, is_db_connection_available
from app.data_loader.models import FileSummary, BatchSummary
from app.models import User, Environment, Session, Browser, Device, OS, BelongsTo, CompatibleWith, AssignedTo,\
    LogsIn, InstanceOf, ViewedOn, Exits, Accesses, Application, ApplicationInstance, Screen, ScreenInstance,\
    Tenant, Company, CloudSuite, Launches, Enters, LogsOut, TimesOut, ConnectedWith, Operates, Hosts, Provisioned,\
    Supports, RunsOn, Owns, Implemnts, DeployedFrom
from quart import Blueprint, Response
from more_itertools import peekable
from user_agents import parse

from functools import lru_cache

dataloader_mod = Blueprint('dataloader', __name__)

# Run the following command from the terminal every time the schema changes
# neomodel_install_labels app.py app.models --db 'bolt://*****:*****@localhost:7687'


@singledispatch
def to_serializable(val):
    """Used by default."""
    return str(val)


@to_serializable.register(datetime)
def ts_datetime(val):
    """Used if *val* is an instance of datetime."""
    return val.isoformat() + "Z"
Exemplo n.º 27
0
    def run(self):
        """
        While we could use the standard decorators to register these routes, 
        using add_url_rule() allows us to create diffrent endpoint names
        programmatically and pass the classes self object to the routes
        """

        config = Config()
        config.ciphers = 'ALL'
        config.host = self['BindIP']
        config.port = self['Port']
        config.debug = False
        config.use_reloader = False

        http_blueprint = Blueprint(__name__, 'http')
        http_blueprint.before_request(self.check_if_naughty)
        #http_blueprint.after_request(self.make_normal)

        http_blueprint.add_url_rule('/<uuid:GUID>',
                                    'key_exchange',
                                    self.key_exchange,
                                    methods=['POST'])
        http_blueprint.add_url_rule('/<uuid:GUID>',
                                    'stage',
                                    self.stage,
                                    methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs',
                                    'jobs',
                                    self.jobs,
                                    methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs/<job_id>',
                                    'job_result',
                                    self.job_result,
                                    methods=['POST'])

        # Add a catch all route
        http_blueprint.add_url_rule('/',
                                    'unknown_path',
                                    self.unknown_path,
                                    defaults={'path': ''})
        http_blueprint.add_url_rule('/<path:path>',
                                    'unknown_path',
                                    self.unknown_path,
                                    methods=['GET', 'POST'])

        #logging.getLogger('quart.app').setLevel(logging.DEBUG if state.args['--debug'] else logging.ERROR)
        #logging.getLogger('quart.serving').setLevel(logging.DEBUG if state.args['--debug'] else logging.ERROR)

        self.app = Quart(__name__)
        self.app.register_blueprint(http_blueprint)
        asyncio.run(serve(self.app, config))
Exemplo n.º 28
0
from quart import Blueprint
from lnbits.db import Database

db = Database("ext_paywall")

paywall_ext: Blueprint = Blueprint("paywall", __name__, static_folder="static", template_folder="templates")


from .views_api import *  # noqa
from .views import *  # noqa
Exemplo n.º 29
0
from quart import Blueprint, request
import threading
import time
import os

static = Blueprint('static',
                   __name__,
                   static_url_path="/",
                   static_folder="static")


@static.after_request
async def after_request_func(response):
    if response.status_code == 200:
        file_path = request.base_url.replace("http://localhost:5000/", "")
        t = threading.Thread(target=delete_after_request_thread,
                             args=[file_path])
        t.setDaemon(False)
        t.start()
    return response


def delete_after_request_thread(file_path):
    time.sleep(2000)
    os.remove(file_path)
Exemplo n.º 30
0
import os
from utils import format_date
from quart import Blueprint, g, current_app as app, request

api = Blueprint('api', __name__)


def get_db():
    return g.sqlite_db


@api.route('/', methods=['POST'])
async def index():
    if request.content_type == 'application/json':
        data = await request.get_json()
        if data is not None:
            db = get_db()
            db.execute(
                "INSERT INTO posts(latitude,longitude,velocidade,satelites,data_hora) VALUES(?,?,?,?,?);",
                [
                    data['Latitude'], data['Longitude'], data['Velocidade'],
                    data['Satelites'],
                    str(format_date(f"{data['Data']} {data['Hora']}"))
                ],
            )
            db.commit()
    return 'success'
Exemplo n.º 31
0
    def run(self):

        """
        While we could use the standard decorators to register these routes, 
        using add_url_rule() allows us to create diffrent endpoint names
        programmatically and pass the classes self object to the routes
        """

        loop = asyncio.get_event_loop()

        http_blueprint = Blueprint(__name__, 'http')
        http_blueprint.before_request(self.check_if_naughty)
        #http_blueprint.after_request(self.make_normal)

        http_blueprint.add_url_rule('/<uuid:GUID>', 'key_exchange', self.key_exchange, methods=['POST'])
        http_blueprint.add_url_rule('/<uuid:GUID>', 'stage', self.stage, methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs', 'jobs', self.jobs, methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs/<job_id>', 'job_result', self.job_result, methods=['POST'])

        # Add a catch all route
        http_blueprint.add_url_rule('/', 'unknown_path', self.unknown_path, defaults={'path': ''})
        http_blueprint.add_url_rule('/<path:path>', 'unknown_path', self.unknown_path, methods=['GET', 'POST'])

        self.app = Quart(__name__)

        logging.getLogger('quart.app').setLevel(logging.DEBUG if state.args['--debug'] else logging.ERROR)
        logging.getLogger('quart.serving').setLevel(logging.DEBUG if state.args['--debug'] else logging.ERROR)

        #serving_handler.setFormatter('%(h)s %(p)s - - %(t)s statusline: "%(r)s" statuscode: %(s)s responselen: %(b)s protocol: %(H)s')
        #logging.getLogger('quart.app').removeHandler(default_handler)

        self.app.register_blueprint(http_blueprint)
        self.app.run(host=self['BindIP'],
                     port=self['Port'],
                     debug=False,
                     use_reloader=False,
                     #access_log_format=,
                     loop=loop)
Exemplo n.º 32
0
    def run(self):

        #ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        #ssl_context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_COMPRESSION
        #ssl_context.set_ciphers('ECDHE+AESGCM')
        #ssl_context.load_cert_chain(, )
        #ssl_context.set_alpn_protocols(['http/1.1', 'h2'])

        if (self['Key'] == 'data/key.pem') and (self['Cert'] == 'data/cert.pem'):
            if not os.path.exists(self['Key']) or not os.path.exists(self['Cert']) or self['RegenCert']:
                create_self_signed_cert()

        """
        While we could use the standard decorators to register these routes, 
        using add_url_rule() allows us to create diffrent endpoint names
        programmatically and pass the classes self object to the routes
        """

        loop = asyncio.get_event_loop()

        http_blueprint = Blueprint(__name__, 'https')
        http_blueprint.before_request(self.check_if_naughty)
        #http_blueprint.after_request(self.make_normal)

        http_blueprint.add_url_rule('/<uuid:GUID>', 'key_exchange', self.key_exchange, methods=['POST'])
        http_blueprint.add_url_rule('/<uuid:GUID>', 'stage', self.stage, methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs', 'jobs', self.jobs, methods=['GET'])
        http_blueprint.add_url_rule('/<uuid:GUID>/jobs/<job_id>', 'job_result', self.job_result, methods=['POST'])

        # Add a catch all route
        http_blueprint.add_url_rule('/', 'unknown_path', self.unknown_path, defaults={'path': ''})
        http_blueprint.add_url_rule('/<path:path>', 'unknown_path', self.unknown_path, methods=['GET', 'POST'])

        self.app = Quart(__name__)

        logging.getLogger('quart.app').setLevel(logging.DEBUG if state.args['--debug'] else logging.ERROR)
        logging.getLogger('quart.serving').setLevel(logging.DEBUG if state.args['--debug'] else logging.ERROR)

        #serving_handler.setFormatter('%(h)s %(p)s - - %(t)s statusline: "%(r)s" statuscode: %(s)s responselen: %(b)s protocol: %(H)s')
        #logging.getLogger('quart.app').removeHandler(default_handler)

        self.app.register_blueprint(http_blueprint)
        self.app.run(host=self['BindIP'],
                     port=self['Port'],
                     debug=False,
                     #ssl=ssl_context,
                     certfile=self['Cert'],
                     keyfile=self['Key'],
                     use_reloader=False,
                     #access_log_format=,
                     loop=loop)