Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rewrite developer server configuration and handler functions #34

Merged
merged 1 commit into from
Apr 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 22 additions & 20 deletions bin/fdbk-server
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
#!/usr/bin/env python3

import argparse
import json
import logging
import sys

try:
from flask_cors import CORS
cors_supported = True
except ImportError:
cors_supported = False

from fdbk.server import generate_app
from fdbk.utils import get_connection_argparser
from fdbk import __version__

def _generate_parser():
parser = argparse.ArgumentParser()
parser.add_argument("-c","--config-file",
help="configuration file path",
default="",
type=str)
parser = get_connection_argparser()
parser.add_argument("--cors",
help="allow cors requests",
action="store_true")
parser.add_argument("--host",
help="hosts to serve to (default = 0.0.0.0)",
default="0.0.0.0",
Expand All @@ -22,26 +26,24 @@ def _generate_parser():
help="port to serve from (default = 8080)",
default=8080,
type=int)
parser.add_argument("--no-front",
help="Disable serving CWD",
action="store_true")
parser.add_argument("-v", "--version",
help="Print package version",
action="store_true")
return parser

_args = _generate_parser().parse_args()
args = _generate_parser().parse_args()

if _args.version:
if args.version:
print(f"fdbk {__version__}")
sys.exit()

_serve_cwd = not _args.no_front
if not _args.config_file:
_config = None
else:
with open(_args.config_file, "r") as f:
_config = json.load(f)
_config["ServeCWD"] = _serve_cwd
if args.cors and not cors_supported:
print("To enable CORS, install flask_cors.")
sys.exit()

app = generate_app(args.db_connection, args.db_parameters, log_level=logging.INFO)

if args.cors and cors_supported:
CORS(app)

generate_app(config=_config, serve_cwd=_serve_cwd, log_level=logging.INFO).run(use_reloader=True, host=_args.host, port=_args.port, threaded=True)
app.run(use_reloader=True, host=args.host, port=args.port, threaded=True)
94 changes: 37 additions & 57 deletions fdbk/server/_server.py
Original file line number Diff line number Diff line change
@@ -1,72 +1,46 @@
import json
import logging
import os

from dateutil.parser import isoparse
from flask import Flask, request, send_from_directory
from flask import Flask, jsonify, request

from fdbk import utils
from fdbk.utils import create_db_connection
from ._server_handlers import ServerHandlers


def generate_app(config=None, serve_cwd=True, log_level=logging.WARN):
default_config = {
"DBConnection": "DictConnection",
"DBParameters": [],
"AllowedActions": [
"add_data",
"add_topic",
"get_comparison",
"get_data",
"get_latest",
"get_overview",
"get_summary",
"get_topics",
"get_topic"
],
"ServeCWD": serve_cwd
}

if not config:
config = default_config
elif isinstance(config, str):
with open(config, "r") as f:
config = json.load(f)
elif not isinstance(config, dict):
raise ValueError("Input configuration not recognized.")

static_folder = os.path.join(
os.getcwd(), "static") if config["ServeCWD"] else None
app = Flask(__name__, static_folder=static_folder)

db_connection = utils.create_db_connection(
config["DBConnection"], config["DBParameters"])

handlers = ServerHandlers(db_connection, config)
def generate_app(db_plugin, db_parameters, log_level=logging.WARN):
app = Flask(__name__)

db_connection = create_db_connection(
db_plugin, db_parameters)

handlers = ServerHandlers(db_connection)

app.logger.setLevel(log_level) # pylint: disable=no-member
app.logger.info('Created "' + # pylint: disable=no-member
config["DBConnection"] +
db_plugin +
'" with parameters: ' +
str(config["DBParameters"]))

# API
str(db_parameters))

if config["ServeCWD"]:
@app.route('/')
def index():
return send_from_directory(os.getcwd(), 'index.html')
def _jsonify(response):
data, code = response
return jsonify(data), code

@app.route('/topics', methods=['GET', 'POST'])
def topics():
if request.method == 'GET':
return handlers.get_topics(request.args.get('type'))
return _jsonify(handlers.get_topics(request.args.get('type')))
if request.method == 'POST':
return handlers.add_topic()
try:
json_in = request.get_json()
except BaseException:
return jsonify({
"error": "No topic data provided in request"
}), 404
return _jsonify(handlers.add_topic(json_in))

@app.route('/topics/<topic_id>', methods=['GET'])
def topics_get(topic_id):
return handlers.get_topic(topic_id)
return _jsonify(handlers.get_topic(topic_id))

def _parse_param(param, parser):
try:
Expand All @@ -77,32 +51,38 @@ def _parse_param(param, parser):
@app.route('/topics/<topic_id>/data', methods=['GET', 'POST'])
def data(topic_id):
if request.method == 'GET':
return handlers.get_data(
return _jsonify(handlers.get_data(
topic_id,
_parse_param(request.args.get('since'), isoparse),
_parse_param(request.args.get('until'), isoparse),
_parse_param(request.args.get('limit'), int))
_parse_param(request.args.get('limit'), int)))
if request.method == 'POST':
return handlers.add_data(topic_id)
try:
json_in = request.get_json()
except BaseException:
return jsonify({
"error": "No topic data provided in request"
}), 404
return _jsonify(handlers.add_data(topic_id, json_in))

@app.route('/topics/<topic_id>/data/latest', methods=['GET', 'POST'])
def latest(topic_id):
return handlers.get_latest(topic_id)
return _jsonify(handlers.get_latest(topic_id))

@app.route('/topics/<topic_id>/summary', methods=['GET'])
def summary(topic_id):
return handlers.get_summary(topic_id)
return _jsonify(handlers.get_summary(topic_id))

@app.route('/comparison/<topic_ids>', methods=['GET'])
def comparison(topic_ids):
return handlers.get_comparison(topic_ids)
return _jsonify(handlers.get_comparison(topic_ids))

@app.route('/comparison', methods=['GET'])
def comparison_all():
return handlers.get_comparison()
return _jsonify(handlers.get_comparison())

@app.route('/overview', methods=['GET'])
def overview():
return handlers.get_overview()
return _jsonify(handlers.get_overview())

return app
Loading