def create_blueprint(self, appbuilder,
                         endpoint=None,
                         static_folder=None):
        """
            Create Flask blueprint. You will generally not use it

            :param appbuilder:
               the AppBuilder object
            :param endpoint:
               endpoint override for this blueprint, will assume class name if not provided
            :param static_folder:
               the relative override for static folder, if omitted application will use the appbuilder static
        """
        # Store appbuilder instance
        self.appbuilder = appbuilder

        # If endpoint name is not provided, get it from the class name
        self.endpoint = endpoint or self.__class__.__name__

        if self.route_base is None:
            self.route_base = '/' + self.__class__.__name__.lower()

        self.static_folder = static_folder
        if not static_folder:
            # Create blueprint and register rules
            self.blueprint = Blueprint(self.endpoint, __name__,
                                       url_prefix=self.route_base,
                                       template_folder=self.template_folder)
        else:
            self.blueprint = Blueprint(self.endpoint, __name__,
                                       url_prefix=self.route_base,
                                       template_folder=self.template_folder,
                                       static_folder=static_folder)
        self._register_urls()
        return self.blueprint
Example #2
0
    def __init__(
        self,
        import_name,
        static_folder=None,
        static_url_path=None,
        template_folder=None,
        url_prefix=None,
        subdomain=None,
        url_defaults=None,
        root_path=None,
        login_url=None,
        authorized_url=None,
        backend=None,
    ):

        Blueprint.__init__(
            self,
            name="webfinger",
            import_name=import_name,
            static_folder=static_folder,
            static_url_path=static_url_path,
            template_folder=template_folder,
            url_prefix=url_prefix,
            subdomain=subdomain,
            url_defaults=url_defaults,
            root_path=root_path,
        )

        self._managers = []
        self.add_url_rule(rule="/webfinger", endpoint="webfinger", view_func=self.handler)
Example #3
0
class ConfigurableBlueprint(Configurable):
    """
    A Flask-specific configurable unit.

    When configured, initializes a Blueprint with pre-declared routing
    and provides a dedicated `serve` method (which is also a CLI command)
    to debug this blueprint on its own.
    """
    needs = {
        'debug': bool(os.environ.get('DEBUG', False)),
    }

    def init(self):
        # create an configurable-bound blueprint
        # with our methods pre-declared as views
        self.blueprint = Blueprint(self.__class__.__name__, __name__)
        for attr in dir(self):
            meth = getattr(self, attr)
            url_rule = getattr(meth, '_url_rule', None)
            if url_rule:
                self.blueprint.route(url_rule)(meth)

    def serve(self):
        # ad-hoc dedicated devel app for this blueprint
        app = Flask(__name__)
        app.register_blueprint(self.blueprint)
        app.run(debug=self.debug)
Example #4
0
def create():
    """Create blueprint.
    """

    # Create instance
    blueprint = Blueprint('authentication', 'authentication')

    # Controller Proxies
    check_controller = controllers.Check()
    callback_controller = controllers.Callback()

    def check():
        token = request.values.get('jwt')
        next_url = request.args.get('next', None)
        callback_url = 'http://'+os_conductor+url_for('.callback')
        return jsonpify(check_controller(token, next_url, callback_url))

    def callback():
        state = request.args.get('state')
        return callback_controller(state)

    # Register routes
    blueprint.add_url_rule(
        'check', 'check', check, methods=['GET'])
    blueprint.add_url_rule(
        'google_callback', 'callback', callback, methods=['GET'])

    # Return blueprint
    return blueprint
Example #5
0
    def init_app(self, app):
        app.config.setdefault('BOWER_COMPONENTS_ROOT', 'bower_components')
        app.config.setdefault('BOWER_KEEP_DEPRECATED', True)
        app.config.setdefault('BOWER_QUERYSTRING_REVVING', True)
        app.config.setdefault('BOWER_REPLACE_URL_FOR', False)
        app.config.setdefault('BOWER_SUBDOMAIN', None)
        app.config.setdefault('BOWER_TRY_MINIFIED', True)
        app.config.setdefault('BOWER_URL_PREFIX', '/bower')

        blueprint = Blueprint(
            'bower',
            __name__,
            url_prefix=app.config['BOWER_URL_PREFIX'],
            subdomain=app.config['BOWER_SUBDOMAIN'])

        blueprint.add_url_rule('/<component>/<path:filename>', 'serve', serve)

        app.register_blueprint(blueprint)

        if app.config['BOWER_KEEP_DEPRECATED'] is True:
            app.jinja_env.globals['bower_url_for'] = bower_url_for

        if app.config['BOWER_REPLACE_URL_FOR'] is True:
            app.jinja_env.globals['url_for'] = replaced_url_for

        app.url_build_error_handlers.append(handle_url_error)
Example #6
0
    def register_views(self, app):
        blueprint = Blueprint(
            self.config.get('endpoint', 'swagger'),
            __name__,
            url_prefix=self.config.get('url_prefix', None),
            subdomain=self.config.get('subdomain', None),
            template_folder=self.config.get('template_folder', 'templates'),
            static_folder=self.config.get('static_folder', 'static'),
            static_url_path=self.config.get('static_url_path', None)
        )
        for spec in self.config['specs']:
            self.endpoints.append(spec['endpoint'])
            blueprint.add_url_rule(
                spec['route'],
                spec['endpoint'],
                view_func=OutputView().as_view(
                    spec['endpoint'],
                    view_args=dict(
                        app=app, config=self.config,
                        spec=spec, sanitizer=self.sanitizer
                    )
                )
            )

        blueprint.add_url_rule(
            self.config.get('specs_route', '/specs'),
            'specs',
            view_func=SpecsView().as_view(
                'specs',
                view_args=dict(config=self.config)
            )
        )

        app.register_blueprint(blueprint)
Example #7
0
def _register_api(app, options, first_registration=False):
    """
    Register the data with the blueprint.
    """
    _get_data.cache[app] = _get_option('data', options)
    _get_format.cache[app] = dict(
        (f.name, f) for f in _get_option('formats', options)
    )
    _get_auth.cache[app] = (
        _get_option('authorization', options, None) or (lambda a: True)
    )
    allow_profiler = _get_option('allow_profiler', options, False)
    profiler_output = _get_option('profiler_output', options, None)
    profile_by_default = _get_option('profile_by_default', options, False)
    if not allow_profiler and (profiler_output or profile_by_default):
        raise ValueError(
            "cannot set %s%s%s when 'allow_profiler' is False" % (
                'profiler_output' if profiler_output else '',
                ' or ' if profiler_output and profile_by_default else '',
                'profile_by_default' if profile_by_default else '',
            ),
        )
    if allow_profiler:
        if profiler_output is None:
            profiler_output = 'profiler_output'
        if profiler_output != ':response':
            ensure_dir(profiler_output)

    _get_profiler_info.cache[app] = (
        allow_profiler, profiler_output, profile_by_default
    )

    # Call the original register function.
    Blueprint.register(api, app, options, first_registration)
Example #8
0
def create():
    """Create blueprint.
    """

    # Create instance
    blueprint = Blueprint('search', 'search')

    # Controller Proxies
    search_controller = controllers.search

    def search(kind):
        token = request.values.get('jwt')
        userid = None
        try:
            if token is not None:
                token = jwt.decode(token, PRIVATE_KEY)
                userid = token.get('userid')
        except jwt.InvalidTokenError:
            pass
        ret = search_controller(kind, userid, request.args)
        if ret is None:
            abort(400)
        return jsonpify(ret)

    # Register routes
    blueprint.add_url_rule(
        '<kind>', 'search', search, methods=['GET'])

    # Return blueprint
    return blueprint
Example #9
0
class Casl(object):

    def __init__(self, prefix="/casl", name=None, app=None):
        self.name = name
        self.prefix = prefix
        self.app = app

        if not name:
            self.name = __name__
        
        self.routes = [("/word/<word>", "r_word", ["GET"])]

        if self.app is not None:
            self.init_app(app)



    def init_app(self, app):
        """ Register the blueprint to the app
        :param app: Flask Application
        :return: Blueprint for Casl registered in app
        :rtype: Blueprint
        """
        self.blueprint = Blueprint(
            self.name,
            self.name,
            url_prefix=self.prefix,
        )

        for url, name, methods in self.routes:
            self.blueprint.add_url_rule(
                url,
                view_func=getattr(self, name),
                endpoint=name,
                methods=methods
            )

        self.app.register_blueprint(self.blueprint)
        return self.blueprint


    def register_routes(self):
        """ Register routes on app using Blueprint
        :return: FlaskCasl blueprint
        :rtype: flask.Blueprint
        """
        if self.app is not None:
            if not self.blueprint:
                self.blueprint = self.create_blueprint()
            self.app.register_blueprint(self.blueprint)
            return self.blueprint
        return None

    def r_word(self,word):
        response = self.parse(word)
        return response, 200, { "Content-Type": "application/xml"}


    def parse(self, word):
        return "<word>" + word + "</word>"
Example #10
0
 def as_blueprint(self, name=None):
     blueprint = Blueprint(name if name else str(uuid4()), __name__)
     blueprint.add_url_rule(
         '/', view_func=self.jsonrpc, methods=['POST'])
     blueprint.add_url_rule(
         '/map', view_func=self.jsonrpc_map, methods=['GET'])
     return blueprint
Example #11
0
def _register_api(app, options, first_registration=False):
    """
    Register the data with the blueprint.
    """
    _get_data.cache[app] = _get_option('data', options)
    _get_format.cache[app] = {f.name: f for f in _get_option('formats', options)}
    _get_auth.cache[app] = (_get_option('authorization', options, None) or
                            (lambda a: True))
    allow_profiler = _get_option('allow_profiler', options, False)
    profiler_output = _get_option('profiler_output', options, None)
    profile_by_default = _get_option('profile_by_default', options, False)
    if not allow_profiler and (profiler_output or profile_by_default):
        msg = "cannot set %s%s%s when 'allow_profiler' is False"
        raise ValueError(msg % ('profiler_output' if profiler_output else '',
                                ' or ' if profiler_output and profile_by_default else '',
                                'profile_by_default' if profile_by_default else ''))
    if allow_profiler:
        if profiler_output is None:
            profiler_output = 'profiler_output'
        if profiler_output != ':response':
            ensure_dir(profiler_output)

    _get_profiler_info.cache[app] = (allow_profiler,
                                     profiler_output,
                                     profile_by_default)

    # Allowing users to dynamically add datasets to the Blaze server can be
    # dangerous, so we only expose the method if specifically requested
    allow_add = _get_option('allow_add', options, False)
    if allow_add:
        app.add_url_rule('/add', 'addserver', addserver,
                         methods=['POST', 'HEAD', 'OPTIONS'])

    # Call the original register function.
    Blueprint.register(api, app, options, first_registration)
Example #12
0
def create_blueprint(endpoints):
    """Create Invenio-Deposit-REST blueprint."""
    blueprint = Blueprint(
        'invenio_deposit_rest',
        __name__,
        url_prefix='',
    )

    for endpoint, options in (endpoints or {}).items():
        for rule in create_url_rules(endpoint, **options):
            blueprint.add_url_rule(**rule)

        deposit_actions = DepositActionResource.as_view(
            DepositActionResource.view_name.format(endpoint),
            serializers=options.get('record_serializers'),
            pid_type=options['pid_type'],
        )

        blueprint.add_url_rule(
            '{0}/actions/<any(publish,edit,discard):action>'.format(
                options['item_route']
            ),
            view_func=deposit_actions,
            methods=['POST']
        )

    return blueprint
def create_loan_actions_blueprint(app):
    """Create a blueprint for Loan actions."""
    blueprint = Blueprint(
        "invenio_circulation_loan_actions", __name__, url_prefix=""
    )

    endpoints = app.config.get("CIRCULATION_REST_ENDPOINTS", [])
    pid_type = CIRCULATION_LOAN_PID_TYPE
    options = endpoints.get(pid_type, {})
    if options:
        options = deepcopy(options)
        serializers = {}
        if "record_serializers" in options:
            rec_serializers = options.get("record_serializers")
            serializers = {
                mime: obj_or_import_string(func)
                for mime, func in rec_serializers.items()
            }

        loan_actions = LoanActionResource.as_view(
            LoanActionResource.view_name.format(pid_type),
            serializers=serializers,
            ctx={},
        )

        distinct_actions = extract_transitions_from_app(app)
        url = "{0}/<any({1}):action>".format(
            options["item_route"], ",".join(distinct_actions)
        )

        blueprint.add_url_rule(url, view_func=loan_actions, methods=["POST"])

    return blueprint
Example #14
0
class Feedloggr(object):
    def __init__(self, app=None, *args, **kwargs):
        if app:
            self.init_app(app, *args, **kwargs)

    def init_app(self, app, db):
        self.app = app
        # register extension with app
        self.app.extensions = getattr(app, 'extensions', {})
        self.app.extensions['feedloggr'] = self

        self.blueprint = Blueprint(
            'feedloggr',
            __name__,
            template_folder='templates',
            static_folder='static',
            url_prefix = app.config.get('FEEDLOGGR_URL', '/feedloggr'),
        )

        self.blueprint.add_url_rule('/', view_func=index)
        self.blueprint.add_url_rule(
            '/<int:year>-<int:month>-<int:day>',
            view_func=index,
        )

        db_proxy.initialize(db.database)
        create_tables(fail_silently=True)

        app.register_blueprint(self.blueprint)
def create_loan_replace_item_blueprint(app):
    """Create a blueprint for replacing Loan Item."""
    blueprint = Blueprint(
        "invenio_circulation_loan_replace_item", __name__, url_prefix=""
    )

    rec_serializers = {
        "application/json": (
            "invenio_records_rest.serializers" ":json_v1_response"
        )
    }
    serializers = {
        mime: obj_or_import_string(func)
        for mime, func in rec_serializers.items()
    }
    replace_item_view = LoanReplaceItemResource.as_view(
        LoanReplaceItemResource.view_name.format(CIRCULATION_LOAN_PID_TYPE),
        serializers=serializers,
        ctx={},
    )

    url = "circulation/loans/<{0}:pid_value>/replace-item".format(
        _LOANID_CONVERTER
    )
    blueprint.add_url_rule(url, view_func=replace_item_view, methods=["POST"])
    return blueprint
Example #16
0
def create_blueprint(endpoints):
    """Create Invenio-Deposit-UI blueprint."""
    from invenio_records_ui.views import create_url_rule

    blueprint = Blueprint(
        'invenio_deposit_ui',
        __name__,
        static_folder='../static',
        template_folder='../templates',
        url_prefix='',
    )

    for endpoint, options in (endpoints or {}).items():
        blueprint.add_url_rule(**create_url_rule(endpoint, **options))

    @blueprint.route('/deposit')
    @login_required
    def index():
        """List user deposits."""
        return render_template(
            'invenio_deposit/index.html',
        )

    @blueprint.route('/deposit/new')
    @login_required
    def new():
        """Create new deposit."""
        return render_template(
            'invenio_deposit/edit.html', record={'_deposit': {'id': None}},
        )

    return blueprint
Example #17
0
        def wrapper(res):
            if not issubclass(res, Resource):
                raise ValueError('Resource should be subclass of api.Resource.')

            api.resources.append(res)

            url_ = res.meta.url = url or res.meta.url or ('/%s' % res.meta.name)
            view_func = res.as_view(res.meta.name, api)
            api.add_url_rule(url_, view_func=view_func, **options)

            for _, (route_, endpoint_, options_) in res.meta.endpoints.values():
                api.add_url_rule('%s/%s' % (url_, route_.strip('/')), view_func=view_func,
                                 defaults={'endpoint': endpoint_}, **options_)

            url_detail_ = url_detail
            if url_detail is DEFAULT:
                url_detail_ = res.meta.url_detail = res.meta.url_detail or \
                    ('%s/<%s>' % (url_, res.meta.name))

            if url_detail:
                api.add_url_rule(url_detail_, view_func=view_func, **options)

            if api.app is not None:
                Blueprint.register(api, api.app, {}, False)

            return res
Example #18
0
def create_blueprint(endpoints):
    """Factory for Invenio-Records-UI blueprint creation.

    The factory installs one URL route per endpoint defined, and adds an
    error handler for rendering tombstones.

    :param endpoints: Dictionary of endpoints to be installed. See usage
        documentation for further details.
    """
    blueprint = Blueprint(
        'invenio_records_ui',
        __name__,
        url_prefix='',
        template_folder='templates',
        static_folder='static',
    )

    @blueprint.errorhandler(PIDDeletedError)
    def tombstone_errorhandler(error):
        return render_template(
            current_app.config['RECORDS_UI_TOMBSTONE_TEMPLATE'],
            pid=error.pid,
            record=error.record or {},
        ), 410

    for endpoint, options in (endpoints or {}).items():
        blueprint.add_url_rule(**create_url_rule(endpoint, **options))

    return blueprint
Example #19
0
    def create_blueprint(self, baseapp, 
                        endpoint = None, 
                        static_folder = None):
        """
            Create Flask blueprint.
        """
        # Store BaseApp instance
        self.baseapp = baseapp

        # If endpoint name is not provided, get it from the class name
        if not self.endpoint:
            self.endpoint = self.__class__.__name__.lower()

        self.static_folder = static_folder
        if not static_folder:
        # Create blueprint and register rules
            self.blueprint = Blueprint(self.endpoint, __name__,
                                   url_prefix=self.route_base,
                                   template_folder=self.template_folder)
        else:
            self.blueprint = Blueprint(self.endpoint, __name__,
                                   url_prefix=self.route_base,
                                   template_folder=self.template_folder,
                                   static_folder = static_folder)

        self.register_urls()
        return self.blueprint
Example #20
0
 def init_app(self, app):
     if self.app is None:
         self.app = app
         blueprint = Blueprint('sock_js', __name__)
         blueprint.route("/")(self.ws_url_for)
         app.register_blueprint(blueprint, url_prefix='/' + self.url_prefix)
         app.jinja_env.globals[self.url_helper] = self.ws_url_for
