Exemplo n.º 1
0
    def init_app(self, app):
        """Initialise the `app` for use with :py:class:`~Fundatio`.

        This method is automatically invoked if an `app` instance is
        passed to the :py:class:`~Fundatio` constructor.

        Fundatio uses the following configuration variables:

        * ``FUNDATIO_JAVASCRIPT_LIBRARY``
        """

        javascript_library = app.config.setdefault(
            'FUNDATIO_JAVASCRIPT_LIBRARY', DEFAULT_JAVASCRIPT_LIBARY)
        if not javascript_library in JAVASCRIPT_LIBRARIES:
            raise ValueError(
                "Invalid 'FUNDATIO_JAVASCRIPT_LIBRARY' value in config; "
                "must be one of %r, but found %r"
                % (JAVASCRIPT_LIBRARIES, javascript_library))

        icon_sets = app.config.setdefault('FUNDATIO_ICON_SETS', [])
        if set(icon_sets) - ICON_SETS:
            raise ValueError(
                "Invalid 'FUNDATIO_ICON_SETS' value in config; "
                "valid list values are: %s"
                % ', '.join(ICON_SETS))

        blueprint = Blueprint(
            'fundatio',
            __name__,
            static_folder='static',
            # XXX: specify explicit static url path to work around
            # https://github.com/mitsuhiko/flask/issues/348
            static_url_path='%s/foundation' % app.static_url_path,
            template_folder='templates',
        )

        blueprint.add_app_template_filter(
            field_kwargs_filter,
            name='_fundatio_form_field_kwargs')
        blueprint.add_app_template_filter(
            label_kwargs_filter,
            name='_fundatio_form_label_kwargs')

        app.register_blueprint(blueprint)
def create_blueprint(app):
    """Register blueprint routes on app."""
    routes = app.config.get("INVENIO_MARC21_UI_ENDPOINTS")

    blueprint = Blueprint(
        "invenio_records_marc21",
        __name__,
        template_folder="../templates",
    )

    # Record URL rules
    blueprint.add_url_rule(
        routes["index"],
        view_func=marc21_index,
    )

    # Record URL rules
    blueprint.add_url_rule(
        routes["record_detail"],
        view_func=record_detail,
    )

    blueprint.add_url_rule(
        routes["record_export"],
        view_func=record_export,
    )

    # Register error handlers
    blueprint.register_error_handler(PIDDeletedError, record_tombstone_error)
    blueprint.register_error_handler(PIDDoesNotExistError, not_found_error)
    blueprint.register_error_handler(KeyError, not_found_error)
    blueprint.register_error_handler(
        PermissionDeniedError, record_permission_denied_error
    )

    blueprint.add_app_template_filter(pid_url)
    blueprint.add_app_template_filter(sanitize_title)
    return blueprint
Exemplo n.º 3
0
# coding: utf-8

import os
from flask import Blueprint, request, session, current_app, json
from flask import render_template, abort, redirect
from werkzeug.security import gen_salt
from zerqu.libs.cache import cache, ONE_HOUR
from zerqu.libs.utils import is_robot, xmldatetime
from zerqu.rec.timeline import get_all_topics
from zerqu.models import db, User, Cafe, Topic, CafeTopic, Comment


bp = Blueprint('front', __name__, template_folder='templates')
bp.add_app_template_filter(xmldatetime)


@bp.before_request
def manifest_hook():
    manifest_file = current_app.config.get('SITE_MANIFEST')
    if not manifest_file or not os.path.isfile(manifest_file):
        request.manifest = None
        return

    manifest_mtime = os.path.getmtime(manifest_file)
    latest = getattr(current_app, 'manifest_mtime', 0)
    if latest != manifest_mtime:
        current_app.manifest_mtime = manifest_mtime
        with open(manifest_file) as f:
            manifest = json.load(f)
            current_app.manifest = manifest
Exemplo n.º 4
0
     Query, Query_instance, Gps_remap
from tutorial.models import Tabdata_dataset, Tabdata_query, \
     Tabdata_query_instance
from marion_biblio.progressivegenerators import QueueReporter
from tutorial.geocache import get_location
import json
import logging
import gevent
tutorial_bp = Blueprint('tutorial_bp', __name__, template_folder='templates')


def authorlink_filter(s):
    return 'http://scholar.google.com/scholar?q={0}'.format(s)


tutorial_bp.add_app_template_filter(authorlink_filter, "authorlink")


@tutorial_bp.before_request
def before_request():
    g.user = current_user


@tutorial_bp.route("/logout")
def logout():
    logout_user()
    return redirect(url_for('index'))


# @oid.after_login
def after_login(resp):
Exemplo n.º 5
0
trips.add_url_rule('/new', view_func=CreateTripView.as_view('new'))
trips.add_url_rule('/<slug>/update',
                   view_func=UpdateTripView.as_view('update'))

# Points CRUD


def weekday_class(weekday: str) -> str:
    weekday = escape(weekday)
    wday_short = weekday[0:3]
    weekday_classes = TwScheduleClasses.WEEKDAYS
    return weekday_classes.get(wday_short, weekday_classes['_default'])


trips.add_app_template_filter(weekday_class, 'weekday_class')
trips.add_app_template_global(TwScheduleClasses.CELL_CLASS,
                              'schedule_cell_class')
trips.add_app_template_global(TwScheduleClasses.COMMON_WEEKDAY_CLASS,
                              'schedule_weekday_class')


def trip_point_wrapper(f):
    @wraps(f)
    def handler(slug: str, id: int):
        trip = Trip.query.filter_by(slug=slug).first_or_404()
        point = Point.query.filter(Point.trip == trip, Point.id == id)\
                           .first_or_404()

        add_breadcrumb('Trips', url_for('.index'))
        add_breadcrumb(trip.name, url_for('.show', slug=trip.slug))
Exemplo n.º 6
0
import logging
from datetime import datetime
from collections import Counter

