Exemple #1
0
import re

from flask import request
from flask_compress import Compress
from auslib.web.admin.views.validators import BalrogRequestBodyValidator
from raven.contrib.flask import Sentry

import connexion
import logging
log = logging.getLogger(__name__)

validator_map = {'body': BalrogRequestBodyValidator}

# TODO set debug=False after fully migrating all the admin APIs
connexion_app = connexion.App(__name__,
                              specification_dir='swagger/',
                              validator_map=validator_map,
                              debug=True)
connexion_app.add_api("api.yaml",
                      validate_responses=True,
                      strict_validation=True)
app = connexion_app.app
sentry = Sentry()

from auslib.web.admin.views.permissions import \
    PermissionScheduledChangesView, PermissionScheduledChangeView, \
    EnactPermissionScheduledChangeView, PermissionScheduledChangeHistoryView, \
    PermissionScheduledChangeSignoffsView
from auslib.web.admin.views.releases import ReleaseScheduledChangeHistoryView, \
    ReleaseScheduledChangeSignoffsView, \
    ReleaseScheduledChangesView, ReleaseScheduledChangeView, \
    EnactReleaseScheduledChangeView
Exemple #2
0
import os
import connexion
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

basedir = os.path.abspath(os.path.dirname(__file__))

# Create Connexion app instance
connex_app = connexion.App(__name__, specification_dir=basedir)

# Get underlying Flask app instance
app = connex_app.app

sqlite_url = "sqlite:///" + os.path.join(basedir, "people.db")

# Configure SQLAlchemy
app.config['SQLALCHEMY_ECHO'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = sqlite_url
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Create db instance
db = SQLAlchemy(app)

# Initialize Marshmallow
ma = Marshmallow(app)
Exemple #3
0
def get_connections_by_account(account_id, region, date=None):
    res = []
    if not date:
        date = flask.request.args.get('date')
    for conn, score in scan.get_stored_connections(account_id, region, date):
        src, dst = conn.split('->', 1)
        dst, dst_port = dst.rsplit(':', 1)
        dst_port = int(dst_port)
        res.append({
            'source': src,
            'dest': dst,
            'dest_port': dst_port,
            'score': score
        })
    return res


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)

    logging.getLogger(
        'botocore.vendored.requests.packages.urllib3.connectionpool').setLevel(
            logging.WARNING)
    # the following line is only needed for OAuth support
    api_args = {'tokeninfo_url': os.environ.get('HTTP_TOKENINFO_URL')}
    app = connexion.App(__name__, port=8080, debug=True, server='gevent')
    app.add_api('swagger.yaml', arguments=api_args)
    bg_thread = BackgroundThread()
    bg_thread.start()
    app.run()
Exemple #4
0
def main():
    app = connexion.App(__name__, specification_dir='./swagger/')
    app.app.json_encoder = encoder.JSONEncoder
    app.add_api('swagger.yaml', arguments={'title': 'NFVO Module Service'})
    app.run(port=8181)
from flask import g, render_template
import connexion

# Create the application instance
app = connexion.App(__name__, specification_dir="./")

# Read the swagger.yml file to configure the endpoints
app.add_api('swagger.yml')

# Create a URL route in our application for "/"
@app.route('/')
def home():
    """
    This function just responses to the brower URL localhost:5000

    :return:    the rendered template 'home.html
    """
    return render_template('home.html')

# If we're running in stand alone mode, run the application
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
Exemple #6
0
def configure(binder: Binder) -> Binder:
    binder.bind(
        ElasticSearchIndex,
        ElasticSearchIndex(
            ElasticSearchFactory(
                os.environ['ELASTICSEARCH_HOST'],
                os.environ['ELASTICSEARCH_PORT'],
            ), 'rooms', 'room', room_mapping))

    return binder


if __name__ == '__main__':
    # logging.basicConfig(level=logging.INFO, filename='app.log')
    app = connexion.App(__name__, specification_dir='swagger/')
    app.add_api('indexer.yaml', resolver=RestyResolver('api'))
    FlaskInjector(app=app.app, modules=[configure])
    handler = graypy.GELFHandler(os.environ['GRAYLOG_HOST'],
                                 int(os.environ['GRAYLOG_PORT']))
    # app.logger.addHandler(handler)
    logger = logging.getLogger('app')
    logger.setLevel(logging.INFO)
    logger.addHandler(handler)
    app.run(port=9090)

