Example #1
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(__name__)
    app.config['PROPAGATE_EXCEPTIONS'] = True
    app.logger.setLevel(app.config['LOG_LEVEL'])
    app.register_blueprint(mainbp)
    return app
Example #2
0
def build_app():
    '''
    Build the Flask app
    '''
    app = Flask(__name__)

    def make_json_error(ex):
        '''
        Return errors as JSON objects
        '''
        status = getattr(ex, 'code', 500)

        response = jsonify(message='Error {0}: {1}'.format(
            status,
            ex if app.debug else 'Internal server error',
        ))
        response.status_code = status

        return response

    # Allow using custom error handler when debug=True
    app.config['PROPAGATE_EXCEPTIONS'] = False
    app.error_handler_spec[None][500] = make_json_error

    jobs = JobsView.as_view('jobs')
    app.add_url_rule('/jobs', view_func=jobs, methods=['GET', 'POST'])
    app.add_url_rule('/jobs/<jid>', view_func=jobs, methods=['GET'])

    runners = RunnersView.as_view('runners')
    app.add_url_rule('/runners', view_func=runners, methods=['GET', 'POST'])

    return app
Example #3
0
def create_app(config_file):
    """

    Create app object
    Parameters:
    @config_file: python module with application settings
    """

    app = Flask(__name__)
    app.config.from_object(config_file)
    app.config['PROPAGATE_EXCEPTIONS'] = True
    #db.init_app(app)
    #db.create_all(db.engine)

    #Registering modules
    from main import main
    app.register_blueprint(main)

    from post import post
    app.register_blueprint(post, url_prefix="/post")

    from users import user
    app.register_blueprint(user, url_prefix="/user")
    
    return app
