summaryrefslogtreecommitdiff
path: root/run.py
blob: 0ac5101484ee27a3c768e5cfc08fbf343c97c706 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python3
import os
import sys
import logging
from configparser import ConfigParser

from flask import Flask

from guard import application, model, proxyfix


def make_app(config):
    app = Flask("Guard")
    app.secret_key = config["Guard"]["Adminsecret"] + os.uname()[1]

    model.db.init(os.path.join(os.path.dirname(__file__), "db.sqlite"))
    model.db.connect()
    model.db.create_tables(filter(lambda t: not t.table_exists(), [model.Access]))

    log_format = "%(asctime)-15s %(levelname)s [%(module) 15s] %(message)s"
    if config["Guard"]["Debug"] == "true":
        logging.basicConfig(level=logging.INFO, format=log_format)
        logging.info("Running in DEBUG mode!")
    else:
        logging.basicConfig(level=logging.ERROR, format=log_format)
        logging.info("Running in production mode!")

    application.make_app(app, config["Guard"])

    app.wsgi_app = proxyfix.fix(app.wsgi_app)
    return app


def get_config(path: str = None) -> ConfigParser:
    config = ConfigParser()
    config["Guard"] = {
        'url': "http://localhost:8086/write",
        "port": "8001",
        "cookiename": "token",
        "adminsecret": "changeme",
        "gen_token_len": 22,
        "debug": "false",
    }
    if path is not None:
        config.read(path)
    return config


def start():
    if len(sys.argv) == 2:
        config = get_config(sys.argv[1])
        app = make_app(config)
        app.run(host="0.0.0.0", port=int(config["Guard"]["Port"]),
                debug=config["Guard"]["Debug"] == "true",
                use_reloader=config["Guard"]["Debug"] == "true")
    else:
        print("# {} >config.defaults.ini".format(sys.argv[0]))
        get_config().write(sys.stdout)
        sys.exit(1)


if __name__ == "__main__":
    start()
else:  # for running gunicorn3
    config = get_config('config')
    application = make_app(config)