Esempio n. 1
0
def create_app(config, debug=False, testing=False, config_overrides=None):
  """Application factory
  """
  # define the WSGI application object
  flask_app = Flask(__name__)

  # configuration
  flask_app.config.from_object(config)
  flask_app.debug = debug
  flask_app.testing = testing

  if config_overrides:
    flask_app.config.update(config_overrides)

  # initialize the database
  db.init_app(flask_app)

  # blueprints
  from app.users import users_blueprint
  flask_app.register_blueprint(users_blueprint)

  # flask-restful
  from app.users import UserListAPI, UserAPI

  api = Api(prefix='/api/v0')
  api.add_resource(UserListAPI, '/users', endpoint='users')
  api.add_resource(UserAPI, '/users/<id>', endpoint='user')

  api.init_app(flask_app)

  cors = CORS(resources={r'/api/*': {'origins': '*'}})
  cors.init_app(flask_app)

  return flask_app
Esempio n. 2
0
def create_app(config_filemane):
  """Application factory
  """
  # define the WSGI application object
  flask_app = Flask(__name__)

  # configuration
  flask_app.config.from_object(config_filemane)

  # initialize the database
  db.init_app(flask_app)

  # blueprints
  from app.users import users_blueprint
  from app.trips import trips_blueprint
  flask_app.register_blueprint(users_blueprint)
  flask_app.register_blueprint(trips_blueprint)

  # flask-restful
  from app.users import UserListAPI, UserAPI
  from app.trips import TripListAPI, TripAPI
  api = Api(prefix='/api/v0')
  api.add_resource(UserListAPI, '/users', endpoint='users')
  api.add_resource(UserAPI, '/users/<id>', endpoint='user')
  api.add_resource(TripListAPI, '/trips', endpoint='trips')
  api.add_resource(TripAPI, '/trips/<int:id>', endpoint='trip')
  api.init_app(flask_app)

  cors = CORS(resources={r'/api/v0/*': {'origins': '*'}})
  cors.init_app(flask_app)

  return flask_app
Esempio n. 3
0
def create_app(config):

    """A factory that returns an application object from the passed config.

    The factory accepts further configuration from ENV variables. Some simple
    checks for core configuration settings are made to raise errors early
    if vital information is missing.

    """

    import os
    from flask import Flask
    from flask.ext.babel import Babel
    from flask.ext.cors import CORS
    from flask.ext.markdown import Markdown
#    from flask.ext.assets import Environment, Bundle
    from .components import api, pages
    from .components.commons import context_processors, encoders

    app_label = 'web'

    # Get the static and template folder for the passed theme
    static_folder = os.path.join('theme', 'static')
    template_folder = os.path.join('theme', 'templates')

    # Construct app and service objects
    app = Flask(app_label, template_folder=template_folder,
                static_folder=static_folder, static_url_path='/static')
    trans = Babel()
    cors = CORS(resources=r'/api/*', allow_headers='Content-Type')
#    assets = Environment()

    # Configure the app with defaults
    app.config.from_object(config)

    # Set app core services
    trans.init_app(app)
    cors.init_app(app)
#    assets.init_app(app)
    Markdown(app)

    # Register routable components
    app.register_blueprint(api.blueprint)
    app.register_blueprint(pages.blueprint)

    # Set additional jinja2 extensions
    app.jinja_env.add_extension('jinja2.ext.do')

    # Set custom context processors
    app.context_processor(context_processors.inject_app_data)

    # Set custom encoders
    app.json_encoder = encoders.JSONEncoder

    # Register webassets bundles
#    sass = Bundle('css/base.scss', filters='pyscss', output='css/base.css')
#    assets.register('sass', sass)

    return app
Esempio n. 4
0
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 28 16:43:34 2016

@author: stefan
"""

from flask import Flask
from flask import request
import pandas as pd
import json
from sklearn.neighbors import BallTree
from sklearn import preprocessing
from flask.ext.cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

winger = ['AM(R)','AM(L)','F(R)','F(L)','M(R)','M(L)']
gf = ['AM(R)','AM(L)','AM(C)','F(R)','F(L)','F(C)']
target = ['F(C)']
dlf = ['AM(R)','AM(L)','AM(C)','F(R)','F(L)','F(C)']
aplay = ['AM(R)','AM(L)','AM(C)']
play = ['M(C)','AM(C)']
stopper = ['D(C)']
bwm = ['DM(C)','M(C)']
btb = ['DM(C)','M(C)','AM(C)','M(R)','M(L)']
gm = ['M(C)']
wf = ['AM(R)','AM(L)','F(R)','F(L)','F(C)']
fb = ['D(R)','D(L)','D(C)','DM(R)','DM(L)']
bpd = ['D(R)','D(L)','D(C)']
Esempio n. 5
0
from os import environ

import requests
from flask import Flask
from flask.ext.cors import CORS
from flask.json import jsonify

app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
# You can get API_KEY from here: https://www.explara.com/a/account/manage/app-settings
# Your API_KEY = '<YourKeyHere>'
API_KEY = environ['API_KEY']
TICKETS_URL = 'https://www.explara.com/api/e/get-tickets'
# EVENT_ID you can get via this request: https://www.explara.com/api/e/get-all-events
EVENT_ID = environ['EVENT_ID']


@app.route('/api/tickets-left/')
def get_remaining_tickets_count():
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': "Bearer %s" % API_KEY
    }
    payload = {'eventId': EVENT_ID}
    response = requests.post(TICKETS_URL, data=payload, headers=headers)
    data = response.json()
    try:
        data_response = {'tickets_left': data["tickets"][0]["quantity"]}
    except KeyError:
        return jsonify(**data)
    return jsonify(**data_response)
import stinger.stinger_net as sn
import stinger.stinger_core as sc

# Value of -1 in either field disables its use as a threshold
TIMEOUT_SECS = 1
BATCH_THRESHOLD = -1

application = Flask(__name__)
api = Api(
    application,
    version='1.1',
    title='STINGER API',
    description='An API to interface with the STINGER graph database',
)
cors = CORS(application)


@api.route('/insert', endpoint='insert')
class Insert(Resource):
    edge = api.model(
        'Edge', {
            'src': fields.String(required=True, description='Source vertex'),
            'dest': fields.String(required=True,
                                  description='Destination vertex'),
            'type': fields.String(required=False, description='Edge type'),
            'weight': fields.Integer(required=False,
                                     description='Edge weight'),
            'time': fields.Integer(required=False, description='Timestamp')
        })
    edgesSpec = api.model(
Esempio n. 7
0
def create_app():
    """
    Create the api as it's own app so that it's easier to scale it out on it's
    own in the future.

    :return:         A flask object/wsgi callable.
    """
    import cf_deployment_tracker
    from bluemix_service_discovery.service_publisher import ServicePublisher
    from server.config import Config
    from os import environ as env
    from server.exceptions import APIException
    from server.web.utils import request_wants_json
    from server.web.rest.root import root_v1_blueprint
    from server.web.rest.demos import demos_v1_blueprint, setup_auth_from_request
    from server.web.rest.shipments import shipments_v1_blueprint
    from server.web.rest.distribution_centers import distribution_centers_v1_blueprint
    from server.web.rest.retailers import retailers_v1_blueprint
    from server.web.rest.products import products_v1_blueprint

    # Emit Bluemix deployment event
    cf_deployment_tracker.track()

    # Create the app
    logistics_wizard = Flask('logistics_wizard', static_folder=None)
    CORS(logistics_wizard,
         origins=[re.compile('.*')],
         supports_credentials=True)
    if Config.ENVIRONMENT == 'DEV':
        logistics_wizard.debug = True

    # Register the blueprints for each component
    logistics_wizard.register_blueprint(root_v1_blueprint,
                                        url_prefix='/api/v1')
    logistics_wizard.register_blueprint(demos_v1_blueprint,
                                        url_prefix='/api/v1')
    logistics_wizard.register_blueprint(shipments_v1_blueprint,
                                        url_prefix='/api/v1')
    logistics_wizard.register_blueprint(distribution_centers_v1_blueprint,
                                        url_prefix='/api/v1')
    logistics_wizard.register_blueprint(retailers_v1_blueprint,
                                        url_prefix='/api/v1')
    logistics_wizard.register_blueprint(products_v1_blueprint,
                                        url_prefix='/api/v1')

    logistics_wizard.before_request(setup_auth_from_request)

    def exception_handler(e):
        """
        Handle any exception thrown in the interface layer and return
        a JSON response with the error details. Wraps python exceptions
        with a generic exception message.

        :param e:  The raised exception.
        :return:   A Flask response object.
        """
        if not isinstance(e, APIException):
            exc = APIException(u'Server Error', internal_details=unicode(e))
        else:
            exc = e
        current_app.logger.error(exc)
        return Response(json.dumps(compose_error(exc, e)),
                        status=exc.status_code,
                        mimetype='application/json')

    def not_found_handler(e):
        current_app.logger.exception(e)
        if request_wants_json():
            status_code = 404
            return Response(json.dumps({
                'code': status_code,
                'message': 'Resource not found.'
            }),
                            status=status_code,
                            mimetype='application/json')
        else:
            # TODO: Default to the root web page
            # return index()
            pass

    def bad_request_handler(e):
        current_app.logger.exception(e)
        status_code = 400
        return Response(json.dumps({
            'code': status_code,
            'message': 'Bad request.'
        }),
                        status=status_code,
                        mimetype='application/json')

    # Register error handlers
    logistics_wizard.errorhandler(Exception)(exception_handler)
    logistics_wizard.errorhandler(400)(bad_request_handler)
    logistics_wizard.errorhandler(404)(not_found_handler)

    # Register app with Service Discovery and initiate heartbeat cycle if running in PROD
    if Config.SD_STATUS == 'ON' and env.get('VCAP_APPLICATION') is not None:
        from signal import signal, SIGINT, SIGTERM
        from sys import exit

        # Create service publisher and register service
        creds = json.loads(
            env['VCAP_SERVICES'])['service_discovery'][0]['credentials']
        publisher = ServicePublisher(
            'lw-controller',
            300,
            'UP',
            json.loads(env['VCAP_APPLICATION'])['application_uris'][0],
            'http',
            tags=[
                'logistics-wizard', 'front-end', env['LOGISTICS_WIZARD_ENV']
            ],
            url=creds['url'],
            auth_token=creds['auth_token'])
        publisher.register_service(True)

        # Set up exit handlers for gracefully killing heartbeat thread
        def exit_app(*args):
            deregister_app(publisher)
            exit(0)

        signal(SIGTERM, exit_app)
        signal(SIGINT, exit_app)
        atexit.register(destroy_app, publisher)

    return logistics_wizard
Esempio n. 8
0
import os, sys
import json

from flask import Flask, Response
from flask import request, jsonify

from flask.ext.cors import CORS, cross_origin

app = Flask(__name__)
cors = CORS(app, resources={r"/response": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'
app.config["DEBUG"] = True


class DataStorage(object):
    def __init__(self, filename='reponses.jsons'):
        self.filename = filename

    def appendResponse(self, response):
        with open(self.filename, 'a') as fl:
            fl.write('{}\n'.format(json.dumps(response)))


DS = DataStorage()


@app.route('/response', methods=['POST'])
@cross_origin(origin='*',
              headers=['access-control-allow-origin', 'Content-Type'])
def collect_response():
    resp = json.loads(request.data)
Esempio n. 9
0
from os import environ

from flask import Flask

app = Flask(__name__)
app.debug = bool(environ.get('DEBUG'))
app.config.from_object('config')

from flask.ext.cors import CORS
CORS(app, resources={r"/*": {"origins": "*"}}, allow_headers=['X-Requested-With', 'Content-Type', 'Authorization', 'user-aws-key', 'Accept', 'Access-Control-Allow-Origin'])

from views.swagger import swagger_bp
from views.user_management import user_management_bp
from app.views.aws.account_management import aws_account_management_bp
from app.views.aws.cost.cost import aws_cost_cost_bp
from app.views.aws.cost.stats import aws_cost_stats_bp
from app.views.aws.forecast import aws_forecast_bp
from app.views.aws.usage import aws_usage_bp
from views.google import google_bp
from views.ms_azure import ms_azure_bp
from views.compare_providers import compare_providers_bp
import views.health

app.register_blueprint(swagger_bp)
app.register_blueprint(user_management_bp)
app.register_blueprint(aws_account_management_bp)
app.register_blueprint(aws_cost_cost_bp)
app.register_blueprint(aws_cost_stats_bp)
app.register_blueprint(aws_forecast_bp)
app.register_blueprint(aws_usage_bp)
app.register_blueprint(google_bp)
Esempio n. 10
0
CORS(app,
     resources={
         r"/capturarVuelo": {
             "origins": "*"
         },
         r"/guardarWaypoints": {
             "origins": "*"
         },
         r"/guardarBlanco": {
             "origins": "*"
         },
         r"/guardarNegro": {
             "origins": "*"
         },
         r"/capturarNegro": {
             "origins": "*"
         },
         r"/capturarBlanco": {
             "origins": "*"
         },
         r"/crearMision": {
             "origins": "*"
         },
         r"/conectarDron": {
             "origins": "*"
         },
         r"/calibrar": {
             "origins": "*"
         },
         r"/enviarAltitudVelocidad": {
             "origins": "*"
         },
         r"/login": {
             "origins": "*"
         }
     })
Esempio n. 11
0
from flask import request
import os
import signal
import copy
import websites
from scrader_logger import LOG
import mongo
import utils
import socket

DEBUG = False  # Enable this to print python crashes and exceptions

app = flask.Flask(__name__, static_url_path='/static')

# Make cross-origin AJAX possible (for all domains on all routes)
CORS(app, resources={r"*": {"origins": "*"}})

NEXT = 0


@app.route('/scrader/companies/<user_id>'.format(methods=['GET']))
def get_companies_html(user_id):
    """ GET Server Status API endpoint
        Args:
        Returns:
            dict: A JSON object containing the nfvacc server status information
    """
    first_name = "None"
    user = mongo.find_one_match('users', {"user_id": user_id})
    if user is not None:
        last_name = user.get('name')
Esempio n. 12
0
from flask import Flask
from flask.ext.cors import CORS
from flask_restful import Resource, Api
from resources.home import Home
from resources.socket import Socket

app = Flask(__name__)
api = Api(app)
app.config.from_pyfile('config.cfg')

cors = CORS(app,
            resources={r"/socket/*": {
                "origins": app.config['CORS_ORIGINS']
            }})

# Add resources
api.add_resource(Home, '/')
api.add_resource(Socket, '/socket/<string:socketNumber>/<string:socketState>')

if __name__ == '__main__':
    app.run(host=app.config['HOST'],
            port=app.config['PORT'],
            debug=app.config['DEBUG'])
Esempio n. 13
0
app.permanent_session_lifetime = timedelta(minutes=15)
app.config['WTF_CSRF_ENABLED'] = False
app.config['LOGGER_NAME'] = 'st'
app.config['SESSION_COOKIE_NAME'] = 'st'
app.config['SESSION_TYPE'] = 'sqlalchemy'
app.config['SESSION_PERMANENT'] = True
app.config['SESSION_SQLALCHEMY_TABLE'] = 'sessions'
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

Session(app)

CORS(app,
     resources=r'*',
     headers=[
         'Content-Type', 'Authorization', 'Access-Control-Allow-Credentials',
         'Access-Control-Allow-Origin'
     ],
     supports_credentials=True)

app.register_blueprint(pg, url_prefix='/sync')

root_dir = os.path.dirname(os.path.abspath(__file__))
static_dir = os.path.join(root_dir, 'app/static')
app.config['UPLOADED_DEFAULTS_DEST'] = os.path.join(static_dir,
                                                    'uploads/defaults')
default_uploader = UploadSet('defaults', DEFAULTS)
configure_uploads(app, default_uploader)


@app.route('/')
Esempio n. 14
0
log.setLevel(logging.DEBUG) if config.DEBUG else log.setLevel(logging.INFO)
fh = logging.StreamHandler(sys.stdout)
fh.setLevel(logging.DEBUG) if config.DEBUG else fh.setLevel(logging.INFO)
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
log.addHandler(fh)

## create object db_connector
db = db_connector.DbConnector('rapni')

### Some initialization
app = Flask(__name__)
api = Api(app)
cors = CORS(app, resources={r"/*": {"origins": config.ALLOWED_CORS_DOMAINS}})
auth = HTTPBasicAuth()

parser = reqparse.RequestParser()
parser.add_argument('data', type=str)

## RESTful APP
##


## This is a generic resource class for this API
## providing the main method behaviour
##
class IdsResource(Resource):
    """ The generic resource class for the API:
    /resource/<identifier>
