예제 #1
0
    def create():
        blueprint = Blueprint('people', 'people')

        blueprint.add_url_rule(
            '/person',
            view_func=PeopleListOrCreateView.as_view('people-list-or-create'),
        )

        return blueprint
예제 #2
0
    def create_module_blueprint(self, model, methods=READONLY_METHODS, url_prefix='/module', module_name=None, jqgrid=None,
                               module_link=None, authentication_required=None,
                               template_name=None, template_folder=None, form=None, view=ModuleView):

        if module_name is None:
            module_name = model.__tablename__

        view_endpoint = '/%s' % module_name
        apiname = ModuleManager.APINAME_FORMAT % module_name


        if jqgrid == None:
            pager = "jqgrid_%s_pager" % module_name
            jqgrid = JqGrid(self.model, data_url='api'+view_endpoint, pager_id=pager)

        if template_name is None:
            template_name = 'core/simple_crud.html'

        view_func =  view.as_view(apiname, template_name=template_name, jqgrid=jqgrid, model=model, module_name=module_name)

        blueprintname = self._next_blueprint_name(apiname)

        if template_folder:
            blueprint = Blueprint(blueprintname, __name__, url_prefix=url_prefix, template_folder=template_folder)
        else:
            blueprint = Blueprint(blueprintname, __name__, url_prefix=url_prefix)

        # endpoint functions views
        blueprint.add_url_rule(view_endpoint+'/<method>', view_func=view_func)

        url_view = url_prefix + view_endpoint + '/view'
        if module_link:
            module_link['url'] = url_view
            self.app.config['MODULE_LIST'].append(module_link)
        else:
            module_link = {'url':url_view, 'label':module_name.title(), 'icon_class':'nails'}
            self.app.config['MODULE_LIST'].append(module_link)


        return blueprint
예제 #3
0
파일: home.py 프로젝트: guoyu07/firefly
# coding=utf-8
from __future__ import absolute_import
from flask import request, jsonify, redirect, url_for
from flask.views import MethodView
from flask.blueprints import Blueprint
from flask_login import login_user, current_user, login_required

from firefly.forms.user import LoginForm, RegisterForm
from firefly.models.topic import (Category, Post, Comment, get_all_posts,
                                  get_post)
from firefly.models.user import User
from firefly.libs.template import render_template


bp = Blueprint("home", __name__, url_prefix="/")


class HomeView(MethodView):

    def get(self):
        posts = get_all_posts()
        return render_template('index.html', posts=posts)


class CreateTopicView(MethodView):
    decorators = [login_required]

    def post(self):
        title = request.form.get('title')
        content = request.form.get('content')
        category_id = request.form.get('category', '')
예제 #4
0
# -*- coding: utf-8 -*-

from flask import request, jsonify, abort, redirect, url_for
from flask.blueprints import Blueprint

import database as db
from flask_login import login_user, login_required, logout_user

bp = Blueprint('auth', __name__)


@bp.route('/login', methods=['POST'])
def login():
    res = {'status': 'ERROR', 'message': 'Invalid user or password'}

    email = request.form.get('email')
    password = request.form.get('password')

    # not valid parameters or malformed request
    if not email or not password:
        abort(400)

    user = db.get(db.User, "email", email)

    if not user:
        return jsonify(res)

    if not user.is_valid_password(password):
        return jsonify(res)

    # set the current logged in user to flask_login
예제 #5
0
파일: home.py 프로젝트: tmacjx/firefly
# coding=utf-8
from flask import request, jsonify, redirect, url_for
from flask.views import MethodView
from flask.blueprints import Blueprint
from flask_mako import render_template, render_template_def
from flask_login import current_user, logout_user

from firefly.models.topic import Category, Post


bp = Blueprint("home", __name__, url_prefix="/")


class HomeView(MethodView):
    def get(self):
        posts = Post.objects.all()
        return render_template("index.html", posts=posts)


class CreateView(MethodView):
    def post(self):
        title = request.form.get("title")
        content = request.form.get("content")
        category_id = request.form.get("category", "")
        if category_id.isdigit():
            category_id = int(category_id)
        category = Category.objects.filter(id=category_id).first()
        post = Post(title=title, content=content, category=category)
        post.save()
        html = render_template_def("/widgets/topic_item.html", "main", post=post, is_new=True)
예제 #6
0
파일: keyboard.py 프로젝트: Auston/firefly
# coding=utf-8
from flask import request
from flask.views import MethodView
from flask.blueprints import Blueprint
from flask_mako import render_template

from firefly.models.consts import KEYBOARD_URL_MAPS


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


class KeyboardView(MethodView):
    def get(self):
        url = request.args.get('url', '')
        url_pattern = url.rsplit('/', 1)[0]
        keyboards = KEYBOARD_URL_MAPS['default']
        if url_pattern in KEYBOARD_URL_MAPS:
            keyboards += KEYBOARD_URL_MAPS[url_pattern]
        return render_template('widgets/keyboard.html', keyboards=keyboards)


bp.add_url_rule('/', view_func=KeyboardView.as_view('keyboard'))
예제 #7
0
        ticket = TicketModel.add_to_process(data.get('processId'), data.get('ticket'))
        return {'ticket': ticket}

    def delete(self, _id):
        res = TicketModel.delete_from_process(request.args.get('processId'), _id)
        return {'ticket': res}

    def patch(self, _id):
        data = request_data_to_dict(request.form)

        # Move ticket to another process
        if 'oldProcessId' in data and 'newProcessId' in data:
            ticket = TicketModel.move_to_process(
                old_process_id=data.get('oldProcessId'),
                new_process_id=data.get('newProcessId'),
                ticket=data.get('ticket')
            )
        # Edit existing ticket
        else:
            ticket = TicketModel.modify(data.get('processId'), _id, data.get('ticket'))

        return {'ticket': ticket}


ticket_blueprint = Blueprint('ticket_blueprint', __name__)
ticket_view = TicketResource.as_view('ticket_view')

