Пример #1
0
def create_blueprint(name, import_name, **kwargs):
    ''' Provides basic blueprint creation for all API handlers.
    '''
    url_prefix = kwargs.pop('url_prefix', '')
    bp = Blueprint(name, import_name, url_prefix=url_prefix)

    # Set App level before-request middleware.
    bp.before_app_first_request(lambda: None)

    # Set global before-request
    bp.before_app_request(lambda: None)

    return bp
Пример #2
0
def create_blueprint(import_name, oauth_authorize=None, oauth_access_token=None):
    bp = Blueprint('swagger_ui', import_name, template_folder='templates',
                   static_folder='static', static_url_path='/static/swagger')
    bp.route('/spec', endpoint='spec')(spec)
    bp.route('/o2c.html', endpoint='o2c')(oauth2callback)
    bp.route('/', endpoint='swagger_ui')(swagger_ui_view)

    if oauth_authorize and oauth_access_token:
        def setup_oauth_url():
            authorize_url = url_for(oauth_authorize, _external=True)
            access_token_url = url_for(oauth_access_token, _external=True)
            SwaggerUI().spec["securityDefinitions"]["oauth"]["authorizationUrl"] = authorize_url
            SwaggerUI().spec['info']['description'] = SwaggerUI().spec['info']['description'].replace(
                '{{OAUTH_AUTHORIZE_URL}}', access_token_url)

        bp.before_app_first_request(setup_oauth_url)

    return bp
Пример #3
0
def api_factory(name):
    """Construct a Blueprint and a REMOTE decorator to set up an API.

    RPC calls are availiable at the url /name/
    """
    api = Blueprint(name, __name__, url_prefix='/'+name)

    # set up the database
    def setup_bind(state):
        """Add the database to the config."""
        database_path = os.path.join(state.app.config['datadir'], name + '.dat')
        state.app.config['SQLALCHEMY_BINDS'][name] = 'sqlite:///' + database_path
    api.record_once(setup_bind)
    def initialize_database():
        """Create the database."""
        database.create_all(name)
    api.before_app_first_request(initialize_database)

    # create a base class for models
    class BoundMeta(type(database.Model)):
        """Metaclass for Model which allows __abstract__ base classes."""
        def __init__(self, cls_name, bases, attrs):
            assert '__bind_key__' not in attrs
            if not attrs.get('__abstract__', False):
                attrs['__bind_key__'] = name
            super(BoundMeta, self).__init__(cls_name, bases, attrs)
    class BoundModel(database.Model, metaclass=BoundMeta):
        """Base class for models which have __bind_key__ set automatically."""
        __abstract__ = True
        query = object.__getattribute__(database.Model, 'query')
        def __init__(self, *args, **kwargs):
            super(BoundModel, self).__init__(*args, **kwargs)

    # create a JSON-RPC API endpoint
    rpc_api = JSONRPCAPI(SmartDispatcher())
    assert type(rpc_api.dispatcher == SmartDispatcher)
    api.add_url_rule('/', 'rpc', rpc_api.as_view(), methods=['POST'])

    return api, rpc_api.dispatcher.add_method, BoundModel
Пример #4
0
        if action.action_type == "water":
            set_reminder(action.data)

        scrollphathd.show()


@atexit.register
def stop_background_thread():
    state.get_scheduler().shutdown(wait=False)
    api_thread = StoppableThread(target=run)
    api_thread.stop()
    print('bye fella')


scrollphathd_blueprint.before_app_first_request(start_background_thread)

# Autoscroll handling
autoscroll = AutoScroll()
state = State()
state.get_scheduler().add_job(func=water_reminder,
                              trigger="interval",
                              seconds=0,
                              id='water_reminder')
state.get_scheduler().start(paused=True)