Esempio n. 15
0
# coding: utf-8

from __future__ import (print_function, unicode_literals, absolute_import)

from flask import Flask
from flask.ext.mongoengine import MongoEngine
from flask.ext.cors import CORS
from flask.ext.cache import Cache

app = Flask(__name__)
app.config.from_object('app.settings')

enable_cors = app.config.get("ENABLE_CORS", False)
if enable_cors:
    CORS(app, resources={
        r"/properties/*": {
            "origins": "*"
        },
    })

db = MongoEngine(app)
cache = Cache(config={"CACHE": app.config.get("CACHE_TYPE")})
cache.init_app(app)

from app.resources import properties

app.register_blueprint(properties.blueprint)
Esempio n. 16
0
#!/usr/bin/python
# -*- coding:utf-8 -*-
from flask.ext.login import LoginManager
from flask.ext.mail import Mail
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.pagedown import PageDown
from flask.ext.cors import CORS
from flask.ext.bootstrap import Bootstrap
import logging

mail = Mail()

db = SQLAlchemy()

pagedown = PageDown()

bootstrap = Bootstrap()

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'

cors = CORS()
logging.getLogger('flask_cors').level = logging.DEBUG
Esempio n. 17
0
    from flask.ext.cors import CORS, cross_origin
except ImportError:
    # Path hack allows examples to be run without installation.
    import os
    parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    os.sys.path.insert(0, parentdir)

    from flask.ext.cors import CORS, cross_origin

app = Flask(__name__)

# Set CORS options on app configuration
app.config['CORS_HEADERS'] = "Content-Type"
app.config['CORS_RESOURCES'] = {r"/api/*": {"origins": "*"}}

cors = CORS(app)

## Equivalent to (but using both is not advised)
cors = CORS(app,
            resources={r"/api/*": {
                "origins": "*"
            }},
            headers="Content-Type")


@app.route("/")
def helloWorld():
    '''
        Since the path '/' does not match the regular expression r'/api/*',
        this route does not have CORS headers set.
    '''
Esempio n. 18
0
#!/usr/env/bin python

import os

from flask import Flask, g, render_template
from flask.ext.misaka import Misaka
from lib import db, filters
from themes import themes

from flask.ext.cors import CORS

theme = os.environ.get('THEME', 'new')
blog = Flask(__name__,
             static_folder=themes[theme]['static'],
             template_folder=themes[theme]['templates'])
CORS(blog)
Misaka(blog, tables=True)

blog.config['FREEZER_RELATIVE_URLS'] = True
blog.config['MONGODB_DATABASE_URI'] = 'mongodb://localhost:27017'
blog.config['BASE_DIR'] = os.path.abspath(os.path.dirname(__file__))

blog.jinja_env.filters['human_readable_date'] = filters.human_readable_date
blog.jinja_env.filters['clean_date'] = filters.clean_date
blog.jinja_env.filters['urlencode'] = filters.urlencode
blog.jinja_env.filters['urldecode'] = filters.urldecode
blog.jinja_env.filters['md'] = filters.md

blog.secret_key = 'test'

def main():
    # Parse command line arguments
    parser = argparse.ArgumentParser(description='Run all modules defined for '
                                     'this system')
    parser.add_argument('--verbose', '-v', action='count', default=0)
    parser.add_argument('--log', default=None)
    args = parser.parse_args()

    # Configure logging
    logger = logging.getLogger("openag_brain")
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        "%(levelname)s %(asctime)s (%(name)s): %(message)s")
    stream_log_level = max(10, 30 - 10 * args.verbose)
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(formatter)
    stream_handler.setLevel(stream_log_level)
    logger.addHandler(stream_handler)
    if args.log:
        file_handler = logging.FileHandler(args.log)
        file_handler.setFormatter(formatter)
        file_handler.setLevel(min(logging.INFO, stream_log_level))
        logger.addHandler(file_handler)

    # Connect to the databases
    module_db = db_server[DbName.MODULE]
    module_type_db = db_server[DbName.MODULE_TYPE]
    module_connection_db = db_server[DbName.MODULE_CONNECTION]
    env_data_db = db_server[DbName.ENVIRONMENTAL_DATA_POINT]

    # Construct all of the modules
    for mod_id in module_db:
        if mod_id.startswith('_'):
            continue
        mod_info = ModuleModel.load(module_db, mod_id)
        mod_type_info = ModuleTypeModel.load(module_type_db, mod_info.type)
        package_path, class_name = mod_type_info._id.split(':')
        py_mod = import_module(package_path)
        mod_class = getattr(py_mod, class_name)
        mod = mod_class(mod_id)

    # Initialize all of the modules
    for mod_id in module_db:
        if mod_id.startswith('_'):
            continue
        mod_info = ModuleModel.load(module_db, mod_id)
        mod = Module.get_by_id(mod_id)
        params = mod_info.parameters
        for arg_name in mod.init.__code__.co_varnames[1:mod.init.__code__.
                                                      co_argcount]:
            annotation = mod.init.__annotations__.get(arg_name, '')
            if isinstance(annotation, Parameter) and arg_name in params:
                params[arg_name] = annotation.encode(params[arg_name])
        mod.init(**mod_info.parameters)

    # Hook up all of the connections
    for mod_conn_id in module_connection_db:
        if mod_conn_id.startswith('_'):
            continue
        mod_conn = ModuleConnectionModel.load(module_connection_db,
                                              mod_conn_id)
        output_module = Module.get_by_id(mod_conn.output_module)
        input_module = Module.get_by_id(mod_conn.input_module)
        output = getattr(output_module, mod_conn.output_name)
        input = getattr(input_module, mod_conn.input_name)
        output.output_to(input)

    # Run all of the modules
    threads = []
    for mod_id in module_db:
        if mod_id.startswith('_'):
            continue
        mod = Module.get_by_id(mod_id)
        mod.start()
    logger.info("Running {} modules".format(len(module_db)))

    # Create and run a Flask app for calling endpoints
    app = Flask(__name__)
    # Set cross-origin headers
    CORS(app)
    app.debug = True

    mod_id = uuid4().hex
    while Module.get_by_id(mod_id):
        mod_id = uuid4().hex
    app.mod = Module(mod_id)
    app.mod.start()

    def find_recipe_start(env_data_db, env_id):
        """Given a pointer to the environmental data point db, return the
        latest recipe start for a given environment.
        returns a Dict or None.
        """
        # Query latest view with key (requires this design doc to exist)
        recipe_start_view = env_data_db.view(
            'openag/latest',
            key=[env_id, EnvironmentalVariable.RECIPE_START, 'desired'])
        recipe_end_view = env_data_db.view(
            'openag/latest',
            key=[env_id, EnvironmentalVariable.RECIPE_END, 'desired'])
        # Collect results of iterator (ViewResult has no next method).
        recipe_starts = [recipe_start for recipe_start in recipe_start_view]
        recipe_ends = [recipe_end for recipe_end in recipe_end_view]
        # Narrow list of results down to one and unbox the value
        recipe_start = recipe_starts[0].value if len(recipe_starts) else None
        recipe_end = recipe_ends[0].value if len(recipe_ends) else None

        # If we have a recipe_end, check that it is older than the latest
        # recipe_start
        if recipe_start and recipe_end and recipe_start[
                "timestamp"] > recipe_end["timestamp"]:
            return recipe_start
        # If we don't have a recipe end, but do have a recipe_start, return it.
        elif recipe_start:
            return recipe_start
        else:
            return None

    def find_env_recipe_handler_id(module_db, env_id):
        """Find ID of recipe handler that is running in current environment.
        Returns ID or None.
        """
        recipe_type = 'openag.brain.modules.recipe_handler:RecipeHandler'
        module_view = module_db.view('openag/by_type')

        recipe_handler_ids = [
            module.id for module in module_view if module.key == recipe_type
        ]

        return recipe_handler_ids[0] if len(recipe_handler_ids) > 0 else None

    @app.route("/api/{v}/module/<mod_id>/<endpoint>".format(v=API_VER),
               methods=['POST'])
    def serve_endpoint(mod_id, endpoint):
        return getattr(app.mod.ask(mod_id), endpoint)(**request.json)

    @app.route("/api/{v}/environment/<env_id>".format(v=API_VER),
               methods=['GET'])
    def serve_environment(env_id):

        recipe_handler_id = find_env_recipe_handler_id(module_db, env_id)
        recipe_start = find_recipe_start(env_data_db, env_id)
        recipe_id = recipe_start["value"] if recipe_start else None
        recipe_start_timestamp = recipe_start[
            "timestamp"] if recipe_start else None

        return jsonify(env_id=env_id,
                       recipe_id=recipe_id,
                       recipe_start_timestamp=recipe_start_timestamp,
                       recipe_handler_id=recipe_handler_id)

    http_server = WSGIServer(('', 5000), app)
    logger.info("Listening for requests on http://localhost:5000/")
    http_server.serve_forever()
