Пример #1
0
 def _setup_dynamic_flask_blueprint_api(self):
     # Create a dynamic flask blueprint with a known prefix
     api = uuid.uuid4().hex
     url_prefix = '/_%s_TEST' % api
     blueprint = blueprints.Blueprint(api, __name__, url_prefix=url_prefix)
     self.url_prefix = url_prefix
     self.flask_blueprint = blueprint
     self.cleanup_instance('flask_blueprint', 'url_prefix')
Пример #2
0
    def __init__(self, app, model, url_prefix):
        model = model
        blueprint = blueprints.Blueprint("app_error",
                                         'app_error',
                                         root_path=root_path,
                                         template_folder="templates",
                                         url_prefix=url_prefix)

        @blueprint.route('/')
        def view_list():
            """
            List exceptions based on the page number
            :return: rendered template
            """
            title = "App Error"
            page = request.args.get('page', 1, type=int)
            error = False
            errors = model.get_exceptions_per_page(page_number=page)
            next_url = url_for('app_error.view_list', page=errors.next_num) \
                if errors.has_next else None
            prev_url = url_for('app_error.view_list', page=errors.prev_num) \
                if errors.has_prev else None
            return render_template('list.html',
                                   error=error,
                                   title=title,
                                   errors=errors,
                                   next_url=next_url,
                                   prev_url=prev_url)

        @blueprint.route('/<string:rhash>')
        def view_detail(rhash):
            """
            Display a specific exception having hash rhash
            :param rhash:  hash key of the exception
            :return: detailed view page
            """
            obj = model.get_entity(rhash)
            error = False
            if obj is None:
                abort(404)
            title = "%s : %s" % (obj.method, obj.path)

            return render_template('detail.html',
                                   error=error,
                                   title=title,
                                   obj=obj)

        @blueprint.route('/delete_entity/<string:rhash>')
        def view_delete(rhash):
            """
            Delete a specific exceptions identified by rhash
            :param rhash: hash key of the exception
            :return: redirect back to the home page
            """
            model.delete_entity(rhash)
            return redirect(url_for('app_error.view_list'))

        app.register_blueprint(blueprint)
Пример #3
0
    def __init__(self,
                 blueprint_url_prefix='',
                 api_url_prefix='',
                 default_mediatype='application/json',
                 decorators=None,
                 errors=None):
        self.__before_request_functions_added = False
        self.__after_request_functions_added = False

        self._default_mediatype = default_mediatype
        blueprint_url_prefix = blueprint_url_prefix.rstrip('/')
        api_url_prefix = api_url_prefix.rstrip('/')

        if api_url_prefix and not api_url_prefix.startswith('/'):
            self._api_url_prefix = '/%s' % api_url_prefix
        else:
            # NOTE(morgan): If the api_url_prefix is empty fall back on the
            # class-level defined `_api_url_prefix` if it is set.
            self._api_url_prefix = (api_url_prefix
                                    or getattr(self, '_api_url_prefix', ''))

        if blueprint_url_prefix and not blueprint_url_prefix.startswith('/'):
            self._blueprint_url_prefix = self._build_bp_url_prefix(
                '/%s' % blueprint_url_prefix)
        else:
            self._blueprint_url_prefix = self._build_bp_url_prefix(
                blueprint_url_prefix)

        self.__blueprint = blueprints.Blueprint(
            name=self._name,
            import_name=self._import_name,
            url_prefix=self._blueprint_url_prefix)
        self.__api = flask_restful.Api(
            app=self.__blueprint,
            prefix=self._api_url_prefix,
            default_mediatype=self._default_mediatype,
            decorators=decorators,
            errors=errors)

        # NOTE(morgan): Make sure we're using oslo_serialization.jsonutils
        # instead of the default json serializer. Keystone has data types that
        # the default serializer cannot handle, representation is a decorator
        # but since we instantiate the API in-line we need to do some magic
        # and call it as a normal method.
        self.__api.representation('application/json')(self._output_json)

        self._add_resources()
        self._add_mapped_resources()

        # Apply Before and After request functions
        self._register_before_request_functions()
        self._register_after_request_functions()
        # Assert is intended to ensure code works as expected in development,
        # it is fine to optimize out with python -O
        msg = '%s_request functions not registered'
        assert self.__before_request_functions_added, msg % 'before'  # nosec
        assert self.__after_request_functions_added, msg % 'after'  # nosec
Пример #4
0
    def __init__(self, name='auth', url_prefix='/auth'):
        self.blueprint = blueprints.Blueprint(
            name,
            __name__,
            url_prefix=url_prefix,
            template_folder=self.get_template_folder())

        self.blueprint.route(self.get_login_endpoint())(
            self.generate_login_view())
        self.blueprint.route(self.get_authenticate_endpoint(),
                             methods=('POST', ))(
                                 self.generate_authenticate_view())
Пример #5
0
def website_create():

  website = blueprints.Blueprint('website',
                                 __name__,
                                 url_prefix='/website',
                                 static_folder = "dist/static",
                                 template_folder = "dist")
  @website.route('/')
  def index():
    return render_template("index.html")

  # @website.route("/static/<path:path>")
  # def static_dir(path):
  #     return send_from_directory("dist/static", path)

  return website
Пример #6
0
    def __init__(self,
                 blueprint_url_prefix='',
                 api_url_prefix='',
                 default_mediatype='application/json',
                 decorators=None,
                 errors=None):
        self.__before_request_functions_added = False
        self.__after_request_functions_added = False

        self._default_mediatype = default_mediatype
        blueprint_url_prefix = blueprint_url_prefix.rstrip('/')
        api_url_prefix = api_url_prefix.rstrip('/')

        if api_url_prefix and not api_url_prefix.startswith('/'):
            self._api_url_prefix = '/%s' % api_url_prefix
        else:
            self._api_url_prefix = api_url_prefix

        if blueprint_url_prefix and not blueprint_url_prefix.startswith('/'):
            self._blueprint_url_prefix = self._build_bp_url_prefix(
                '/%s' % blueprint_url_prefix)
        else:
            self._blueprint_url_prefix = self._build_bp_url_prefix(
                blueprint_url_prefix)

        self.__blueprint = blueprints.Blueprint(
            name=self._name,
            import_name=self._import_name,
            url_prefix=self._blueprint_url_prefix)
        self.__api = flask_restful.Api(
            app=self.__blueprint,
            prefix=self._api_url_prefix,
            default_mediatype=self._default_mediatype,
            decorators=decorators,
            errors=errors)
        self._add_resources()
        self._add_mapped_resources()

        # Apply Before and After request functions
        self._register_before_request_functions()
        self._register_after_request_functions()
        # Assert is intended to ensure code works as expected in development,
        # it is fine to optimize out with python -O
        msg = '%s_request functions not registered'
        assert self.__before_request_functions_added, msg % 'before'  # nosec
        assert self.__after_request_functions_added, msg % 'after'  # nosec
Пример #7
0
 def __init__(self,
              blueprint_url_prefix='',
              api_url_prefix='',
              default_mediatype='application/json',
              decorators=None,
              errors=None):
     self._blueprint_url_prefix = blueprint_url_prefix
     self._default_mediatype = default_mediatype
     self._api_url_prefix = api_url_prefix
     self.__blueprint = blueprints.Blueprint(
         name=self._name,
         import_name=self._import_name,
         url_prefix=self._build_bp_url_prefix(self._blueprint_url_prefix))
     self.__api_bp = flask_restful.Api(
         app=self.__blueprint,
         prefix=self._api_url_prefix,
         default_mediatype=self._default_mediatype,
         decorators=decorators,
         errors=errors)
     self._add_resources()
Пример #8
0
from flask import blueprints

common = blueprints.Blueprint("common", __name__)

from . import image
from . import location
from . import video
from . import audio
Пример #9
0
    services_response_schema,
    RevisionsResponse,
    revisions_response_schema,
)
from confidant.services import (
    credentialmanager,
    iamrolemanager,
    keymanager,
    servicemanager,
    webhook,
)
from confidant.utils import maintenance, misc
from confidant.utils.dynamodb import decode_last_evaluated_key

logger = logging.getLogger(__name__)
blueprint = blueprints.Blueprint('services', __name__)

acl_module_check = misc.load_module(settings.ACL_MODULE)


@blueprint.route('/v1/roles', methods=['GET'])
@authnz.require_auth
def get_iam_roles_list():
    """
    Get a list of IAM roles from the configured AWS account.

    .. :quickref: IAM Roles; Get a list of IAM roles from the configured
                  AWS account.

    **Example request**:
Пример #10
0
from flask import blueprints

from .github import GitHubIdentityVerificationCallbackResource
from .slack import SlackEventSubscriptionResource, SlackSlashCommandDispatchResource
from busy_beaver.config import SLACK_SIGNING_SECRET
from busy_beaver.decorators import verify_slack_signature

integration_bp = blueprints.Blueprint("integrations", __name__)
slack_verification_required = verify_slack_signature(SLACK_SIGNING_SECRET)

view = SlackEventSubscriptionResource.as_view("slack_event_subscription")
integration_bp.add_url_rule("/slack-event-subscription",
                            view_func=slack_verification_required(view))

view = SlackSlashCommandDispatchResource.as_view(
    "slack_slash_command_dispatcher")
integration_bp.add_url_rule("/slack-slash-commands",
                            view_func=slack_verification_required(view))

integration_bp.add_url_rule(
    "/github-integration",
    view_func=GitHubIdentityVerificationCallbackResource.as_view(
        "github_verification"),
)
Пример #11
0
from flask import blueprints
auth = blueprints.Blueprint('auth', __name__)
from app.auth import views
Пример #12
0
from urlparse import urlparse

from flask import (blueprints, flash, g, jsonify, redirect, request, send_file,
                   url_for)

from patchserver.database import db
from patchserver.exc import InvalidPatchDefinitionError, InvalidWebhook
from patchserver.models import ApiToken, SoftwareTitle, WebhookUrls
from patchserver.routes.api_operations import (
    create_criteria_objects, create_extension_attributes, create_patch_objects,
    lookup_software_title, create_backup_archive, restore_backup_archive)
from patchserver.routes.auth import api_auth
from patchserver.routes.validator import validate_json
from patchserver.routes.webhooks import webhook_event

blueprint = blueprints.Blueprint('api', __name__, url_prefix='/api/v1')


@blueprint.route('/token', methods=['POST'])
def token_create():
    """Create an API token for the server.

    .. :quickref: Token; Create the API token.

    **Example Request:**

    .. sourcecode:: http

        POST /api/v1/token HTTP/1.1

    **Example Response:**
Пример #13
0
from flask import request
from flask import blueprints

from application.middles import testMiddle as m
from application.controller import route

bp = blueprints.Blueprint('test', __name__, url_prefix='/example')


@route(bp, '/get_test_info', methods=['POST'])
def get_test_info():
    params = request.get_json(force=True)
    result = m.get_test(**params)
    return result




Пример #14
0
import asyncio
import json
import re
import time

from flask import blueprints, Response

from common import config
from database import Database
from model import Channel
from telegram_async import AsyncTelegramClient

add_channel_endpoint = blueprints.Blueprint("add_channel", __name__)

CHANNEL_NAME_PATTERN = re.compile(r"^[\w_\-]+$")

telethon_api = AsyncTelegramClient()
db = Database(
    "dbname='telegram' user='******' host='localhost' password='******'" %
    (config["db_password"], ))
loop = asyncio.get_event_loop()


def matches_channel_name(channel_name):
    return CHANNEL_NAME_PATTERN.match(channel_name) is not None