# if __name__ == '__main__':
#     app = connexion.App(__name__, specification_dir='swagger/')
#     app.add_api('app.yaml', resolver=RestyResolver('api'))
#     FlaskInjector(app=app.app, modules=[configure])
#     app.run(port=9090)
Exemple #7
0
def main():
    app = connexion.App(__name__, specification_dir='./swagger/')
    app.app.json_encoder = encoder.JSONEncoder
    app.add_api('swagger.yaml', arguments={'title': 'Upgrade server'})
    app.app.config.from_pyfile('config.cfg')
    app.run(port=8080)
Exemple #8
0
 def create_app(self):
     logging.getLogger('connexion.operation').setLevel('ERROR')
     app = connexion.App(__name__, specification_dir='../openapi/')
     app.app.json_encoder = JSONEncoder
     app.add_api('openapi.yaml', pythonic_params=True)
     return app.app
Exemple #9
0
# https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/#a-minimal-application
# https://dev.to/hackersandslackers/manage-database-models-with-flask-sqlalchemy-22n8
# https://testdriven.io/blog/developing-a-single-page-app-with-flask-and-vuejs/
# https://github.com/zalando/connexion

# from flask import Flask, request
# from flask_json import FlaskJSON, JsonError, json_response, as_json
from flask_cors import CORS
import connexion

from models import db, User, Shop, ShopInventory, Club, YTChannel

import time

app = connexion.App(__name__,
                    specification_dir='swagger/',
                    resolver=RestyResolver('api'))
app.add_api('fpv_db_api.yaml')

# config
app.config["DEBUG"] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'

# enable connexion

# enable FlaskJson
# FlaskJSON(app)
# enable CORS
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

Exemple #10
0
import requests

from flask import redirect, jsonify
import connexion
from flask_script import Manager

from thoth.common import SafeJSONEncoder
from thoth.common import init_logging
from thoth.storages import SolverResultsStore
import thoth_user_api

from .configuration import Configuration

# Expose for uWSGI.
app = connexion.App(__name__)
application = app.app
init_logging()
_LOGGER = logging.getLogger('thoth.user_api')

app.add_api(Configuration.SWAGGER_YAML_PATH)
application.json_encoder = SafeJSONEncoder
manager = Manager(application)
# Needed for session.
application.secret_key = Configuration.APP_SECRET_KEY


@app.route('/')
def base_url():
    """Redirect to UI by default."""
    return redirect('api/v1/ui')
Exemple #11
0
import json
import os
import connexion
from flask import Response
from sqlalchemy.orm.exc import NoResultFound

from seattle_flu_incidence_mapper.orm_config import setup_db
from seattle_flu_incidence_mapper.utils import set_marshmallow, ModelExecutionException

basedir = os.path.abspath(os.path.dirname(__file__))
true_vals = ['1', 'y', 'yes', 't', 'true']
# Create the Connexion application instance
connex_app = connexion.App("seattle_flu_incidence_mapper.config",
                           specification_dir=os.path.join(basedir, 'swagger'))

# Get the underlying Flask app instance
app = connex_app.app
app.config['WORKER_IMAGE'] = os.environ.get(
    'WORKER_IMAGE',
    'idm-docker-production.packages.idmod.org/sfim-worker:latest')
app.config['MODEL_STORE'] = os.environ.get(
    'MODEL_STORE',
    os.path.abspath(os.path.join(os.getcwd(), "../../test_model_store")))
app.config['MODEL_HOST_PATH'] = os.environ.get(
    'MODEL_HOST_PATH',
    os.path.abspath(os.path.join(os.getcwd(), "../../test_model_store")))

db = setup_db(basedir, app)
set_marshmallow(app)

# DO NOT MOVE this line. The order matters here
Exemple #12
0
'''
Server module, this can be used from the command line or via uWSGI
'''

import os

import connexion
import docopt

import mailscanner

PORT = os.environ.get('PORT', 5000)
DEBUG = os.environ.get('DEBUG', False)

SERVER_IN = os.path.dirname(os.path.abspath(__file__))
# WSGI module level variable
application = connexion.App(__name__, port=PORT, specification_dir=SERVER_IN)
application.add_api('api.yml')
mailscanner.server.replies.load_model_codec(
    os.path.join(SERVER_IN, '../../var/data/replies.weights'),
    os.path.join(SERVER_IN, '../../var/data/replies.pickle'))

if __name__ == '__main__':
    application.run(debug=DEBUG)
Exemple #13
0
"""
Main module of the server file
"""

# 3rd party moudles
from flask import render_template
import connexion

# Create the application instance
app = connexion.App(__name__,
                    specification_dir='./swagger',
                    template_folder="templates")

# read the swagger.yml file to configure the endpoints
app.add_api('swagger.yml')