from my.util import i2ch
from my.db import datastore
from google.appengine.api import memcache

from flask import Blueprint, Markup, request
apis = Blueprint('apis', __name__)

def replace_id(value, id):
    """ID に strong タグを付けて強調する"""
    result = value.replace(id, '<strong>' + id + '</strong>')
    return Markup(result)
apis.add_app_template_filter(replace_id)

@apis.route('/userlist.js')
def userlistjs():
    """ユーザー一覧を JavaScript の変数として出力する"""
    memcache_key = 'userlistjs';
    ids = memcache.get(memcache_key)
    if ids is None:
        ids = json.dumps(datastore.get_all_ids(), indent=0)
        memcache.add(memcache_key, ids, 60 * 60 * 24)
    return 'var userlist = ' + ids + ';';

# /system/ 以下の URL は cron などでアプリから実行される前提であるものとする

@apis.route('/system/delete')
def delete():
Exemplo n.º 7
0
def create_blueprint(endpoints):
    """Create Invenio-Records-REST blueprint.

    :params endpoints: Dictionary representing the endpoints configuration.
    :returns: Configured blueprint.
    """
    endpoints = endpoints or {}

    blueprint = Blueprint(
        'reroils_record_editor',
        __name__,
        template_folder='templates',
        static_folder='static',
        url_prefix='/editor',
    )
    rec_types = endpoints.keys()
    blueprint.add_app_template_filter(can_edit)
    blueprint.add_app_template_filter(jsondumps)
    blueprint.register_error_handler(PermissionDenied,
                                     permission_denied_page)
    menu_func = partial(init_menu, endpoints=endpoints)
    menu_func.__module__ = init_menu.__module__
    menu_func.__name__ = init_menu.__name__
    blueprint.before_app_request(menu_func)
    for rec_type in rec_types:
        # search view
        if endpoints.get(rec_type, {}).get('api'):
            search_func = partial(search, record_type=rec_type,
                                  endpoints=endpoints)
            search_func.__module__ = search.__module__
            search_func.__name__ = search.__name__
            blueprint.add_url_rule('/search/%s' % rec_type,
                                   endpoint='search_%s' % rec_type,
                                   view_func=search_func)
        # create view
        create_func = partial(create, record_type=rec_type,
                              endpoints=endpoints)
        create_func.__module__ = create.__module__
        create_func.__name__ = create.__name__
        blueprint.add_url_rule('/create/%s' % rec_type,
                               endpoint='create_%s' % rec_type,
                               view_func=create_func)
        # update view
        update_func = partial(update, record_type=rec_type,
                              endpoints=endpoints)
        update_func.__module__ = update.__module__
        update_func.__name__ = update.__name__
        blueprint.add_url_rule('/update/%s/<int:pid>' % rec_type,
                               endpoint='update_%s' % rec_type,
                               view_func=update_func)
        # delete view
        delete_func = partial(delete, record_type=rec_type,
                              endpoints=endpoints)
        delete_func.__module__ = delete.__module__
        delete_func.__name__ = delete.__name__
        blueprint.add_url_rule('/delete/%s/<int:pid>' % rec_type,
                               endpoint='delete_%s' % rec_type,
                               view_func=delete_func)
        # save api
        save_func = partial(save, record_type=rec_type, endpoints=endpoints)
        save_func.__module__ = save.__module__
        save_func.__name__ = save.__name__
        blueprint.add_url_rule('/save/%s' % rec_type,
                               endpoint='save_%s' % rec_type,
                               view_func=save_func, methods=['POST'])
    return blueprint
Exemplo n.º 8
0
def timestamp_representation(timestamp):
    if not timestamp:
        return None
    dt = datetime.fromtimestamp(timestamp)
    dt_str = dt.astimezone(TIMEZONE).replace(microsecond=0).isoformat(sep=" ")
    return f"{dt_str} ({timestamp})"


def python_pretty_representation(string):
    try:
        return pformat(literal_eval(string))
    except (ValueError, SyntaxError):
        return string


bp.add_app_template_filter(literal_eval, "literal_eval")
bp.add_app_template_filter(date_representation, "date_representation")
bp.add_app_template_filter(timestamp_representation,
                           "timestamp_representation")
bp.add_app_template_filter(python_pretty_representation,
                           "python_pretty_representation")

TASKS_EVENTS_DEFAULT_PAGE = 1
TASKS_EVENTS_DEFAULT_LIMIT = 100


@bp.route("/", methods=["GET"])
@login_groups_required(["admins"])
def celery():
    return redirect(url_for("celery_views.feeds"))
Exemplo n.º 9
0
bp.add_url_rule('get_img/', view_func=GetImgView.as_view('get_img'))  # 公告展示
bp.add_url_rule('search/', view_func=SearchView.as_view('search'))  # 公告展示
bp.add_url_rule('tags/', view_func=TagsView.as_view('tags'))  # 公告展示

# 公告模块
bp.add_url_rule('announcement/',
                view_func=AnnouncementView.as_view('announcement'))  # 公告展示

# 快速关注公众号(彩蛋 )
bp.add_url_rule('wechat_github/',
                view_func=WechatGithubView.as_view('wechat_github'))  # 快速关注公众号

# 2019年报(公众号图表总结 )
bp.add_url_rule('year_report/',
                view_func=YearReportView.as_view('year_report'))  # 年报总结

# 公众号展示
bp.add_url_rule('account_list/',
                view_func=AccountListView.as_view('account_list'))  # 公众号展示

# 前端过滤器
bp.add_app_template_filter(tools.filter_html, 'Html')
bp.add_app_template_filter(tools.url_remove_info, 'url_remove_info')
bp.add_app_template_filter(tools.markdown2html, 'markdown2html')


@bp.app_errorhandler(404)
def page_not_found(error):

    return render_template('front/front_404.html'), 404