def main():
    # Parser handling
    parser = ArgumentParser()
    parser.add_argument("-p",
Пример #5
0
def create_blueprint():

    gitpages_web_ui = Blueprint(
        'gitpages_web_ui',
        __name__,
        template_folder='templates',
    )

    gitpages_web_ui.add_url_rule(
        '/',
        'index_view',
        index_view_default_ref,
        defaults={
            'page_number': 1,
        },
    )

    gitpages_web_ui.add_url_rule(
        '/index/page/<int:page_number>/',
        'index_view',
        index_view_default_ref,
    )

    gitpages_web_ui.add_url_rule(
        '/feed/atom',
        'atom_feed',
        atom_feed,
    )
    gitpages_web_ui.add_url_rule(
        '/feed/rss',
        'rss_feed_redirect',
        rss_feed_redirect,
    )

    gitpages_web_ui.add_url_rule(
        '/' + '/'.join(
            [
                'archives',
                '<git_ref:tree_id>',
                '<int(fixed_digits=4):year>',
                '<int(fixed_digits=2):month>',
                '<int(fixed_digits=2):day>',
                '<slug>',
            ]
        ) + '/',
        'page_archive_view_ref',
        page_archive_view,
    )
    gitpages_web_ui.add_url_rule(
        '/' + '/'.join(
            [
                'archives',
                '<int(fixed_digits=4):year>',
                '<int(fixed_digits=2):month>',
                '<int(fixed_digits=2):day>',
                '<slug>',
            ]
        ) + '/',
        'page_archive_view',
        page_archive_view_default_ref,
    )

    gitpages_web_ui.add_url_rule(
        '/' + '/'.join(
            [
                'archives',
                '<int(fixed_digits=4):year>',
                '<int(fixed_digits=2):month>',
                '<int(fixed_digits=2):day>',
            ]
        ) + '/',
        'daily_archive',
        daily_archive_default,
        defaults={
            'page_number': 1,
        },
    )

    gitpages_web_ui.add_url_rule(
        '/' + '/'.join(
            [
                'archives',
                '<int(fixed_digits=4):year>',
                '<int(fixed_digits=2):month>',
            ]
        ) + '/',
        'monthly_archive',
        monthly_archive_default,
        defaults={
            'page_number': 1,
        },
    )

    gitpages_web_ui.add_url_rule(
        '/' + '/'.join(
            [
                'archives',
                '<int(fixed_digits=4):year>',
            ]
        ) + '/',
        'yearly_archive',
        yearly_archive_default,
        defaults={
            'page_number': 1,
        },
    )

    gitpages_web_ui.add_url_rule(
        '/' + '/'.join(
            [
                'attachment',
                '<git_ref:tree_id>',
            ]
        ),
        'attachment',
        attachment,
        defaults=dict(
            inline=False,
        ),
    )

    gitpages_web_ui.add_url_rule(
        '/' + '/'.join(
            [
                'attachment',
                '<git_ref:tree_id>',
                'inline',
            ]
        ),
        'inline_attachment',
        attachment,
        defaults=dict(
            inline=True,
        ),
    )

    gitpages_web_ui.before_app_first_request(setup_gitpages_application)
    gitpages_web_ui.before_request(setup_gitpages)
    gitpages_web_ui.teardown_request(teardown_gitpages)

    return gitpages_web_ui
Пример #6
0
        if action.action_type == "flip":
            matrix11x7.flip(x=action.data[0], y=action.data[1])

        if action.action_type == "autoscroll":
            autoscroll.config(action.data[0], action.data[1])

        matrix11x7.show()


def start_background_thread():
    api_thread = StoppableThread(target=run)
    api_thread.start()


matrix11x7_blueprint.before_app_first_request(start_background_thread)

# Autoscroll handling
autoscroll = AutoScroll()


def main():
    # Parser handling
    parser = ArgumentParser()
    parser.add_argument("-p",
                        "--port",
                        type=int,
                        help="HTTP port.",
                        default=8080)
    parser.add_argument("-H",
                        "--host",
Пример #7
0
from flask import Blueprint, render_template, abort
from web.flask_core.core import render_page
from web.utils import Topic

classnotes = Blueprint('classnotes', __name__, template_folder="templates")
classnotes.before_app_first_request(Topic.setup)

@classnotes.route('/')
def index():
    topics = Topic.get_list()
    return render_page('classnotes/index.html', topics=topics)

@classnotes.route('/<topic_id>')
def topic(topic_id):
    top = Topic.get_by_id(topic_id)
    if top is None:
        abort(404)
    return top.render()
Пример #8
0
from flask import Blueprint, render_template, flash, redirect, url_for, request
from flask import current_app
from os.path import join as os_join_path
from collections import namedtuple
import apachelog
import re
import models

#------------------------------------------------------------------------------#
# Controllers
#------------------------------------------------------------------------------#

bp = Blueprint('logbrowser', __name__, template_folder='templates',
              static_folder='static', static_url_path='/static.logbrowser')
bp.before_app_first_request(models.init)
blueprints = [bp]

@bp.route("/")
def index():
    return render_template("logbrowser/index.html")

@bp.route("/<handle>")
@bp.route("/<handle>/raw", defaults={'use_default_filters': False})
def log_view(handle, use_default_filters=True):
    log = models.logs[handle]
    filters = request.args.copy()
    if use_default_filters:
        for k,val in log.default_filters.items():
            if isinstance(val, (str, unicode)):
                filters.add(k, val)
            else: