示例#1
0
def create_blueprint(config, url_endpoint, context_processors):
    """Create UI blueprint for invenio-workflows-ui."""
    blueprint = Blueprint(
        'invenio_workflows_ui',
        __name__,
        url_prefix=url_endpoint,
        template_folder='../templates',
        static_folder='../static',
    )

    @blueprint.route('/', methods=['GET', 'POST'])
    @blueprint.route('/index', methods=['GET', 'POST'])
    @login_required
    @action_admin_permission.require(http_exception=403)
    def index():
        """Display basic dashboard interface of Workflows UI."""
        return render_template(
            current_app.config['WORKFLOWS_UI_INDEX_TEMPLATE'])

    @blueprint.route('/list', methods=[
        'GET',
    ])
    @blueprint.route('/list/', methods=[
        'GET',
    ])
    @blueprint.route('/list/<search_value>', methods=[
        'GET',
    ])
    @login_required
    @action_admin_permission.require(http_exception=403)
    def list_objects(search_value=None):
        """Display main table interface of workflows UI."""
        return render_template(
            current_app.config['WORKFLOWS_UI_LIST_TEMPLATE'],
            search=search_value)

    @blueprint.route('/<int:objectid>', methods=['GET', 'POST'])
    @blueprint.route('/details/<int:objectid>', methods=['GET', 'POST'])
    @login_required
    @action_admin_permission.require(http_exception=403)
    def details(objectid):
        """Display info about the object."""
        try:
            workflow_object = workflow_object_class.get(objectid)
        except WorkflowsMissingObject:
            abort(404)

        return render_template(
            current_app.config['WORKFLOWS_UI_DETAILS_TEMPLATE'],
            workflow_object=workflow_object,
        )

    for proc in context_processors:
        blueprint.context_processor(obj_or_import_string(proc))

    return blueprint
示例#2
0
def create_blueprint(config, url_endpoint, context_processors):
    """Create UI blueprint for invenio-workflows-ui."""
    blueprint = Blueprint(
        'invenio_workflows_ui',
        __name__,
        url_prefix=url_endpoint,
        template_folder='../templates',
        static_folder='../static',
    )

    @blueprint.route('/', methods=['GET', 'POST'])
    @blueprint.route('/index', methods=['GET', 'POST'])
    @login_required
    def index():
        """Display basic dashboard interface of Workflows UI."""
        if not admin_permission_factory().can():
            abort(403)
        return render_template(
            current_app.config['WORKFLOWS_UI_INDEX_TEMPLATE']
        )

    @blueprint.route('/list', methods=['GET', ])
    @blueprint.route('/list/', methods=['GET', ])
    @blueprint.route('/list/<search_value>', methods=['GET', ])
    @login_required
    def list_objects(search_value=None):
        """Display main table interface of workflows UI."""
        if not admin_permission_factory().can():
            abort(403)
        return render_template(
            current_app.config['WORKFLOWS_UI_LIST_TEMPLATE'],
            search=search_value
        )

    @blueprint.route('/<int:objectid>', methods=['GET', 'POST'])
    @blueprint.route('/details/<int:objectid>', methods=['GET', 'POST'])
    @login_required
    def details(objectid):
        """Display info about the object."""
        if not admin_permission_factory().can():
            abort(403)
        try:
            workflow_object = workflow_object_class.get(objectid)
        except WorkflowsMissingObject:
            abort(404)

        return render_template(
            current_app.config['WORKFLOWS_UI_DETAILS_TEMPLATE'],
            workflow_object=workflow_object,
        )

    for proc in context_processors:
        blueprint.context_processor(obj_or_import_string(proc))

    return blueprint
示例#3
0
    def create_blueprint(cls, app):
        """
        Method to create a blueprint, derived from a SilverFlask Controller.
        It is one instance per blueprint. TODO: This might be a bad design and
        it should probably better be one instance per request.
        :param app: current app (in flask initialization)
        :return: Blueprint
        """
        inst = cls()
        endpoint = cls.__name__
        url_prefix = cls.url_prefix

        static_folder = 'static'
        static_url_path = '/static'
        if hasattr(cls, 'static_folder'):
            static_folder = cls.static_folder
            static_url_path = '/static'
        print(static_folder)
        blueprint = Blueprint(endpoint,
                              __name__,
                              url_prefix=url_prefix,
                              static_folder=static_folder,
                              static_url_path=static_url_path)
        blueprint.jinja_loader = ThemeTemplateLoader()

        view_funcs = {}
        for url in cls.urls:
            action = cls.urls[url]
            kwargs = {'methods': ['GET']}
            if action in cls.allowed_actions:
                kwargs['methods'] += ['POST']

            blueprint.add_url_rule(url, cls.urls[url],
                                   getattr(inst, cls.urls[url]), **kwargs)

        if hasattr(cls, 'before_request'):
            blueprint.before_request(getattr(inst, 'before_request'))

        template_functions = {}
        for fun in cls.template_functions:
            template_functions[fun] = getattr(inst,
                                              inst.template_functions[fun])

        blueprint.context_processor(lambda: template_functions)

        for m in cls.mro():
            if hasattr(m, 'init_blueprint'):
                m.init_blueprint(blueprint)

        return blueprint
示例#4
0
def web_init() -> Blueprint:
    web_bp = Blueprint('web', __name__, template_folder='templates', static_folder='static')

    web_bp.context_processor(inject_version)

    web_bp.add_url_rule('/', 'index', zoe_api.web.start.index)
    web_bp.add_url_rule('/user', 'home_user', zoe_api.web.start.home_user)

    web_bp.add_url_rule('/executions/new', 'execution_define', zoe_api.web.executions.execution_define)
    web_bp.add_url_rule('/executions/start', 'execution_start', zoe_api.web.executions.execution_start, methods=['POST'])
    web_bp.add_url_rule('/executions/restart/<int:execution_id>', 'execution_restart', zoe_api.web.executions.execution_restart)
    web_bp.add_url_rule('/executions/terminate/<int:execution_id>', 'execution_terminate', zoe_api.web.executions.execution_terminate)
    web_bp.add_url_rule('/executions/inspect/<int:execution_id>', 'execution_inspect', zoe_api.web.executions.execution_inspect)

    return web_bp