def create_blueprint(endpoints):
    """Create Invenio-Records-REST blueprint."""
    blueprint = Blueprint(
        'invenio_records_rest',
        __name__,
        url_prefix='',
    )

    for endpoint, options in (endpoints or {}).items():
        for rule in create_url_rules(endpoint, **options):
            blueprint.add_url_rule(**rule)

    # catch record validation errors
    @blueprint.errorhandler(ValidationError)
    def validation_error(error):
        """Catch validation errors."""
        return RESTValidationError().get_response()

    @blueprint.errorhandler(RequestError)
    def elasticsearch_badrequest_error(error):
        """Catch errors of ElasticSearch."""
        def first(function, iterable, default=None):
            """Return the first item from iterable which function is true."""
            for item in iterable:
                if function(item):
                    return item
            return default

        handlers = map(lambda c: elasticsearch_error_handlers.get(c['type']),
                       error.info['error']['root_cause'])
        handler = first(lambda h: h, handlers, lambda h: h)
        return handler(error)

    return blueprint
Example #22
0
def create_blueprint(blueprint_name, conf):
    webcams_blueprint = Blueprint(blueprint_name, __name__, **conf)

    webcams_blueprint.add_url_rule('/', view_func=Webcams.as_view('webcams'))

    webcams_blueprint.add_url_rule('/<slug>', view_func=StillImage.as_view('webcam'))

    return webcams_blueprint
def test_Blueprint_root_widget_condition():
    bp = Blueprint('test', __name__)
    eq_(bp.root_widget_templates or [], [])

    def maybe():
        return False
    bp.root_widget_template('foo.html', priority=13, condition=maybe)
    eq_(bp.root_widget_templates, [(13, 'foo.html', maybe)])
Example #24
0
def create_blueprint(blueprint_name, conf):
    contact_blueprint = Blueprint(blueprint_name, __name__, **conf)

    contact_blueprint.add_url_rule('/', view_func=get_routes)

    contact_blueprint.add_url_rule('/search',
                                   view_func=Search.as_view('search'))
    return contact_blueprint
 def __init__(self, name, mongo):
     Blueprint.__init__(self, name, __name__)
     self.mongo = mongo
     self.add_url_rule('', 'get_items', self.get_items, methods=['GET'])
     self.add_url_rule('/<item_id>', 'get_item', self.get_item, methods=['GET'])
     self.add_url_rule('', 'create_item', self.create_item, methods=['POST'])
     self.add_url_rule('/<item_id>', 'update_item', self.update_item,  methods=['PUT'])
     self.add_url_rule('/<item_id>', 'delete_item', self.delete_item, methods=['DELETE'])
Example #26
0
 def as_blueprint(cls, name=None):
     name = name or cls.endpoint
     bp = Blueprint(name, cls.__module__, url_prefix=cls.url_prefix)
     for endpoint, options in cls.url_rules.iteritems():
         url_rule = options.get('rule', '')
         defaults = options.get('defaults', {})
         bp.add_url_rule(url_rule, defaults=defaults, view_func=cls.as_view(endpoint))
     return bp
Example #27
0
    def __init__(self, name, import_name, **kwargs):
        self.required_permission = None

        if 'required_permission' in kwargs:
            self.required_permission = kwargs['required_permission']
            del(kwargs['required_permission'])

        oBlueprint.__init__(self, name, import_name, **kwargs)
Example #28
0
    def __init__(self):
        Blueprint.__init__(self, 'contact_us', __name__, url_prefix='/contact_us',
                           template_folder='views',
                           static_folder='static',
                           static_url_path='/static/home')

        @self.route('/', methods=['GET'])
        def api_index():
            return render_template("contact_us_index.html")
Example #29
0
    def test_url_with_blueprint_absolute_scheme(self):
        app = Flask(__name__)
        bp = Blueprint("foo", __name__, url_prefix="/foo")
        bp.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        app.register_blueprint(bp)
        field = fields.Url(absolute=True, scheme='https')

        with app.test_request_context("/foo/hey", base_url="http://localhost"):
            self.assertEquals("https://localhost/foo/3", field.output("hey", Foo()))
Example #30
0
 def __init__(self, *args, **kwargs):
     if "dup_on_startswith" in kwargs:
         ds = kwargs.pop("dup_on_startswith")
         if isinstance(ds, basestring) or not hasattr(ds, "__iter__"):
             self._dup_on_startswith = {ds}
         else:
             self._dup_on_startswith = set(ds)
     Blueprint.__init__(self, *args, **kwargs)
     self.decorators = {}
Example #31
0
import config
from flask import Blueprint
from urllib.parse import unquote

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


# Create a function called "chunks" with two arguments, l and n:
def chunks(l, n):
    # For item i in a range that is a length of l,
    for i in range(0, len(l), n):
        # Create an index range for l of n items:
        yield l[i:i+n]


@playlists.route('/playlists')
def get_playlists():
    return config.sp.current_user_playlists()


@playlists.route('/playlists/combine/<playlist_ids>/name/<name>')
def combine_playlists(playlist_ids, name):
    user_id = config.sp.current_user()['id']
    name = unquote(name)

    # For now, playlist ids are coming in as a comma separated list
    playlist_ids = playlist_ids.split(',')
    tracks = set()
    for id in playlist_ids:
        playlist_details = config.sp.user_playlist_tracks(user_id, id)
        for item in playlist_details['items']:
Example #32
0
from flask import Blueprint
from main import db
from flask import render_template, url_for, redirect, abort
from main.decks.forms import CreateDeckForm, CreateCardForm
from main.models import User, Deck, Card
from flask_login import current_user, login_required
import random

decks = Blueprint('decks', __name__)


@decks.route('/decks', methods=['GET', 'POST'])
@login_required
def all_decks():
    form = CreateDeckForm()
    if form.validate_on_submit():
        deck = Deck(title=form.title.data, owner_id=current_user.id)
        db.session.add(deck)
        db.session.commit()
        return redirect(url_for('decks.all_decks'))
    return render_template('decks.html', title="Decks", form=form, Card=Card)


@decks.route('/deck/<int:deck_id>', methods=['GET', 'POST'])
@login_required
def deck(deck_id):
    deck = Deck.query.get_or_404(deck_id)
    # TODO: Deck should exist!

    # Shouldn't want users to access decks they dont own!
    if deck.owner_id != current_user.id:
Example #33
0
from flask import Blueprint

campaign_manager = Blueprint(
        'campaign_manager',
        __name__,
        template_folder='templates',
        static_folder='static',
        static_url_path='/static'
)

from campaign_manager import views
Example #34
0
import eventlet
from flask import Blueprint, request
from flask_login import current_user

import context
from db import db_service
from lib import ai, elo
from lib.game import Game, GameState, Speed
from lib.replay import Replay
from web import game_states


TICK_PERIOD = 0.1
DEFAULT_RATING = 1200

game = Blueprint('game', __name__)

socketio = None  # populated by initialize()


def generate_game_id():
    return ''.join(random.choice(string.ascii_uppercase + string.digits) for i in xrange(6))


@game.route('/api/game/new', methods=['POST'])
def new():
    data = json.loads(request.data)
    speed = data['speed']
    bots = data.get('bots', {})
    bots = {int(player): ai.get_bot(difficulty) for player, difficulty in bots.iteritems()}
    username = data.get('username')
Example #35
0
import os
from flask import (Blueprint, send_from_directory)

static_folder = '../../../front/dist/'
static_blueprint = Blueprint('static', __name__, static_folder=static_folder)

static_file_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                               static_folder)


@static_blueprint.route('/')
def app():
    return send_from_directory(static_file_dir, 'index.html')


@static_blueprint.route('/<query>')
def app_routes(query):
    return send_from_directory(static_file_dir, 'index.html')


@static_blueprint.route('/<path:path>')
def static_proxy(path):
    """ static folder serve """
    file_name = path.split('/')[-1]
    dir_name = os.path.join(static_file_dir, '/'.join(path.split('/')[:-1]))
    return send_from_directory(dir_name, file_name)
Example #36
0
# Copyright (C) 2017 Linaro Limited
# Author: Andy Doan <*****@*****.**>

from flask import Blueprint, request

from jobserv.api.run import _authenticate_runner, _get_run, _handle_triggers
from jobserv.jsend import jsendify
from jobserv.models import BuildStatus, Run, Test, TestResult, db
from jobserv.storage import Storage

prefix = '/projects/<project:proj>/builds/<int:build_id>/runs/<run>/tests'
blueprint = Blueprint('api_test', __name__, url_prefix=prefix)


@blueprint.route('/', methods=('GET', ))
def test_list(proj, build_id, run):
    r = _get_run(proj, build_id, run)
    return jsendify({'tests': [x.as_json(detailed=False) for x in r.tests]})


@blueprint.route('/<test>/', methods=('GET', ))
def test_get(proj, build_id, run, test):
    r = _get_run(proj, build_id, run)
    t = Test.query.filter_by(run_id=r.id, name=test).first_or_404()
    return jsendify({'test': t.as_json(detailed=True)})


def create_test_result(test, test_result_dict):
    name = test_result_dict['name']
    status = BuildStatus[test_result_dict['status']]
    context = test_result_dict.get('context')
Example #37
0
""" Wibed experiment-api functionality. """

from flask import Blueprint, jsonify
from models.experiment import Experiment
from blueprints.userapi.commandapi import commandExecutions
import logging

bpExperimentAPI = Blueprint("userAPI.experiment", __name__, template_folder="../templates")

@bpExperimentAPI.route("/experimentInfo/<name>", methods=["GET"])
def experimentInfo(name):
    experiment = Experiment.query.filter_by(name=name).first()
    if experiment:
    	nodes = experiment.nodes
	resultName = name+"_"+str(experiment.creationTime)
	resultName = resultName.replace(" ","_")
	resultName = resultName.replace(":","-")
        output = {
            	"id": experiment.id,
                "nodes": [node.id for node in experiment.nodes],
                "commands": [command.id for command in experiment.commands],
		"resultdir": resultName
                }
        return jsonify(output)

    else:
        return jsonify({"error": "wrong ID"})

@bpExperimentAPI.route("/experimentNodes/<name>", methods=["GET"])
def experimentNodes(name):
    experiment = Experiment.query.filter((Experiment.name==name) & (Experiment.status==Experiment.Status.RUNNING) ).first()
from flask import Blueprint, jsonify, request
from off_chain_api.app_setup import db
from off_chain_api.model.user_type import UserType, user_type_schema, user_types_schema

user_type_routes = Blueprint('user_type_routes',
                             __name__,
                             template_folder='routes')


@user_type_routes.route('/user_type', methods=['GET'])
def get_all():
    all_user_types = UserType.query.all()
    results = user_types_schema.dump(all_user_types)
    return jsonify(results)


@user_type_routes.route('/user_type/<user_type_id>', methods=['GET'])
def get(user_type_id):
    return user_type_schema.jsonify(UserType.query.get(user_type_id))


@user_type_routes.route('/user_type/type_code/<type_code>', methods=['GET'])
def get_by_type_code(type_code):
    user_type = UserType.query.filter_by(type_code=type_code).first()
    return user_type_schema.jsonify(user_type)


@user_type_routes.route('/user_type', methods=['POST'])
def add():
    parameters = request.json
Example #39
0
    SubPostContentHistory,
    SubPostTitleHistory,
    SubPostReport,
    SubUserFlairChoice,
)
from ..forms import EditSubFlair, EditSubForm, EditSubCSSForm, EditMod2Form, EditSubRule
from ..forms import (
    BanUserSubForm,
    CreateSubFlair,
    PostComment,
    CreateSubRule,
    AssignSubUserFlair,
)
from .. import misc

blueprint = Blueprint("sub", __name__)


@blueprint.route("/<sub>/")
@blueprint.route("/<sub>")
def view_sub(sub):
    """ Here we can view subs """
    if sub.lower() == "all":
        return redirect(url_for("home.all_hot", page=1))

    try:
        sub = Sub.get(fn.Lower(Sub.name) == sub.lower())
    except Sub.DoesNotExist:
        abort(404)

    try:
Example #40
0
from flask import Blueprint,g,current_app,jsonify
from flask_restful import Resource,marshal_with,Api,fields
from models import Article
from flask_httpauth import HTTPBasicAuth #导入认证类
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
article_bp = Blueprint('article',__name__)

api = Api(article_bp)
auth = HTTPBasicAuth()  #实例化一个认证对象



@auth.verify_password
def verify_password(username_or_token,password):
    #如果传入用户名和密码 然后进行相关的验证
    if username_or_token == 'kangbazi' and password == '123456':
        g.username = username_or_token
        return True

    #当你传过来的是一个token

    s = Serializer(current_app.config['SECRET_KEY'],expires_in=3600) #验证token是否合法
    try:
        data = s.loads(username_or_token)
        g.username = data.get('username')
        return True
    except:
        return False


Example #41
0
## You should have received a copy of the GNU General Public License
## along with Zenodo. If not, see <http://www.gnu.org/licenses/>.
##
## In applying this licence, CERN does not waive the privileges and immunities
## granted to it by virtue of its status as an Intergovernmental Organization
## or submit itself to any jurisdiction.


import requests
from flask import Blueprint, request, current_app, abort
from invenio.utils.persistentid import is_doi

blueprint = Blueprint(
    'zenodo_citationformatter',
    __name__,
    url_prefix="/citeproc",
    static_folder="static",
    template_folder="templates",
)


@blueprint.route('/format', methods=['GET'])
def format():
    doi = request.args.get('doi', '')
    lang = request.args.get(
        'lang', current_app.config['CITATIONFORMATTER_DEFAULT_LANG'])
    style = request.args.get(
        'style', current_app.config['CITATIONFORMATTER_DEFAULT_STYLE'])

    # Abort early on invalid DOI.
    if not is_doi(doi):
Example #42
0
# -*- coding:utf8 -*-
'''
index page.
'''
__all__ = []
__version__ = '0.0.1'
__author__ = 'Bevis'

from flask import Blueprint
import app
from ..models import Remark_Attitude

# 通过实例化一个 Blueprint 类对象可以创建蓝本。
comment = Blueprint('comment', __name__)
# 动态加载到app的路由链表中
app.fetchRoute(comment, '/comment')


# 把简评模型条件填充到模板中
@comment.app_context_processor
def inject_permission():
    return dict(Remark_Attitude=Remark_Attitude)


from . import views
Example #43
0
from flask import Blueprint

bp = Blueprint('pgf', __name__)

from app.pgf import player_game_finder
Example #44
0
from flask import Blueprint, render_template, json, jsonify, request, flash, url_for, current_app
from timeline import Timeline
from forms import SearchForm
from election import Election

ca = Blueprint('ca', __name__, template_folder='templates', static_folder='static')

@ca.route('/', methods=['GET','POST'])
def index():
	if request.method == 'POST':
		form = SearchForm(request.form)
		if form.validate():
			year = form.year.data
			e = loadElectionData(year)
			return render_template('ca/map.html', e=e)
		else:
			flash('Please choose an election year')
			return frontPage()
	else: 
		return frontPage()

def frontPage():
	return render_template('ca/index.html', form=SearchForm())

@ca.route('/getCurrentElectionJson')
def getCurrentElectionJson():
	return jsonify(current_app.current_election_json)
	
@ca.route('/getTimelinePath/<year>/<name>/<state>')
def getTimelinePath(year, name, state):
	return render_template('ca/timeline.html', year=year, name=name, state=state)
Example #45
0
from flask import Blueprint, render_template
from flask_login import current_user, login_required

from wikiflix.core import NavBar
from wikiflix.models import CarouselImage
from wikiflix.models.wiki import wiki


blueprint = Blueprint("home", __name__, template_folder="templates", static_folder="static")


@blueprint.route("/")
def home():
	recently_added_wiki = wiki.query.order_by(wiki.titel.desc()).limit(3).all()
	
	carousel = CarouselImage.query.all()

	navbar = NavBar.default_bar(active_page="Home")
	return render_template("home.html", navbar=navbar, recently_added_wiki=recently_added_wiki, carousel=carousel)

@blueprint.route("/profile")
@login_required
def profile():
	navbar = NavBar.default_bar()

	return render_template("profile.html", navbar=navbar)

@blueprint.route("/profile/collected")
def profile_collected_wiki():
	navbar = NavBar.default_bar()
Example #46
0
import functools
import json
from utils import uog
from flask import (Blueprint, flash, g, redirect, render_template, request,
                   session, url_for, jsonify)

courses_bp = Blueprint('courses', __name__, url_prefix='/courses')


@courses_bp.route('/', methods={'POST'})
def getCourses():
    courses = uog.webadvisorQuery(request.form or json.loads(request.data))
    only_data = courses['data'].values()
    return render_template(
        'results.html', title='Results',
        courses=only_data), 200 if courses['success'] else 400
from flask import Blueprint
from flask_restx import Api, fields

from .resources import PlayerItemResource, PlayerResource, PlayerResourceStats

bp = Blueprint("restapi", __name__, url_prefix="/api/")


api = Api(bp, doc='/', version='1.0', title='PesMaster Database API',
    description="Uma API com o banco de dados do PES2021 convertido para PES6\n\nDesenvolvido por: Fábio Vitor \n\nGithub: https://github.com/FVitor7\nemail: [email protected]\n\nPara acessar a api vá para a url: http://localhost:5000/api/v1/")


ns = api.namespace("players", description="API  operations")

player = api.model('API', {
    "id": fields.Integer(readonly=True, description='Necessário para identificar o jogador'),
    "image": fields.String(required=True, description='URL da imagem do jogador'),
    "name": fields.String(required=True, description='Nome do Jogador'),
    "nation": fields.String(required=True, description='Nacionalidade do Jogador'),
    "over": fields.String(required=True, description='Overall do Jogador'),
    "pos": fields.String(required=True, description='Posição do Jogador'),
    "selfLink": fields.String(required=True, description='Link externo do Jogador'),
    "team": fields.String(required=True, description='Time do Jogador'),
})



def init_app(app):
    app.register_blueprint(bp)
    api.add_resource(PlayerResource, "/v1/")
    api.add_resource(PlayerItemResource, "/v1/<player_id>")
Example #48
0
from flask import Blueprint, redirect, render_template, request, url_for, session, jsonify
agent_blueprint = Blueprint('agent', __name__, template_folder='templates', static_folder='static')

@agent_blueprint.route('/index/')
def index():
    return ''
@agent_blueprint.route('/bill/')
def bill():
    return ''
@agent_blueprint.route('/daystatis/')
def daystatis():
    return ''
Example #49
0
import json
import os
import hashlib
from tools import rand_string
from flask import Blueprint, request
from public import api_factory, err_factory, check_login

icon_api = Blueprint('icon_api', __name__)


def file_md5(file_path):
    with open(file_path, 'rb') as f:
        md5obj = hashlib.md5()
        md5obj.update(f.read())
        _hash = md5obj.hexdigest()
    return str(_hash).upper()


def parsing(icon_path):
    result = []
    with open(icon_path, 'r', encoding='utf-8') as f:
        readlines = f.read().split('\n')
    for line_ in readlines:
        line = line_.replace(' ', '')
        if line.find(':before') != -1:
            class_ = line.split(':')[0].replace('.', '')
            result.append(class_)
    return result


def write_file(icon_path, list_):
Example #50
0
File: news.py Project: wleddy/news
from flask import request, session, g, redirect, url_for, abort, \
     render_template, flash, Blueprint, Response
from takeabeltof.date_utils import getDatetimeFromString
from news.models import Article 
from users.admin import login_required, table_access_required
from takeabeltof.utils import cleanRecordID, printException, render_markdown_for, render_markdown_text

mod = Blueprint('news',__name__, template_folder='../templates', url_prefix='/news')


def setExits():
    g.homeURL = url_for('.display')
    g.listURL = g.homeURL
    g.editURL = url_for('.edit')
    g.deleteURL = url_for('.delete')
    g.viewURL = url_for('.view',article_handle = -1)
    g.title = 'News'

@mod.route('/', methods=["GET",])
def display():
    setExits()
    #import pdb; pdb.set_trace()
    rendered_html = render_markdown_for(__file__,mod,'news/news.md')
    
    recs = Article(g.db).select()
    
    return render_template('news/news.html',
        rendered_html=rendered_html, recs = recs,
        )    

@mod.route('/view', methods=["GET",])
Example #51
0
from flask_login import login_user, current_user, logout_user, login_required
from wtgnc import db
from flask import render_template, url_for, session, flash, redirect, request, Blueprint
from wtgnc.models import User, Pick, WeeklyResult, WeeklyStanding
from wtgnc.users.forms import RegistrationForm, LoginForm, UpdateAccountForm, RequestResetTokenForm, PasswordResetForm
from wtgnc.users.utils import send_reset_email, save_picture

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

@users.route('/register', methods=['GET', 'POST'])
@login_required
def register():
    if current_user.is_authenticated and current_user.role != 'admin':
        flash('You are already logged in as a registered user.  Contact a commissioner to register a new account.', 'info')
        return redirect(url_for('main.home'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(user_first_name=form.user_first_name.data, user_last_name=form.user_last_name.data, display_name=form.display_name.data, email=form.email.data, role=form.role.data)
        user.set_pw(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash(f'Account created for {form.display_name.data}!', 'success')
        return redirect(url_for('main.home'))
    return render_template('users/register.html', title='Register', form=form)


@users.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        flash('You are already logged in.', 'info')
        return redirect(url_for('main.home'))
Example #52
0
import io
import base64
from flask import Flask, Blueprint, render_template, request
from PIL import Image
from model import new_net, model_eval_prep, model_eval

net = model_eval_prep(new_net(), path="./model.pt")
bp = Blueprint("", __name__)


def create_app():
    app = Flask(__name__)
    app.register_blueprint(bp)
    return app


@bp.route("/", methods=["GET"])
def index():
    return render_template("index.html")


@bp.route("/eval", methods=["POST"])
def eval():
    global net
    data = request.get_json()
    image = Image.open(io.BytesIO(base64.b64decode(data["data"]))).convert("RGB")
    return {"data": model_eval(net, image)}
Example #53
0
from flask import Blueprint, request, jsonify, abort
import flask
from authlib.client import OAuth1Session
import redis
from decouple import config
import tweepy
import json
from authlib.jose import jwt
import datetime
from .models import User, db
from functools import wraps

AUTH = Blueprint('auth', __name__)
REDIS_URL_STRING = config('REDIS_URL')
R = redis.Redis.from_url(REDIS_URL_STRING)
APP = flask.current_app


class JWTHS256():
    def __init__(self, key, iss):
        self.key = key
        self.header = {'alg': 'HS256'}
        self.iss = iss

    def encode(self, payload):
        now = datetime.datetime.now()
        tomorrow = now + datetime.timedelta(days=1)
        new_payload = {
            'iat': int(now.timestamp()),
            'exp': int(tomorrow.timestamp()),
            'iss': self.iss
Example #54
0
from flask import Flask, request, render_template, jsonify, Blueprint
import get_orgs
import requests
import ast



api_call = Blueprint('api_call', __name__)

query = "black transmens inc" #would come from requests.args

@api_call.route('/backend/search', methods=['GET', 'POST'])
def search_data():

    # Assuming the request is coming from an AJAX call
    # Gets value of term user sent in
    if request.method == "POST":
        json_data = request.get_json()
        # Value in the dict could be labeled differently
        search_term = json_data["search_term"]

        if search_term in get_orgs.org_list():
            org_index = get_orgs.org_list().index(search_term)
            ein = get_orgs.ein_list()[org_index]
            #link = get_orgs.donation_links()[org_index]

            org_data = {
                "ein": ein,
                "name": search_term
            }
Example #55
0
File: app.py Project: viyh/pyrrot
    return js, 200, {"Content-Type": "application/javascript; charset=utf-8"}


@app.route("/<path:filename>")
def send_static(filename):
    return send_from_directory("static", filename)


@app.route("/favicon.ico")
def send_favicon():
    return send_file("static/images/left.gif", mimetype="image/gif")


# API

v1 = Blueprint("v1", "v1")


@v1.route("/", methods=["GET"])
def home():
    return "<h1>pyrrot</h1><p>API to generate Party Parrots.</p>"


@v1.route("/parrots", methods=["GET"])
def parrotlist():
    return jsonify(list(PARROTS.keys()))


@v1.route("/parrots/<string:name>", methods=["GET", "POST"])
def parrot(name):
    params = request.args
Example #56
0
#各組分別在各自的 .py 程式中建立應用程式 (第1步/總共3步)
from flask import Blueprint, render_template

# 利用 Blueprint建立 ag1, 並且 url 前綴為 /ag1, 並設定 template 存放目錄
scrum6_task40323233 = Blueprint('scrum6_task40323233', __name__, url_prefix='/bg9', template_folder='templates')

# scrum6_task33 為完整可以單獨執行的繪圖程式
@scrum6_task40323233.route('/scrum6_33_1')
def scrum6_33_1():
    outstring = '''

from javascript import JSConstructor
from browser import window
import math
cango = JSConstructor(window.Cango)
cobj = JSConstructor(window.Cobj)
shapedefs = window.shapeDefs
obj2d = JSConstructor(window.Obj2D)
cgo = cango("plotarea")
cgo.setWorldCoords(-250, -250, 500, 500) 

        
#cgo.drawText("使用 Cango 繪圖程式庫!", 0, 0, {"fontSize":60, "fontWeight": 1200, "lorg":5 })
deg = math.pi/180  
def O(x, y, rx, ry, rot, color, border, linewidth):
    # 旋轉必須要針對相對中心 rot not working yet
    chamber = "M -6.8397, -1.4894 \
                     A 7, 7, 0, 1, 0, 6.8397, -1.4894 \
                     A 40, 40, 0, 0, 1, 6.8397, -18.511 \
                     A 7, 7, 0, 1, 0, -6.8397, -18.511 \
                     A 40, 40, 0, 0, 1, -6.8397, -1.4894 z"
import facebook

from flask import url_for, current_app, Blueprint, request, redirect
from superform.utils import login_required
from superform.models import db, Channel

facebook_page = Blueprint('facebook_callback', __name__)

@facebook_page.route("/callback_fb", methods=['GET', 'POST'])
@login_required(admin_required=True)
def callback_fb():
    """Page where Facebook returns the code to get the access token.
        Generate the access token from the code and save it to the DB."""
    id_channel = request.args.get('state')
    code = request.args.get('code')
    if id_channel is None:
        return redirect(url_for("channels.channel_list"))

    app_id = current_app.config["FACEBOOK_APP_ID"]
    app_secret = current_app.config["FACEBOOK_APP_SECRET"]
    canvas_url = url_for('facebook_callback.callback_fb', _external=True)
    graph = facebook.GraphAPI()
    try:
        res = graph.get_access_token_from_code(code, canvas_url, app_id, app_secret)
        access_token = res['access_token']
    except facebook.GraphAPIError:
        access_token = 'Unable to generate access_token'

    channel = Channel.query.get(id_channel)
    if channel == None or channel.module != 'superform.plugins.facebook':
        return redirect(url_for("channels.channel_list"))
Example #58
0
from flask import Blueprint, render_template, url_for, flash, redirect, request, abort
from flask_login import current_user, login_required
from flaskblog import db
from flaskblog.models import Post
from flaskblog.posts.forms import PostForm
from flaskblog.posts.utils import save_picture

from Dash.dashapp import UPLOAD_DIRECTORY
import os

posts = Blueprint('posts', __name__)


@posts.route('/post/new', methods=['GET', 'POST'])
@login_required
def new_post():
    form = PostForm()
    if form.validate_on_submit():

        picture_file = None
        print(form.picture.data)
        #If there is picture data, change profile picture
        if form.picture.data:
            print('form.picture.data has the picture')

            picture_file = save_picture(form.picture.data)
        #Create post and add to database
        post = Post(title=form.title.data,
                    content=form.content.data,
                    author=current_user,
                    image_file=picture_file)
from flask import Blueprint, render_template, url_for, flash, request, session, g
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import redirect
import functools
from app import db
from ..forms import SignupForm, UserLoginForm, UsermodifyForm, RegistForm
from ..models import User, Evaluate
import logging

bp = Blueprint('evaluate', __name__, url_prefix='/evaluate')


def login_required(view):
    @functools.wraps(view)
    def wrapped_view(**kwargs):
        if g.user is None:
            return redirect(url_for('auth.login'))
        return view(**kwargs)

    return wrapped_view


@bp.before_app_request
def load_logged_in_user():
    user = session.get('user')
    if user is None:
        g.user = None
    else:
        g.user = User.query.get(user)

Example #60
0
from flask import Blueprint, request, jsonify, make_response
from flask_restful import Api, Resource
from http_status import HttpStatus
from models import orm, NotificationCategory, NotificationCategorySchema, Notification, NotificationSchema
from sqlalchemy.exc import SQLAlchemyError
from helpers import PaginationHelper
from flask_httpauth import HTTPBasicAuth
from flask import g
from models import User, UserSchema

auth = HTTPBasicAuth()

service_blueprint = Blueprint('service', __name__)
notification_category_schema = NotificationCategorySchema()
notification_schema = NotificationSchema()
user_schema = UserSchema()
service = Api(service_blueprint)


@auth.verify_password
def verify_user_password(name, password):
    user = User.query.filter_by(name=name).first()
    if not user or not user.verify_password(password):
        return False
    g.user = user
    return True


class AuthenticationRequiredResource(Resource):
    method_decorators = [auth.login_required]
    user_schema = UserSchema()