ticket_blueprint.add_url_rule('/tickets', 'tickets', ticket_view)
ticket_blueprint.add_url_rule('/tickets/<string:_id>', 'ticket', ticket_view)

예제 #8
0
    def get(self):
        processes = ProcessModel.query(spec={})
        return {'processes': [p for p in processes]}

    def post(self):
        process = request.form.to_dict()
        process_id = ProcessModel.create(process)
        return {'process': {'_id': process_id}}

    def delete(self, _id):
        ProcessModel.delete(_id)
        return {'process': {}}

    def patch(self, _id):
        process = request.form.to_dict()
        # Get id of process will be updated
        _id = process['_id']
        # Delete _id in process for update process without touching _id
        del process['_id']
        process = ProcessModel.modify(_id, process)
        return {'process': process}


process_blueprint = Blueprint('process_blueprint', __name__)
process_view = ProcessResource.as_view('process_view')

process_blueprint.add_url_rule('/processes', 'processes', process_view)
process_blueprint.add_url_rule('/processes/<string:_id>', 'process', process_view)

예제 #9
0
파일: generic.py 프로젝트: gwTumm/sipa
from flask.ext.login import current_user, login_user, logout_user, \
    login_required
from sqlalchemy.exc import DatabaseError
from ldap3 import LDAPCommunicationError

from sipa.forms import flash_formerrors, LoginForm, AnonymousContactForm
from sipa.model import dormitory_from_name, user_from_ip, premature_dormitories
from sipa.units import dynamic_unit
from sipa.utils import get_user_name, redirect_url
from sipa.utils.exceptions import UserNotFound, InvalidCredentials
from sipa.utils.mail_utils import send_mail
from sipa.utils.git_utils import get_repo_active_branch, get_latest_commits

logger = logging.getLogger(__name__)

bp_generic = Blueprint('generic', __name__)


@bp_generic.before_app_request
def log_request():
    if 'sentry' in current_app.extensions:
        current_app.extensions['sentry'].client.extra_context({
            'current_user': get_user_name(current_user),
            'ip_user': get_user_name(user_from_ip(request.remote_addr))
        })

    logging.getLogger(__name__ + '.http').debug(
        'Incoming request: %s %s', request.method, request.path,
        extra={'tags': {'user': get_user_name(current_user),
                        'ip': request.remote_addr}}
    )
예제 #10
0
from flask import Response, jsonify, make_response, request
from flask import current_app as app
from flask.blueprints import Blueprint

from amundsen_application.log.action_log import action_logging
from amundsen_application.api.utils.metadata_utils import marshall_dashboard_partial
from amundsen_application.api.utils.request_utils import get_query_param, request_search
from amundsen_application.api.utils.search_utils import generate_query_json, has_filters, \
    map_table_result, transform_filters
from amundsen_application.models.user import load_user, dump_user

LOGGER = logging.getLogger(__name__)

REQUEST_SESSION_TIMEOUT_SEC = 3

search_blueprint = Blueprint('search', __name__, url_prefix='/api/search/v0')

SEARCH_DASHBOARD_ENDPOINT = '/search_dashboard'
SEARCH_DASHBOARD_FILTER_ENDPOINT = '/search_dashboard_filter'
SEARCH_TABLE_ENDPOINT = '/search'
SEARCH_TABLE_FILTER_ENDPOINT = '/search_table'
SEARCH_USER_ENDPOINT = '/search_user'


@search_blueprint.route('/table', methods=['POST'])
def search_table() -> Response:
    """
    Parse the request arguments and call the helper method to execute a table search
    :return: a Response created with the results from the helper method
    """
    try:
예제 #11
0
def createBlueprint(RESULTS, RACE, serverInfo, getCurrentProfile):
    APP = Blueprint('json', __name__)
    RHData = RESULTS.rhDataObj

    @APP.route('/api/pilot/all')
    def api_pilot_all():
        pilots = RHData.get_pilots()
        payload = []
        for pilot in pilots:
            payload.append(pilot)

        return json.dumps({"pilots": payload}, cls=AlchemyEncoder), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    @APP.route('/api/pilot/<int:pilot_id>')
    def api_pilot(pilot_id):
        pilot = RHData.get_pilot(pilot_id)

        return json.dumps({"pilot": pilot}, cls=AlchemyEncoder), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    @APP.route('/api/heat/all')
    def api_heat_all():
        all_heats = {}
        for heat in RHData.get_heats():
            heat_id = heat.id
            note = heat.note
            race_class = heat.class_id

            heatnodes = RHData.get_heatNodes_by_heat(heat.id)
            pilots = {}
            for pilot in heatnodes:
                pilots[pilot.node_index] = pilot.pilot_id

            locked = RHData.savedRaceMetas_has_heat(heat.id)

            all_heats[heat_id] = {
                'note': note,
                'heat_id': heat_id,
                'class_id': race_class,
                'nodes_pilots': pilots,
                'locked': locked
            }

        return json.dumps({"heats": all_heats}, cls=AlchemyEncoder), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    @APP.route('/api/heat/<int:heat_id>')
    def api_heat(heat_id):
        heat = RHData.get_heat(heat_id)
        if heat:
            note = heat.note
            race_class = heat.class_id

            heatnodes = RHData.get_heatNodes_by_heat(heat.id)
            pilots = {}
            for pilot in heatnodes:
                pilots[pilot.node_index] = pilot.pilot_id

            locked = RHData.savedRaceMetas_has_heat(heat.id)

            heat = {
                'note': note,
                'heat_id': heat_id,
                'class_id': race_class,
                'nodes_pilots': pilots,
                'locked': locked
            }
        else:
            heat = None

        payload = {
            'setup': heat,
            'leaderboard': RESULTS.calc_heat_leaderboard(heat_id)
        }

        return json.dumps({"heat": payload}, cls=AlchemyEncoder), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    @APP.route('/api/class/all')
    def api_class_all():
        race_classes = RHData.get_raceClasses()
        payload = []
        for race_class in race_classes:
            payload.append(race_class)

        return json.dumps({"classes": payload}, cls=AlchemyEncoder), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    @APP.route('/api/class/<int:class_id>')
    def api_class(class_id):
        race_class = RHData.get_raceClass(class_id)

        return json.dumps({"class": race_class}, cls=AlchemyEncoder), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    @APP.route('/api/format/all')
    def api_format_all():
        formats = RHData.get_raceFormats()
        payload = []
        for race_format in formats:
            payload.append(race_format)

        return json.dumps({"formats": payload}, cls=AlchemyEncoder), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    @APP.route('/api/format/<int:format_id>')
    def api_format(format_id):
        raceformat = RHData.get_raceFormat(format_id)

        return json.dumps({"format": raceformat}, cls=AlchemyEncoder), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    @APP.route('/api/profile/all')
    def api_profile_all():
        profiles = RHData.get_profiles()
        payload = []
        for profile in profiles:
            payload.append(profile)

        return json.dumps({"profiles": payload}, cls=AlchemyEncoder), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    @APP.route('/api/profile/<int:profile_id>')
    def api_profile(profile_id):
        profile = RHData.get_profile(profile_id)

        return json.dumps({"profile": profile}, cls=AlchemyEncoder), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    @APP.route('/api/race/current')
    def api_race_current():
        results = RESULTS.calc_current_race_leaderboard(
            RACE, getCurrentProfile())

        payload = {"raw_laps": RACE.node_laps, "leaderboard": results}

        return json.dumps({"race": payload}, cls=AlchemyEncoder), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    @APP.route('/api/race/all')
    def api_race_all():
        heats = []
        for heat in RHData.get_heats():
            max_rounds = RHData.get_max_round(heat.id)
            heats.append({"id": heat.id, "rounds": max_rounds})

        payload = {
            "heats": heats,
            "leaderboard": RESULTS.calc_event_leaderboard()
        }

        return json.dumps({"races": payload}, cls=AlchemyEncoder), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    @APP.route('/api/race/<int:heat_id>/<int:round_id>')
    def api_race(heat_id, round_id):
        race = RHData.get_savedRaceMeta_by_heat_round(heat_id, round_id)

        pilotraces = []
        for pilotrace in RHData.get_savedPilotRaces_by_savedRaceMeta(race.id):
            laps = []
            for lap in RHData.get_savedRaceLaps_by_savedPilotRace(
                    pilotrace.id):
                laps.append({
                    'id': lap.id,
                    'lap_time_stamp': lap.lap_time_stamp,
                    'lap_time': lap.lap_time,
                    'lap_time_formatted': lap.lap_time_formatted,
                    'source': lap.source,
                    'deleted': lap.deleted
                })

            pilot_data = RHData.get_pilot(pilotrace.pilot_id)
            if pilot_data:
                nodepilot = pilot_data.callsign
            else:
                nodepilot = None

            pilotraces.append({
                'callsign': nodepilot,
                'pilot_id': pilotrace.pilot_id,
                'node_index': pilotrace.node_index,
                'laps': laps
            })
        payload = {
            'start_time_formatted': race.start_time_formatted,
            'nodes': pilotraces,
            'sort': RHData.get_option('pilotSort'),
            'leaderboard': RESULTS.calc_race_leaderboard(heat_id, round_id)
        }

        return json.dumps({"race": payload}, cls=AlchemyEncoder), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    @APP.route('/api/status')
    def api_status():
        data = {
            "server_info": {
                "server_api": serverInfo['server_api'],
                "json_api": serverInfo['json_api'],
                "node_api_best": serverInfo['node_api_best'],
                "release_version": serverInfo['release_version'],
                "node_api_match": serverInfo['node_api_match'],
                "node_api_lowest": serverInfo['node_api_lowest'],
                "node_api_levels": serverInfo['node_api_levels']
            },
            "state": {
                "current_heat": RACE.current_heat,
                "num_nodes": RACE.num_nodes,
                "race_status": RACE.race_status,
                "currentProfile": RHData.get_option('currentProfile'),
                "currentFormat": RHData.get_option('currentFormat'),
            }
        }

        return json.dumps({"status": data}), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    @APP.route('/api/options')
    def api_options():
        opt_query = RHData.get_options()
        options = {}
        if opt_query:
            for opt in opt_query:
                if opt.option_name not in ['eventResults', 'secret_key']:
                    options[opt.option_name] = opt.option_value

            payload = options
        else:
            payload = None

        return json.dumps({"options": payload}, cls=AlchemyEncoder), 201, {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        }

    return APP
예제 #12
0
from flask.blueprints import Blueprint
from flask import request, session
from controllers.usuario import UsuarioController

usuario = Blueprint("usuarios", __name__)


@usuario.route("/", methods=["GET"])
def listar_usuarios():
    pagina = request.args.get('pagina', 1)
    codigo = request.args.get('codigo', "")
    nombre = request.args.get('nombres', "")
    cedula = request.args.get('cedula', "")
    apellidos = request.args.get('apellidos', "")
    return UsuarioController().get_lista_usuarios(pagina, codigo, nombre,
                                                  cedula, apellidos)