Example #4
0
def make_oauth_wsgi(oauth, next_app, config=None):
    app = Flask(__name__, static_folder=None)
    app.config['PROPAGATE_EXCEPTIONS'] = True

    if config:
        app.config.update(config)
    else:
        app.config.from_envvar('OAUTH_SETTINGS')

    app.next_app = next_app
    oauth.init_app(app)
    app.add_url_rule('/login', endpoint=None, view_func=login)
    app.add_url_rule('/logout', endpoint=None, view_func=logout)
    app.add_url_rule('/login/oauth_callback', endpoint=None, view_func=authorized)
    app.add_url_rule(
        '/',
        endpoint=None, view_func=default_handler,
        methods=['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],
    )
    app.add_url_rule(
        '/<path:any>',
        endpoint=None, view_func=default_handler,
        methods=['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],

    )

    auth = get_auth_provider(oauth)
    if not auth._tokengetter:
        auth.tokengetter(get_oauth_token)

    app.wsgi_app = ProxyFix(app.wsgi_app)

    return app
Example #5
0
def start(application):
    """Start the web frontend"""

    # Make sure our views can access the main application
    global app
    app = application

    static_path = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        '../static/'
    )

    config = app.get_config()

    frontend = Flask(__name__, static_folder=static_path)

    # Make sure we crash if there's some bug in the frontend code, this is so
    # we'll find the bugs
    frontend.config['PROPAGATE_EXCEPTIONS'] = True

    frontend.add_url_rule('/', view_func=MainView.as_view('index'))
    frontend.add_url_rule('/data.json', view_func=DataView.as_view('data'))

    # Set up the route for static files
    @frontend.route('/static/<path:filename>')
    def send_static(filename):
        return send_from_directory(static_path, filename)

    frontend.run(host='0.0.0.0', port=config.http_port)

    return frontend
Example #6
0
def generate_app():
    app = Flask(__name__)
    app.config['PROPAGATE_EXCEPTIONS'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DB_URI']
    with open("/data/secret_key") as fd:
        app.config['SECRET_KEY'] = fd.read().strip()
    return app
Example #7
0
def setup_app(env, debug=False, output_path=None, ui_lang='en'):
    app = Flask('lektor.admin')
    app.lektor_info = LektorInfo(env, output_path, ui_lang)
    app.debug = debug
    app.config['PROPAGATE_EXCEPTIONS'] = True

    register_modules(app)

    return app
def initialize_app():
    flask_app = Flask(__name__)
    flask_app.config['PROPAGATE_EXCEPTIONS'] = True
    flask_cache = Cache(
        flask_app,
        config={
            'CACHE_TYPE': 'simple',
            'CACHE_DEFAULT_TIMEOUT': REFRESH_INTERVAL
        })
    return flask_app, flask_cache
def flask_app(page_size, num_objects):

    app = Flask(__name__)
    app.config['PROPAGATE_EXCEPTIONS'] = True

    @app.route('/')
    @paginated_view(renderer=lambda obj: obj, default_page_size=page_size)
    def view_objects():
        return FakeCursor([{'id': i, 'type': 'session'} for i in range(num_objects)])

    return app
def flask_app():

    app = Flask(__name__)
    app.config['PROPAGATE_EXCEPTIONS'] = True

    @app.route('/')
    def view_objects():  # pylint: disable=unused-variable
        return jsonify({
            'sessions': [{'id': i, 'type': 'session'}
                         for i in range(10)]})
    return app
Example #11
0
    def setUp(self):

        self.cookbook = API('cookbook', "http://localhost:8881/api")

        @self.cookbook.action
        def cabbage(spicy, capitalize=False):
            if spicy:
                c = "kimchi"
            else:
                c = "sauerkraut"
            if capitalize:
                return c.capitalize()
            else:
                return c

        @self.cookbook.action
        def pounds_to_kilos(pounds):
            if pounds > 100:
                raise APIError('Too many pounds', http_code=501)
            return 0.453592 * pounds * pounds / pounds

        @self.cookbook.action
        def noop():
            return None

        api.apio_index = RemoteAPI(index_spec)

        with patch.object(requests, 'post') as mock_post:
            # Load API
            mock_post.return_value.status_code = 200
            mock_post.return_value.json = cookbook_spec
            from apio.index import cookbook as remote_cookbook
            self.remote_cookbook = remote_cookbook
            mock_post.assert_called_with('http://api.apio.io/actions/get_spec', headers={'Content-Type': 'application/json'}, data=json.dumps("cookbook"))

        # Create test client for some HTTP tests
        from flask import Flask
        app = Flask(__name__, static_folder=None)
        app.register_blueprint(self.cookbook.get_blueprint(), url_prefix="/api")
        self.werkzeug_client = app.test_client()

        # Test debug mode
        app = Flask(__name__, static_folder=None)
        app.config['PROPAGATE_EXCEPTIONS'] = True
        app.register_blueprint(self.cookbook.get_blueprint(debug=True), url_prefix="/api")
        self.werkzeug_client_debug = app.test_client()
Example #12
0
def create_app():
    """
    Flask app factory method
    """
    DB_USER = os.environ.get('DB_USER', 'postgres')
    DB_PASS = os.environ.get('DB_PASS', 'postgres')
    DB_HOST = os.environ.get('DB_HOST', '127.0.0.1')
    DB_PORT = os.environ.get('DB_PORT', 5432)
    DB_NAME = os.environ.get('DB_NAME', 'potion_test')
    SECRET_KEY = os.environ.get('SECRET_KEY', '123456')
    app = Flask(__name__)
    app.secret_key = SECRET_KEY
    app.config['DEBUG'] = True
    app.config['PROPAGATE_EXCEPTIONS'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://%s:%s@%s:%s/%s' % (
        DB_USER, DB_PASS, DB_HOST, DB_PORT, DB_NAME)
    return app
Example #13
0
    def run(self, *args, **kwargs):
        """Runs the API as a Flask app. All arguments channelled into Flask#run
        except for `register_api`, which is a boolean that defaults to True
        and determines whether you want your API pushed to APIO index.
        """

        debug = kwargs.get('debug', False)
        if kwargs.pop('register_api', True):
            ensure_bootstrapped()
            apio_index.actions.register_api(self.spec)
        if 'dry_run' in kwargs.keys(): return
        app = Flask(__name__, static_folder=None)
        # Flask will catch exceptions to return a nice HTTP response
        # in debug mode, we want things to FAIL!
        app.config['PROPAGATE_EXCEPTIONS'] = debug
        blueprint = self.get_blueprint(debug=debug)
        app.register_blueprint(blueprint)
        app.run(*args, **kwargs)
Example #14
0
    def _generate_app(self):
        app = Flask(__name__)
        app.config['PROPAGATE_EXCEPTIONS'] = True
        app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres:///ealgis'
        app.config['BROWSERID_LOGIN_URL'] = "/api/0.1/login"
        app.config['BROWSERID_LOGOUT_URL'] = "/api/0.1/logout"
	with open('/etc/ealgis/secret_key') as secret_fd:
	    secret_key = secret_fd.read().rstrip()
        app.config['SECRET_KEY'] = secret_key
        app.config['TESTING'] = True

        login_manager = LoginManager()
        login_manager.user_loader(self.get_user_by_id)
        login_manager.init_app(app)

        browserid = BrowserID()
        browserid.user_loader(self.browserid_get_user)
        browserid.init_app(app)

        return app
Example #15
0
    def _generate_app(self):
        app = Flask(__name__)
        app.wsgi_app = ReverseProxied(app.wsgi_app)
        app.config['PROPAGATE_EXCEPTIONS'] = True
        app.config['SQLALCHEMY_DATABASE_URI'] = self._connection_string()
        app.config['BROWSERID_LOGIN_URL'] = "/api/0.1/login"
        app.config['BROWSERID_LOGOUT_URL'] = "/api/0.1/logout"

        with open('/data/secret_key') as secret_fd:
            secret_key = secret_fd.read().rstrip()
        app.config['SECRET_KEY'] = secret_key
        # Warning: this *disables* authentication on the API
        # app.config['TESTING'] = True

        login_manager = LoginManager()
        login_manager.user_loader(self.get_user_by_id)
        login_manager.init_app(app)

        browserid = BrowserID()
        browserid.user_loader(self.browserid_get_user)
        browserid.init_app(app)

        return app
Example #16
0
def webapp(request):
    app = Flask(__name__)
    app.config['PROPAGATE_EXCEPTIONS'] = True
    app.config['DEBUG'] = True

    api = SimpleAPI(app)

    @api.include
    def api_no_args():
        return 'ok no args'

    @api.include
    def sum(a: int, b: int, c: int=3):
        return a + b + c

    @api.include
    def mul(a: int, b: int): # use direct types
        return a * b

    @api.include
    @_decorator
    def div(a: int, b: int): # use decorator
        return a / b

    @api.include
    def echo(list_value: list, dict_value: dict):
        return [list_value, dict_value]

    @api.include
    def default_to_none(str_value: str=None):
        return 'Got {!r}'.format(str_value)


    returned = Webapp(app)
    returned.activate()
    request.addfinalizer(returned.deactivate)
    return returned
Example #17
0
import _strptime  # import should prevent thread import blocking issues
# ask Google about:     AttributeError: _strptime

from oasis.lib import OaConfig
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
from flask_wtf.csrf import CSRFProtect

app = Flask(__name__,
            template_folder=os.path.join(OaConfig.homedir, "templates"),
            static_folder=os.path.join(OaConfig.homedir, "static"),
            static_url_path=os.path.join(os.path.sep, OaConfig.staticpath, "static"))
app.secret_key = OaConfig.secretkey
app.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024  # 8MB max file size upload
app.config['PROPAGATE_EXCEPTIONS'] = True  # don't swallow exceptions

# Flask initializes logging lazily and removes existing handlers when it does so,
# so we need to make sure it initializes here, before we add our own (in imports too!)
app.logger.info("Flask starting up")

L = logging.getLogger("oasisqe")
L.setLevel(OaConfig.loglevel)
if OaConfig.email_admins:
    MH = SMTPHandler(OaConfig.smtp_server,
                     OaConfig.email,
                     OaConfig.email_admins,
                     'OASIS Internal Server Error')
    MH.setLevel(logging.CRITICAL)
    L.addHandler(MH)
Example #18
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.orm import mapper, relationship, backref

STATIC_PATH = "/static"
STATIC_FOLDER = os.path.join("..","static")
TEMPLATE_FOLDER = os.path.join("..","templates")

# create database
SQLALCHEMY_DATABASE_FILE = 'bigbang.db'

app = Flask(__name__,
            static_url_path = STATIC_PATH,
            static_folder = STATIC_FOLDER,
            template_folder = TEMPLATE_FOLDER)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + SQLALCHEMY_DATABASE_FILE
app.config['PROPAGATE_EXCEPTIONS'] = True # for debugging; turn off when deployed

# create database object
db = SQLAlchemy(app)

from model.planet import Planet
from model.feed import Feed
from model.feed_content import FeedContent

Planet.feed = relationship(Feed, backref=backref("planet"))
Feed.feed_content = relationship(FeedContent, cascade="delete", backref=backref("feed"))


from bigbang.view import admin
Example #19
0
import copy
import requests
import json
import hmac
import math
import urllib
import urlparse
from hashlib import sha1

import collections

rcpart = Flask(__name__)
rcpart.config['GITHUB_CLIENT_ID'] = os.environ['GITHUB_CLIENT_ID']
rcpart.config['GITHUB_CLIENT_SECRET'] = os.environ['GITHUB_CLIENT_SECRET']
rcpart.config['GITHUB_BASE_URL'] = os.environ['GITHUB_BASE_URL']
rcpart.config['PROPAGATE_EXCEPTIONS'] = True
application = rcpart

es = elasticsearch.Elasticsearch([os.environ['ES_HOST']])

partCategories_string = ""
partCategories = {}

github_cache = pylru.lrucache(64)

from git import Repo

github = GitHub(rcpart)

SOCIAL_BOTS = ["facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)",
               "facebookexternalhit/1.1",
Example #20
0
def create_app(testing=False, live=False):
    from bhs_api.models import User, Role
    from bhs_api.forms import LoginForm

    app = Flask(__name__)
    app.testing = testing

    # load the config file
    conf = get_conf()
    app.conf = conf
    # Our config - need to move everything here
    app.config['VIDEO_BUCKET_URL'] = "https://storage.googleapis.com/bhs-movies"
    app.config['IMAGE_BUCKET_URL'] = "https://storage.googleapis.com/bhs-flat-pics"

    # Set app config
    app.config['DEBUG'] = True
    app.config['FRONTEND_SERVER'] = conf.frontend_server
    app.config['DEFAULT_NEXT'] = '/mjs'
    # Security Config
    app.config['SECRET_KEY'] = conf.secret_key
    app.config['WTF_CSRF_ENABLED'] = False
    app.config['SECURITY_PASSWORDLESS'] = True
    app.config['SECURITY_EMAIL_SENDER'] = 'BH Databases<support@bh.org.il>'
    app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = 'email'
    app.config['SECURITY_EMAIL_SUBJECT_PASSWORDLESS'] = 'Login link for Your Jewish Story'
    app.config['SECURITY_POST_LOGIN_VIEW'] = '/mjs'
    app.config['SECURITY_USER_IDENTITY_ATTRIBUTES'] = ('email', 'username', 'hash')
    # Mail Config
    app.config['MAIL_SERVER'] = conf.mail_server
    app.config['MAIL_PORT'] = conf.mail_port
    # Mail optional username and password
    try:
        app.config['MAIL_USERNAME'] = conf.mail_username
        app.config['MAIL_PASSWORD'] = conf.mail_password
    except AttributeError:
        pass

    # DB Config
    app.config['MONGODB_DB'] = conf.user_db_name
    app.config['MONGODB_HOST'] = conf.user_db_host
    app.config['MONGODB_PORT'] = conf.user_db_port
    # Redis
    app.config['REDIS_HOST'] = conf.redis_host
    app.config['REDIS_PORT'] = conf.redis_port
    app.config['REDIS_PASSWORD'] = getattr(conf, 'redis_password', None)

    # CACHING
    app.config['CACHING_TTL'] = conf.caching_ttl

    app.mail = Mail(app)
    app.db = MongoEngine(app)
    app.user_datastore = MongoEngineUserDatastore(app.db, User, Role)
    app.security = Security(app, app.user_datastore,
                            passwordless_login_form=LoginForm)
    # Create database connection object
    app.client_data_db = pymongo.MongoClient(conf.data_db_host, conf.data_db_port,
                    read_preference=pymongo.ReadPreference.SECONDARY_PREFERRED)
    app.data_db = app.client_data_db[conf.data_db_name]

    # Create the elasticsearch connection
    app.es = elasticsearch.Elasticsearch(conf.elasticsearch_host)
    app.es_data_db_index_name = getattr(conf, "elasticsearch_data_index", app.data_db.name)

    # Add the user's endpoints
    from bhs_api.user import user_endpoints
    app.register_blueprint(user_endpoints)
    # Add the v1 endpoint
    from bhs_api.v1_endpoints import v1_endpoints
    app.register_blueprint(v1_endpoints, url_prefix='/v1')
    # Initialize autodoc - https://github.com/acoomans/flask-autodoc
    #allow CORS
    cors = CORS(app, origins=['*'], headers=['content-type', 'accept',
                                            'authentication-token', 'Authorization'])
    # logging
    if live:
        app.config['PROPAGATE_EXCEPTIONS'] = True
        try:
            fh = logging.FileHandler(conf.log_file)
            formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            fh.setFormatter(formatter)
            app.logger.addHandler(fh)
        except AttributeError:
            pass

    # redis
    try:
        app.redis = redis.StrictRedis(host=conf.redis_host,
                                      port=conf.redis_port,
                                      password = app.config['REDIS_PASSWORD'],
                                      db=0)
    except AttributeError:
        app.redis = None

    return app, conf
from flask import Flask, Response
import json
from datetime import datetime
import gensim
from  gensim.models import Word2Vec, Phrases
import sys
import os

w2v_api = Flask(__name__)
w2v_api.config['PROPAGATE_EXCEPTIONS'] = True

cached_synonyms = {}
start = datetime.now()
print("start loading w2v " + str(start))
# w2v_model = Word2Vec.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)  # C binary format
# w2v_model = Word2Vec.load("en_1000_no_stem/en.model") # MemoryError :-(
try:
  model_filepath = sys.argv[1]
  if model_filepath in ["-d", "--daemonize"]:
    raise IndexError
  w2v_model = Word2Vec.load(model_filepath)  # C binary format
except IndexError:
  print("using default model")
  current_dir = os.path.dirname(__file__)
  model_filepath = os.path.join(current_dir, 'model_sentences_raw_words_trigrams_min_count_50_size_200_downsampling_0.001.bin')
  w2v_model = Word2Vec.load(model_filepath)  # C binary format
print("using model from " + model_filepath)

bigrams_model_name = 'bigrams_model_nyt_sentences_5.5M_5.bin'
trigrams_model_name = "trigrams_model_nyt_sentences_5.5M_5.bin"
ngrams_models = {
Example #22
0
def get_app(rigor_config):
	"""Builds and returns a Flask app object which gets its configuration from the given config file.
	rigor_config is an instance of rigor.config.RigorDefaultConfiguration(path_to_config_file)
	"""

	#================================================================================
	# FLASK HELPERS

	def check_auth(username, password):
		"""This function is called to check if a username /
		password combination is valid.
		"""
		return username == rigor_config.get('webapp', 'http_auth_user') and password == rigor_config.get('webapp', 'http_auth_password')

	def authenticate():
		"""Sends a 401 response that enables basic auth"""
		return Response(
			'Could not verify your access level for that URL.\n'
			'You have to login with proper credentials', 401,
			{'WWW-Authenticate': 'Basic realm="Login Required"'}
		)

	def simulate_slow(fn):
		@functools.wraps(fn)
		def decorated(*args, **kwargs):
			latency = int(rigor_config.get('webapp', 'fake_latency'))
			if latency > 0:
				debug_detail('adding {} seconds of fake delay'.format(latency))
				time.sleep(latency)
			return fn(*args, **kwargs)
		return decorated

	#================================================================================
	# FLASK SETUP

	share_folder = None
	share_folder_locations = ['../../share', '../../../../share', '../share']
	for path in share_folder_locations:
		path = os.path.abspath(os.path.join(os.path.dirname(__file__), path))
		if os.path.exists(path):
			share_folder = os.path.abspath(path)
			break
	if share_folder is None:
		debug_error('ERROR: Share folder not found')
		raise IOError('Share folder not found')
	else:
		debug_detail('found share folder at {}'.format(share_folder))

	app = Flask(
		__name__,
		static_folder=share_folder + '/static',
		template_folder=share_folder + '/templates',
	)
	app.config['SECRET_KEY'] = rigor_config.get('webapp', 'flask_secret_key')

	#================================================================================
	# PLUGINS

	debug_detail('loading backend')
	backend = rigorwebapp.backend.Backend(rigor_config)

	plugin_instances = rigorwebapp.plugin.load_plugin_instances(rigor_config, backend)
	debug_detail('loaded plugin classes:')
	for plugin_instance in plugin_instances:
		debug_detail('    {}'.format(plugin_instance.__class__.__name__))

	#================================================================================
	# ROUTING

	# let plugins add routes
	debug_detail('adding plugin routes')
	for plugin_instance in plugin_instances:
		plugin_instance.add_routes(app, backend, plugin_instances)

	@app.before_request
	# see http://stackoverflow.com/a/13451233/856925 for more thoughts on this
	def require_auth_everywhere():
		if rigor_config.getboolean('webapp', 'use_http_auth'):
			auth = request.authorization
			if not auth or not check_auth(auth.username, auth.password):
				return authenticate()


	@app.route('/')
	def index_redirect():
		initial_db = rigor_config.get('webapp', 'initial_db')
		initial_db = backend._encode_name_for_db(initial_db)
		return redirect('/db/{}/perceptsearch'.format(initial_db))

	app.config['PROPAGATE_EXCEPTIONS'] = True
	debug_detail('ready')

	# set up logging for sqlalchemy
	from logging import getLogger
	from logging import StreamHandler
	getLogger('sqlalchemy').addHandler(StreamHandler())

	return app
from flask import Flask, render_template
from flask.ext.restful import Resource, Api
from flask.ext.sqlalchemy import SQLAlchemy
from flask_restful_swagger import swagger


# Initialize the app and configure
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app.config['PROPAGATE_EXCEPTIONS'] = False


# Initialize database and ORM
db = SQLAlchemy(app)



def initialize_api(app):
    """Initialize API and Add resoruces/routing
    """
    from resources import (
        ProjectResource, ProjectListResource,
        ProjectProgressResource, ProjectProgressListResource)

    errors = {
      'NegativeProgressError': {
          'message': 'Progress can only be positive.',
          'status': 400,
      }
    }
from datetime import datetime
from jinja2 import Template, Environment, FileSystemLoader
from os import environ

from flask import request, session, Flask, render_template, Response, redirect, url_for

from sqlalchemy import *
from sqlalchemy.exc import IntegrityError
from sqlalchemy.exc import CompileError

import gspread
from oauth2client.service_account import ServiceAccountCredentials

# Initialise the Flask app ##
application = Flask(__name__)
application.config['PROPAGATE_EXCEPTIONS'] = True

@application.route('/', defaults={'path': None})
@application.route('/<path:path>')
def main(path=None):
    scope = ['https://spreadsheets.google.com/feeds']

    pk = "-----BEGIN PRIVATE KEY-----{key}-----END PRIVATE KEY-----\n".format(key=environ['PK'])

    key_dict = {
        "type": "service_account",
        "project_id": "devposthackathontweets",
        "private_key_id": "1d02a04353966c7d0f48be5dc6780c20177f96bd",
        "private_key": pk,
        "client_email": "hackathon-manager@devposthackathontweets.iam.gserviceaccount.com",
        "client_id": "105326323772464143676",
Example #25
0
def create_app():
  app = Flask(__name__)
  app.config['PROPAGATE_EXCEPTIONS'] = True
  app.register_blueprint(root)
  return app
Example #26
0
def create_app(verbosity=None):
    """Creates a Flask application object that registers all the blueprints on
    which the actual routes are defined.

    Parameters
    ----------
    verbosity: int, optional
        logging verbosity to override the
        :attr:`logging_verbosity <tmserver.config.ServerConfig.logging_verbosity>`
        setting in the configuration file (default: ``None``)

    Returns
    -------
    flask.Flask
        Flask application

    """
    log_formatter = logging.Formatter(
        fmt='%(process)5d/%(threadName)-12s| %(levelname)-8s| %(message)s [[%(name)s @ %(pathname)s:%(lineno)d]]',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    log_handler = logging.StreamHandler(stream=sys.stdout)
    log_handler.setFormatter(log_formatter)
    if verbosity is None:
        verbosity = cfg.logging_verbosity
    log_level = map_logging_verbosity(verbosity)

    app = Flask('wsgi')
    app.config['PROPAGATE_EXCEPTIONS'] = True

    app.logger.handlers = []  # remove standard handlers
    app.logger.setLevel(log_level)
    app.logger.addHandler(log_handler)

    tmserver_logger = logging.getLogger('tmserver')
    tmserver_logger.setLevel(log_level)
    tmserver_logger.addHandler(log_handler)

    tmlib_logger = logging.getLogger('tmlib')
    tmlib_logger.setLevel(log_level)
    tmlib_logger.addHandler(log_handler)

    flask_jwt_logger = logging.getLogger('flask_jwt')
    flask_jwt_logger.setLevel(log_level)
    flask_jwt_logger.addHandler(log_handler)

    gevent_logger = logging.getLogger('gevent')
    gevent_logger.addHandler(log_handler)
    gc3pie_logger = logging.getLogger('gc3.gc3libs')
    gc3pie_logger.addHandler(log_handler)
    sqlalchemy_logger = logging.getLogger('sqlalchemy.engine')
    sqlalchemy_logger.addHandler(log_handler)
    wsgi_logger = logging.getLogger('wsgi')
    wsgi_logger.addHandler(log_handler)
    if verbosity > 4:
        gevent_logger.setLevel(logging.DEBUG)
        gc3pie_logger.setLevel(logging.DEBUG)
        sqlalchemy_logger.setLevel(logging.DEBUG)
        wsgi_logger.setLevel(logging.DEBUG)
    elif verbosity > 3:
        gevent_logger.setLevel(logging.INFO)
        gc3pie_logger.setLevel(logging.INFO)
        sqlalchemy_logger.setLevel(logging.INFO)
        wsgi_logger.setLevel(logging.INFO)
    else:
        gevent_logger.setLevel(logging.ERROR)
        gc3pie_logger.setLevel(logging.ERROR)
        sqlalchemy_logger.setLevel(logging.ERROR)
        wsgi_logger.setLevel(logging.ERROR)

    app.json_encoder = TmJSONEncoder

    if cfg.secret_key == 'default_secret_key':
        app.logger.warn('The application will run with the default secret key!')
    elif not cfg.secret_key:
        app.logger.critical('Specify a secret key for this application!')
        sys.exit(1)
    app.config['SECRET_KEY'] = cfg.secret_key

    app.config['JWT_EXPIRATION_DELTA'] = cfg.jwt_expiration_delta

    ## Error handling

    # Register custom error classes
    register_http_error_classes(app)

    # Register SQLAlchemy error classes
    @app.errorhandler(NoResultFound)
    def _handle_no_result_found(error):
        response = jsonify(error={
            'message': error.message,
            'status_code': 400,
            'type': error.__class__.__name__
        })
        logger.error('no result found: ' + error.message)
        response.status_code = 400
        return response

    @app.errorhandler(MultipleResultsFound)
    def _multiple_results_found(error):
        response = jsonify(error={
            'message': error.message,
            'status_code': 409,
            'type': error.__class__.__name__
        })
        logger.error('multiple results found: ' + error.message)
        response.status_code = 409
        return response

    @app.errorhandler(IntegrityError)
    def _handle_integrity_error(error):
        response = jsonify(error={
            'error': True,
            'message': error.message,
            'status_code': 500,
            'type': error.__class__.__name__
        })
        logger.error('database integrity error: ' + error.message)
        response.status_code = 500
        return response


    ## Initialize Plugins
    jwt.init_app(app)

    # Create a session scope for interacting with the main database
    engine = create_db_engine(cfg.db_master_uri)
    create_db_tables(engine)
    session_factory = create_db_session_factory()
    session_factory.configure(bind=engine)
    session = flask_scoped_session(session_factory, app)

    from tmserver.extensions import gc3pie
    gc3pie.init_app(app)

    ## Import and register blueprints
    from tmserver.api import api
    app.register_blueprint(api, url_prefix='/api')

    from tmserver.jtui import jtui
    app.register_blueprint(jtui, url_prefix='/jtui')

    # For uWSGI fork()
    engine.dispose()

    return app
Example #27
0
from flask import Flask, render_template, request
import api, os, pytronics, time
import libblinkm, libfourdsystems, libvoltageshield, libservo, joystick
from uwsgidecorators import *

public = Flask(__name__)
public.register_blueprint(api.public)
public.register_blueprint(libblinkm.public)
public.register_blueprint(libfourdsystems.public)
public.register_blueprint(libvoltageshield.public)
public.register_blueprint(libservo.public)
public.register_blueprint(joystick.public)
public.config['PROPAGATE_EXCEPTIONS'] = True

# Include "no-cache" header in all POST responses
@public.after_request
def add_no_cache(response):
    if request.method == 'POST':
        response.cache_control.no_cache = True
    return response

# config for upload
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
ALLOWED_DIRECTORIES = set(['static/uploads/', 'static/pictures/'])
# public.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024

### Home page ###
@public.route('/')
@public.route('/index.html')
def default_page():
    try:
Example #28
0
    def test_dispatcher(self):
        app = Flask(__name__)
        app.config['PROPAGATE_EXCEPTIONS'] = True

        @app.route('/')
        @app.route('/', subdomain='<sub>')
        @app.route('/<path:path>')
        @app.route('/<path:path>', subdomain='<sub>')
        def catchall(sub='', path=None):
            return jsonify(app=[sub, request.script_root, request.path,
                                request.query_string.decode('utf8')])

        def dummy_fetcher(url):
            return {'string': 'dummy ' + url}

        def assert_app(url, host, script_root, path, query_string=''):
            """The URL was dispatched to the app with these parameters."""
            assert json.loads(dispatcher(url)['string']) == {
                'app': [host, script_root, path, query_string]}

        def assert_dummy(url):
            """The URL was not dispatched, the default fetcher was used."""
            assert dispatcher(url)['string'] == 'dummy ' + url

        # No SERVER_NAME config, default port
        with app.test_request_context(base_url='http://a.net/b/'):
            dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher)
        assert_app('http://a.net/b', '', '/b', '/')
        assert_app('http://a.net/b/', '', '/b', '/')
        assert_app('http://a.net/b/c/d?e', '', '/b', '/c/d', 'e')
        assert_app('http://a.net:80/b/c/d?e', '', '/b', '/c/d', 'e')
        assert_dummy('http://a.net/other/prefix')
        assert_dummy('http://subdomain.a.net/b/')
        assert_dummy('http://other.net/b/')
        assert_dummy('http://a.net:8888/b/')
        assert_dummy('https://a.net/b/')

        # Change the context’s port number
        with app.test_request_context(base_url='http://a.net:8888/b/'):
            dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher)
        assert_app('http://a.net:8888/b', '', '/b', '/')
        assert_app('http://a.net:8888/b/', '', '/b', '/')
        assert_app('http://a.net:8888/b/cd?e', '', '/b', '/cd', 'e')
        assert_dummy('http://subdomain.a.net:8888/b/')
        assert_dummy('http://a.net:8888/other/prefix')
        assert_dummy('http://a.net/b/')
        assert_dummy('http://a.net:80/b/')
        assert_dummy('https://a.net/b/')
        assert_dummy('https://a.net:443/b/')
        assert_dummy('https://a.net:8888/b/')

        # Add a SERVER_NAME config
        app.config['SERVER_NAME'] = 'a.net'
        with app.test_request_context():
            dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher)
        assert_app('http://a.net', '', '', '/')
        assert_app('http://a.net/', '', '', '/')
        assert_app('http://a.net/b/c/d?e', '', '', '/b/c/d', 'e')
        assert_app('http://a.net:80/b/c/d?e', '', '', '/b/c/d', 'e')
        assert_app('https://a.net/b/c/d?e', '', '', '/b/c/d', 'e')
        assert_app('https://a.net:443/b/c/d?e', '', '', '/b/c/d', 'e')
        assert_app('http://subdomain.a.net/b/', 'subdomain', '', '/b/')
        assert_dummy('http://other.net/b/')
        assert_dummy('http://a.net:8888/b/')

        # SERVER_NAME with a port number
        app.config['SERVER_NAME'] = 'a.net:8888'
        with app.test_request_context():
            dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher)
        assert_app('http://a.net:8888', '', '', '/')
        assert_app('http://a.net:8888/', '', '', '/')
        assert_app('http://a.net:8888/b/c/d?e', '', '', '/b/c/d', 'e')
        assert_app('https://a.net:8888/b/c/d?e', '', '', '/b/c/d', 'e')
        assert_app('http://subdomain.a.net:8888/b/', 'subdomain', '', '/b/')
        assert_dummy('http://other.net:8888/b/')
        assert_dummy('http://a.net:5555/b/')
        assert_dummy('http://a.net/b/')
Example #29
0
import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath

from monitorcommon import logutil

# add the shared settings file's dir to python path
sys.path.insert(0, dirname(dirname(dirname(abspath(__file__)))))


app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True

# import views configures flask routes
import webapp.views

logutil.setup_logger(logging.DEBUG)
Example #30
0
        if isinstance(v, collections.Mapping):
            r = update(d.get(k, {}), v)
            d[k] = r
        else:
            d[k] = u[k]
    return d


# Init the rcbuild.info app.
rcbuild = Flask(__name__)
sslify = SSLify(rcbuild, skips=["healthz"])
rcbuild.config['GITHUB_CLIENT_ID'] = os.environ['GITHUB_CLIENT_ID']
rcbuild.config['GITHUB_CLIENT_SECRET'] = os.environ['GITHUB_CLIENT_SECRET']
rcbuild.config['GITHUB_BASE_URL'] = os.environ['GITHUB_BASE_URL']
rcbuild.config['GITHUB_AUTH_URL'] = os.environ['GITHUB_AUTH_URL']
rcbuild.config['PROPAGATE_EXCEPTIONS'] = True
rcbuild.config['PERMANENT_SESSION_LIFETIME'] = 365 * 24 * 60 * 60
rcbuild.secret_key = os.environ['SESSION_SECRET_KEY']
application = rcbuild

FERNET_KEY = os.environ['FERNET_KEY']
f = Fernet(FERNET_KEY)

es = elasticsearch.Elasticsearch([os.environ['ES_HOST']])

SILENT_COMMIT_MESSAGE = "Silently upgrade - "

partCategories_string = ""
partCategories = {}

buildSkeleton = {}