示例#5
0
    def create_blueprint(cls, app):
        """
        Method to create a blueprint, derived from a SilverFlask Controller.
        It is one instance per blueprint. TODO: This might be a bad design and
        it should probably better be one instance per request.
        :param app: current app (in flask initialization)
        :return: Blueprint
        """
        inst = cls()
        endpoint = cls.__name__
        url_prefix = cls.url_prefix

        static_folder = "static"
        static_url_path = "/static"
        if hasattr(cls, "static_folder"):
            static_folder = cls.static_folder
            static_url_path = "/static"
        print(static_folder)
        blueprint = Blueprint(
            endpoint, __name__, url_prefix=url_prefix, static_folder=static_folder, static_url_path=static_url_path
        )
        blueprint.jinja_loader = ThemeTemplateLoader()

        view_funcs = {}
        for url in cls.urls:
            action = cls.urls[url]
            kwargs = {"methods": ["GET"]}
            if action in cls.allowed_actions:
                kwargs["methods"] += ["POST"]

            blueprint.add_url_rule(url, cls.urls[url], getattr(inst, cls.urls[url]), **kwargs)

        if hasattr(cls, "before_request"):
            blueprint.before_request(getattr(inst, "before_request"))

        template_functions = {}
        for fun in cls.template_functions:
            template_functions[fun] = getattr(inst, inst.template_functions[fun])

        blueprint.context_processor(lambda: template_functions)

        for m in cls.mro():
            if hasattr(m, "init_blueprint"):
                m.init_blueprint(blueprint)

        return blueprint
示例#6
0
 def flask_blueprint(self):
     b = Blueprint("kuyruk_manager", __name__)
     b.add_url_rule('/', 'index', self._get_index)
     b.add_url_rule('/workers', 'workers', self._get_workers)
     b.add_url_rule('/failed-tasks', 'failed_tasks',
                    self._get_failed_tasks)
     b.add_url_rule('/api/failed-tasks', 'api_failed_tasks',
                    self._api_get_failed_tasks)
     b.add_url_rule('/action', 'action',
                    self._post_action, methods=['POST'])
     b.add_url_rule('/action-all', 'action_all',
                    self._post_action_all, methods=['POST'])
     b.add_url_rule('/requeue', 'requeue_task',
                    self._post_requeue, methods=['POST'])
     b.add_url_rule('/delete', 'delete_task',
                    self._post_delete, methods=['POST'])
     b.context_processor(self._context_processors)
     return b
class Multilang(object):
    def __init__(self):
        self.blueprint = Blueprint(name='multilang',
                                   import_name=__name__,
                                   url_prefix='/<lang>',
                                   template_folder='templates',
                                   static_folder='static')

    def _add_decorators(self):
        self.blueprint.before_request(decorators.verify_lang)
        self.blueprint.url_defaults(decorators.set_app_language)
        self.blueprint.url_value_preprocessor(decorators.get_app_language)

    def _add_exceptions(self):
        self.blueprint.register_error_handler(exceptions.SwitchLanguage,
                                              exceptions.switch_language)
        self.blueprint.register_error_handler(exceptions.Basic404,
                                              exceptions.basic_404)
        self.blueprint.register_error_handler(exceptions.UnsupportedLanguage,
                                              exceptions.unsupported_language)

    def _add_routes(self):
        self.blueprint.add_url_rule('/', view_func=views.index)
        self.blueprint.add_url_rule('/ahoj-svet',
                                    view_func=views.hello_world_sk)
        self.blueprint.add_url_rule('/hello-world',
                                    view_func=views.hello_world_en)

    def _update_jinja_context(self):
        context = {
            'translate': translate_message,
        }

        return context

    def prepare(self):
        self._add_decorators()
        self._add_exceptions()
        self._add_routes()

        self.blueprint.context_processor(self._update_jinja_context)
示例#8
0
def get_blueprint(site_path: str, with_search: bool = True) -> Blueprint:
    """Generate a blueprint for this site on the fly."""
    blueprint = Blueprint(site.get_site_name(),
                          __name__,
                          url_prefix=site.get_url_prefix(),
                          static_folder=site.get_static_path(),
                          template_folder=site.get_templates_path(),
                          static_url_path=f'{site.get_site_name()}_static')
    blueprint.route('/')(from_sitemap)
    blueprint.route('/<path:page_path>')(from_sitemap)
    blueprint.route('/<path:page_path>.html', endpoint="html")(redirect_html)
    blueprint.route('/<path:page_path>.htm', endpoint="htm")(redirect_html)
    if with_search:
        blueprint.route('/search', methods=['GET'])(search)
    blueprint.context_processor(url_for_page_builder)
    blueprint.context_processor(
        lambda: {'site_human_name': site.get_site_human_name()})
    blueprint.context_processor(
        lambda: {'site_human_short_name': site.get_site_human_short_name()})
    return blueprint
示例#9
0
    url_for,
    request,
    current_app as app,
)
from atst.domain.users import Users
from atst.domain.audit_log import AuditLog
from atst.domain.common import Paginator
from atst.domain.exceptions import NotFoundError
from atst.domain.authz.decorator import user_can_access_decorator as user_can
from atst.forms.ccpo_user import CCPOUserForm
from atst.models.permissions import Permissions
from atst.utils.context_processors import atat as atat_context_processor
from atst.utils.flash import formatted_flash as flash

bp = Blueprint("ccpo", __name__)
bp.context_processor(atat_context_processor)


@bp.route("/activity-history")
@user_can(Permissions.VIEW_AUDIT_LOG, message="view activity log")
def activity_history():
    if app.config.get("USE_AUDIT_LOG", False):
        pagination_opts = Paginator.get_pagination_opts(request)
        audit_events = AuditLog.get_all_events(pagination_opts)
        return render_template("audit_log/audit_log.html",
                               audit_events=audit_events)
    else:
        return redirect("/")


@bp.route("/ccpo-users")
示例#10
0
from flask import Blueprint

task_orders_bp = Blueprint("task_orders", __name__)

from . import index
from . import new
from . import downloads
from atst.utils.context_processors import portfolio as portfolio_context_processor