Esempio n. 20
0
import grp
import sys

from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
import geventwebsocket
import websocket

import settings
from emulator import Emulator
from uuid import uuid4, UUID
import logging
import atexit

app = Flask(__name__)
cors = CORS(app, headers=["X-Requested-With", "X-CSRFToken", "Content-Type"], resources="/qemu/*")
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s %(asctime)s: %(message)s")

emulators = {}

@app.route('/qemu/launch', methods=['POST'])
def launch():
    if request.headers.get('authorization', None) != settings.LAUNCH_AUTH_HEADER:
        abort(403)
    if len(emulators) >= settings.EMULATOR_LIMIT:
        abort(503)
    uuid = uuid4()
    if '/' in request.form['platform'] or '/' in request.form['version']:
        abort(400)
    emu = Emulator(
        request.form['token'],
Esempio n. 21
0
from flask.ext.mongoengine import MongoEngine
from flask.ext.login import LoginManager
from flask.ext.cache import Cache
from flask.ext.bcrypt import Bcrypt
from flask.ext.cors import CORS
from flask.ext.mail import Mail, Message
from celery import Celery

app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {"DB": "tumblelog"}
app.config["SECRET_KEY"] = "KeepThisS3cr3t"
app.config["CACHE_TYPE"] = "simple"
CORS(app,
     resources={r'/api/*': {
         "origins": "*"
     }},
     allow_headers=[
         'Authorization', 'Content-Type', 'Access-Control-Allow-Origin'
     ])

app.config.update(
    DEBUG=True,
    #EMAIL SETTINGS
    MAIL_SERVER='smtp.gmail.com',
    MAIL_PORT=587,
    MAIL_USE_TLS=True,
    MAIL_USE_SSL=False,
    MAIL_USERNAME='******',
    MAIL_PASSWORD='******')

flask_mail = Mail(app)
Esempio n. 22
0
    def run(self):
        ''' Run flask app'''
        app = Flask(__name__)
        CORS(app, resources={r"/prediction/*": {"origins": "*"}})
        self.app = app

        @app.route('/dist/<path:path>')
        def static_file_dist(path):
            return open("ui/dist/" + path).read()

        @app.route('/large/<path:path>')
        def static_file_large(path):
            return open("ui/large/" + path, 'rb').read()

        @app.route('/')
        def home():
            # Inject game data into HTML
            board_init = 'initialBoard = ""'  # backup variable
            board = {}
            for row in range(19):
                board_row = {}
                for col in range(19):
                    # Get the cell value
                    cell = str(self.bot.go_board.board.get((col, row)))
                    # Replace values with numbers
                    # Value will be be 'w' 'b' or None
                    cell = cell.replace("None", "0")
                    cell = cell.replace("b", "1")
                    cell = cell.replace("w", "2")
                    # Add cell to row
                    board_row[col] = int(cell)  # must be an int
                # Add row to board
                board[row] = board_row
            board_init = str(board)  # lazy convert list to JSON

            return open("ui/demoBot.html").read().replace(
                '"__i__"', 'var boardInit = ' +
                board_init)  # output the modified HTML file

        @app.route('/sync', methods=['GET', 'POST'])
        def exportJSON():
            export = {}
            export["hello"] = "yes?"
            return jsonify(**export)

        @app.route('/prediction', methods=['GET', 'POST'])
        def next_move():
            '''Predict next move and send to client.

            Parses the move and hands the work off to the bot.
            '''
            content = request.json
            col = content['i']
            row = content['j']
            print('Received move:')
            print((col, row))
            self.bot.apply_move('b', (row, col))

            bot_row, bot_col = self.bot.select_move('w')
            print('Prediction:')
            print((bot_col, bot_row))
            result = {'i': bot_col, 'j': bot_row}
            json_result = jsonify(**result)
            return json_result

        self.app.run(host='0.0.0.0',
                     port=self.port,
                     debug=True,
                     use_reloader=False)
Esempio n. 23
0
def create_application(config, log_filename='rest_server.log'):
    '''
    Creates the flask application and database.

    Using a function to avoid using global variables.

    :param BaseConfig config:
        One configuration object.

    :param str log_filename:
        The file to generate log messages.
        If None do not generate log file.

    :return tuple(Flask, SqlAlchemy):
        Returns the flask application and sql-alchemy database.
    '''
    from flask import Flask
    from flask.ext.sqlalchemy import SQLAlchemy
    from flask.ext.cors import CORS
    import flask.ext.restless
    from logging.handlers import RotatingFileHandler
    import logging

    app = Flask(__name__)

    # Logging
    if log_filename is not None:
        handler = RotatingFileHandler(log_filename,
                                      maxBytes=10000,
                                      backupCount=1)
        handler.setLevel(logging.INFO)
        app.logger.addHandler(handler)

    # Enable different origin to access the REST API.
    cors = CORS(app)

    app.config.from_object(config)

    db = SQLAlchemy(app)

    # Define the Task model. The actual database is defined by the application configuration object
    # (SQLALCHEMY_DATABASE_URI).
    class Task(db.Model):

        __tablename__ = "tasks"

        id = db.Column(db.Integer, primary_key=True, autoincrement=True)
        task = db.Column(db.String(255), unique=True, nullable=False)
        done = db.Column(db.Boolean, nullable=False, default=False)

        def __init__(self, task, done=False, id=None):
            self.id = id
            self.task = task
            self.done = done

    class RestLogger(object):
        """
        Generates log messages by handling pre/post processors for restless api.
        """
        def __init__(self, logger, message, getter=lambda x: x):
            self.__logger = logger
            self.__message = message
            self.__getter = getter

        def __call__(self, **kwargs):
            try:
                values = self.__getter(kwargs)
                message = self.__message.format(**values)
            except Exception:
                message = "Error formating log message with:\n  * message: {}\n  * keys: {}".format(
                    self.__message, [i for i in values.keys()])
            self.__logger.info(message)

    # RESTless automatically creates the REST API based in a Model. Changes the defaults valus to match the required
    # API.
    restless_manager = flask.ext.restless.APIManager(app,
                                                     flask_sqlalchemy_db=db)
    blueprint = restless_manager.create_api_blueprint(
        Task,
        methods=('GET', 'POST', 'DELETE', 'PATCH'),
        url_prefix='',
        collection_name='task',
        allow_delete_many=True,
        preprocessors={
            'DELETE_SINGLE':
            [RestLogger(app.logger, "Deleting {instance_id}")],
            'DELETE_MANY': [RestLogger(app.logger, "Deleting all!")],
        },
        postprocessors={
            'POST': [
                RestLogger(app.logger,
                           "Adding \"{task}\"",
                           getter=lambda x: x['result'])
            ],
            'PATCH_SINGLE': [
                RestLogger(app.logger,
                           "Editing {id}",
                           getter=lambda x: x['result'])
            ],
        })
    app.register_blueprint(blueprint)

    return app, db
Esempio n. 24
0
from flask.ext.cache import Cache
from flask_sslify import SSLify
from moztelemetry.histogram import Histogram
from joblib import Parallel, delayed
from functools import wraps
from gevent.monkey import patch_all
from psycogreen.gevent import patch_psycopg
from psycopg2.pool import SimpleConnectionPool
from aggregator import simple_measures_labels, count_histogram_labels
from db import get_db_connection_string, histogram_revision_map

pool = None
app = Flask(__name__)
app.config.from_object('config')

CORS(app, resources=r'/*', allow_headers='Content-Type')
cache = Cache(app, config={'CACHE_TYPE': app.config["CACHETYPE"]})
sslify = SSLify(app, skips=['status'])

patch_all()
patch_psycopg()
cache.clear()


def cache_request(f):
    @wraps(f)
    def decorated_request(*args, **kwargs):
        rv = cache.get(request.url)
        if rv is None:
            rv = f(*args, **kwargs)
            cache.set(request.url, rv, timeout=app.config["TIMEOUT"])
Esempio n. 25
0
from newapp import get_model
from flask import Blueprint, render_template

from flask.ext.cors import CORS

appview = Blueprint('appview', __name__)
CORS(appview)


@appview.route("/")
def home():
    return render_template("home.html")
Esempio n. 26
0
#from mysql.connector import (connection)
import MySQLdb
import json
import sys
import urllib2
from crossdomain import crossdomain
from flask.ext.cors import CORS, cross_origin
from xml.etree import cElementTree as ET

app.config[
    'SQLALCHEMY_DATABASE_URI'] = 'mysql://*****:*****@websys3/websysS16GB6'
db = SQLAlchemy(app)

cors = CORS(app,
            resources={r"/*": {
                "origins": "*"
            }},
            supports_credentials=True)
app.config['CORS_HEADERS'] = 'Content-Type'
#@cross_origin(origin='*',headers=['Content-Type','Authorization'])

lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'


@lm.user_loader
def load_user(id):
    return User.query.get(int(id))

Esempio n. 27
0
from boto.mturk.connection import MTurkConnection
from celery import Celery
import redis

app = Flask(__name__)

app.config.from_object(os.environ['APP_SETTINGS'])

api = Api(app)

app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app,
            resources={
                "/taboo": {
                    "origins": "*"
                },
                "/train": {
                    "origins": "*"
                }
            })