Exemplo n.º 10
0
# -*- coding: utf-8 -*-
from flask import Blueprint
from v2ex.utils import format_time

main = Blueprint('main', __name__)
main.add_app_template_filter(format_time, 'format_time')

from . import views 

Exemplo n.º 11
0
from ui import search_apis
from ui.utils import mongo_collections_utils

ui = Blueprint('ui', __name__,
               template_folder='./templates',
               static_folder='./static',
               )


# using the method
@jinja2.contextfilter
def get_domain(context, url):
    return "%s" % urlparse(url).netloc


ui.add_app_template_filter(get_domain)


LEADING_PARENTS = 2


##-----------Helper Functions -----------##
def render(templateName, data=None, **kwargs):
    """
    FLask Jinja rendering functio
    :param templateName: jinja template name
    :param data: json data for the template
    :return: html
    """
    if data is None:
        data = {}
Exemplo n.º 12
0
from app.auth import login_groups_required
from app.utils import (
    typing_is_dict,
    typing_is_list,
    prozorro_api_tender_path,
    prozorro_api_item_path,
    prozorro_api_complaint_path,
    prozorro_portal_tender_path,
    prozorro_api_url,
    prozorro_portal_url,
    url_for_search,
)

bp = Blueprint("app_views", __name__, template_folder="templates")

bp.add_app_template_filter(typing_is_dict, "typing_is_dict")
bp.add_app_template_filter(typing_is_list, "typing_is_list")

bp.add_app_template_filter(prozorro_portal_url, "prozorro_portal_url")
bp.add_app_template_filter(prozorro_portal_tender_path,
                           "prozorro_portal_tender_path")
bp.add_app_template_filter(prozorro_api_url, "prozorro_api_url")
bp.add_app_template_filter(prozorro_api_tender_path,
                           "prozorro_api_tender_path")
bp.add_app_template_filter(prozorro_api_item_path, "prozorro_api_item_path")
bp.add_app_template_filter(prozorro_api_complaint_path,
                           "prozorro_api_complaint_path")

bp.add_app_template_global(url_for_search, "url_for_search")

Exemplo n.º 13
0
from flask import Blueprint
from starling.flask.template_filter import *


def format_property_name(string):
    return format_pathname(string, 50)


dashboard = Blueprint("dashboard",
                      __name__,
                      template_folder="templates",
                      static_folder="static")
dashboard.add_app_template_filter(format_time_point)
dashboard.add_app_template_filter(format_pathname)
dashboard.add_app_template_filter(format_property_name)
dashboard.add_app_template_filter(format_uuid)

from . import views
Exemplo n.º 14
0
from flask_login import current_user
import pytz
from pygments import highlight
from pygments.lexers import guess_lexer, get_lexer_by_name
from pygments.formatters import html

filters = Blueprint('filters', __name__)


def base_datetime_filter(value, format_):
    if current_user.is_anonymous:
        usertz = pytz.timezone(current_app.config['TIME_ZONE'])
    else:
        usertz = pytz.timezone(current_user.timezone)
    if value:
        utc_value = pytz.utc.localize(value)
        user_value = usertz.normalize(utc_value)
        return user_value.strftime(format_)
    else:
        return "None"


def datetime_filter(value):
        return base_datetime_filter(value, "%Y-%m-%d %H:%M:%S %Z")
filters.add_app_template_filter(datetime_filter)


def forum_datetime(value):
    return base_datetime_filter(value, '%b %d, %Y %H:%M')
filters.add_app_template_filter(forum_datetime)
Exemplo n.º 15
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Blueprint

account_blueprint = Blueprint('account',
                              __name__,
                              template_folder='../templates/account/')


def index_rank(index):
    return int(index) + 1


account_blueprint.add_app_template_filter(index_rank, 'torank')

from . import views
Exemplo n.º 16
0
            return all_pkt_data[i][pkt_time][0].timestamp.isoformat(sep=' ')
        except KeyError:
            continue
    else:
        return ""


def get_valid_pkt_data(pkt_data):
    try:
        return int(pkt_data)
    except UndefinedError:
        return 0


def get_packet_length(pkt_data, pkt_time):
    pkt_list = pkt_data.get(pkt_time)

    if pkt_list is None:
        return 0
    else:
        return len(pkt_list)


pcap_blueprint.add_app_template_filter(get_valid_timestamp,
                                       'get_valid_timestamp')
pcap_blueprint.add_app_template_filter(get_packet_length, 'get_packet_length')
pcap_blueprint.add_app_template_filter(get_valid_pkt_data,
                                       'get_valid_pkt_data')

from . import views
Exemplo n.º 17
0
    def init_app(self, app):
        app.config.setdefault('BOOTSTRAP_USE_MINIFIED', True)
        app.config.setdefault('BOOTSTRAP_CDN_FORCE_SSL', False)

        app.config.setdefault('BOOTSTRAP_QUERYSTRING_REVVING', True)
        app.config.setdefault('BOOTSTRAP_SERVE_LOCAL', False)

        app.config.setdefault('BOOTSTRAP_LOCAL_SUBDOMAIN', None)

        blueprint = Blueprint(
            'bootstrap',
            __name__,
            template_folder='templates',
            static_folder='static',
            # static_url_path=app.static_url_path + '/bootstrap',
            subdomain=app.config['BOOTSTRAP_LOCAL_SUBDOMAIN'])

        # add the form rendering template filter
        blueprint.add_app_template_filter(render_form)

        app.register_blueprint(blueprint, url_prefix='/bootstrap')

        app.jinja_env.globals['bootstrap_is_hidden_field'] =\
            is_hidden_field_filter
        app.jinja_env.globals['bootstrap_find_resource'] =\
            bootstrap_find_resource
        app.jinja_env.add_extension('jinja2.ext.do')

        if not hasattr(app, 'extensions'):
            app.extensions = {}

        local = StaticCDN('bootstrap.static', rev=True)
        static = StaticCDN()

        def lwrap(cdn, primary=static):
            return ConditionalCDN('BOOTSTRAP_SERVE_LOCAL', primary, cdn)

        popper = lwrap(
            WebCDN('//cdnjs.cloudflare.com/ajax/libs/popper.js/%s/' %
                   POPPER_VERSION), local)

        bootstrap = lwrap(
            WebCDN('//stackpath.bootstrapcdn.com/bootstrap/%s/' %
                   BOOTSTRAP_VERSION), local)

        fontawesome = lwrap(
            WebCDN('//stackpath.bootstrapcdn.com/font-awesome/%s/' %
                   FONTAWESOME_VERSION), local)

        jquery = lwrap(
            WebCDN('//cdnjs.cloudflare.com/ajax/libs/jquery/%s/' %
                   JQUERY_VERSION), local)

        app.extensions['bootstrap'] = {
            'cdns': {
                'local': local,
                'static': static,
                'popper': popper,
                'bootstrap': bootstrap,
                'jquery': jquery,
                'fontawesome': fontawesome
            },
        }

        # setup support for flask-nav
        renderers = app.extensions.setdefault('nav_renderers', {})
        renderer_name = (__name__ + '.nav', 'BootstrapRenderer')
        renderers['bootstrap'] = renderer_name

        # make bootstrap the default renderer
        renderers[None] = renderer_name