task_orders_bp.context_processor(portfolio_context_processor)
示例#11
0
def create_blueprint(config, context_processors):
    """Create Invenio-Deposit-REST blueprint with all views."""
    blueprint = Blueprint(
        'invenio_workflows_rest',
        __name__,
        url_prefix='',
    )

    workflow_object_serializers = config.get('workflow_object_serializers')
    search_serializers = config.get('search_serializers')
    action_serializers = config.get('action_serializers')
    bulk_action_serializers = config.get('bulk_action_serializers')
    default_media_type = config.get('default_media_type')
    search_index = config.get('search_index')
    max_result_window = config.get('max_result_window')

    search_factory = config.get('search_factory', default_query_factory)

    search_factory = obj_or_import_string(search_factory)

    workflow_object_serializers = {
        mime: obj_or_import_string(func)
        for mime, func in workflow_object_serializers.items()
    }
    search_serializers = {
        mime: obj_or_import_string(func)
        for mime, func in search_serializers.items()
    }
    bulk_action_serializers = {
        mime: obj_or_import_string(func)
        for mime, func in bulk_action_serializers.items()
    }
    action_serializers = {
        mime: obj_or_import_string(func)
        for mime, func in action_serializers.items()
    }

    list_view = WorkflowsListResource.as_view(
        WorkflowsListResource.view_name,
        search_serializers=search_serializers,
        workflow_object_serializers=workflow_object_serializers,
        default_media_type=default_media_type,
        search_index=search_index,
        search_factory=search_factory,
        max_result_window=max_result_window
    )
    list_route = config.get('list_route')

    item_view = WorkflowObjectResource.as_view(
        WorkflowObjectResource.view_name,
        serializers=workflow_object_serializers,
        default_media_type=default_media_type,
    )
    item_route = config.get('item_route')

    actions_segment = "action/<any(resolve,restart,continue):action>"

    action_route = os.path.join(
        item_route,
        actions_segment
    )
    action_view = WorkflowActionResource.as_view(
        WorkflowActionResource.view_name,
        serializers=action_serializers,
        default_media_type=default_media_type,
    )

    bulk_action_route = os.path.join(
        list_route,
        actions_segment
    )
    bulk_action_view = WorkflowBulkActionResource.as_view(
        WorkflowBulkActionResource.view_name,
        serializers=bulk_action_serializers,
        default_media_type=default_media_type,
    )

    views = [
        dict(rule=list_route, view_func=list_view),
        dict(rule=item_route, view_func=item_view),
        dict(rule=action_route, view_func=action_view),
        dict(rule=bulk_action_route, view_func=bulk_action_view),
    ]

    for rule in views:
        blueprint.add_url_rule(**rule)

    for proc in context_processors:
        blueprint.context_processor(obj_or_import_string(proc))

    return blueprint
示例#12
0
def create_blueprint(config, url_endpoint, context_processors):
    """Create UI blueprint for invenio-workflows-ui."""

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

    index = config.get('search_index')
    doc_type = config.get('search_type')
    search_factory = config.get('search_factory', default_query_factory)
    search_factory = obj_or_import_string(search_factory)

    searcher = RecordsSearch(index=index,
                             doc_type=doc_type).params(version=True)

    def _search(**kwargs):
        search, dummy = search_factory(blueprint, searcher, **kwargs)
        return search.execute()

    @blueprint.route('/', methods=['GET', 'POST'])
    @blueprint.route('/index', methods=['GET', 'POST'])
    @login_required
    def index():
        """Display basic dashboard interface of Workflows UI."""
        q = '_workflow.status:"{0}"'
        error_state_total = _search(q=q.format(ObjectStatus.labels[
            ObjectStatus.ERROR.value])).hits.total
        halted_state_total = _search(q=q.format(ObjectStatus.labels[
            ObjectStatus.HALTED.value])).hits.total
        return render_template(
            current_app.config['WORKFLOWS_UI_INDEX_TEMPLATE'],
            error_state_total=error_state_total,
            halted_state_total=halted_state_total)

    @blueprint.route('/load', methods=['GET', 'POST'])
    @login_required
    def load():
        """Load objects for the table."""
        query_string = request.args.get("search") or ""  # empty to show all
        sort_key = request.args.get('sort_key', "_workflow.modified")
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 25, type=int)

        # __, results = searcher.search(
        #     query_string=search, size=per_page, page=page, sort_key=sort_key
        # )
        search = searcher[(page - 1) * per_page:page * per_page]
        search, dummy = search_factory(blueprint,
                                       search,
                                       sort=sort_key,
                                       q=query_string)
        search_result = search.execute()

        current_app.logger.debug("Total hits: {0}".format(
            search_result.hits.total))
        pagination = Pagination(page, per_page, search_result.hits.total)

        # Make sure requested page is within limits.
        if pagination.page > pagination.pages:
            pagination.page = pagination.pages

        pages_iteration = []
        for iter_page in pagination.iter_pages():
            res = {"page": iter_page}
            if iter_page == pagination.page:
                res["active"] = True
            else:
                res["active"] = False
            pages_iteration.append(res)

        table_data = {
            'rows': [],
            'pagination': {
                "page": pagination.page,
                "pages": pagination.pages,
                "iter_pages": pages_iteration,
                "per_page": pagination.per_page,
                "total_count": pagination.total_count
            }
        }

        # Add current ids in table for use by previous/next
        session['workflows_ui_sort_key'] = sort_key
        session['workflows_ui_per_page'] = per_page
        session['workflows_ui_page'] = page
        session['workflows_ui_search'] = query_string

        table_data["rows"] = get_rows(search_result)
        table_data["rendered_rows"] = "".join(table_data["rows"])
        return jsonify(table_data)

    @blueprint.route('/list', methods=[
        'GET',
    ])
    @blueprint.route('/list/', methods=[
        'GET',
    ])
    @blueprint.route('/list/<search_value>', methods=[
        'GET',
    ])
    @login_required
    def list_objects(search_value=None):
        """Display main table interface of workflows UI."""
        search_value = search_value or session.get(
            "workflows_ui_search", '_workflow.status:"{0}"'.format(
                ObjectStatus.labels[ObjectStatus.HALTED.value]))
        sort_key = request.args.get('sort_key', "_workflow.modified")
        page = request.args.get('page', session.get('workflows_ui_page', 1))
        per_page = request.args.get('per_page',
                                    session.get('workflows_ui_per_page', 25))
        return render_template(
            current_app.config['WORKFLOWS_UI_LIST_TEMPLATE'],
            search=search_value,
            total=_search(q=search_value, sort=sort_key).hits.total,
            type_list=get_data_types(),
            name_list=get_workflow_names(),
            per_page=per_page)

    @blueprint.route('/<int:objectid>', methods=['GET', 'POST'])
    @blueprint.route('/details/<int:objectid>', methods=['GET', 'POST'])
    @login_required
    def details(objectid):
        """Display info about the object."""
        workflow_object = WorkflowObject.query.get_or_404(objectid)

        previous_object_id, next_object_id = get_previous_next_objects(
            session.get("workflows_ui_current_ids"), objectid)

        formatted_data = workflow_object.get_formatted_data()
        action_name = workflow_object.get_action()
        if action_name:
            action = actions[action_name]
            rendered_actions = action().render(workflow_object)
        else:
            rendered_actions = {}

        return render_template(
            current_app.config['WORKFLOWS_UI_DETAILS_TEMPLATE'],
            workflow_object=workflow_object,
            rendered_actions=rendered_actions,
            data_preview=formatted_data,
            workflow_name=workflow_object.get_workflow_name() or "",
            previous_object_id=previous_object_id,
            next_object_id=next_object_id,
        )

    for proc in context_processors:
        blueprint.context_processor(obj_or_import_string(proc))

    return blueprint
示例#13
0
def create_blueprint(config, url_endpoint, context_processors):
    """Create UI blueprint for invenio-workflows-ui."""

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

    index = config.get('search_index')
    doc_type = config.get('search_type')
    search_factory = config.get(
        'search_factory', default_query_factory
    )
    search_factory = obj_or_import_string(search_factory)

    searcher = RecordsSearch(
        index=index,
        doc_type=doc_type
    ).params(version=True)

    def _search(**kwargs):
        search, dummy = search_factory(blueprint, searcher, **kwargs)
        return search.execute()

    @blueprint.route('/', methods=['GET', 'POST'])
    @blueprint.route('/index', methods=['GET', 'POST'])
    @login_required
    def index():
        """Display basic dashboard interface of Workflows UI."""
        q = '_workflow.status:"{0}"'
        error_state_total = _search(
            q=q.format(ObjectStatus.labels[ObjectStatus.ERROR.value])
        ).hits.total
        halted_state_total = _search(
            q=q.format(ObjectStatus.labels[ObjectStatus.HALTED.value])
        ).hits.total
        return render_template(current_app.config['WORKFLOWS_UI_INDEX_TEMPLATE'],
                               error_state_total=error_state_total,
                               halted_state_total=halted_state_total)

    @blueprint.route('/load', methods=['GET', 'POST'])
    @login_required
    def load():
        """Load objects for the table."""
        query_string = request.args.get("search") or ""  # empty to show all
        sort_key = request.args.get('sort_key', "_workflow.modified")
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 25, type=int)

        # __, results = searcher.search(
        #     query_string=search, size=per_page, page=page, sort_key=sort_key
        # )
        search = searcher[(page-1)*per_page:page*per_page]
        search, dummy = search_factory(blueprint, search, sort=sort_key, q=query_string)
        search_result = search.execute()

        current_app.logger.debug("Total hits: {0}".format(
            search_result.hits.total
        ))
        pagination = Pagination(page, per_page, search_result.hits.total)

        # Make sure requested page is within limits.
        if pagination.page > pagination.pages:
            pagination.page = pagination.pages

        pages_iteration = []
        for iter_page in pagination.iter_pages():
            res = {"page": iter_page}
            if iter_page == pagination.page:
                res["active"] = True
            else:
                res["active"] = False
            pages_iteration.append(res)

        table_data = {
            'rows': [],
            'pagination': {
                "page": pagination.page,
                "pages": pagination.pages,
                "iter_pages": pages_iteration,
                "per_page": pagination.per_page,
                "total_count": pagination.total_count
            }
        }

        # Add current ids in table for use by previous/next
        session['workflows_ui_sort_key'] = sort_key
        session['workflows_ui_per_page'] = per_page
        session['workflows_ui_page'] = page
        session['workflows_ui_search'] = query_string

        table_data["rows"] = get_rows(search_result)
        table_data["rendered_rows"] = "".join(table_data["rows"])
        return jsonify(table_data)

    @blueprint.route('/list', methods=['GET', ])
    @blueprint.route('/list/', methods=['GET', ])
    @blueprint.route('/list/<search_value>', methods=['GET', ])
    @login_required
    def list_objects(search_value=None):
        """Display main table interface of workflows UI."""
        search_value = search_value or session.get(
            "workflows_ui_search",
            '_workflow.status:"{0}"'.format(
                ObjectStatus.labels[ObjectStatus.HALTED.value]
            )
        )
        sort_key = request.args.get(
            'sort_key', "_workflow.modified"
        )
        page = request.args.get(
            'page', session.get('workflows_ui_page', 1)
        )
        per_page = request.args.get(
            'per_page', session.get('workflows_ui_per_page', 25)
        )
        return render_template(
            current_app.config['WORKFLOWS_UI_LIST_TEMPLATE'],
            search=search_value,
            total=_search(
                q=search_value, sort=sort_key
            ).hits.total,
            type_list=get_data_types(),
            name_list=get_workflow_names(),
            per_page=per_page
        )

    @blueprint.route('/<int:objectid>', methods=['GET', 'POST'])
    @blueprint.route('/details/<int:objectid>', methods=['GET', 'POST'])
    @login_required
    def details(objectid):
        """Display info about the object."""
        workflow_object = WorkflowObject.query.get_or_404(objectid)

        previous_object_id, next_object_id = get_previous_next_objects(
            session.get("workflows_ui_current_ids"),
            objectid
        )

        formatted_data = workflow_object.get_formatted_data()
        action_name = workflow_object.get_action()
        if action_name:
            action = actions[action_name]
            rendered_actions = action().render(workflow_object)
        else:
            rendered_actions = {}

        return render_template(
            current_app.config['WORKFLOWS_UI_DETAILS_TEMPLATE'],
            workflow_object=workflow_object,
            rendered_actions=rendered_actions,
            data_preview=formatted_data,
            workflow_name=workflow_object.get_workflow_name() or "",
            previous_object_id=previous_object_id,
            next_object_id=next_object_id,
        )

    for proc in context_processors:
        blueprint.context_processor(obj_or_import_string(proc))

    return blueprint
示例#14
0
文件: blueprint.py 项目: v1psta/atst
from flask import Blueprint

from atst.utils.context_processors import portfolio as portfolio_context_processor

applications_bp = Blueprint("applications", __name__)
applications_bp.context_processor(portfolio_context_processor)
示例#15
0
文件: app.py 项目: keyz/dagster
def instantiate_app_with_views(
    context: IWorkspaceProcessContext,
    schema,
    app_path_prefix,
    target_dir=os.path.dirname(__file__),
    graphql_middleware=None,
    include_notebook_route=False,
) -> Flask:
    app = Flask(
        "dagster-ui",
        static_url_path=app_path_prefix,
        static_folder=os.path.join(target_dir, "./webapp/build"),
    )
    subscription_server = DagsterSubscriptionServer(schema=schema)

    # Websocket routes
    sockets = Sockets(app)
    sockets.add_url_rule(
        f"{app_path_prefix}/graphql",
        "graphql",
        dagster_graphql_subscription_view(subscription_server, context),
    )

    # HTTP routes
    bp = Blueprint("routes", __name__, url_prefix=app_path_prefix)
    bp.add_url_rule("/graphiql", "graphiql",
                    lambda: redirect(f"{app_path_prefix}/graphql", 301))
    bp.add_url_rule(
        "/graphql",
        "graphql",
        DagsterGraphQLView.as_view(
            "graphql",
            schema=schema,
            graphiql=True,
            graphiql_template=PLAYGROUND_TEMPLATE,
            context=context,
            middleware=graphql_middleware,
        ),
    )

    bp.add_url_rule(
        # should match the `build_local_download_url`
        "/download/<string:run_id>/<string:step_key>/<string:file_type>",
        "download_view",
        download_log_view(context),
    )

    bp.add_url_rule(
        "/download_debug/<string:run_id>",
        "download_dump_view",
        download_dump_view(context),
    )

    # these routes are specifically for the Dagit UI and are not part of the graphql
    # API that we want other people to consume, so they're separate for now.
    # Also grabbing the magic global request args dict so that notebook_view is testable
    if include_notebook_route:
        bp.add_url_rule("/dagit/notebook", "notebook",
                        lambda: notebook_view(context, request.args))
    bp.add_url_rule("/dagit_info", "sanity_view", info_view)

    index_path = os.path.join(target_dir, "./webapp/build/index.html")

    telemetry_enabled = is_dagit_telemetry_enabled(context.instance)

    def index_view(*args, **kwargs):  # pylint: disable=unused-argument
        try:
            with open(index_path) as f:
                rendered_template = render_template_string(f.read())
                return (rendered_template.replace(
                    'href="/', f'href="{app_path_prefix}/').replace(
                        'src="/', f'src="{app_path_prefix}/').replace(
                            "__PATH_PREFIX__", app_path_prefix).replace(
                                '"__TELEMETRY_ENABLED__"',
                                str(telemetry_enabled).lower()).replace(
                                    "NONCE-PLACEHOLDER",
                                    uuid.uuid4().hex))
        except FileNotFoundError:
            raise Exception(
                """Can't find webapp files. Probably webapp isn't built. If you are using
                dagit, then probably it's a corrupted installation or a bug. However, if you are
                developing dagit locally, your problem can be fixed as follows:

                cd ./python_modules/
                make rebuild_dagit""")

    bp.add_url_rule("/", "index_view", index_view)
    bp.add_url_rule("/<path:path>", "catch_all", index_view)

    bp.context_processor(lambda: {"app_path_prefix": app_path_prefix})

    app.app_protocol = lambda environ_path_info: "graphql-ws"
    app.before_request(initialize_counts)
    app.register_blueprint(bp)
    app.register_error_handler(404, index_view)
    app.after_request(return_counts)

    CORS(app)

    return app
示例#16
0
文件: app.py 项目: xjhc/dagster
def instantiate_app_with_views(context,
                               schema,
                               app_path_prefix,
                               target_dir=os.path.dirname(__file__)):
    app = Flask(
        "dagster-ui",
        static_url_path=app_path_prefix,
        static_folder=os.path.join(target_dir, "./webapp/build"),
    )
    subscription_server = DagsterSubscriptionServer(schema=schema)

    # Websocket routes
    sockets = Sockets(app)
    sockets.add_url_rule(
        f"{app_path_prefix}/graphql",
        "graphql",
        dagster_graphql_subscription_view(subscription_server, context),
    )

    # HTTP routes
    bp = Blueprint("routes", __name__, url_prefix=app_path_prefix)
    bp.add_url_rule("/graphiql", "graphiql",
                    lambda: redirect(f"{app_path_prefix}/graphql", 301))
    bp.add_url_rule(
        "/graphql",
        "graphql",
        DagsterGraphQLView.as_view(
            "graphql",
            schema=schema,
            graphiql=True,
            graphiql_template=PLAYGROUND_TEMPLATE,
            executor=Executor(),
            context=context,
        ),
    )

    bp.add_url_rule(
        # should match the `build_local_download_url`
        "/download/<string:run_id>/<string:step_key>/<string:file_type>",
        "download_view",
        download_log_view(context),
    )

    bp.add_url_rule(
        "/download_debug/<string:run_id>",
        "download_dump_view",
        download_dump_view(context),
    )

    # these routes are specifically for the Dagit UI and are not part of the graphql
    # API that we want other people to consume, so they're separate for now.
    # Also grabbing the magic global request args dict so that notebook_view is testable
    bp.add_url_rule("/dagit/notebook", "notebook",
                    lambda: notebook_view(request.args))
    bp.add_url_rule("/dagit_info", "sanity_view", info_view)

    index_path = os.path.join(target_dir, "./webapp/build/index.html")

    def index_view():
        try:
            with open(index_path) as f:
                rendered_template = render_template_string(f.read())
                return rendered_template.replace(
                    'src="/static', f'src="{app_path_prefix}/static').replace(
                        'href="/static', f'href="{app_path_prefix}/static')
        except FileNotFoundError:
            raise Exception(
                """Can't find webapp files. Probably webapp isn't built. If you are using
                dagit, then probably it's a corrupted installation or a bug. However, if you are
                developing dagit locally, your problem can be fixed as follows:

                cd ./python_modules/
                make rebuild_dagit""")

    def error_redirect(_path):
        return index_view()

    bp.add_url_rule("/", "index_view", index_view)
    bp.context_processor(lambda: {"app_path_prefix": app_path_prefix})

    app.app_protocol = lambda environ_path_info: "graphql-ws"
    app.register_blueprint(bp)
    app.register_error_handler(404, error_redirect)

    # if the user asked for a path prefix, handle the naked domain just in case they are not
    # filtering inbound traffic elsewhere and redirect to the path prefix.
    if app_path_prefix:
        app.add_url_rule("/", "force-path-prefix",
                         lambda: redirect(app_path_prefix, 301))

    CORS(app)
    return app
示例#17
0
文件: views.py 项目: vitalk/work
    :license: MIT
"""
from flask import (
    abort,
    Blueprint,
    render_template,
    request,
    url_for,
)
from jinja2.exceptions import TemplateNotFound

from work.models.menu import Menu


frontend = Blueprint('frontend', __name__, static_folder='../static')
frontend.context_processor(lambda: {'site_nav': site_nav()})


def site_nav():
    return Menu((
        [url_for('frontend.index'), u'Кто я'],
        [url_for('frontend.made'), u'Работы'],
        [url_for('frontend.contact'), u'Контакты'],
    ), [request.endpoint, request.view_args])


@frontend.route('/')
def index():
    return render_template('frontend/index.html')

示例#18
0
def create_blueprint(config, context_processors):
    """Create Invenio-Deposit-REST blueprint with all views."""
    blueprint = Blueprint(
        'invenio_workflows_rest',
        __name__,
        url_prefix='',
    )

    workflow_object_serializers = config.get('workflow_object_serializers')
    search_serializers = config.get('search_serializers')
    action_serializers = config.get('action_serializers')
    bulk_action_serializers = config.get('bulk_action_serializers')
    default_media_type = config.get('default_media_type')
    search_index = config.get('search_index')
    max_result_window = config.get('max_result_window')

    search_factory = config.get('search_factory', default_query_factory)

    search_factory = obj_or_import_string(search_factory)

    workflow_object_serializers = {
        mime: obj_or_import_string(func)
        for mime, func in workflow_object_serializers.items()
    }
    search_serializers = {
        mime: obj_or_import_string(func)
        for mime, func in search_serializers.items()
    }
    bulk_action_serializers = {
        mime: obj_or_import_string(func)
        for mime, func in bulk_action_serializers.items()
    }
    action_serializers = {
        mime: obj_or_import_string(func)
        for mime, func in action_serializers.items()
    }

    list_view = WorkflowsListResource.as_view(
        WorkflowsListResource.view_name,
        search_serializers=search_serializers,
        workflow_object_serializers=workflow_object_serializers,
        default_media_type=default_media_type,
        search_index=search_index,
        search_factory=search_factory,
        max_result_window=max_result_window)
    list_route = config.get('list_route')

    item_view = WorkflowObjectResource.as_view(
        WorkflowObjectResource.view_name,
        serializers=workflow_object_serializers,
        default_media_type=default_media_type,
    )
    item_route = config.get('item_route')

    actions_segment = "action/<any(resolve,restart,continue):action>"

    action_route = os.path.join(item_route, actions_segment)
    action_view = WorkflowActionResource.as_view(
        WorkflowActionResource.view_name,
        serializers=action_serializers,
        default_media_type=default_media_type,
    )

    bulk_action_route = os.path.join(list_route, actions_segment)
    bulk_action_view = WorkflowBulkActionResource.as_view(
        WorkflowBulkActionResource.view_name,
        serializers=bulk_action_serializers,
        default_media_type=default_media_type,
    )

    views = [
        dict(rule=list_route, view_func=list_view),
        dict(rule=item_route, view_func=item_view),
        dict(rule=action_route, view_func=action_view),
        dict(rule=bulk_action_route, view_func=bulk_action_view),
    ]

    for rule in views:
        blueprint.add_url_rule(**rule)

    for proc in context_processors:
        blueprint.context_processor(obj_or_import_string(proc))

    return blueprint
示例#19
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Blueprint
from utils.webcore import register_url

from .urls import urlpatterns
from .drops import *
from . import admin  # noqa  这样才能激活后台。

books = Blueprint(
    name='books',
    import_name=__name__,
    # template_folder='templates', static_folder='static'
)

books.before_request(check_ContentType)

books.after_request(cross_domain)

books.context_processor(csrf_token)

register_url(books, urlpatterns)
示例#20
0
class ModelEditor(object):
    """Factory class for creating model editor views
    TODO: write documentation
    """
    def __init__(self, app=None, modeldb=None):
        self.bp = Blueprint('modeleditor',
                            __name__,
                            static_folder='static',
                            template_folder='templates')
        self.bp.record(self.onregister)
        self.bp.context_processor(self.context_processor)

        @self.bp.before_request
        def before_request():
            if not request.form:
                request.form = None

        @self.bp.app_template_global()
        def savemodelform(model):
            return forms.SaveModelForm(obj=model, prefix='savemodel')

        self.modeldb = modeldb or ModelDB()

        #set up the spec registry and add the defaults
        self.specregistry = OrderedDict()
        self.registerspectype(emissionspec.CombinedSpec,
                              forms.RadioactiveContamForm, "RadioactiveContam")
        self.registerspectype(emissionspec.RadonExposure,
                              forms.RadonExposureForm)
        self.registerspectype(emissionspec.CosmogenicActivation,
                              forms.CosmogenicActivationForm)
        #dust is not well developed yet...
        #self.registerspectype(emissionspec.DustAccumulation,
        #forms.DustAccumulationForm)

        #apply all our routes
        baseroute = '/edit/<modelid>'
        self.bp.add_url_rule('/new',
                             view_func=self.newmodel,
                             methods=('POST', ))
        self.bp.add_url_rule('/del',
                             view_func=self.delmodel,
                             methods=('POST', ))
        self.bp.add_url_rule(baseroute + '/',
                             view_func=self.editmodel,
                             methods=('GET', 'POST'))
        self.bp.add_url_rule(baseroute + '/save',
                             view_func=self.savemodel,
                             methods=('POST', ))
        self.bp.add_url_rule(baseroute + '/newcomponent',
                             view_func=self.newcomponent,
                             methods=('POST', ))
        self.bp.add_url_rule(baseroute + '/delcomponent/<componentid>',
                             view_func=self.delcomponent,
                             methods=('POST', ))
        self.bp.add_url_rule(baseroute + '/newplacement/<parentid>/<childid>',
                             view_func=self.newplacement,
                             methods=('POST', ))
        self.bp.add_url_rule(baseroute +
                             '/delplacement/<parentid>/<int:index>',
                             view_func=self.delplacement,
                             methods=('POST', ))
        self.bp.add_url_rule(baseroute + '/newspec',
                             view_func=self.newspec,
                             methods=('POST', ))
        self.bp.add_url_rule(baseroute + '/delspec/<specid>',
                             view_func=self.delspec,
                             methods=('POST', ))
        self.bp.add_url_rule(baseroute + '/attachspec/<compid>/<specid>',
                             view_func=self.attachspec,
                             methods=('POST', ))
        self.bp.add_url_rule(baseroute + '/detachspec/<compid>/<int:index>',
                             view_func=self.detachspec,
                             methods=('POSt', ))
        self.bp.add_url_rule(baseroute + '/setquerymod/<compid>/<specid>',
                             view_func=self.setquerymod,
                             methods=('POST', ))
        self.bp.add_url_rule(baseroute + '/editcomponent/<componentid>',
                             view_func=self.editcomponent,
                             methods=('GET', 'POST'))
        self.bp.add_url_rule(baseroute + '/editspec/<specid>',
                             view_func=self.editspec,
                             methods=('GET', 'POST'))
        self.bp.add_url_rule(baseroute + '/bindsimdata',
                             view_func=self.bindsimdata,
                             methods=('GET', 'POST'))

        @self.bp.route('/help')
        def help():
            return render_template('help.html')

        if app:
            self.init_app(app)

    def onregister(self, setupstate):
        #make sure bootstrap is registered
        if not 'bootstrap' in setupstate.app.blueprints:
            Bootstrap(setupstate.app)
        setupstate.app.jinja_env.globals['bootstrap_is_hidden_field'] = \
            is_hidden_field

        #initialize the modeldb
        #todo: make sure this only gets done once
        self.modeldb.init_app(setupstate.app)

        #update the spec form choices
        forms.BoundSpecForm.category.choices = [
            (val.cls, name) for name, val in self.specregistry.items()
        ]

    def init_app(self, app, url_prefix='/models'):
        app.register_blueprint(self.bp, url_prefix=url_prefix)

    def registerspectype(self, cls, form, name=None):
        """Register a new EmissionSpec class and form for editing
        Args:
            cls: class or constructor, should inherit from EmissionSpec
            form: WTForm for editing, should inherit from EmissionspecForm
            name (str): Name for this class, if None, use cls.__name__
        """
        name = name or cls.__name__
        self.specregistry[name] = SpecEntry(cls, form)

    def context_processor(self):
        """Register global variables available to templates"""
        return dict(spectypes=list(self.specregistry.keys()), forms=forms)

    def addlinks(self, form, modelid):
        """Replace names in subfield forms with links"""
        for field in form:
            if hasattr(field, 'entries'):
                for entry in field:
                    href = None
                    field = None
                    if entry.form_class is forms.PlacementForm:
                        href = url_for('.editcomponent',
                                       modelid=modelid,
                                       componentid=entry['component'].data)
                        field = 'cls'
                    elif entry.form_class is forms.BoundSpecForm:
                        href = url_for('.editspec',
                                       modelid=modelid,
                                       specid=entry['id'].data)
                        field = 'name'
                    if href:
                        entry[field].link = href
                        #entry[field].data = ("<a href='%s'>%s</a>"
                        #                      %(href, entry[field].data))

    ##### modeleditor API #######
    #todo: implement some caching here!
    def newmodel(self):
        """Create a new bare model or clone an existing one for editing"""
        name = ""
        simsdbview = None
        if request.form:
            name = request.form.get('name', name)
            simsdbview = request.form.get('backend', simsdbview)
        importfile = None
        if request.files:
            importfile = request.files.get('importmodel', importfile)

        if importfile:
            #try to convert file data
            try:
                filecontents = importfile.read()
                rawmodel = json.loads(filecontents.decode())
                newmodel = bgmodel.BgModel.buildfromdict(rawmodel)
            except BaseException as e:
                flash("Error raised parsing input file: '%s'" % e, "danger")
                return redirect(url_for('index'))
            if name:
                newmodel.name = name
            if simsdbview:
                newmodel.simsdb = simsdbview
            newid = self.modeldb.write_model(newmodel, temp=True)
        else:
            derivedFrom = request.values.get('derivedFrom', None)
            newmodel = self.modeldb.new_model(derivedFrom, name=name)
            newid = newmodel.id
        #todo: handle error no model returned, probably DB down
        return redirect(url_for('.editmodel', modelid=str(newid)))

    def delmodel(self):
        modelid = request.form.get('modelid', None)
        try:
            ndeleted = self.modeldb.del_model(modelid)
        except KeyError as e:
            abort(404, e)
        except ValueError as e:
            abort(403, e)

        if ndeleted == 1:
            flash("Successfully deleted model %s" % modelid, 'success')
        else:
            flash("An error occurred trying to delete this model", 'warning')
        return redirect(url_for('index'))

    #all endpoints build on the same route from here out
    def editmodel(self, modelid):
        """return a page with forms for model editing"""
        bypasscache = request.args.get('bypasscache', False)
        model = getmodelordie(modelid, toedit=True, bypasscache=bypasscache)
        return render_template('editmodel.html', model=model)

    def savemodel(self, modelid):
        """Save the model to the DB, making sure all edit details fields
        validated
        """
        model = getmodelordie(modelid, toedit=True)
        form = forms.SaveModelForm(request.form, obj=model, prefix='savemodel')
        if request.method == 'POST' and form.validate():
            form.populate_obj(model)
            # make sure the simulation data is updated
            simsdb = get_simsdb(model=model)
            error = ""
            if not simsdb:
                error += " No registered SimulationsDB"
            try:
                # temporarily force update always
                #update = form.updatesimdata.data
                update = True
                simsdb.updatesimdata(model,
                                     attach=True,
                                     findnewmatches=update,
                                     findnewdata=update)
            except units.errors.DimensionalityError as e:
                error += " Invalid unit settings: '%s'" % e
            # make sure the model is valid
            if error or not model.validate():
                flash("The model failed to validate: %s" % error, 'error')
                return url_for('.editmodel', modelid=modelid, bypasscache=True)
            self.modeldb.write_model(model, temp=False, bumpversion="major")
            flash("Model '%s' successfully saved" % (model.name), 'success')
            return redirect(url_for("index"))

        #we should only get here if the form failed...
        return redirect(url_for('.editmodel', modelid=modelid))

    #todo: implement delete functionality

    ###Component/spec editing API
    ###Actions are:
    # new component (child of X)
    # delete component
    # new placement
    # delete placement
    # new spec
    # delete spec
    # place spec
    # remove spec
    # edit query modifier
    # edit component (metadata, etc)

    def newcomponent(self, modelid):
        model = getmodelordie(modelid, toedit=True)
        clonefrom = request.values.get('clonefrom')
        if clonefrom:
            oldcomp = getcomponentordie(model, clonefrom)
            newcomp = oldcomp.clone()
        else:
            newcomp = (Assembly() if request.values.get('class') == 'Assembly'
                       else Component())
        parentid = request.values.get('parent')
        if parentid:
            parent = getcomponentordie(model, parentid)
            replace = int(request.values.get('replaceAt', -1))
            if replace >= 0 and replace < len(parent.components):
                placement = parent.components[replace]
                placement.component.placements.remove(placement)
                placement.component = newcomp
                newcomp.placements.add(placement)
            else:
                parent.addcomponent(newcomp)

        model.components[newcomp.id] = newcomp
        self.modeldb.write_model(model)
        return redirect(
            url_for('.editcomponent', modelid=modelid, componentid=newcomp.id))

    def delcomponent(self, modelid, componentid):
        model = getmodelordie(modelid, toedit=True)
        component = getcomponentordie(model, componentid)
        model.delcomponent(componentid)
        self.modeldb.write_model(model)
        return redirect(url_for('.editmodel', modelid=modelid))

    def newplacement(self, modelid, parentid, childid):
        model = getmodelordie(modelid, toedit=True)
        parent = getcomponentordie(model, parentid)
        child = getcomponentordie(model, childid)
        #we also call this for rearranging; if we're already a child, remove it
        if child in parent.getcomponents(deep=False, withweights=False):
            parent.delcomponent(child)
        number = request.values.get('number', 1)
        index = request.values.get('index')
        parent.addcomponent((child, number), index)
        self.modeldb.write_model(model)
        return redirect(
            url_for('.editcomponent', modelid=modelid, componentid=parentid))

    def delplacement(self, modelid, parentid, index):
        model = getmodelordie(modelid, toedit=True)
        parent = getcomponentordie(model, parentid)
        parent.delcomponent(index)
        self.modeldb.write_model(model)
        return redirect(
            url_for('.editcomponent', modelid=modelid, componentid=parentid))

    def newspec(self, modelid):
        model = getmodelordie(modelid, toedit=True)
        newspec = None
        clonefrom = request.values.get('clonefrom')
        if clonefrom:
            prior = getspecordie(model, clonefrom)
            newspec = prior.clone()
        else:
            spectype = request.values.get('type', 'RadioactiveContam')
            if spectype not in self.specregistry:
                abort(404, "Unknown EmissionSpec type ", spectype)
            newspec = self.specregistry[spectype].cls()

        model.specs[newspec.id] = newspec
        self.modeldb.write_model(model)
        return redirect(
            url_for('.editspec', modelid=modelid, specid=newspec.id))

    def delspec(self, modelid, specid):
        model = getmodelordie(modelid, toedit=True)
        spec = getspecordie(model, specid)
        model.delspec(specid)
        self.modeldb.write_model(model)
        return redirect(url_for('.editmodel', modelid=modelid))

    def attachspec(self, modelid, compid, specid):
        model = getmodelordie(modelid, toedit=True)
        comp = getcomponentordie(model, compid)
        spec = getspecordie(model, specid)
        index = request.values.get('index')
        comp.addspec(spec, index=index)
        self.modeldb.write_model(model)
        return redirect(
            url_for('.editcomponent', modelid=modelid, componentid=compid))

    def detachspec(self, modelid, compid, index):
        model = getmodelordie(modelid, toedit=True)
        comp = getcomponentordie(model, compid)
        comp.delspec(index)
        self.modeldb.write_model(model)
        return redirect(
            url_for('.editcomponent', modelid=modelid, componentid=compid))

    def setquerymod(self, modelid, compid, specid):
        model = getmodelordie(modelid, toedit=True)
        comp = getcomponentordie(model, compid)
        querymod = request.values.get('querymod')
        if querymod:
            if isinstance(querymod, str):
                querymod = json.loads(querymod)
                #todo: implement error handling here
            comp.querymods[specid] = querymod
        elif specid in comp.querymods:
            del comp.querymods[specid]

        self.modeldb.write_model(model)
        return redirect(
            url_for('.editcomponent', modelid=modelid, componentid=compid))

    def editcomponent(self, modelid, componentid):
        """return a page with forms for component editing"""
        #todo: do we need to pass different forms for component types here?
        model = getmodelordie(modelid, toedit=True)
        comp = getcomponentordie(model, componentid)
        form = forms.get_form(request.form, comp)
        if request.method == 'POST':
            if form.validate():
                form.populate_obj(comp)
                #make sure the fully assembled object works
                for bs in comp.specs:
                    bs.spec = model.specs.get(bs.spec, bs.spec)
                if hasattr(comp, 'components'):
                    for plc in comp.components:
                        sub = plc.component
                        plc.component = model.components.get(sub, sub)

                status = comp.getstatus()
                if not status:
                    #no errors, so save
                    # sim data associations almost all get out of whack when
                    # anything is changed, so take the heavy-handed method of
                    # deleting all
                    for match in model.getsimdata(rootcomponent=comp):
                        del model.simdata[match.id]
                    self.modeldb.write_model(model)
                    flash(
                        "Changes to component '%s' successfully saved" %
                        comp.name, 'success')
                    return redirect(
                        url_for('.editcomponent',
                                modelid=modelid,
                                componentid=componentid))
                else:
                    flash(
                        "Form validation failed. Correct errors and resubmit",
                        "danger")
                    form.specs.errors.append(status)
            else:
                flash("Form validation failed. Correct errors and resubmit",
                      "danger")

        self.addlinks(form, modelid)
        return render_template('editmodel.html',
                               model=model,
                               editcomponent=comp,
                               form=form)

    def editspec(self, modelid, specid):
        """return a page with forms for componentspec editing"""
        model = getmodelordie(modelid, toedit=True)
        spec = getspecordie(model, specid)
        #find the correct form
        possibleforms = [
            entry.form for entry in self.specregistry.values()
            if entry.cls == type(spec)
        ]
        if len(possibleforms) < 1:
            abort(404, "No form defined for class %s", type(spec).__name__)
        form = possibleforms[0](request.form, obj=spec)
        if request.method == 'POST':
            if form.validate():
                form.populate_obj(spec)
                #make sure the fully assembled spec works
                status = spec.getstatus()
                if not status:
                    #no errors, so save
                    # sim data associations almost all get out of whack when
                    # anything is changed, so take the heavy-handed method of
                    # deleting all
                    for match in model.getsimdata(rootspec=spec):
                        del model.simdata[match.id]
                    self.modeldb.write_model(model)
                    flash(
                        "Changes to spec '%s' successfully saved" % spec.name,
                        'success')
                    return redirect(
                        url_for('.editspec', modelid=modelid, specid=specid))
                else:
                    flash(
                        "Form validation failed. Correct errors and resubmit",
                        "danger")
                    form.normfunc.errors.append(status)
            else:
                flash("Form validation failed. Correct errors and resubmit",
                      "danger")
        self.addlinks(form, modelid)
        return render_template('editmodel.html',
                               model=model,
                               editspec=spec,
                               form=form)

    def bindsimdata(self, modelid):
        """Look for updated simulation data and return a highlight view
        Confirm whether to save new bindings or cancel.

        TODO: This seems like the place to implement manual binding
        """
        model = getmodelordie(modelid, toedit=False)
        if request.method == 'POST' and request.form:
            dbname = request.form.get('simsdb')
            if dbname:
                model.simsdb = dbname
        simsdb = get_simsdb(model=model)
        if not simsdb:
            abort(501, "No registered SimulationsDB")

        try:
            matches = simsdb.updatesimdata(model)
        except units.errors.DimensionalityError as e:
            abort(400, "Invalid unit settings: '%s'" % e)
        #form = forms.BindSimDataForm(request.form)
        if request.method == 'POST' and request.form.get(
                'confirm'):  # and form.validate():
            self.modeldb.removecache(model.id)
            istemp = self.modeldb.is_model_temp(modelid)
            model.simdata = {m.id: m for m in matches}
            try:
                newid = str(
                    self.modeldb.write_model(model,
                                             bumpversion="minor",
                                             temp=istemp))
            except Exception as e:
                abort(501, 'Error saving model: %s' % e)
            if istemp:
                return redirect(url_for('.editmodel', modelid=newid))
            else:
                #TODO: add a url for viewmodel here
                return redirect(url_for('modelviewer.overview', modelid=newid))
                #sort the requests by spec and assembly

        return render_template('bindsimdata.html',
                               model=model,
                               matches=matches)
示例#21
0
from flask import Blueprint
from atst.utils.context_processors import portfolio as portfolio_context_processor

portfolios_bp = Blueprint("portfolios", __name__)
portfolios_bp.context_processor(portfolio_context_processor)
示例#22
0

@blueprint.route('advanced/<string:groups_or_archives>', methods=['GET'])
def group_search(groups_or_archives: str) -> Union[str, Response]:
    """
    Short-cut for advanced search with group or archive pre-selected.

    Note that this only supports options supported in the advanced search
    interface. Anything else will result in a 404.
    """
    response, code, _ = advanced.group_search(request.args, groups_or_archives)
    return render_template(  # type: ignore
        "search/advanced_search.html",
        pagetitle="Advanced Search",
        **response)


@blueprint.route('status', methods=['GET', 'HEAD'])
def service_status() -> Union[str, Response]:
    """
    Health check endpoint for search.

    Exercises the search index connection with a real query.
    """
    return health_check()  # type: ignore


# Register context processors.
for context_processor in context_processors.context_processors:
    blueprint.context_processor(context_processor)