print "Loading mail extension"
sys.stdout.flush()
mail = Mail(app)

print "Loading redis and mongo"

#print "Flush the cache"
app.redis = redis.Redis.from_url(app.config['REDIS_URL'])
#app.redis.flushdb()
Esempio n. 28
0
from flask.ext.cors import CORS

app = Flask(__name__)

if settings.USE_SENTRY:
    app.config['SENTRY_DSN'] = settings.SENTRY_DSN
    sentry = Sentry(app)

try:
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + settings.DB_PATH
except AttributeError:
    app.config['SQLALCHEMY_DATABASE_URI'] = settings.ALCHEMY_URL

api = Api(app)
db = SQLAlchemy(app)
cors = CORS(app, supports_credentials=True)

json_parser = reqparse.RequestParser()
json_parser.add_argument('criticality',
                         type=int,
                         required=True,
                         location='json')
json_parser.add_argument('unix_timestamp',
                         type=int,
                         required=True,
                         location='json')
json_parser.add_argument('category',
                         type=unicode,
                         required=True,
                         location='json')
json_parser.add_argument('description',
Esempio n. 29
0
from jormungandr import compat, utils
import six

app = Flask(__name__)
app.config.from_object('jormungandr.default_settings')
if 'JORMUNGANDR_CONFIG_FILE' in os.environ:
    app.config.from_envvar('JORMUNGANDR_CONFIG_FILE')

# there is a import order problem to get this variable in decorators (current_app is not in the context)
# so we make it a global variable
USE_SERPY = app.config.get('USE_SERPY')

app.request_class = NavitiaRequest
CORS(app,
     vary_headers=True,
     allow_credentials=True,
     send_wildcard=False,
     headers=['Access-Control-Request-Headers', 'Authorization'])
app.config['CORS_HEADERS'] = 'Content-Type'

if 'LOGGER' in app.config:
    logging.config.dictConfig(app.config['LOGGER'])
else:  # Default is std out
    handler = logging.StreamHandler(stream=sys.stdout)
    app.logger.addHandler(handler)
    app.logger.setLevel('INFO')

app.wsgi_app = ReverseProxied(app.wsgi_app)
got_request_exception.connect(log_exception, app)

#we want the old behavior for reqparse
Esempio n. 30
0
    'AC': 'Tech Disaster',
    'TO': 'Tornado',
    'TC': 'Tropical Cyclone',
    'TS': 'Tsunami',
    'VW': 'Violent Wind',
    'WV': 'Wave Surge',
    'WF': 'Wild Fire',
}