Exemplo n.º 18
0
    def init_app(self, app):
        app.config.setdefault("BOOTSTRAP_USE_MINIFIED", True)
        app.config.setdefault("BOOTSTRAP_CDN_FORCE_SSL", False)

        app.config.setdefault("BOOTSTRAP_QUERYSTRING_REVVING", True)
        app.config.setdefault("BOOTSTRAP_SERVE_LOCAL", False)

        app.config.setdefault("BOOTSTRAP_LOCAL_SUBDOMAIN", None)

        blueprint = Blueprint(
            "bootstrap",
            __name__,
            template_folder="templates",
            static_folder="static",
            static_url_path=app.static_url_path + "/bootstrap",
            subdomain=app.config["BOOTSTRAP_LOCAL_SUBDOMAIN"],
        )

        # add the form rendering template filter
        blueprint.add_app_template_filter(render_form)

        app.register_blueprint(blueprint)

        app.jinja_env.globals["bootstrap_is_hidden_field"] = is_hidden_field_filter
        app.jinja_env.globals["bootstrap_find_resource"] = bootstrap_find_resource
        app.jinja_env.add_extension("jinja2.ext.do")

        if not hasattr(app, "extensions"):
            app.extensions = {}

        local = StaticCDN("bootstrap.static", rev=True)
        static = StaticCDN()

        def lwrap(cdn, primary=static):
            return ConditionalCDN("BOOTSTRAP_SERVE_LOCAL", primary, cdn)

        bootstrap = lwrap(
            WebCDN(
                "//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/%s/"
                % BOOTSTRAP_VERSION
            ),
            local,
        )

        jquery = lwrap(
            WebCDN("//cdnjs.cloudflare.com/ajax/libs/jquery/%s/" % JQUERY_VERSION),
            local,
        )

        html5shiv = lwrap(
            WebCDN("//cdnjs.cloudflare.com/ajax/libs/html5shiv/%s/" % HTML5SHIV_VERSION)
        )

        respondjs = lwrap(
            WebCDN(
                "//cdnjs.cloudflare.com/ajax/libs/respond.js/%s/" % RESPONDJS_VERSION
            )
        )

        app.extensions["bootstrap"] = {
            "cdns": {
                "local": local,
                "static": static,
                "bootstrap": bootstrap,
                "jquery": jquery,
                "html5shiv": html5shiv,
                "respond.js": respondjs,
            }
        }

        # setup support for flask-nav
        renderers = app.extensions.setdefault("nav_renderers", {})
        renderer_name = (__name__ + ".nav", "BootstrapRenderer")
        renderers["bootstrap"] = renderer_name

        # make bootstrap the default renderer
        renderers[None] = renderer_name
Exemplo n.º 19
0
# template_folder=path.join(path.pardir,'templates','sam_app')
def sidebar_data():
    recent = Post.query.order_by(Post.publish_data.desc()).limit(5).all()
    top_tags = db.session.query(
        Tag,
        func.count(tags.c.post_id).label('total')).join(tags).group_by(
            Tag).order_by('total DESC').limit(5).all()
    return recent, top_tags


def float_to_percent(float_value):
    per = '{}%'.format((str(round(float_value, 4) * 100))[:5])
    return per


sam_bp.add_app_template_filter(float_to_percent,
                               'float_to_percent')  # 添加jinja2过滤器


@sam_bp.route('/', methods=['GET', 'POST'])
def index():
    # whatch_dir.delay()
    # if request.method == 'GET':
    #     send_mail()
    return render_template('index.html')


@sam_bp.route('/new/', methods=['GET', 'POST'])
@login_required
@default_permission.require(http_exception=403)
def new_post():
    form = PostForm()
Exemplo n.º 20
0
    def get(self):
        return render_template('cms/cms_resetpw.html')

    def post(self):
        form = ResetpwdForm(request.form)
        if form.validate():
            oldpwd = form.oldpwd.data
            newpwd = form.newpwd.data
            user = g.cms_user
            if user.check_password(oldpwd):
                user.password = newpwd
                db.session.commit()
                return field.success()
            else:
                return field.params_error('旧密码错误!')
        else:
            message = form.get_error()
            return field.unauth_error(message=message)


bp.add_url_rule('login/', view_func=LoginView.as_view('login'))
bp.add_url_rule('resetemail/', view_func=ResetEmail.as_view('resetemail'))
bp.add_url_rule('resetpw/', view_func=ReetPWView.as_view('resetpw'))
bp.add_url_rule('secretkey/', view_func=SecretKey.as_view('secretkey'))
bp.add_url_rule('profile/', view_func=ProFileView.as_view('profile'))
bp.add_app_template_filter(StringToInt, 'To')
bp.add_app_template_filter(StatusToString, 'UPORDOWN')
bp.add_app_template_filter(NoneToString, 'None')
bp.add_app_template_filter(NoneToNone, 'Zero')
bp.add_app_template_filter(TitleToShort, 'Title')
Exemplo n.º 21
0
def create_blueprint(endpoints):
    """Create Invenio-Records-REST blueprint.

    :params endpoints: Dictionary representing the endpoints configuration.
    :returns: Configured blueprint.
    """
    endpoints = endpoints or {}

    blueprint = Blueprint(
        'reroils_record_editor',
        __name__,
        template_folder='templates',
        static_folder='static',
        url_prefix='/editor',
    )
    rec_types = endpoints.keys()
    blueprint.add_app_template_filter(can_edit)
    blueprint.add_app_template_filter(jsondumps)
    blueprint.register_error_handler(PermissionDenied, permission_denied_page)
    menu_func = partial(init_menu, endpoints=endpoints)
    menu_func.__module__ = init_menu.__module__
    menu_func.__name__ = init_menu.__name__
    blueprint.before_app_request(menu_func)
    for rec_type in rec_types:
        # search view
        if endpoints.get(rec_type, {}).get('api'):
            search_func = partial(search,
                                  record_type=rec_type,
                                  endpoints=endpoints)
            search_func.__module__ = search.__module__
            search_func.__name__ = search.__name__
            blueprint.add_url_rule('/search/%s' % rec_type,
                                   endpoint='search_%s' % rec_type,
                                   view_func=search_func)
        # create view
        create_func = partial(create,
                              record_type=rec_type,
                              endpoints=endpoints)
        create_func.__module__ = create.__module__
        create_func.__name__ = create.__name__
        blueprint.add_url_rule('/create/%s' % rec_type,
                               endpoint='create_%s' % rec_type,
                               view_func=create_func)
        # update view
        update_func = partial(update,
                              record_type=rec_type,
                              endpoints=endpoints)
        update_func.__module__ = update.__module__
        update_func.__name__ = update.__name__
        blueprint.add_url_rule('/update/%s/<int:pid>' % rec_type,
                               endpoint='update_%s' % rec_type,
                               view_func=update_func)
        # delete view
        delete_func = partial(delete,
                              record_type=rec_type,
                              endpoints=endpoints)
        delete_func.__module__ = delete.__module__
        delete_func.__name__ = delete.__name__
        blueprint.add_url_rule('/delete/%s/<int:pid>' % rec_type,
                               endpoint='delete_%s' % rec_type,
                               view_func=delete_func)
        # save api
        save_func = partial(save, record_type=rec_type, endpoints=endpoints)
        save_func.__module__ = save.__module__
        save_func.__name__ = save.__name__
        blueprint.add_url_rule('/save/%s' % rec_type,
                               endpoint='save_%s' % rec_type,
                               view_func=save_func,
                               methods=['POST'])
    return blueprint
Exemplo n.º 22
0
from flask import Blueprint
from jinja2.runtime import Undefined

main = Blueprint('main', __name__)


def f(s):
    if isinstance(s, Undefined):
        return ''
    return s + '_'


main.add_app_template_filter(f)

from . import views
Exemplo n.º 23
0
from cronq.utils import split_command
from cronq.utils import task_status
from cronq.utils import took

from flask import Blueprint
from flask import Response
from flask import abort
from flask import flash
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for

blueprint_http = Blueprint('blueprint_http', __name__)
blueprint_http.add_app_template_filter(split_command, 'split_command')
blueprint_http.add_app_template_filter(task_status, 'task_status')
blueprint_http.add_app_template_filter(took, 'took')

logger = logging.getLogger(__name__)


@blueprint_http.before_request
def create_storage():
    if request.path.startswith('/static/'):
        return
    g.storage = Storage(isolation_level=None)


@blueprint_http.after_request
def remove_storage(request):
Exemplo n.º 24
0
)
from payments.settings import RELEASE_2020_04_19
from payments.utils import (
    get_payments_registry,
    store_payments_registry_fake,
    generate_report_file,
    generate_report_filename,
    generate_report_title,
    get_payments_registry_fake,
    dumps_payments_registry_fake,
)
from tasks_utils.datetime import get_now, parse_dt_string

bp = Blueprint("payments_views", __name__, template_folder="templates")

bp.add_app_template_filter(date_representation, "date_representation")
bp.add_app_template_filter(payment_message_status, "payment_message_status")
bp.add_app_template_filter(payment_message_list_status,
                           "payment_message_list_status")
bp.add_app_template_filter(complaint_status_description,
                           "complaint_status_description")
bp.add_app_template_filter(complaint_reject_description,
                           "complaint_reject_description")
bp.add_app_template_filter(complaint_funds_description,
                           "complaint_funds_description")


@bp.route("/", methods=["GET"])
@login_groups_required(["admins", "accountants"])
def payment_list():
    report_kwargs = get_report_params()
Exemplo n.º 25
0
    def init_app(self, app):
        app.config.setdefault('BOOTSTRAP_USE_MINIFIED', True)
        app.config.setdefault('BOOTSTRAP_CDN_FORCE_SSL', False)

        app.config.setdefault('BOOTSTRAP_QUERYSTRING_REVVING', True)
        app.config.setdefault('BOOTSTRAP_SERVE_LOCAL', False)

        app.config.setdefault('BOOTSTRAP_LOCAL_SUBDOMAIN', None)

        blueprint = Blueprint(
            'bootstrap',
            __name__,
            template_folder='templates',
            static_folder='static',
            static_url_path=app.static_url_path + '/bootstrap',
            subdomain=app.config['BOOTSTRAP_LOCAL_SUBDOMAIN'])

        # add the form rendering template filter
        blueprint.add_app_template_filter(render_form)

        app.register_blueprint(blueprint)

        app.jinja_env.globals['bootstrap_is_hidden_field'] =\
            is_hidden_field_filter
        app.jinja_env.globals['bootstrap_find_resource'] =\
            bootstrap_find_resource

        if not hasattr(app, 'extensions'):
            app.extensions = {}

        local = StaticCDN('bootstrap.static', rev=True)
        static = StaticCDN()

        def lwrap(cdn, primary=static):
            return ConditionalCDN('BOOTSTRAP_SERVE_LOCAL', primary, cdn)

        bootstrap = lwrap(
            WebCDN('//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/%s/' %
                   BOOTSTRAP_VERSION), local)

        jquery = lwrap(
            WebCDN('//cdnjs.cloudflare.com/ajax/libs/jquery/%s/' %
                   JQUERY_VERSION), local)

        html5shiv = lwrap(
            WebCDN('//cdnjs.cloudflare.com/ajax/libs/html5shiv/%s/' %
                   HTML5SHIV_VERSION))

        respondjs = lwrap(
            WebCDN('//cdnjs.cloudflare.com/ajax/libs/respond.js/%s/' %
                   RESPONDJS_VERSION))

        app.extensions['bootstrap'] = {
            'cdns': {
                'local': local,
                'static': static,
                'bootstrap': bootstrap,
                'jquery': jquery,
                'html5shiv': html5shiv,
                'respond.js': respondjs,
            },
        }

        # setup support for flask-nav
        renderers = app.extensions.setdefault('nav_renderers', {})
        renderer_name = (__name__ + '.nav', 'BootstrapRenderer')
        renderers['bootstrap'] = renderer_name

        # make bootstrap the default renderer
        renderers[None] = renderer_name
Exemplo n.º 26
0
from label_studio.storage import get_storage_form
from label_studio.project import Project
from label_studio.tasks import Tasks
from label_studio.utils.data_manager import prepare_tasks

INPUT_ARGUMENTS_PATH = pathlib.Path("server.json")

logger = logging.getLogger(__name__)
blueprint = Blueprint(
    __package__,
    __name__,
    static_folder="static",
    static_url_path="/static",
    template_folder="templates",
)
blueprint.add_app_template_filter(str2datetime, "str2datetime")


@attr.s(frozen=True)
class LabelStudioConfig:
    input_args = attr.ib()


def set_input_arguments_path(path):
    global INPUT_ARGUMENTS_PATH
    INPUT_ARGUMENTS_PATH = pathlib.Path(path)


@functools.lru_cache(maxsize=1)
def config_from_file():
    try:
Exemplo n.º 27
0
from tutorial.models import User, db, Dataset, Csv_fileref, \
     Query, Query_instance, Gps_remap
from tutorial.models import Tabdata_dataset, Tabdata_query, \
     Tabdata_query_instance
from marion_biblio.progressivegenerators import QueueReporter
from tutorial.geocache import get_location
import json
import logging
import gevent
tutorial_bp = Blueprint('tutorial_bp', __name__, template_folder='templates')


def authorlink_filter(s):
    return 'http://scholar.google.com/scholar?q={0}'.format(s)

tutorial_bp.add_app_template_filter(authorlink_filter, "authorlink")


@tutorial_bp.before_request
def before_request():
    g.user = current_user


@tutorial_bp.route("/logout")
def logout():
    logout_user()
    return redirect(url_for('index'))


# @oid.after_login
def after_login(resp):
Exemplo n.º 28
0
    11: u"Ноябрь",
    12: u"Декабрь"
}


# flask jinja filter definition
def month_tuple_to_string(month):
    ix = int(month[0])
    if ix > 12:
        # year's posts case
        name = u"За весь год"
    else:
        name = MONTHS[ix]
    return u'{0} ({1})'.format(name, month[1])

mod.add_app_template_filter(month_tuple_to_string, 'month_tuple_to_string')


@mod.route('/', defaults={'page': 1})
@mod.route('/page/<int:page>/')
def index(page):
    tag = util.param('tag')
    y = util.param('year')
    m = util.param('month')
    if tag or y or m:
        return abort(404)

    posts = create_posts_query()
    title = ''

    if page > 1:
Exemplo n.º 29
0
    'Procfile', '.gitattributes', '.gitignore']

COPY_DIRS = ('_scss', '_js', 'font')

blueprint = Blueprint('base', __name__)
root = os.path.realpath(os.path.dirname(__file__))

@blueprint.app_template_global('p')
def path_helper(path, **kwargs):
    """
    Helper function for getting preview URLs
    """
    return relative_url_for('preview', path=path, **kwargs)


blueprint.add_app_template_filter(render_template_string, 'render_template_string')

if typogrify:
    for func in [typogrify, amp, widont, smartypants, caps, initial_quotes]:
        blueprint.add_app_template_filter(func, func.__name__)


@blueprint.app_context_processor
def add_to_context():
    """
    General-purpose context processor for this blueprint
    """
    site = g.current_site
    context = {}

    # no assumptions about project config
Exemplo n.º 30
0
ui = Blueprint(
    'ui',
    __name__,
    template_folder='../templates',
    static_folder='../static',
)


# using the method
@jinja2.contextfilter
def get_domain(context, url):
    return "%s" % urlparse(url).netloc


ui.add_app_template_filter(get_domain)
ui.add_app_template_filter(getWeekString)

##-----------Helper Functions -----------##


def render(templateName, data=None, **kwargs):
    """
    FLask Jinja rendering function
    :param templateName: jinja template name
    :param data: json data for the template
    :return: html
    """

    portalCount = getPortalCount()
    #print portalCount
Exemplo n.º 31
0
from label_studio.utils.uri_resolver import resolve_task_data_uri
from label_studio.utils.auth import requires_auth
from label_studio.storage import get_storage_form
from label_studio.project import Project
from label_studio.tasks import Tasks
from label_studio.utils.data_manager import prepare_tasks