# Create a URL route in our application for "/"
@app.route('/')
def home():
    """
    This function just responds to the browser URL
    localhost:5000/
    :return:        the rendered template "home.html"
    """
    return render_template("home.html")


if __name__ == '__main__':
    app.run(port=10000, debug=False)
Exemple #14
0
def app():
    app = connexion.App(__name__, specification_dir=SWG_DIR)
    app.add_api('openapi.yaml', arguments={'title': 'qg_api'}, pythonic_params=True)
    app.app.config['SQLALCHEMY_DATABASE_URI'] = QG_DB_URI
    # db.init_app(app.app)
    return app.app
Exemple #15
0
import connexion
import numpy as np
import os
import yaml
from flask import send_from_directory, redirect

from lstmdata.data_handler import LSTMDataHandler
import lstmdata.read_index as ri

__author__ = 'Hendrik Strobelt'

CONFIG_FILE_NAME = 'lstm.yml'
data_handlers = {}
index_map = {}

app = connexion.App(__name__, debug=False)


def get_context(**request):
    project = request['project']
    if project not in data_handlers:
        return 'No such project', 404
    else:
        dh = data_handlers[project]  # type: LSTMDataHandler

        # check if source is exists
        if not dh.is_valid_source(request['source']):
            return 'No valid source. Valid are: ' + ' -- '.join(
                dh.valid_sources()), 404

        # cell selection by bitmask vs. cell array
Exemple #16
0
import connexion
from flask_cors import CORS

from openapi_server import url_encoder

app = connexion.App(__name__, specification_dir='./openapi/')
app.add_api('openapi.yaml',
            arguments={'title': 'API: Shorten URL'},
            pythonic_params=True)
app.app.json_encoder = url_encoder.JSONEncoder
CORS(app.app)
def create_app(config_name, start_tasks=False, start_payload_tracker=False):
    connexion_options = {"swagger_ui": True}

    # This feels like a hack but it is needed.  The logging configuration
    # needs to be setup before the flask app is initialized.
    configure_logging(config_name)

    app_config = Config(RuntimeEnvironment.server)
    app_config.log_configuration(config_name)

    connexion_app = connexion.App("inventory",
                                  specification_dir="./swagger/",
                                  options=connexion_options)

    # Read the swagger.yml file to configure the endpoints
    with open("swagger/api.spec.yaml", "rb") as fp:
        spec = yaml.safe_load(fp)

    for api_url in app_config.api_urls:
        if api_url:
            connexion_app.add_api(
                spec,
                arguments={"title": "RestyResolver Example"},
                resolver=RestyResolver("api"),
                validate_responses=True,
                strict_validation=True,
                base_path=api_url,
            )
            logger.info("Listening on API: %s", api_url)

    # Add an error handler that will convert our top level exceptions
    # into error responses
    connexion_app.add_error_handler(InventoryException, render_exception)

    flask_app = connexion_app.app

    flask_app.config["SQLALCHEMY_ECHO"] = False
    flask_app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    flask_app.config["SQLALCHEMY_DATABASE_URI"] = app_config.db_uri
    flask_app.config["SQLALCHEMY_POOL_SIZE"] = app_config.db_pool_size
    flask_app.config["SQLALCHEMY_POOL_TIMEOUT"] = app_config.db_pool_timeout

    flask_app.config["INVENTORY_CONFIG"] = app_config

    db.init_app(flask_app)

    flask_app.register_blueprint(monitoring_blueprint,
                                 url_prefix=app_config.mgmt_url_path_prefix)

    @flask_app.before_request
    def set_request_id():
        threadctx.request_id = request.headers.get(REQUEST_ID_HEADER,
                                                   UNKNOWN_REQUEST_ID_VALUE)

    if start_tasks:
        init_tasks(app_config)
    else:
        logger.warning(
            "WARNING: The tasks subsystem has been disabled.  "
            "The message queue based event notifications have been disabled.")

    payload_tracker_producer = None
    if start_payload_tracker is False:
        # If we are running in "testing" mode, then inject the NullProducer.
        payload_tracker_producer = payload_tracker.NullProducer()

        logger.warning(
            "WARNING: Using the NullProducer for the payload tracker producer.  "
            "No payload tracker events will be sent to to payload tracker.")

    payload_tracker.init_payload_tracker(app_config,
                                         producer=payload_tracker_producer)

    # HTTP request metrics
    if config_name != "testing":
        PrometheusMetrics(
            flask_app,
            defaults_prefix="inventory",
            group_by="url_rule",
            path=None,
            excluded_paths=[
                "^/metrics$", "^/health$", "^/version$", r"^/favicon\.ico$"
            ],
        )

    return flask_app