@usuario.route("/registro", methods=["GET", "POST"])
def registro_usuario():
    if request.method == "GET":
        return UsuarioController().get_registro()
    codigo = request.form.get('codigo', None)
    nombres = request.form.get('nombres', None)
    apellidos = request.form.get('apellidos', None)
    cedula = request.form.get('cedula', None)
    email = request.form.get('email', None)
    contrasena = request.form.get('contrasena', None)
    tipo_usuario = request.form.get('tipo_usuario', 0)
    return UsuarioController().crear_usuario(codigo, nombres, apellidos,
                                             cedula, email, contrasena,
예제 #13
0
from flask import jsonify, request
from flask.blueprints import Blueprint

from main.service.tareas_service import crear_tarea, eliminar_asociaciones
from main.service.tickets_service import (archivar, crear, editar,
                                          obtener_ticket_por, obtener_data_diaria,
										  obtener_data_acumulada)
from main.service.tickets_service import \
    obtener_tickets as obtener_tickets_service
from main.settings import CODIGO_HTTP

tickets = Blueprint('tickets', __name__)


@tickets.route('/tickets', methods=['GET'])
def obtener_tickets():
	query_params = request.args

	respuesta = obtener_tickets_service(query_params)

	return jsonify(respuesta), CODIGO_HTTP["OK"]

@tickets.route('/tickets/<int:id>', methods=['GET'])
def obtener_ticket(id):
	try:
		ticket = obtener_ticket_por(id)
		return jsonify(ticket), CODIGO_HTTP["OK"]
	except:
		return jsonify({'mensaje': 'Ticket no encontrado'}), CODIGO_HTTP["BAD_REQUEST"]

@tickets.route('/tickets', methods=['POST'])
예제 #14
0
from flask.blueprints import Blueprint
from flask import render_template
from Models.Interval import Interval

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


@intervals.route('/intervals')
def index():
    return render_template('intervals.html', intervals=Interval.query.all())
예제 #15
0
파일: user.py 프로젝트: mmint-kanban/kanban
# coding=utf-8
from flask.blueprints import Blueprint
from flask.globals import request

from api.core.views import BaseResourceView
from api.models.user import UserModel


class UserResource(BaseResourceView):
    """ Resource for authentication """

    def get(self):
        # Search user
        users = UserModel.search(
            keyword=request.args.get('keyword'),
            fields=('username', '_id')
        )
        return {'users': users}

    def post(self, _id=None):
        UserModel.register(request.form)
        return 'ok'

user_blueprint = Blueprint('user_blueprint', __name__)
user_view = UserResource.as_view('user_view')

user_blueprint.add_url_rule('/users', 'users', user_view)
user_blueprint.add_url_rule('/users/<string:_id>', 'user', user_view)

예제 #16
0
    MSG_WRONG_PASSWORD, MSG_NO_APP_NAME, MSG_APP_NAME_DUPLICATED, \
    MSG_SERVER_ERROR, MSG_SAVE_SUCC, MESSAGE_INFO, MESSAGE_WARNING, \
    MSG_RECORD_NOT_EXIST, MSG_DELETE_SUCC, MSG_UPDATE_SUCC, MSG_NO_ID_SUPPLIED, \
    MSG_NO_ENOUGH_PARAMS, MSG_WRONG_CONFIRM_PASSWORD
from sys2do.model.logic import AppObject, AppArticle
from webhelpers import paginate
from sys2do.setting import PAGINATE_PER_PAGE, APP_FOLDER, APP_PACKAGE, \
    UPLOAD_FOLDER_PREFIX, UPLOAD_FOLDER_URL, UPLOAD_FOLDER, WEBSITE_ROOT
from sys2do.util.apphelper import createApp
import shutil
from sys2do.model.system import UploadFile
from sys2do.util.qr_helper import createQR

__all__ = ['bpConsoles']

bpConsoles = Blueprint('bpConsoles', __name__)

class ConsolesView(BasicView):

    template_dir = 'consoles'


    @templated()
    def index(self):
        session['current_app_id'] = None



    @templated()
    def updateProfile(self):
        uid = session['user_profile']['id']
예제 #17
0
파일: user.py 프로젝트: IanZhao/firefly
# coding=utf-8
from __future__ import absolute_import

from flask.views import MethodView
from flask.blueprints import Blueprint


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


class UserView(MethodView):
    def get(self, id):
        return ''

bp.add_url_rule('/<id>/', view_func=UserView.as_view('detail'))
예제 #18
0
파일: actors.py 프로젝트: IamFive/ifanhao
# -*- coding: utf-8 -*-
#
# @author: Five
# Created on 2013-8-5
#

from flask.blueprints import Blueprint
from ifanhao.common.web.renderer import smart_render
from ifanhao.models import Actor
from flask.globals import g
from sqlalchemy.sql.expression import desc

bp_actors = Blueprint('actors', __name__)


@bp_actors.route('/', methods=['GET'])
@bp_actors.route('/<int:page>', methods=['GET'])
@smart_render()
def get_actor_list(page=1):

    # filter conditions
    k = g.formdata.get('k', '')

    q = Actor.query
    if k:
        like_str = '%' + k + '%'
        q = q.filter(Actor.name.like(like_str) | Actor.cn_name.like(like_str))

    pagination = q.order_by(desc(Actor.cup)).paginate(page, per_page=12)

    return dict(pagination=pagination, k=k)
예제 #19
0
from flask import redirect
from flask import render_template
from flask import request
from flask import send_from_directory
from flask import url_for
from flask.blueprints import Blueprint

from mycodo.config import MYCODO_VERSION
from mycodo.config import THEMES_DARK
from mycodo.config_translations import TRANSLATIONS
from mycodo.databases.models import Misc
from mycodo.mycodo_client import DaemonControl
from mycodo.mycodo_flask.routes_authentication import admin_exists

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

logger = logging.getLogger(__name__)


def before_request_admin_exist():
    """
    Ensure databases exist and at least one user is in the user database.
    """
    if not admin_exists():
        return redirect(url_for("routes_authentication.create_admin"))
blueprint.before_request(before_request_admin_exist)


@blueprint.context_processor
예제 #20
0
#
# Created by dp on 2014-12-25.
# ================================================================================ #
from flask.blueprints import Blueprint
from flask.globals import g
from wtforms.fields.core import SelectField
from wtforms.fields.simple import TextField
from wtforms.validators import DataRequired

from blueprints import DefaultForm, render, create_form, mismatch, delete_form, \
    update_form
from natives.menu import menubar, contextmenu
from natives.role import Role
from utility.localization import localize

blueprint = Blueprint("Role Controller", __name__)


# Forms
# -------------------------------------------------------------------------------- #
class FormRole(DefaultForm):
    name = TextField(localize("administration", "roles.field_name"),
                     validators=[DataRequired()])
    description = TextField(localize("administration",
                                     "roles.field_description"),
                            validators=[DataRequired()])
    parent_id = SelectField(localize("administration",
                                     "roles.field_parent_id"),
                            coerce=int)

예제 #21
0
파일: __init__.py 프로젝트: zbing3/firefly
# coding=utf-8
from flask.blueprints import Blueprint

from .category import category_view

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

bp.add_url_rule('/category/', defaults={'name': None}, view_func=category_view)
bp.add_url_rule('/category/<string:name>', view_func=category_view)
예제 #22
0
# coding=utf-8
import os
from flask import abort
from flask.blueprints import Blueprint
from flask.ext.restful import Api, reqparse, fields, marshal_with
from aireadManager.utils.permissions import Permissions
from aireadManager.utils.restful import Resource
from aireadManager.model.group_permission import GroupPermissionModel
from aireadManager.model import db
from aireadManager.utils.errors import Code

__author__ = 'airead'

path = os.path.splitext(os.path.basename(__file__))[0]
blueprint = Blueprint(path, __name__, url_prefix='/' + path)
api = Api(blueprint)

group_permission_fields = {
    'id': fields.Integer,
    'group_id': fields.Integer,
    'permission_id': fields.Integer
}


def get_parser(required=False):
    parser = reqparse.RequestParser()
    parser.add_argument('group_id', type=int, required=required)
    parser.add_argument('permission_id', type=int, required=required)

    return parser
예제 #23
0
파일: home.py 프로젝트: dongweiming/firefly
# coding=utf-8
from __future__ import absolute_import
from flask import request, jsonify, redirect, url_for
from flask.views import MethodView
from flask.blueprints import Blueprint
from flask_mako import render_template, render_template_def
from flask_login import login_user, current_user, login_required

from firefly.forms.user import LoginForm, RegisterForm
from firefly.models.topic import Category, Post
from firefly.models.user import User


bp = Blueprint("home", __name__, url_prefix="/")


class HomeView(MethodView):
    def get(self):
        posts = Post.objects.all()
        return render_template('index.html', posts=posts)


class CreateView(MethodView):
    decorators = [login_required]

    def post(self):
        title = request.form.get('title')
        content = request.form.get('content')
        category_id = request.form.get('category', '')
        if category_id.isdigit():
            category_id = int(category_id)
예제 #24
0
import ujson
from flask import Response
from flask.blueprints import Blueprint
from werkzeug.exceptions import HTTPException

from ..utils.api_view import HEADERS
from .views import AddImportView, ImportCitizenView, ImportCitizensListView, ImportBirthdaysView, ImportTownsStateView

module = Blueprint("citizens", __name__)


@module.app_errorhandler(HTTPException)
def http_err_handler(error) -> Response:
    error_message = {"error": {"message": error.description}}
    return Response(ujson.dumps(error_message), error.code, HEADERS)


module.add_url_rule(
    "/imports",
    view_func=AddImportView.as_view("add_import"),
)
module.add_url_rule(
    "/imports/<int:import_id>/citizens/<int:citizen_id>",
    view_func=ImportCitizenView.as_view("citizen"),
)
module.add_url_rule(
    "/imports/<int:import_id>/citizens",
    view_func=ImportCitizensListView.as_view("citizens_list"),
)
module.add_url_rule(
    "/imports/<int:import_id>/citizens/birthdays",
예제 #25
0
from flask.blueprints import Blueprint
from test.views import DetailView

testxx = Blueprint("test", __name__)

testxx.add_url_rule('/',view_func=DetailView.as_view('detail'))
예제 #26
0
from flask.blueprints import Blueprint
from flask import jsonify, request
from flask.helpers import make_response
from models import Zone
from monitoring.constants import ROLE_USER

from server.database import db
from server.decorators import authenticated, restrict_host
from server.ipc import IPCClient
from server.tools import process_ipc_response

zone_blueprint = Blueprint("zone", __name__)


@zone_blueprint.route("/api/zones/", methods=["GET"])
@authenticated(role=ROLE_USER)
@restrict_host
def get_zones():
    return jsonify([
        i.serialize
        for i in db.session.query(Zone).filter_by(deleted=False).all()
    ])


@zone_blueprint.route("/api/zones/", methods=["POST"])
@authenticated()
@restrict_host
def create_zone():
    zone = Zone()
    zone.update(request.json)
    if not zone.description:
예제 #27
0
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from flask.blueprints import Blueprint

from database.models import GlobalSettings
from forms import forms_settings
from utils.routes import allowed_access
from utils.routes import page_dict

logger = logging.getLogger('bitchan.routes_pgp')

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


@blueprint.context_processor
def global_var():
    return page_dict()


@blueprint.before_request
def before_view():
    if (GlobalSettings.query.first().enable_verification
            and ("verified" not in session or not session["verified"])):
        session["verified_msg"] = "You are not verified"
        return redirect(url_for('routes_verify.verify_wait'))
    session["verified_msg"] = "You are verified"
예제 #28
0
from flask.blueprints import Blueprint
from flask import request, abort

from cebulany.auth import token_required
from cebulany.export_data import fill_transactions
from cebulany.csv import parse_lines as parse_file

upload_page = Blueprint('upload_page', 'upload')


@upload_page.route('/api/transactions/upload', methods=['POST'])
@token_required
def upload_transactions():
    file = request.files.get('file')
    if file is None:
        abort(400, 'No file in args')

    if file.filename == '':
        abort(400, 'No selected file')

    lines = parse_file(line.decode('utf-8') for line in file.stream)
    fill_transactions(lines)

    return 'OK', 200
예제 #29
0
from flask import render_template
from flask.blueprints import Blueprint

from flaskblog import services

bp = Blueprint('index', __name__)

@bp.route('/')
def index():
    blogs = services.get_all_blogs()
    return render_template('index/index.html', blogs=blogs)
예제 #30
0
from mycodo.mycodo_flask.authentication_routes import admin_exists
from mycodo.mycodo_flask.authentication_routes import clear_cookie_auth
from mycodo.utils.database import db_retrieve_table_daemon

from mycodo.config import (
    INFLUXDB_USER,
    INFLUXDB_PASSWORD,
    INFLUXDB_DATABASE,
    INSTALL_DIRECTORY,
    LOG_PATH,
    MYCODO_VERSION,
    PATH_CAMERAS,
)

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

logger = logging.getLogger(__name__)
influx_db = InfluxDB()


def before_request_admin_exist():
    """
    Ensure databases exist and at least one user is in the user database.
    """
    if not admin_exists():
        return redirect(url_for("authentication_routes.create_admin"))


blueprint.before_request(before_request_admin_exist)
예제 #31
0
# -*- coding: utf-8 -*-

"""
.. module:: pravis.simple
   :synopsis: Blueprint setup for Simple module
"""

from flask.blueprints import Blueprint
from pravis.simple.views import LoginView

blueprint = Blueprint('simple', __name__, url_prefix='/simple/')
blueprint.add_url_rule('/', view_func=LoginView.as_view('simple'))
예제 #32
0
#-*- coding:utf-8 -*-
from flask.blueprints import Blueprint

photolog = Blueprint('photolog', __name__)
예제 #33
0
파일: generic.py 프로젝트: agdsn/sipa
from sqlalchemy.exc import DatabaseError
from ldap3.core.exceptions import LDAPCommunicationError

from sipa.backends.exceptions import BackendError
from sipa.forms import flash_formerrors, LoginForm, AnonymousContactForm, \
    OfficialContactForm
from sipa.mail import send_official_contact_mail, send_contact_mail
from sipa.backends.extension import backends
from sipa.units import dynamic_unit, format_money
from sipa.utils import get_user_name, redirect_url
from sipa.model.exceptions import UserNotFound, InvalidCredentials
from sipa.utils.git_utils import get_repo_active_branch, get_latest_commits

logger = logging.getLogger(__name__)

bp_generic = Blueprint('generic', __name__)


@bp_generic.before_app_request
def log_request():
    if 'sentry' in current_app.extensions:
        current_app.extensions['sentry'].client.extra_context({
            'current_user': get_user_name(current_user),
            'ip_user': get_user_name(backends.user_from_ip(request.remote_addr))
        })

    logging.getLogger(__name__ + '.http').debug(
        'Incoming request: %s %s', request.method, request.path,
        extra={'tags': {'user': get_user_name(current_user),
                        'ip': request.remote_addr}}
    )
예제 #34
0
# -*- coding: utf-8 -*-
from flask.blueprints import Blueprint
from flask import render_template

bp = Blueprint('home', __name__)


@bp.route("/")
def index():
    return render_template("home/index.html")
예제 #35
0
파일: user.py 프로젝트: guoyu07/firefly
# coding=utf-8
from __future__ import absolute_import

from flask import url_for, redirect

from flask.views import MethodView
from flask.blueprints import Blueprint
from flask.ext.login import login_required, current_user
from firefly.libs.template import render_template
from firefly.forms.user import ProfileForm


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


class UserView(MethodView):
    def get(self, id):
        return ''


class UserSettingsView(MethodView):
    decorators = [login_required]

    def get(self):
        return render_template('user/settings.html', user=current_user)

    def post(self):
        form = ProfileForm()
        form.save()
        return redirect(url_for('user.settings'))
예제 #36
0
#-*- coding: utf-8 -*-
from flask.blueprints import Blueprint
from flask.templating import render_template
from jinja2.exceptions import TemplateNotFound
from werkzeug.exceptions import abort

admin_page = Blueprint(
    'admin_page', __name__, template_folder='templates',
    url_prefix='/admin')  #admin_page객체로 매핑하는 url은 '/amdin'접두사가 붙게 된다.


@admin_page.route('/', defaults={'page': 'index'})
@admin_page.route('/<page>')
def admin_index(page):
    try:
        return render_template('/admin/%s.html' % page)
    except TemplateNotFound:
        abort(404)
예제 #37
0
파일: home.py 프로젝트: Auston/firefly
# coding=utf-8
from flask import request, jsonify, redirect, url_for
from flask.views import MethodView
from flask.blueprints import Blueprint
from flask_mako import render_template
from flask_login import current_user, logout_user

from firefly.models.topic import Category, Post


bp = Blueprint("home", __name__, url_prefix="/")


class HomeView(MethodView):
    def get(self):
        posts = Post.objects.all()
        return render_template('index.html', posts=posts)


class CreateView(MethodView):
    def post(self):
        title = request.form.get('title')
        content = request.form.get('content')
        category_id = request.form.get('category', '')
        if category_id.isdigit():
            category_id = int(category_id)
        category = Category.objects.filter(id=category_id).first()
        post = Post(title=title, content=content, category=category)
        post.save()
        return jsonify(ok=0)
예제 #38
0
import django.utils.regex_helper as regex_helper
from flask.blueprints import Blueprint
from markupsafe import escape
import models
from flask import Flask, request

blue = Blueprint('blue', __name__)
db = Flask(__name__.split('.')[0])

@blue.route('/ok')
def okroute():
    return '{request:{pk}}'

@blue.route('/sd', methods=['GET', 'POST'])
def parsing():
    from models import mymodel

    model = request.args['model']
    model = mymodel
    return model().create()

@blue.endpoint('app.auth')
def authentification():
    return 'example'


@blue.app_template_filter('/<int:id>')
def search(db, id: int):
    return db[id]

예제 #39
0

from sys2do.views import BasicView
from sys2do.util.decorator import templated, login_required
from sys2do.model.master import InventoryLocation, InventoryItem
from sys2do.model import DBSession
from sys2do.util.common import _g, _error
from sys2do.constant import MESSAGE_INFO, MSG_SAVE_SUCC, MSG_SERVER_ERROR, \
    MESSAGE_ERROR




__all__ = ['bpWarehouse']

bpWarehouse = Blueprint('bpWarehouse', __name__)

class WarehouseView(BasicView):

#    decorators = [login_required]

    @templated('warehouse/index.html')
    def index(self):
        result = DBSession.query(InventoryLocation).filter(InventoryLocation.active == 0).order_by(InventoryLocation.id)
        return {'result' : result}

    @templated('warehouse/add.html')
    def add(self):
        root_locations = DBSession.query(InventoryLocation).filter(and_(InventoryLocation.active == 0,
                                                       InventoryLocation.parent_id == None)).order_by(InventoryLocation.name)
예제 #40
0
# -*- coding: utf-8 -*-
from flask import request, jsonify
from flask.blueprints import Blueprint
from ai_clients import image_classify_client
import base64

image_classify = Blueprint('image_classify', __name__)

ALLOWED_EXTENSIONS = ['png', 'jpg', 'bmp']
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@image_classify.route('/general', methods=['post'])
def advanced_general():
    image = request.files.get('image')

    if not image:
        return jsonify({
            'result': False,
            'msg': u'缺少image',
        })

    if not(image and allowed_file(image.filename)):
        return jsonify({
            'result': False,
            'msg': u'文件上传失败,只允许jpg/png/bmp',
        })

    # 不存储
    data = image.read()
    res = image_classify_client.advancedGeneral(data)
from flask.blueprints import Blueprint

main_blueprint = Blueprint('main_blueprint', __name__)

from . import views
예제 #42
0
파일: router.py 프로젝트: jsdxuser/v2
from flask import jsonify, request
from flask.blueprints import Blueprint
from flask_babel import gettext

from base.models import Msg, User
from init import db
from util import server_info, config, v2_jobs, file_util

server_bp = Blueprint('server', __name__, url_prefix='/server')


@server_bp.route('/status', methods=['GET'])
def status():
    result = server_info.get_status()
    return jsonify(result)


@server_bp.route('/settings', methods=['GET'])
def settings():
    sets = config.all_settings()
    return jsonify([s.to_json() for s in sets])


@server_bp.route('/setting/update/<int:setting_id>', methods=['POST'])
def update_setting(setting_id):
    key = request.form['key']
    name = request.form['name']
    value = request.form['value']
    value_type = request.form['value_type']
    if key == 'cert_file' or key == 'key_file':
        if value and not file_util.is_file(value):
예제 #43
0
from sys2do.util.common import _g, getMasterAll, _error, _info
from sys2do.constant import MESSAGE_INFO, MSG_SAVE_SUCC, MSG_UPDATE_SUCC, \
    MSG_SERVER_ERROR, SYSTEM_DATE_FORMAT, MSG_NO_ID_SUPPLIED, \
    MSG_RECORD_NOT_EXIST
from sys2do.model.logic import OrderHeader, DeliverHeader, DeliverDetail
from sys2do.setting import PAGINATE_PER_PAGE, TMP_FOLDER, TEMPLATE_FOLDER
from sys2do.model.system import SystemLog
from sys2do.util.excel_helper import ProfitReport
from sys2do.model.auth import User




__all__ = ['bpFin']

bpFin = Blueprint('bpFin', __name__)

class FinView(BasicView):

    decorators = [login_required]

    @templated('fin/index.html')
    @mark_path('FIN_INDEX')
    def index(self):
        if _g('SEARCH_SUBMIT'):  # come from search
            values = {'page' : 1}
            for f in ['no', 'create_time_from', 'create_time_to', 'ref_no', 'customer_id', 'source_company_id',
                      'source_province_id', 'source_city_id', 'destination_province_id', 'destination_city_id',
                      'approve', 'paid', 'is_exception', 'is_less_qty', 'is_return_note'] :
                values[f] = _g(f)
                values['field'] = _g('field', None) or 'create_time'
예제 #44
0
from flask import render_template, flash, url_for, redirect
from flask.blueprints import Blueprint
from pathlib import Path
import numpy as np
import json
import joblib

from app.forms import PredictDataForm
from app.model.train import trainModel

main = Blueprint('main', __name__)
model_folder = Path('app/model/')


@main.route("/", methods=['GET', 'POST'])
@main.route("/home", methods=['GET', 'POST'])
def home():
    filename = model_folder / 'model_params.sav'
    classifier = joblib.load(filename)

    with open(model_folder / 'scaling_params.json') as file:
        scaling_params = json.load(file)

    embarked_q = 0
    embarked_s = 0
    form = PredictDataForm()
    if form.validate_on_submit():
        if form.embarked.data == 'cherbourg':
            embarked_q = 0
            embarked_s = 0
        elif form.embarked.data == 'queenstown':
예제 #45
0
파일: category.py 프로젝트: guoyu07/firefly
# coding=utf-8
from __future__ import absolute_import
from flask.views import MethodView
from flask.blueprints import Blueprint

from firefly.models.topic import Category, Post
from firefly.libs.template import render_template


bp = Blueprint("category", __name__, url_prefix="/category")


class CategoryView(MethodView):

    def get(self, slug):
        category = Category.objects.get_or_404(_slug=slug)
        posts = Post.objects.filter(
            category=category
        ).order_by("-recent_activity_time")
        return render_template('categories/detail.html',
                               category=category.name,
                               posts=posts)

bp.add_url_rule('/<slug>/', view_func=CategoryView.as_view('detail'))
예제 #46
0
# -*- coding: utf-8 -*-
from flask import g, request, render_template, abort
from flask.blueprints import Blueprint
from . import weak_load_page_by_url
from atuin.settings import CACHE_DEFAULT_TIME

bp = Blueprint('atuincms.router', __name__)


@bp.route("<path:p_url>",
          methods=['GET', 'POST', 'HEAD', 'PUT', 'DELETE', 'OPTIONS'])
@bp.route("/", methods=['GET', 'POST', 'HEAD', 'PUT', 'DELETE', 'OPTIONS'])
def route_pages(p_url=None):
    url = request.path

    if len(request.args) > 0:
        cache_key = request.full_path
    else:
        cache_key = request.path

    # try to load the response for the page from cache
    response = g.cache.get(cache_key)
    if response is not None:
        # print 'response not none!! SERVING CACHE for cache_key: ' + url
        return response

    # cached page not found, try to render the page
    p = weak_load_page_by_url(url)
    if p:
        response = p.handle_request()
        if p.cacheable:
예제 #47
0
파일: auth.py 프로젝트: mmint-kanban/kanban
        user = AuthModel.get_current_user()
        return {'user': user}

    def post(self):
        """ Login user """

        user = AuthModel.auth(request.form.get('username'), request.form.get('password'))
        if user:
            session_id = AuthModel.login(user)
            resp = jsonify({'user': user})
            resp.set_cookie(SESSION_NAME, session_id)
            return resp
        else:
            raise CannotLogin('Cannot login user. Please verify your information.')

    def delete(self):
        """ Logout user """

        resp = Response()
        session_id = request.cookies.get(SESSION_NAME)
        if session_id:
            Db.sessions.remove({'_id': session_id})
            resp.set_cookie(SESSION_NAME, '', expires=0)
        return resp

auth_blueprint = Blueprint('auth_blueprint', __name__)
auth_view = AuthResource.as_view('auth_view')

auth_blueprint.add_url_rule('/auth', 'auth', auth_view)
예제 #48
0
from flask.blueprints import Blueprint
from api.sql import *
from flask import abort

# get_top_ba_players, get_player_stats, get_teams, get_team_players

api = Blueprint('api', __name__)


@api.route('/single_player_stats/<player_id>', methods=['GET'])
def single_player_stats(player_id):
    return get_single_player_stats(player_id=player_id)

@api.route('/get_top_stat_players/<>')


# @api.route('/update_single_player_stats/<player_id>', methods=['POST'])
# def update_single_player_stats(player_id):
#     update_single_player_stats
예제 #49
0
파일: post.py 프로젝트: dongweiming/firefly
# coding=utf-8
from __future__ import absolute_import
from flask import request, redirect, url_for, abort
from flask.views import MethodView
from flask.blueprints import Blueprint
from flask_mako import render_template
from flask_mongoengine.wtf import model_form
from flask_login import current_user

from firefly.models.user import User
from firefly.models.topic import Post, Comment


bp = Blueprint("post", __name__, url_prefix="/post")


class DetailView(MethodView):

    form = model_form(Comment, exclude=['created_at', 'author', 'id'])

    def get_context(self, id):
        post = Post.objects.get_or_404(id=id)
        form = self.form(request.form)

        context = {
            "post": post,
            "form": form
        }
        return context

    def get(self, id):
예제 #50
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2017-05-25 20:59:55
# @Author  : love3forever
# @Link    : http://example.org
# @Version : $Id$
from flask.blueprints import Blueprint
from flask_restful import Resource, Api, abort
from flask import jsonify
from dataCollector import data_poster
from common_funcs import output
from static_data import static_playlist_detail, static_playlist_comments

playlist_blueprint = Blueprint(__name__, 'playlist')
playlistAPI = Api(playlist_blueprint, prefix='/api/v1/playlist')


@playlistAPI.resource('/detail/<string:playlistId>')
class PlaylistDetail(Resource):
    """docstring for PlaylistDetail"""
    def get(self, playlistId):
        if playlistId:
            data = data_poster.get_playlist_detail(playlistId)
            if data:
                return output(jsonify(data))
            else:
                abort(404, description='no playlist detail info')
        else:
            abort(404, description='do request with right playlist please')

예제 #51
0
###########################################
'''
from flask.blueprints import Blueprint
from flask.views import View
from flask.helpers import url_for, flash
from sys2do.constant import MESSAGE_ERROR, MSG_NO_SUCH_ACTION
from werkzeug.utils import redirect
from sys2do.util.common import _g
from sys2do.views import BasicView
from sys2do.model.master import Customer
from sys2do.model import DBSession
from flask.templating import render_template

__all__ = ['bpMaster']

bpMaster = Blueprint('bpMaster', __name__)

class MasterView(BasicView):

    def index(self):
        type = _g('type')
        master_mapping = {
                          'customer' : Customer,
#                          'vendor' : Vendor,
#                          'item' : Item,
                          }

        if type not in master_mapping :
            flash(MSG_NO_SUCH_ACTION, MESSAGE_ERROR)
            return redirect('/index')
예제 #52
0
    InventoryInNote, InventoryNoteDetail, InventoryOutNote, \
    InventoryLocationItem
from sys2do.model import DBSession
from sys2do.util.common import _g, _gl, _gp, _error, _info
from sys2do.constant import MESSAGE_INFO, MSG_SAVE_SUCC, MSG_NO_ID_SUPPLIED, \
    MESSAGE_ERROR, MSG_SERVER_ERROR, MSG_DELETE_SUCC, MSG_UPDATE_SUCC

from sys2do.setting import PAGINATE_PER_PAGE
from sys2do.util.logic_helper import getInNoteNo, getOutNo
from sys2do.model.system import SystemLog



__all__ = ['bpInventory']

bpInventory = Blueprint('bpInventory', __name__)

class InventoryView(BasicView):

    decorators = [login_required, tab_highlight('TAB_MAIN'), ]

    @templated('inventory/index.html')
    @mark_path('INVENTORY_INDEX')
    def index(self):
        if _g('SEARCH_SUBMIT'):  # come from search
            values = {'page' : 1}
            for f in ['item_id', 'location_id', 'children_location' ] :
                values[f] = _g(f)
        else:  # come from paginate or return
            values = session.get('inventory_index_values', {})
            if _g('page') : values['page'] = int(_g('page'))