INPUT_ARGUMENTS_PATH = pathlib.Path("server.json")

logger = logging.getLogger(__name__)
blueprint = Blueprint(__package__,
                      __name__,
                      static_folder='static',
                      static_url_path='/static',
                      template_folder='templates')
blueprint.add_app_template_filter(str2datetime, 'str2datetime')


@attr.s(frozen=True)
class LabelStudioConfig:
    input_args = attr.ib()


def set_input_arguments_path(path):
    global INPUT_ARGUMENTS_PATH
    INPUT_ARGUMENTS_PATH = pathlib.Path(path)


@functools.lru_cache(maxsize=1)
def config_from_file():
    try:
Exemplo n.º 32
0
# coding: utf-8

from flask import Blueprint, request, session, current_app
from flask import render_template, abort, redirect
from werkzeug.security import gen_salt
from zerqu.libs.cache import cache, ONE_HOUR
from zerqu.libs.utils import is_robot, xmldatetime
from zerqu.rec.timeline import get_all_topics
from zerqu.models import db, User, Cafe, Topic, CafeTopic, Comment

bp = Blueprint('front', __name__, template_folder='templates')
bp.add_app_template_filter(xmldatetime)


def render(template, **kwargs):
    key = 'front:page:%s' % request.path
    content = render_template(template, **kwargs)
    cache.set(key, content, timeout=ONE_HOUR)
    return render_content(content)


def render_content(content):
    use_app = session.get('app')

    base_url = current_app.config.get('SITE_CANONICAL_URL')
    if not base_url:
        base_url = current_app.config.get('SITE_URL')

    if base_url:
        link = '%s%s' % (base_url.rstrip('/'), request.path)
    else:
Exemplo n.º 33
0
def create_blueprint(app):
    """Register blueprint routes on app."""
    routes = app.config.get("APP_RDM_ROUTES")

    blueprint = Blueprint(
        "invenio_app_rdm_records",
        __name__,
        template_folder="../templates",
    )

    # Record URL rules
    blueprint.add_url_rule(
        routes["record_detail"],
        view_func=record_detail,
    )

    blueprint.add_url_rule(
        routes["record_latest"],
        view_func=record_latest,
    )

    app_ext = app.extensions['invenio-rdm-records']
    schemes = app_ext.records_service.config.pids_providers.keys()
    schemes = ','.join(schemes)

    if schemes:
        blueprint.add_url_rule(
            routes["record_from_pid"].format(schemes=schemes),
            view_func=record_from_pid,
        )

    blueprint.add_url_rule(
        routes["record_export"],
        view_func=record_export,
    )

    blueprint.add_url_rule(
        routes["record_file_preview"],
        view_func=record_file_preview,
    )

    blueprint.add_url_rule(
        routes["record_file_download"],
        view_func=record_file_download,
    )

    # Deposit URL rules
    blueprint.add_url_rule(
        routes["deposit_search"],
        view_func=deposit_search,
    )

    blueprint.add_url_rule(
        routes["deposit_create"],
        view_func=deposit_create,
    )

    blueprint.add_url_rule(
        routes["deposit_edit"],
        view_func=deposit_edit,
    )

    # Register error handlers
    blueprint.register_error_handler(PIDDeletedError, record_tombstone_error)
    blueprint.register_error_handler(PIDDoesNotExistError, not_found_error)
    blueprint.register_error_handler(PIDUnregistered, not_found_error)
    blueprint.register_error_handler(KeyError, not_found_error)
    blueprint.register_error_handler(PermissionDeniedError,
                                     record_permission_denied_error)

    # Register template filters
    blueprint.add_app_template_filter(can_list_files)
    blueprint.add_app_template_filter(doi_identifier)
    blueprint.add_app_template_filter(make_files_preview_compatible)
    blueprint.add_app_template_filter(pid_url)
    blueprint.add_app_template_filter(select_preview_file)
    blueprint.add_app_template_filter(to_previewer_files)
    blueprint.add_app_template_filter(vocabulary_title)
    blueprint.add_app_template_filter(has_previewable_files)
    blueprint.add_app_template_filter(order_entries)

    return blueprint
Exemplo n.º 34
0
                    x.name,
                    "incidences":
                    IncidenceModel.query.filter_by(fk_disease=x.id).count(),
                    "lastIncidence":
                    IncidenceModel.query.filter_by(fk_disease=x.id).order_by(
                        IncidenceModel.incidenceDate.desc()).first().
                    incidenceDate if IncidenceModel.query.filter_by(
                        fk_disease=x.id).count() > 0 else 'Sem dados'
                }, diseases))

        return diseases

    except SQLAlchemyError as error:
        res = json.dumps({"Erro": str(error.__dict__['orig'])})
        return None

    except Exception as error:
        res = json.dumps({"Erro": str(error)})
        return None


def dateformat(value, format='%d/%m/%Y'):
    try:
        value = value.strftime(format)
        return value
    except Exception as error:
        return value


incidenceBp.add_app_template_filter(f=dateformat)
Exemplo n.º 35
0
    vals = val.split('\r\n') if '\r\n' in val else val.split('\n')
    return ''.join('<p>{}</p>'.format(v) for v in vals)


def level_to_proficiency(val):
    val = int(val) if val is not None else 5
    proficiency_dict = {
        (10, 10): 'Guru',
        (9, 9): 'Expert',
        (8, 8): 'Pro',
        (7, 6): 'Advanced',
        (5, 5): 'Intermediate',
        (4, 3): 'Skilled',
        (2, 2): 'Beginner',
        (1, 0): 'Novice'
    }
    for k, v in proficiency_dict.items():
        high, low = k
        if high >= val >= low:
            return v


def process_urls(url):
    return url.strip('http://').strip('https://')

filters.add_app_template_filter(process_newlines, 'process_newlines')
filters.add_app_template_filter(level_to_proficiency, 'level_to_proficiency')
filters.add_app_template_filter(process_newlines_short, 'process_newlines_short')
filters.add_app_template_filter(process_urls, 'process_urls')

Exemplo n.º 36
0
# Author: jianglin
# Email: [email protected]
# Created: 2017-03-17 13:49:48 (CST)
# Last Update:星期日 2017-8-27 22:58:3 (CST)
#          By:
# Description:
# **************************************************************************
from flask import Blueprint
from .views import (BlogListView, BlogView, RssView, ArchiveView)
from .filters import (safe_markdown, random_fortune, tag_archives,
                      category_archives, time_archives, orgmode)

site = Blueprint('blog', __name__)
bloglist_view = BlogListView.as_view('bloglist')
site.add_url_rule('', view_func=bloglist_view)
site.add_url_rule('/', view_func=bloglist_view)
site.add_url_rule('/<int:blogId>', view_func=BlogView.as_view('blog'))
site.add_url_rule('/archives', view_func=ArchiveView.as_view('archive'))
site.add_url_rule('/rss', view_func=RssView.as_view('rss'))

site.add_app_template_global(random_fortune)
site.add_app_template_global(tag_archives)
site.add_app_template_global(category_archives)
site.add_app_template_global(time_archives)
site.add_app_template_filter(safe_markdown)
site.add_app_template_filter(orgmode)


def init_app(app):
    app.register_blueprint(site, url_prefix='/blog')
Exemplo n.º 37
0
    def init_app(self, app):
        app.config.setdefault('BOOTSTRAP_USE_MINIFIED', True)
        app.config.setdefault('BOOTSTRAP_CDN_FORCE_SSL', False)

        app.config.setdefault('BOOTSTRAP_QUERYSTRING_REVVING', True)
        app.config.setdefault('BOOTSTRAP_SERVE_LOCAL', False)

        app.config.setdefault('BOOTSTRAP_LOCAL_SUBDOMAIN', None)

        blueprint = Blueprint(
            'bootstrap',
            __name__,
            template_folder='templates',
            static_folder='static',
            static_url_path=app.static_url_path + '/bootstrap',
            subdomain=app.config['BOOTSTRAP_LOCAL_SUBDOMAIN'])

        # add the form rendering template filter
        blueprint.add_app_template_filter(render_form)

        app.register_blueprint(blueprint)

        app.jinja_env.globals['bootstrap_is_hidden_field'] =\
            is_hidden_field_filter
        app.jinja_env.globals['bootstrap_find_resource'] =\
            bootstrap_find_resource

        if not hasattr(app, 'extensions'):
            app.extensions = {}

        local = StaticCDN('bootstrap.static', rev=True)
        static = StaticCDN()

        def lwrap(cdn, primary=static):
            return ConditionalCDN('BOOTSTRAP_SERVE_LOCAL', primary, cdn)

        bootstrap = lwrap(
            WebCDN('//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/%s/' %
                   BOOTSTRAP_VERSION), local)

        jquery = lwrap(
            WebCDN('//cdnjs.cloudflare.com/ajax/libs/jquery/%s/' %
                   JQUERY_VERSION), local)

        html5shiv = lwrap(
            WebCDN('//cdnjs.cloudflare.com/ajax/libs/html5shiv/%s/' %
                   HTML5SHIV_VERSION))

        respondjs = lwrap(
            WebCDN('//cdnjs.cloudflare.com/ajax/libs/respond.js/%s/' %
                   RESPONDJS_VERSION))

        app.extensions['bootstrap'] = {
            'cdns': {
                'local': local,
                'static': static,
                'bootstrap': bootstrap,
                'jquery': jquery,
                'html5shiv': html5shiv,
                'respond.js': respondjs,
            },
        }

        # setup support for flask-nav
        renderers = app.extensions.setdefault('nav_renderers', {})
        renderer_name = (__name__ + '.nav', 'BootstrapRenderer')
        renderers['bootstrap'] = renderer_name

        # make bootstrap the default renderer
        renderers[None] = renderer_name
Exemplo n.º 38
0
from flask import Blueprint, flash, g, redirect, render_template, request, session, url_for

from app.database import db, User, Activity


def set_last_class_filter(index):
    if index % 2 == 0:
        return "last"
    else:
        return ""


bp = Blueprint('module', __name__)

bp.add_app_template_filter(set_last_class_filter, "set_last_class_filter")


@bp.route('/virtue', methods=['GET', 'POST'])
def virtue():
    if (request.method == 'GET'):
        act = Activity.query.filter(Activity.label == 'virtue').all()
        return render_template('Virtue.html', item=act)


@bp.route('/wisdom', methods=['GET', 'POST'])
def wisdom():
    if (request.method == 'GET'):
        act = Activity.query.filter(Activity.label == 'wisdom').all()
        return render_template('Wisdom.html', item=act)
Exemplo n.º 39
0
        seconds = (value - 25569) * 86400.0
        parsed = datetime.datetime.utcfromtimestamp(seconds)
    else:
        parsed = dateutil.parser.parse(value)
    if convert_tz:
        local_zone = dateutil.tz.gettz(convert_tz)
        parsed = parsed.astimezone(tz=local_zone)

    if format:
        return parsed.strftime(format)
    else:
        return parsed


@filters.app_template_filter('pprint_lines')
def pprint_lines(value):
    """
    Pretty print lines
    """
    pformatted = pformat(value, width=1, indent=4)
    formatted = "{0}\n {1}\n{2}".format(
        pformatted[0],
        pformatted[1:-1],
        pformatted[-1]
    )
    return Markup(formatted)

# add slughifi
filters.add_app_template_filter(slughifi)

Exemplo n.º 40
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Blueprint

account_blueprint = Blueprint('account', __name__, template_folder='../templates/account/')


def index_rank(index):
    return int(index) + 1

account_blueprint.add_app_template_filter(index_rank, 'torank')


from . import views