@add_channel_endpoint.route("/add_channel/<string:channel>")
def add_channel(channel):
    """
    Suggest a channel
Пример #15
0
from flask import render_template, make_response, url_for, redirect, current_app, request, session
from flask import blueprints as bp
from flask_login import current_user, login_user, logout_user, login_required
from flask_principal import identity_changed, identity_loaded, AnonymousIdentity, Identity

from functools import wraps

from genius.db.model import Book, User
from genius.global_settings import NAV_TABS
from genius.util.form_util import render_form

from .forms import LoginForm
from .errors import FormNotMatchException

home_bp = bp.Blueprint('home', __name__, url_prefix='/')


@home_bp.route('/')
def send_home():
    books = (Book.newly_books(), Book.most_copies(), Book.most_copies())
    rank_types = (u'新书速递', u'畅销', u'最受关注')
    book_rank_map = {rank_type: target_books for rank_type, target_books in zip(rank_types, books)}
    return render_template('index.j2', book_rank_map=book_rank_map)


@home_bp.route('/login', methods=['POST', 'GET'])
@render_form(LoginForm, 'login.j2')
def login(form: LoginForm):
    user = form.match_db()  # will throws FormNotMatchException if not match
    login_user(user)
    identity = Identity(user.id)
Пример #16
0
def get_bp(name):
    """Return blueprint for Image management."""
    bp = blueprints.Blueprint(name, __name__)

    @bp.route('<image_id>/', methods=['GET'])
    def show(image_id):
        """Present details page for single image object.

        Tries using both Glance and Nova services because they provide
        different info set about an image.
        """
        glance_image = clients.admin_clients().glance.images.get(image_id)
        nova_image = clients.admin_clients().nova.images.get(image_id)
        return {
            'glance_image': glance_image,
            'nova_image': nova_image,
            'title': bp.name.replace('global_', '').replace('_',
                                                            ' ').capitalize(),
            'subtitle': 'Image details',
        }

    def get_tenant_id():
        return getattr(flask.g, 'tenant_id', clients.get_systenant_id())

    @bp.route('')
    def index():
        """List images.

        Admin (global visibility level) should see only images from
        systenant. Project members should see images for projects only.
        """
        images = get_images_list()
        if not hasattr(flask.g, 'tenant_id'):
            images = filter(lambda x: getattr(x, 'is_public', False), images)
        p = pagination.Pagination(images)
        data = p.slice(images)
        return {
            'images': data,
            'pagination': p,
            'delete_form': forms.DeleteForm(),
            'title': bp.name.replace('global_', '').replace('_',
                                                            ' ').capitalize(),
            'subtitle': 'List of existing images'
        }

    @bp.route('new/', methods=['GET'])
    def new():
        """Present image upload form.

        TODO(apugachev): remove from templ location images older then X hours
        """
        images = get_images_list()
        check = lambda f: lambda x: getattr(x, 'container_format') == f
        kernels = filter(check('aki'), images)
        initrds = filter(check('ari'), images)
        dump = lambda d: json.dumps([{
            'name': x.name,
            'container_format': x.container_format,
            'id': x.id
        } for x in d])
        return {
            'kernel_list': dump(kernels),
            'initrd_list': dump(initrds),
            'title': bp.name.replace('global_', '').replace('_',
                                                            ' ').capitalize(),
            'subtitle': 'Add new image'
        }

    @bp.route('upload/', methods=['POST'])
    def upload():
        """Save uploaded file.

        Handles AJAX call, saves file in temp location, returns filename.

        TODO(apugachev): remove from templ location images older then X hours
        """
        storage = flask.request.files['file']
        filename = focus.files_uploads.save(storage)
        flask.current_app.cache.set(os.path.basename(filename),
                                    {'transferred': -1})
        return filename

    @bp.route('create/', methods=['POST'])
    def create():
        """Create image via Glance API.

        - validates form
        - creates image via API
        - cleans up tmp file
        - returns successful message

        New image uploaded in tenant systenant publicly if blueprint is in
        admin context. Otherwise image uploaded in the tenant used for the
        project and is not public. With default Glance settings (owner means
        tenant) this would restrict access to the image for members of the
        project.

        During the process of upload ongoing progress is memcached.

        TODO(apugachev): remove from templ location images older then X hours
        """
        def create_image(uploaded_filename,
                         name,
                         container,
                         disk_format,
                         kernel_id=None,
                         ramdisk_id=None):
            tenant_id = get_tenant_id()
            properties = {
                'image_state': 'available',
                'project_id': tenant_id,
                'architecture': 'x86_64',
                'image_location': 'local'
            }
            if kernel_id is not None:
                properties['kernel_id'] = kernel_id
            if ramdisk_id is not None:
                properties['ramdisk_id'] = ramdisk_id
            uploaded_filename = focus.files_uploads.path(uploaded_filename)
            try:
                kwargs = {
                    'name': name,
                    'container_format': container,
                    'disk_format': disk_format,
                    'data': open(uploaded_filename),
                    'is_public': not hasattr(flask.g, 'tenant_id'),
                    'properties': properties,
                }
            except IOError, e:
                e.public_message = 'Uploaded file is missing'
                flask.current_app.logger.error(str(e))
                raise
            try:
                user_clients = clients.user_clients(tenant_id)
                callback = ProgressRecorder(
                    user_clients.http_client,
                    os.path.basename(uploaded_filename),
                    os.fstat(kwargs['data'].fileno()).st_size)
                with callback:
                    img = user_clients.image.images.create(**kwargs)
            except RuntimeError as e:
                flask.flash(e.message, 'error')
            else:
                flask.flash('Image with name %s registered.' % img.name,
                            'success')
                return img.id
            finally:
                try:
                    kwargs['data'].close()
                    os.unlink(uploaded_filename)
                except OSError:
                    # nothing to do, temporal file was removed by something
                    pass

        # TODO(apugachev): validate thoroughly, do not rely on js to do it
        if flask.request.form['upload_type'] == 'solid':
            create_image(flask.request.form['uploaded_filename'],
                         flask.request.form['name'], 'bare',
                         flask.request.form['disk_format'])
        elif flask.request.form['upload_type'] == 'amazon_like':
            if flask.request.form['uploaded_kernel'] != u'null':
                kernel_id = create_image(flask.request.form['uploaded_kernel'],
                                         flask.request.form['kernel'], 'aki',
                                         'aki')
            else:
                kernel_id = flask.request.form['kernel']
            if flask.request.form['uploaded_initrd'] != u'null':
                ramdisk_id = create_image(
                    flask.request.form['uploaded_initrd'],
                    flask.request.form['initrd'], 'ari', 'ari')
            else:
                ramdisk_id = flask.request.form['initrd']
            create_image(flask.request.form['uploaded_filesystem'],
                         flask.request.form['name'], 'ami', 'ami', kernel_id,
                         ramdisk_id)
        # NOTE(apugachev) for big this will fail to load and BrokenPipe
        # will be raised inside Flask
        return flask.jsonify({})
Пример #17
0
from flask import blueprints

from .github_summary import PublishGitHubSummaryResource
from .retweeter import TwitterPollingResource
from .upcoming_events import PublishUpcomingEventsResource
from .update_events import AddEventPollingResource
from .youtube_post import YouTubePollingResource

poller_bp = blueprints.Blueprint("poller", __name__)

poller_bp.add_url_rule(
    "/github-summary",
    view_func=PublishGitHubSummaryResource.as_view("post_github_summary"),
    methods=["POST"],
)

poller_bp.add_url_rule(
    "/twitter",
    view_func=TwitterPollingResource.as_view("twitter_poller"),
    methods=["POST"],
)

poller_bp.add_url_rule(
    "/upcoming-events",
    view_func=PublishUpcomingEventsResource.as_view("post_upcoming_events"),
    methods=["POST"],
)

poller_bp.add_url_rule(
    "/sync-event-database",
    view_func=AddEventPollingResource.as_view("meetup_poller"),
Пример #18
0
from confidant import authnz, settings
from confidant.services import certificatemanager
from confidant.schema.certificates import (
    certificate_authority_response_schema,
    certificate_authorities_response_schema,
    certificate_expanded_response_schema,
    certificate_response_schema,
    CertificateAuthorityResponse,
    CertificateAuthoritiesResponse,
    CertificateResponse,
)
from confidant.utils import misc

logger = logging.getLogger(__name__)
blueprint = blueprints.Blueprint('certificates', __name__)

acl_module_check = misc.load_module(settings.ACL_MODULE)


@blueprint.route('/v1/certificates/<ca>/<cn>', methods=['GET'])
@authnz.require_auth
def get_certificate(ca, cn):
    '''
    Get a certificate from the provided CA, for the provided CN.

    .. :quickref: Certificate; Get certificate from the provided CA, for the
                  provided CN.

    **Example request**:
Пример #19
0
# -*- coding: utf-8 -*-

# @Time    : 2021/1/5 下午2:46
# @Author  : cyq
# @File    : __init__.py.py

from flask import blueprints

myBug = blueprints.Blueprint("myBug", __name__, url_prefix="/api")

from . import users, product, bugs, search
Пример #20
0
from hashlib import sha256
from flask import redirect, render_template, json, request, blueprints
from uuid import uuid4
from datetime import datetime, timedelta
import db

from user import User

app = blueprints.Blueprint('app', __name__)


@app.route('/oauth/authorize', methods=['GET'])
def authorize_form():
    response_type = request.args.get('response_type', None)
    client_id = request.args.get('client_id', None)
    state = request.args.get('state', None)

    if client_id is None:
        return 'missing client_id', 400

    try:
        new_client_id = int(client_id)
    except:
        return 'invalid client_id', 400

    if new_client_id not in db.client:
        print(client_id)
        return 'no id in database', 400

    if response_type is None:
        return redirect(db.client[new_client_id]['redirect_uri'] +
Пример #21
0
from flask import blueprints

lg = blueprints.Blueprint('login', __name__)
Пример #22
0
from flask import blueprints, current_app, jsonify, request
from graphlite import V
import logging
from sqlalchemy.orm.exc import NoResultFound

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

from family_tree.database import Address, Person

blueprint = blueprints.Blueprint('person', __name__)


@blueprint.route('/person/<person_id>', methods=['GET'])
def get_person(person_id):
    db = current_app.config['db']
    try:
        person = db.session.query(Person).filter_by(id=person_id).one()
        record = person.json
        address_id = record.pop('address_id')
        address = db.session.query(Address).filter_by(id=address_id).one()
        record['address'] = address.json
    except NoResultFound:
        return jsonify(False), 404

    return jsonify(record)


@blueprint.route('/person/add', methods=['POST'])
def add_person():
    record = request.get_json()
Пример #23
0
from flask import blueprints, current_app, flash, jsonify, redirect, request, url_for
from sqlalchemy.exc import IntegrityError

from ..exc import (
    InvalidPatchDefinitionError,
    SoftwareTitleNotFound,
    Unauthorized
)

blueprint = blueprints.Blueprint('error_handlers', __name__)


@blueprint.app_errorhandler(Unauthorized)
def unauthorized(err):
    current_app.logger.error(err.message)

    if request.args.get('redirect'):
        flash(
            {
                'title': 'Unauthorized',
                'message': err.message
            },
            'warning')
        return redirect(url_for('web_ui.index'))
    else:
        return jsonify({'unauthorized': err.message}), 401


@blueprint.app_errorhandler(InvalidPatchDefinitionError)
def error_invalid_patch_definition(err):
    current_app.logger.error(err.message)
Пример #24
0
def get_bp(blueprint_name):
    """Return blueprint for Security_Group management."""
    bp = blueprints.Blueprint(blueprint_name, __name__)

    @bp.route('<security_group_id>/', methods=['GET'])
    def show(security_group_id, add_form=None):
        """Present details page for single security group object.
        """
        security_group = (clients.user_clients(
            flask.g.tenant_id).compute.security_groups.get(security_group_id))
        return {
            'security_group':
            security_group,
            'add_form':
            add_form
            or forms.SecurityGroupRuleAdd(security_group_id=security_group_id),
            'delete_form':
            forms.DeleteForm(),
            'title':
            bp.name.replace('global_', '').replace('_', ' ').capitalize(),
            'subtitle':
            'Security group details',
        }

    @bp.route('')
    def index():
        """List security groups.
        """
        security_groups = (clients.user_clients(
            flask.g.tenant_id).compute.security_groups.list())
        p = pagination.Pagination(security_groups)
        data = p.slice(security_groups)
        return {
            'security_groups': data,
            'pagination': p,
            'delete_form': forms.DeleteForm(),
            'title': bp.name.replace('global_', '').replace('_',
                                                            ' ').capitalize(),
            'subtitle': 'List of existing security groups'
        }

    @bp.route('new/', methods=['GET', 'POST'])
    def new():
        """Create security_group.
        """
        form = forms.SecurityGroupCreate()
        if form.validate_on_submit():
            try:
                security_group = (clients.user_clients(
                    flask.g.tenant_id).compute.security_groups.create(
                        name=form.name.data,
                        description=form.description.data))
            except exceptions.HttpException as ex:
                flask.flash(ex.message, 'error')
            else:
                flask.flash('Security group %s created.' % form.name.data,
                            'success')
                return flask.redirect(flask.url_for('.index'))
        return {
            'form': form,
            'title': bp.name.replace('global_', '').replace('_',
                                                            ' ').capitalize(),
            'subtitle': 'Add new security group'
        }

    @bp.route('<security_group_id>/delete/', methods=['POST'])
    def delete(security_group_id):
        form = forms.DeleteForm()
        if form.validate_on_submit():
            try:
                (clients.user_clients(
                    flask.g.tenant_id).compute.security_groups.delete(
                        security_group_id))
            except exceptions.HttpException as ex:
                flask.flash(ex.message, 'error')
            else:
                flask.flash('Security group successfully deleted', 'success')
        else:
            flask.flash('Invalid form', 'error')
        return flask.redirect(flask.url_for('.index'))

    @bp.route('<security_group_id>/<rule_id>/delete', methods=['POST'])
    def delete_rule(security_group_id, rule_id):
        form = forms.DeleteForm()
        if form.validate_on_submit():
            (clients.user_clients(
                flask.g.tenant_id).compute.security_group_rules.delete(rule_id)
             )
            flask.flash('Security group rule successfully deleted', 'success')
        else:
            flask.flash('Invalid form', 'error')
        return flask.redirect(
            flask.url_for('.show', security_group_id=security_group_id))

    @bp.route('<security_group_id>/add_rule', methods=['GET', 'POST'])
    def add_rule(security_group_id):
        form = forms.SecurityGroupRuleAdd(security_group_id=security_group_id)
        if form.validate_on_submit():
            try:
                group_id = int(form.group_id.data)
                cidr = None
            except ValueError:
                group_id = None
                cidr = form.cidr.data
            try:
                (clients.user_clients(
                    flask.g.tenant_id).compute.security_group_rules.create(
                        security_group_id, form.ip_protocol.data,
                        form.from_port.data, form.to_port.data, cidr,
                        group_id))
            except exceptions.HttpException as ex:
                flask.flash(ex.message, 'error')
            else:
                flask.flash('Security group rule successfully added',
                            'success')
                return flask.redirect(
                    flask.url_for('.show',
                                  security_group_id=security_group_id))

        return {
            'form': form,
            'security_group_id': security_group_id,
            'title': bp.name.replace('global_', '').replace('_',
                                                            ' ').capitalize(),
            'subtitle': 'Add new rule'
        }

    return bp
Пример #25
0
# You should have received a copy of the GNU Lesser General Public
# License along with this program. If not, see
# <http://www.gnu.org/licenses/>.

import flask
from flask import blueprints

from focus import clients

from focus.views import environments
from focus.views import forms
from focus.views import pagination

from openstackclient_base.exceptions import HttpException

bp = environments.admin(blueprints.Blueprint('networks', __name__))


@bp.route('')
def index():
    try:
        networks = clients.admin_clients().compute.networks.list()
    except HttpException as ex:
        networks = []
    tenants = clients.admin_clients().identity_admin.tenants.list()
    tenants = dict(((t.id, t.name) for t in tenants))
    p = pagination.Pagination(len(networks))
    offset = p.limit_offset()
    networks = [net._info for net in networks[offset[0]:offset[1]]]
    for net in networks:
        net["label"] = tenants.get(net["project_id"], net["label"])
Пример #26
0
from flask import current_app, blueprints, request, jsonify
from marshmallow import Schema, fields, post_load
from sqlalchemy.orm import sessionmaker

from kv_store.controller.value import ValueController
from kv_store.model.value import Value

blueprint = blueprints.Blueprint('value', __name__)


@blueprint.route('/value', methods=['POST'])
@blueprint.route('/value/<key>', methods=['PUT'])
def set(key=None):
    status_code = None
    controller = ValueController()
    schema = ValueAccessorSchema()
    value = schema.load(request.get_json())

    if key:
        value.key = key
        new_value = controller.update(value)
        status_code = 200
    else:
        new_value = controller.create(value)
        status_code = 201

    return schema.dump(new_value), status_code


@blueprint.route('/value/<key>', methods=['GET'])
def get(key):
Пример #27
0
from flask import blueprints
user = blueprints.Blueprint('user', __name__)
from app.user import views
Пример #28
0
from flask import (blueprints, request, redirect, session, render_template,
                   jsonify)
import os
from markupsafe import Markup, escape
from ProcessaTicketAPI.ProcessaTicketClasses import TicketProcessor
from settings import APP_1_HOME_URL, APP_3_HOME_URL

ProcessaTicket_blueprint = blueprints.Blueprint('ProcessaTicket_blueprint',
                                                __name__)


@ProcessaTicket_blueprint.route("/")
def show_welcome_page():
    return render_template('welcome_page.html',
                           url='/process',
                           home_url='//' + APP_1_HOME_URL,
                           get_result_url='//' + APP_3_HOME_URL)


@ProcessaTicket_blueprint.route('/process', methods=['POST'])
def process_calculation_request_and_redirect():

    tickprocs = TicketProcessor(jsonify(request.form).json)

    result = tickprocs.process()

    session['result'] = result

    return redirect('/process_result')

Пример #29
0
from ..models import db, Person, Address
from flask import blueprints
from flask import jsonify
from faker import Faker

fake = Faker()
blueprint = blueprints.Blueprint('generate_data', __name__)

# for testing purposes only.
@blueprint.route('/generate_data', methods=['GET'])
def generate_data():
    db.drop_all()
    db.create_all()
    grandpa_1 = make_person()
    grandma_1 = make_person(last_name=grandpa_1.last_name)
    child_1 = make_person(last_name=grandpa_1.last_name, parents=[grandpa_1, grandma_1])

    grandpa_2 = make_person()
    grandma_2 = make_person(last_name=grandpa_2.last_name)
    child_2 = make_person(last_name=child_1.last_name, parents=[grandpa_2, grandma_2])
    
    grandchild_1 = make_person(last_name=child_1.last_name, parents=[child_1, child_2])
    grandchild_2 = make_person(last_name=child_1.last_name, parents=[child_1, child_2])
    
    db.session.commit()
    return jsonify('data created')


def make_person(last_name=None, addresses=None, parents=None):
    person = Person(
        first_name = fake.first_name(),
Пример #30
0
from flask import blueprints, render_template, session, request, current_app, redirect
from flask_directory_example import db
from .. import models

ac = blueprints.Blueprint('ac', __name__)


@ac.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        user = request.form.get('user')
        pwd = request.form.get('pwd')

        obj = db.session.query(models.Users).filter(
            models.Users.name == user, models.Users.pwd == pwd).first()
        db.session.remove()  #在请求结束时删除数据库会话
        if not obj:
            return render_template('login.html')
        current_app.auth_manage.login(user)  #用户验证成功设置session
        return redirect('/index')


@ac.route('/logout')
def logout():
    current_app.auth_manage.logout()
    return redirect('/login')