tips = {
    'Earthquake':
    " Quick Tip : If you're indoors, stand against a wall near the center of the building, stand in a doorway, or crawl under heavy furniture (a desk or table). Stay away from windows and outside doors.If you're outdoors, stay in the open away from power lines or anything that might fall. Stay away from buildings (stuff might fall off the building or the building could fall on you)."
}

app = Flask(__name__)
CORS(app)


@app.route("/", methods=['GET', 'POST'])
def hello():
    temp_json = {}
    for item in data['items']:
        temp_json_item = {}
        temp_json_item['coordinates'] = item['where']
        try:
            temp_json_item['event_type'] = types[item['gdacs_eventtype']]
        except:
            temp_json_item['event_type'] = item['gdacs_eventtype']
        try:
            temp_json_item['tip'] = tips[types[item['gdacs_eventtype']]]
        except:
Esempio n. 31
0
import os
from flask import Flask
from flask.ext.cors import CORS
from diary_app.database import db

# Initialize App
application = Flask(__name__)
CORS(application)
application.config.from_object(
    'diary_app.config.' + os.getenv('EPILEPSY_CONFIG'))

# Initialize Logging
'''
from diary_app.utils import logger
application.logger.addHandler(logger.get_rotating_file_handler(APP_LOG_FILE))
items_log = logger.get_logger(JOB_ITEMS_LOG_FILE, log_level=LOG_LEVEL)
tasks_log = logger.get_logger(TASKS_LOG_FILE,  log_level=LOG_LEVEL)
jobs_log = logger.get_logger(JOBS_LOG_FILE, log_level=LOG_LEVEL)
'''

# Import APIs
import diary_app.users.api
import diary_app.events.api
import diary_app.charts.api


@application.teardown_appcontext
def shutdown_session(exception=None):
    db.remove()
Esempio n. 32
0
def init():
    CORS(app)
    app.config['CORS_HEADERS'] = 'Content-Type'
    global module_obj
    module_obj = ResponseMachine.ResponseClassifierRequests(topn=20)
Esempio n. 33
0
prepare_data()


@APP.route('/earthquakes', methods=['GET'])
def earthquakes_by_year():
    """Return The trend per year"""
    data = VARS['data']
    grouped = data.groupby('year')
    count = grouped['mag'].count()
    return count.to_csv(None, index=False)


@APP.route('/earthquakes/<year>', methods=['GET'])
def earthquakes_in_year(year='2015'):
    """Filter the dataset by year and return in csv format"""
    data = VARS['data']
    filtered_data = data[data['year'] == year]
    return filtered_data.to_csv(None, index=False)


@APP.route('/', methods=['GET'])
def dashboard():
    """Return the HTML for the dashboard"""
    return None


if __name__ == "__main__":
    CORS(APP)
    APP.run(debug=True)