コード例 #1
0
def register_basic_api(view, endpoint, url, methods=None):
    if methods is None:
        methods = [
            'GET',
        ]
    view_func = view.as_view(endpoint)
    app.add_url_rule('{}'.format(url), view_func=view_func, methods=methods)
コード例 #2
0
def init_rules():
	if not isdir(app.config["RULE_DIR"]):
		return
	listfile = listdir(app.config["RULE_DIR"])
	for file_ in listfile:
		if isfile(app.config["RULE_DIR"] + "/" + file_):
			if app.spec.match_file(file_):
				continue
			with open(app.config["RULE_DIR"] + "/" + file_, encoding='utf-8') as fil_data:
				yaml = load(fil_data)

				if 'rule' in yaml.keys():
					if '/' in yaml['func']:
						# from a Plugin
						plugin_value, post_value = yaml['func'].split('/')
						if plugin_value not in app.plugins.keys():
							continue
						if not hasattr(app.plugins[plugin_value], post_value):
							continue
						if not callable(getattr(app.plugins[plugin_value], post_value)):
							continue
						func = getattr(app.plugins[plugin_value], post_value)

						app.add_url_rule(
											rule=yaml['rule'],
											view_func=func,
											defaults={},
											methods=['GET', 'POST']
											)


					else:
						#TODO, no general rules for now
						pass
コード例 #3
0
def register_crud(app,
                  url=None,
                  endpoint=None,
                  model=None,
                  form=None,
                  exclude=[],
                  rel_mode=None,
                  decorators=[],
                  **kwargs):
    view = CRUIDAPI.as_view(endpoint,
                            endpoint=endpoint,
                            model=model,
                            form=form,
                            exclude=exclude,
                            rel_mode=rel_mode,
                            **kwargs)

    for decorator in decorators:
        view = decorator(view)

    app.add_url_rule('%s/' % url, view_func=view, methods=['GET', 'POST'])
    app.add_url_rule('%s/<int:obj_id>/' % url, view_func=view)
    app.add_url_rule('%s/<operation>/' % url, view_func=view, methods=['GET'])
    app.add_url_rule('%s/<operation>/<int:obj_id>/' % url,
                     view_func=view,
                     methods=['GET'])
    app.add_url_rule('%s/<operation>/<obj_id>/' % url,
                     view_func=view,
                     methods=['GET', 'POST'])
コード例 #4
0
def register_api(view, endpoint, url):
    """
    Registers the given view at the endpoint, accessible by the given url.
    """
    url = '/'.join((API_PREFIX, view.api_version, url))
    view = view.as_view(endpoint)

    @wraps(view)
    def api_wrapper(*args, **kwds):
        #TODO(martinis) add tests
        # Any client can check for the latest version
        try:
            request.fields = {}
            message = "success"
            if request.args.get('client_version'):
                check_version(request.args['client_version'])

            user = auth.authenticate()

            if not isinstance(user, models.User):
                return user

            session['user'] = user
            logging.info("User is %s.", user.email)

            rval = view(*args, **kwds)

            if (isinstance(rval, Response)
                    or isinstance(rval, werkzeug.wrappers.Response)):
                pass
            elif isinstance(rval, list):
                rval = utils.create_api_response(200, message, rval)
            elif (isinstance(rval, collections.Iterable)
                  and not isinstance(rval, dict)):
                rval = utils.create_api_response(*rval)
            else:
                rval = utils.create_api_response(200, message, rval)
            return rval

        except IncorrectVersionError as e:
            logging.warn(e.message)
            return utils.create_api_response(e.code, e.message, e.data)

        except APIException as e:
            logging.exception(e.message)
            return utils.create_api_response(e.code, e.message, e.data)

        except Exception as e:  #pylint: disable=broad-except
            logging.exception(e.message)
            return utils.create_api_response(500, 'internal server error :(')

    app.add_url_rule('%s' % url,
                     view_func=api_wrapper,
                     defaults={'path': None},
                     methods=['GET', 'POST'])
    app.add_url_rule('%s/<path:path>' % url,
                     view_func=api_wrapper,
                     methods=['GET', 'POST', 'DELETE', 'PUT'])
コード例 #5
0
ファイル: route_utils.py プロジェクト: cameron/jot
 def method_route_decorator(endpoint):
   wrapper = return_json(endpoint)
   if json_spec:
     wrapper = json_spec(spec)(endpoint)
   wrapper = return_json(wrapper)
   endpoint.__name__ = endpoint.__name__ + '-'
   functools.update_wrapper(wrapper, endpoint)
   app.add_url_rule('/api' + path, wrapper.__name__, wrapper, methods=methods)
   return wrapper
コード例 #6
0
ファイル: views.py プロジェクト: gsubram4/tile-server
def generate_tile_provider(tile_dir):
    def inner(filename):
        zoom = getZoom(filename)
        data_dir = os.path.join(tiles_base_dir, tile_dir, zoom)
        return send_from_directory(data_dir, filename)

    print '/%s/<path:filename>' % (tile_dir)
    app.add_url_rule('/%s/<path:filename>' % (tile_dir), tile_dir, inner)
    return inner
コード例 #7
0
ファイル: __init__.py プロジェクト: polowis/Pandoru_template
 def get(self, url, view_class, func_name=None):
     if isinstance(view_class, Controller):
         view_function = getattr(view_class(), func_name)
     else:
         view_function = view_class
     app.add_url_rule(url,
                      func_name,
                      view_func=view_function,
                      methods=['GET'])
コード例 #8
0
ファイル: urls.py プロジェクト: jackzhao-mj/ok
def register_api(view, endpoint, url):
    """
    Registers the given view at the endpoint, accessible by the given url.
    """
    url = '/'.join((API_PREFIX, view.api_version, url))
    view = view.as_view(endpoint)

    @wraps(view)
    def api_wrapper(*args, **kwds):
        #TODO(martinis) add tests
        # Any client can check for the latest version
        try:
            request.fields = {}
            message = "success"
            if request.args.get('client_version'):
                check_version(request.args['client_version'])

            user = auth.authenticate()

            if not isinstance(user, models.User):
                return user

            session['user'] = user
            logging.info("User is %s.", user.email)

            rval = view(*args, **kwds)

            if (isinstance(rval, Response) or
                    isinstance(rval, werkzeug.wrappers.Response)):
                pass
            elif isinstance(rval, list):
                rval = utils.create_api_response(200, message, rval)
            elif (isinstance(rval, collections.Iterable)
                  and not isinstance(rval, dict)):
                rval = utils.create_api_response(*rval)
            else:
                rval = utils.create_api_response(200, message, rval)
            return rval

        except IncorrectVersionError as e:
            logging.warn(e.message)
            return utils.create_api_response(e.code, e.message, e.data)

        except APIException as e:
            logging.exception(e.message)
            return utils.create_api_response(e.code, e.message, e.data)

        except Exception as e: #pylint: disable=broad-except
            logging.exception(e.message)
            return utils.create_api_response(500, 'internal server error :(')

    app.add_url_rule(
        '%s' % url, view_func=api_wrapper, defaults={'path': None},
        methods=['GET', 'POST'])
    app.add_url_rule(
        '%s/<path:path>' % url, view_func=api_wrapper,
        methods=['GET', 'POST', 'DELETE', 'PUT'])
コード例 #9
0
ファイル: __init__.py プロジェクト: polowis/Pandoru_template
 def post(self, url, view_function, name=None):
     if isinstance(view_function, str):
         try:
             function = import_module(str(getModule(view_function)))
             res = getattr(function, str(getFunction(view_function)))()
         except:
             raise ImportError('Module:', view_function, 'not found')
     else:
         res = view_function
     app.add_url_rule(url, name, view_func=res, methods=['POST'])
コード例 #10
0
 def track_changes(self, model, alias='empty', fields=None, decorator=None):
     app.add_url_rule('/%s/<int:obj_id>/history' % alias,
                      'show_history_%s' % alias,
                      decorator(self.show_history))
     event.listen(
         model, 'after_insert',
         partial(self.tracker, db_alias=alias, fields=fields, is_new=True))
     event.listen(
         model, 'after_update',
         partial(self.tracker, db_alias=alias, fields=fields, is_new=False))
コード例 #11
0
def make_flask_routes():
    """
    flask routes
    """
    from app import app

    app.add_url_rule("/", endpoint="home", view_func=home, methods=["GET"])
    app.add_url_rule("/alert/mem", endpoint="mem_test", view_func=mem_test, methods=["GET"])
    app.add_url_rule("/alert/cpu", endpoint="cpu_test", view_func=cpu_test, methods=["GET"])
    app.add_url_rule("/users", endpoint="all_users", view_func=all_users, methods=["GET"])
    app.add_url_rule("/<string:username>", endpoint="user_greeting", view_func=greeting, methods=["GET"])
コード例 #12
0
ファイル: schema.py プロジェクト: n4djib/flask-code-base
def add_url_rules():
    # /graphql-query
    app.add_url_rule('/graphql-query',
                     view_func=GraphQLView.as_view('graphql-query',
                                                   schema=schema_query,
                                                   graphiql=True))

    # /graphql-mutation
    app.add_url_rule('/graphql-mutation',
                     view_func=GraphQLView.as_view('graphql-mutation',
                                                   schema=schema_mutation,
                                                   graphiql=True))
コード例 #13
0
ファイル: helpers.py プロジェクト: Se7ge/simplelogs
def url(url_rule, import_name, **options):
    """Generating new urls for url_rule by func_name

    We further optimize this in terms of amount of keystrokes needed to write Lazy views loading by having a function
    that calls into add_url_rule() by prefixing a string with the project name and a dot, and by wrapping view_func in
    a LazyView as needed.

    One thing to keep in mind is that before and after request handlers have to be in a file that is imported upfront
     to work properly on the first request. The same goes for any kind of remaining decorator.

    """
    view = LazyView('app.' + import_name)
    app.add_url_rule(url_rule, view_func=view, **options)
コード例 #14
0
ファイル: helpers.py プロジェクト: MarsStirner/simplelogs
def url(url_rule, import_name, **options):
    """Generating new urls for url_rule by func_name

    We further optimize this in terms of amount of keystrokes needed to write Lazy views loading by having a function
    that calls into add_url_rule() by prefixing a string with the project name and a dot, and by wrapping view_func in
    a LazyView as needed.

    One thing to keep in mind is that before and after request handlers have to be in a file that is imported upfront
     to work properly on the first request. The same goes for any kind of remaining decorator.

    """
    view = LazyView('app.' + import_name)
    app.add_url_rule(url_rule, view_func=view, **options)
コード例 #15
0
def register_view(url, endpoint=None, view=None):
    """
    Register view with given URL.
    Usually used as decorator.

    Args:
        url: Base URL for given view.
        endpoint: Name of the endpoint. Same with view class name by default.
        view: View class.
    Returns:
        View class.
    """
    # Use as decorator
    if view == None:
        return lambda view: register_view(url, endpoint, view)
    # Process action or data handlers
    for handler_type in HANDLER_TYPES:
        handlers = {}
        setattr(view, "_%s_handlers" % handler_type, handlers)
        # Search for handlers
        for _, value in view.__dict__.items():
            target = get_metadata(value, handler_type)
            if target:
                handlers[target] = value
    # Register routes
    view_func = view.as_view(endpoint or view.__name__)
    app.add_url_rule(url,
                     view_func=view_func,
                     methods=["GET", "POST", "OPTION"],
                     defaults={
                         "ph1": None,
                         "ph2": None
                     })
    app.add_url_rule("%s/<int:ph1>" % url,
                     view_func=view_func,
                     methods=["GET", "OPTION"],
                     defaults={"ph2": None})
    app.add_url_rule("%s/<string:ph1>" % url,
                     view_func=view_func,
                     methods=["GET", "POST", "OPTION"],
                     defaults={"ph2": None})
    app.add_url_rule("%s/<int:ph1>/<string:ph2>" % url,
                     view_func=view_func,
                     methods=["GET", "POST", "OPTION"])
    app.add_url_rule("%s/<int:ph1>" % url,
                     view_func=view_func,
                     methods=["PATCH", "DELETE"])
    return view
コード例 #16
0
def register_rules():

    app.yasifipo_send_static_file = yasifipo_send_static_file

    # static rule
    app.static_folder = 'static'
    if not yasifipo_is_server() or (
            'yasifipo_subdirectory' not in app.yasifipo['config']
            or app.yasifipo['config']['yasifipo_subdirectory'] == ''):
        app.static_url_path = '/static'
    else:
        app.static_url_path = '/' + app.yasifipo['config'][
            'yasifipo_subdirectory'] + '/static'

    app.add_url_rule(rule=app.static_url_path + '/<path:filename>',
                     endpoint='static',
                     view_func=app.yasifipo_send_static_file)

    # General rule
    app.add_url_rule(rule='/<path:path>/',
                     view_func=render_file,
                     defaults={},
                     methods=['GET', 'POST'])

    # Root rule
    if yasifipo_is_server():
        if 'yasifipo_subdirectory' not in app.yasifipo[
                'config'] or app.yasifipo['config'][
                    'yasifipo_subdirectory'] == '':
            app.add_url_rule(rule='/',
                             view_func=render_root,
                             defaults={},
                             methods=['GET', 'POST'])
    else:
        app.add_url_rule(rule='/',
                         view_func=render_root,
                         defaults={},
                         methods=['GET', 'POST'])


# File rule
    app.add_url_rule(rule='/<path:id_>',
                     view_func=return_file,
                     defaults={},
                     methods=['GET'])
コード例 #17
0
def sass(app, inputDir='scss', outputPath='static', force=False, cacheDir="public/static"):
	static_url_path = app.static_url_path
	inputDir = _getDirPath(inputDir)
	cacheDir = _getDirPath(cacheDir or outputPath, True)

	def _sass(filepath):
		sassfile = "%s/%s.scss" % (inputDir, filepath)
		cacheFile = "%s/%s.css" % (cacheDir, filepath)

		# Source file exists, and needs regenerating
		if os.path.isfile(sassfile) and (force or not os.path.isfile(cacheFile) or \
				os.path.getmtime(sassfile) > os.path.getmtime(cacheFile)):
			_convert(inputDir, sassfile, cacheFile)
			app.logger.debug('Compiled %s into %s' % (sassfile, cacheFile))

		return send_from_directory(cacheDir, filepath + ".css")

	app.add_url_rule("/%s/<path:filepath>.css" % (outputPath), 'sass', _sass)
コード例 #18
0
ファイル: urls.py プロジェクト: sheep0x/ok
def register_api(view, endpoint, url):
    """
    Registers the given view at the endpoint, accessible by the given url.
    """
    url = API_PREFIX + '/' + url
    view = view.as_view(endpoint)

    @wraps(view)
    def wrapped(*args, **kwds):
        #TODO(martinis) add tests
        if 'client_version' in request.args:
            if request.args['client_version'] != app.config['CLIENT_VERSION']:
                logging.info(
                    "Client out of date. Client version {} != {}".format(
                        request.args['client_version']),
                    app.config['CLIENT_VERSION'])
                return utils.create_api_response(403, "incorrect client version", {
                    'supplied_version': request.args['client_version'],
                    'correct_version': app.config['CLIENT_VERSION']
                })

        user = auth.authenticate()
        if not isinstance(user, models.User):
            return user
        session['user'] = user
        logging.info("User is %s.", user.email)

        try:
            return view(*args, **kwds)
        except (WebArgsException, BadValueError) as e:
            message = "Invalid arguments: %s" % e.message
            logging.warning(message)
            return utils.create_api_response(400, message)
        except Exception as e: #pylint: disable=broad-except
            #TODO(martinis) add tests
            error_message = traceback.format_exc()
            logging.error(error_message)
            return utils.create_api_response(500, 'internal server error:\n%s' %
                                             error_message)

    app.add_url_rule('%s' % url, view_func=wrapped, defaults={'path': None},
            methods=['GET', 'POST'])
    app.add_url_rule('%s/<path:path>' % url, view_func=wrapped,
            methods=['GET', 'POST', 'DELETE', 'PUT'])
コード例 #19
0
ファイル: routes.py プロジェクト: publicscience/brain
def register_api(view, endpoint, url, id='id', id_type='int'):
    """
    Covenience function for building APIs.
    """
    view_func = view.as_view(endpoint)
    app.add_url_rule(url, defaults={id: None}, view_func=view_func, methods=['GET'])
    app.add_url_rule(url, view_func=view_func, methods=['POST'])
    app.add_url_rule('%s<%s:%s>' % (url, id_type, id), view_func=view_func, methods=['GET', 'PUT', 'DELETE'])
コード例 #20
0
ファイル: routes.py プロジェクト: ashendge/devops-interview
def make_flask_routes():
    """
    flask routes
    """
    from app import app

    app.add_url_rule('/', endpoint='home', view_func=home, methods=['GET'])
    app.add_url_rule('/alert/mem',
                     endpoint='mem_test',
                     view_func=mem_test,
                     methods=['GET'])
    app.add_url_rule('/alert/cpu',
                     endpoint='cpu_test',
                     view_func=cpu_test,
                     methods=['GET'])
    app.add_url_rule('/users',
                     endpoint='all_users',
                     view_func=all_users,
                     methods=['GET'])
    app.add_url_rule('/<string:username>',
                     endpoint='user_greeting',
                     view_func=greeting,
                     methods=['GET'])
コード例 #21
0
ファイル: routes.py プロジェクト: publicscience/brain
def register_api(view, endpoint, url, id='id', id_type='int'):
    """
    Covenience function for building APIs.
    """
    view_func = view.as_view(endpoint)
    app.add_url_rule(url,
                     defaults={id: None},
                     view_func=view_func,
                     methods=['GET'])
    app.add_url_rule(url, view_func=view_func, methods=['POST'])
    app.add_url_rule('%s<%s:%s>' % (url, id_type, id),
                     view_func=view_func,
                     methods=['GET', 'PUT', 'DELETE'])
コード例 #22
0
def register_api(view, endpoint, url, pk='id', pk_type='int'):
    view_func = view.as_view(endpoint)
    app.add_url_rule(url,
                     defaults={pk: None},
                     view_func=view_func,
                     methods=[
                         'GET',
                     ])
    app.add_url_rule(url, view_func=view_func, methods=[
        'POST',
    ])
    app.add_url_rule('{}/<{}:{}>'.format(url, pk_type, pk),
                     view_func=view_func,
                     methods=['GET', 'PUT', 'DELETE'])
コード例 #23
0
ファイル: user.py プロジェクト: yanbf/game
def register_api(view, endpoint, url, pk='id', pk_type='int'):
    view_func = view.as_view(endpoint)
    app.add_url_rule(
        url,
        defaults={pk: None},
        view_func=view_func,
        methods=['GET', ]
    )
    app.add_url_rule(url, view_func=view_func, methods=['POST', ])
    app.add_url_rule(
        '%s<%s:%s>' % (url, pk_type, pk),
         view_func=view_func,
         methods=['GET', 'PUT', 'DELETE']
    )
コード例 #24
0
ファイル: helpers.py プロジェクト: hcutler/Events-API
def register_api(view, endpoint, url, pk="_id", pk_type="string"):
    """
    Register a MethodView to the app.

    -   `view` should be the MethodView to register.
    -   `endpoint` will be the name of the of the endpoint that the view will
        have.
    -   `url` should be the base url for the entity. For a 'User' entity, it
        might be '/users/'.
    -   `pk` should be the name for the primary key. Defaults to '_id'.
    -   `pk_type` should be the type of the primary key. Defaults to string.
    """
    view_func = view.as_view(endpoint)
    app.add_url_rule(url, defaults={pk: None}, view_func=view_func, methods=["GET"])
    app.add_url_rule(url, view_func=view_func, methods=["POST"])
    app.add_url_rule("%s<%s:%s>" % (url, pk_type, pk), view_func=view_func, methods=["GET", "PUT", "DELETE"])
コード例 #25
0
def register_api(view, endpoint, url, pk='id', pk_type='int', version=None):
    if version:
        url_api = '/api/' + version + url
    else:
        url_api = '/api/v1/' + url
    view_func = view.as_view(endpoint)
    app.add_url_rule(url_api,
                     defaults={pk: None},
                     view_func=view_func,
                     methods=[
                         'GET',
                     ])
    app.add_url_rule(url_api, view_func=view_func, methods=[
        'POST',
    ])
    app.add_url_rule('%s/<%s:%s>' % (url_api, pk_type, pk),
                     view_func=view_func,
                     methods=['GET', 'PUT', 'DELETE'])
コード例 #26
0
ファイル: utils.py プロジェクト: fastfuse/street-witness
def register_api(view, endpoint, url, pk='id', pk_type='any'):
    """
    Function to simplify registration of API Views (based on MethodView)
    Deprecated
    """
    view_func = view.as_view(endpoint)
    app.add_url_rule(url,
                     defaults={pk: None},
                     view_func=view_func,
                     methods=[
                         'GET',
                     ])
    app.add_url_rule(url, view_func=view_func, methods=[
        'POST',
    ])
    app.add_url_rule('{url}<{pk_type}:{pk}>'.format(url=url,
                                                    pk_type=pk_type,
                                                    pk=pk),
                     view_func=view_func,
                     methods=['GET', 'PUT', 'DELETE'])
コード例 #27
0
def register_complex_api(view,
                         endpoint,
                         url_path_one,
                         url_path_two,
                         pk='id',
                         pk_type='int'):
    view_func = view.as_view(endpoint)
    app.add_url_rule('{}/<{}:{}>{}'.format(url_path_one, pk_type, pk,
                                           url_path_two),
                     view_func=view_func,
                     methods=[
                         'GET',
                     ])
    app.add_url_rule('{}/<{}:{}>{}'.format(url_path_one, pk_type, pk,
                                           url_path_two),
                     view_func=view_func,
                     methods=[
                         'POST',
                     ])
    app.add_url_rule('{}/<{}:{}>{}'.format(url_path_one, pk_type, pk,
                                           url_path_two),
                     view_func=view_func,
                     methods=['GET', 'PUT', 'DELETE'])
コード例 #28
0
ファイル: product.py プロジェクト: ztybuaa/amc
# -*- coding: utf-8 -*-

from app import app

from flask import Flask, render_template, views

from models import Product


class ProductView(views.MethodView):
    
    def get(self):
        products = Product.query.all()
        return render_template('product.html', products=products)


app.add_url_rule('/index/product/', view_func=ProductView.as_view('show_products'))

コード例 #29
0
ファイル: views.py プロジェクト: aemarse/my_guardian
	Returns or updates the details on a specific
	article according to its object_id
	"""

	# Returns json string of a specific article
	def get(self, object_id):
		article = Article.objects(pk=object_id)
		return article.to_json()

	# Updates title of a specific article
	def post(self):
		article_json = request.json
		article_id = article_json["id"]
		article_title = article_json["title"]

		Article.objects(id=article_id).update_one(set__title=article_title)

		return Article.objects.get(id=article_id).to_json()

# Register the URLs
app.add_url_rule('/articles',
	view_func=ArticleList.as_view('article_list'))

article_view = ArticleDetail.as_view('article_detail')
app.add_url_rule('/article/<object_id>',
	view_func=article_view,
	methods=['GET',])
app.add_url_rule('/article',
	view_func=article_view,
	methods=['POST',])
コード例 #30
0
ファイル: views.py プロジェクト: maxtv1982/Python-web
            email = obj.email
        else:
            raise errors.NotFound
        task = send_email.delay(email)
        return jsonify({'task_id': task.id})


@app.route('/email-send-all/', methods=['POST'])
def post_all():
    tasks_id = {}
    emails = Users.query.all()
    print(emails)
    for email in emails:
        print(email.email)
        task = send_email.delay(email.email)
        tasks_id[email.email] = task.id
    print(tasks_id)
    return jsonify(tasks_id)


sender = Sender.as_view('sender')
app.add_url_rule('/email/<string:task_id>', view_func=sender, methods=['GET'])
app.add_url_rule('/email-send/<int:user_id>', view_func=sender, methods=['POST'])

app.add_url_rule('/api/users/<int:user_id>', view_func=UserView.as_view('users_get'), methods=['GET', ])
app.add_url_rule('/api/login/', view_func=UserView.as_view('users_create'), methods=['POST', ])

app.add_url_rule('/api/posts/<int:post_id>', view_func=PostView.as_view('posts_get'), methods=['GET', ])
app.add_url_rule('/api/posts/', view_func=PostView.as_view('posts_create'), methods=['POST', ])
app.add_url_rule('/api/posts/<int:post_id>', view_func=PostView.as_view('posts_delete'), methods=['DELETE', ])
app.add_url_rule('/api/posts/<int:post_id>', view_func=PostView.as_view('posts_put'), methods=['PUT', ])
コード例 #31
0
# -*- coding: utf-8 -*-
'''
Created on 2016年10月19日

@author: hustcc
'''
from app import app, weixin
from app.utils import OtherUtil

app.add_url_rule('/wx/weixin.html', view_func=weixin.view_func)


@weixin.register(type='event', event='subscribe')
def send_welcome(**kwargs):
    username = kwargs.get('sender')
    sender = kwargs.get('receiver')
    return weixin.reply(username, sender=sender, content=u'感谢关注 在线工具 公众号!')


@weixin.register(type='event', event='CLICK')
def restart_im(**kwargs):
    username = kwargs.get('sender')
    sender = kwargs.get('receiver')

    event_key = kwargs.get('event_key')
    if event_key == 'restart_im':
        OtherUtil.restart_im()

    return weixin.reply(username, sender=sender, content=u'感谢关注!')

コード例 #32
0
from flask_graphql import GraphQLView

from schema import schema
from app import app

app.add_url_rule('/graphql',
                 view_func=GraphQLView.as_view('graphql',
                                               schema=schema,
                                               graphiql=True))

if __name__ == '__main__':
    app.run()
コード例 #33
0
ファイル: server.py プロジェクト: shykes/gordon
from app import app
from views import index
from views import hook
from views import maintainers
from views import lead_maintainer

import logging

logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG)

app.add_url_rule('/', 'index', index, methods=['GET'])
app.add_url_rule('/', 'hook', hook, methods=['POST'])
app.add_url_rule('/maintainers/<issue>',
                 'maintainer',
                 maintainers,
                 methods=['GET'])
app.add_url_rule('/lead_maintainer/<issue>',
                 'lead_maintainer',
                 lead_maintainer,
                 methods=['GET'])

if __name__ == "__main__":
    app.run('0.0.0.0')
コード例 #34
0
ファイル: auth.py プロジェクト: ybz/platka
from httplib import NO_CONTENT
from flask.views import MethodView
from flask.ext.login import current_user
from app import app
from utils.flask_utils import json_response

class SessionApi(MethodView):
    def marshal_user(self, user):
        return {
            'username': user.username
        }
    def get(self):
        print '\n\n\n current_user %s' % current_user
        if current_user:
            return json_response(self.marshal_user(current_user))
        return ('', NO_CONTENT, {})
    def put(self):
        return json_response({ 'method' : 'put' })

app.add_url_rule('/api/session', view_func=SessionApi.as_view('api_session'))
コード例 #35
0
from flask.views import View
from app import app


class ListView(View):
    def get_template_name(self):
        raise NotImplementedError()

    def render_template(self, context):
        return render_template(self.get_template_name(), **context)

    def dispatch_request(self):
        context = {'objects': self.get_objects()}
        return self.render_template(context)


class ShowPatients(View):

    def get_template_name(self):
        return patients.html

    def get_objects(self):
        return Patients.query.all()


app.add_url_rule('/patients/', view_func=ShowPatients.as_view('show_patients'))
コード例 #36
0
ファイル: views.py プロジェクト: yaacov/ltmodbus
                    
                    return self.render('admin/home.html', form=form, return_url = '/admin/')
            except Exception, e:
                flash('%s' % e, 'error')
                logger.run = False
                logger.busy_flag = False
        
        return self.render('admin/home.html', form=form)
    
    @expose("/stop/", methods=('POST',))
    def stop(self):
         global logger
        
         logger.run = False
         logger.busy_flag = False
         logger.busy_percent = 0
         logger.error = None
         
         flash('Stoping earlier request.')
         return redirect("/admin")

class State(View):

    def dispatch_request(self):
        global logger
        
        return jsonify(state=logger.error, run=logger.busy_flag, percent=logger.busy_percent)

app.add_url_rule('/state.json', view_func=State.as_view('state.json'))

コード例 #37
0
ファイル: routes.py プロジェクト: frnsys/parrott
    def delete(self, tweet_id):
        tweet = app.parrott.memory.recall(tweet_id)
        app.parrott.memory.forget(tweet)
        return ""

    # Auditing a tweet.
    def put(self, tweet_id):
        tweet = app.parrott.memory.recall(tweet_id)
        positive = request.json['positive'] # bool
        app.parrott.audit(tweet, positive)
        return jsonify(data=request.json)

# Build the actual REST routes.
tweet_view = TweetAPI.as_view('tweet')
app.add_url_rule('/api/tweet/',
                defaults={'tweet_id': None},
                view_func=tweet_view,
                methods=['GET'])
app.add_url_rule('/api/tweet/',
                view_func=tweet_view,
                methods=['POST'])
app.add_url_rule('/api/tweet/<tweet_id>',
                view_func=tweet_view,
                methods=['GET', 'PUT', 'DELETE'])



# Serve the index.html page,
# which will start require.js.
@app.route('/')
@app.route('/index')
def index():
コード例 #38
0
ファイル: inventory.py プロジェクト: ztybuaa/amc
# -*- coding: utf-8 -*-

from app import app

from flask import Flask, render_template, views

from models import Product


class InventoryView(views.MethodView):
    
    def get(self):
        products = Product.query.all()
        return render_template('inventory.html', products=products)


app.add_url_rule('/index/inventory/', view_func=InventoryView.as_view('show_inventory'))


コード例 #39
0
    def register():
        view = CourseAPI.as_view('course_api')

        app.add_url_rule('/api/courses/', view_func=view,
                         methods=['DELETE', 'GET', 'POST'])
コード例 #40
0
ファイル: income.py プロジェクト: ztybuaa/amc
# -*- coding: utf-8 -*-

from app import app

from flask import Flask, render_template, views

from models import User, Product, Customer, Supplier, Order, Purchase, Income, Expenditure


class IncomeView(views.MethodView):
    
    def get(self):
        incomes = Income.query.all()
        return render_template('income.html', incomes=incomes)



app.add_url_rule('/index/income/', view_func=IncomeView.as_view('show_incomes'))

コード例 #41
0
ファイル: server.py プロジェクト: keeb/relayr
from app import app
from views import index
from views import sav
from init.first import check_db
from init.first import create_db

app.add_url_rule('/', 'index', index, methods=['GET'])
app.add_url_rule('/', 'sav', sav, methods=['POST'])


if __name__=="__main__":
    # check to see if the relayr database is set up..
    if not check_db():
        create_db()

    app.run('0.0.0.0')
コード例 #42
0
ファイル: customer.py プロジェクト: ztybuaa/amc
# -*- coding: utf-8 -*-

from app import app

from flask import Flask, render_template, views

from models import User, Product, Customer, Supplier, Order, Purchase, Income, Expenditure


class CustomerView(views.MethodView):
    
    def get(self):
        customers = Customer.query.all()
        return render_template('customer.html', customers=customers)


app.add_url_rule('/index/customer/', view_func=CustomerView.as_view('show_customers'))


コード例 #43
0
ファイル: views.py プロジェクト: boyxiaolong/flask_blog
@app.route('/post/<int:post_id>')
def post_detail(post_id):
    post = Post.query.filter_by(id=post_id).first()
    return render_template('post_detail.html', post=post)

@app.route('/aboutme')
def about():
    return render_template('aboutme.html')

@app.route('/archive')
def archive():
    print('archive')
    posts = Post.query.all()
    return render_template('archive.html', posts=posts)

class LoginRequestView(MethodView):
    def get(self):
        return render_template('login.html', form=UserRegisterForm())

    def post(self):
        print('post')
        form = UserRegisterForm(request.form)
        if form.validate():
            username = form.username.data
            pwd = form.password.data
            print(username, pwd)
            user = UserInfo.query.filter_by(username=username).first()

app.add_url_rule('/login', view_func=LoginRequestView.as_view('login'))
コード例 #44
0
ファイル: views.py プロジェクト: calcutec/flask-burtonblog
def home():
    if current_user.is_authenticated():
        return redirect(url_for('photos', category="latest"))
    else:
        return PhotoPage(title="home").render()


class SignupAPI(MethodView):
    def post(self):
        page = SignupPage(form=SignupForm(), category="signup")
        if page.assets['body_form']:
            return page.render()
        else:
            return redirect(url_for("members", nickname=current_user.nickname))
signup_api_view = SignupAPI.as_view('signup')  # URLS for MEMBER API
app.add_url_rule('/signup/', view_func=signup_api_view, methods=["GET", "POST"])  # Display and Validate Signup Form


class LoginAPI(MethodView):
    def post(self):
        page = LoginPage(form=LoginForm(), category="login")
        if page.assets['body_form']:
            return page.render()
        else:
            return redirect(url_for("members", nickname=current_user.nickname))

    def get(self, get_provider=None, provider=None):
        if get_provider is not None:    # GET OAUTH PROVIDER
            if not current_user.is_anonymous():
                return redirect(url_for('home'))
            oauth = OAuthSignIn.get_provider(get_provider)
コード例 #45
0
ファイル: purchase.py プロジェクト: ztybuaa/amc
# -*- coding: utf-8 -*-

from app import app

from flask import Flask, render_template, views

from models import Purchase


class PurchaseView(views.MethodView):
    
    def get(self):
        purchases = Purchase.query.all()
        return render_template('purchase.html', purchases=purchases)


app.add_url_rule('/index/purchase/', view_func=PurchaseView.as_view('show_purchases'))
コード例 #46
0
ファイル: runningroutesadmin.py プロジェクト: louking/steeps
    def get( self ):
    #----------------------------------------------------------------------
        # googleauth.clear_credentials()
        configfile = current_app.config['APP_JS_CONFIG']
        args = dict(
                    pagename = 'please sign in',
                    pagejsfiles = addscripts([
                                              configfile,
                                             ]),
                    pagecssfiles = addscripts([
                                               'runningroute-admin.css',
                                              ])
                   )
        return render_template('authorize.html', **args)

app.add_url_rule('/authorize', view_func=Authorize.as_view('authorize'), methods=['GET',])

#############################################
# files handling
rrfiles = RunningRoutesFiles(
             app = app,
             uploadendpoint = 'admin/upload',
            )

#############################################
# admin views
def jsconfigfile():
    with app.app_context(): 
        return current_app.config['APP_JS_CONFIG']

admin_dbattrs = 'id,name,distance,start location,latlng,surface,elevation gain,map,fileid,description,active'.split(',')
コード例 #47
0
ファイル: project.py プロジェクト: publicscience/hive
    @requires_login
    def put(self, slug):
        # CURRENTLY UNUSED.
        ctx = self.get_context(slug=slug)
        project = ctx['project']
        form = ctx['form']

        if form.validate():
            form.populate_obj(project)
            project.save()
            return redirect(url_for('project_api', slug=project.slug))

        return redirect(url_for('project_api', slug=project.slug))

    @requires_login
    def delete(self, slug):
        ctx = self.get_context(slug=slug)
        project = ctx['project']
        project.delete()

        return jsonify({'success':True})

register_api(ProjectAPI, 'project_api', '/p/', id='slug', id_type='string')
app.add_url_rule('/', defaults={'slug': None}, view_func=ProjectAPI.as_view('index'), methods=['GET'])


@app.route('/new')
@requires_login
def new_project():
    return render_template('project/new.html', form=project_form(request.form))
コード例 #48
0
# -*- coding: utf-8 -*-
# @Date    : 2017-08-10 21:11:38
# @Author  : lileilei
from app import app
from .views import *
app.add_url_rule('/', view_func=IndexView.as_view('index'))
app.add_url_rule('/font', view_func=FontView.as_view('font'))
app.add_url_rule('/front_model/<int:model_id>',
                 view_func=Font_modelView.as_view('front_model'))
app.add_url_rule('/home', view_func=HomeView.as_view('home'))
app.add_url_rule('/login', view_func=Login.as_view('login'))
app.add_url_rule('/eidituser/<string:user_name>',
                 view_func=Eidituser.as_view('eidituser'))
app.add_url_rule('/delete/<user_name>',
                 view_func=DeleteView.as_view('deleteusername'))
app.add_url_rule('/register', view_func=Register.as_view('register'))
app.add_url_rule('/users', view_func=UserView.as_view('users'))
app.add_url_rule(
    '/editparameter_response/<model_id>&<interface_id>&<parameter_id>',
    view_func=Editparameter_reposseView.as_view('editparameter_response'))
コード例 #49
0
ファイル: order.py プロジェクト: ztybuaa/amc
# -*- coding: utf-8 -*-

from app import app

from flask import Flask, render_template, views

from models import Order


class OrderView(views.MethodView):
    
    def get(self):
        orders = Order.query.all()
        return render_template('order.html', orders=orders)


app.add_url_rule('/index/order/', view_func=OrderView.as_view('show_orders'))
コード例 #50
0
ファイル: url.py プロジェクト: panboyz/automation
# -*- coding: utf-8 -*-
# @Date    : 2017-08-09 20:05:32
# @Author  : lileilei
from app.views import *
from app import app
app.add_url_rule('/load/<string:filename>',view_func=LoadView.as_view('load'))
app.add_url_rule('/add_moel',view_func=AddmodelView.as_view('add_moel'))
app.add_url_rule('/add_pro',view_func=AddproView.as_view('add_pro'))
app.add_url_rule('/dele_moel/<int:id>',view_func=DelemodelView.as_view('dele_moel'))
app.add_url_rule('/dele_pro/<int:id>',view_func=DeleproView.as_view('dele_pro'))
app.add_url_rule('/edit_moel/<int:id>',view_func=EditmoelView.as_view('edit_moel'))
app.add_url_rule('/edit_pro/<int:id>',view_func=EditproView.as_view('edit_pro'))
app.add_url_rule('/deletre/<int:id>',view_func=DeleteResultView.as_view('deletre'))
app.add_url_rule('/addevent',view_func=ADDTesteventView.as_view('addevent'))
app.add_url_rule('/deleteevent/<int:id>',view_func=DeleteEventViews.as_view('delete'))
app.add_url_rule('/editevent/<int:id>',view_func=EditEventViews.as_view('editevents'))
コード例 #51
0
ファイル: routes.py プロジェクト: publicscience/brain
                brain.MKV.spasm = form.spasm.data

            # If the ngram size has changed,
            # the brain needs to be retrained.
            if form.ngram_size.data != brain.MKV.n:
                logger.info('Brain ngram size changed! Retraining...')
                brain.MKV.n = form.ngram_size.data
                brain.retrain()

            config.save()
            flash('I will change my ways.')
            return redirect(url_for('config_api'))

        return redirect(url_for('config_api'))
config_api = ConfigAPI.as_view('config_api')
app.add_url_rule('/config/', view_func=config_api, methods=['GET', 'POST'])


class DocAPI(MethodView):
    form = model_form(Doc, exclude=['created_at'])

    @requires_auth
    def get(self):
        form = self.form(request.form)
        return render_template('train.html', form=form)

    def post(self):
        form = self.form(request.form)

        if form.validate():
            doc = Doc()
コード例 #52
0
from app import app
from utils import pages, add, user
import os
from flask import render_template, request, redirect, session, send_from_directory
app.add_url_rule('/favicon.ico', '/favicon.ico')


@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico',
                               mimetype='image/vnd.microsoft.icon')


@app.route("/")
def index():
    osastot = pages.osastoNames()
    return render_template("index.html", osastot=osastot)


@app.route("/new")
def new():
    return render_template("new.html")


@app.route("/ostoskori")
def ostoskori():
    summa = pages.getSumma(session["username"])[0]
    tuotteet = pages.tuotteetById(pages.koriTuotteet(session["username"]))
    return render_template("ostoskori.html", summa=summa, tuotteet=tuotteet)
コード例 #53
0
ファイル: views.py プロジェクト: calcutec/homeporch
            return json.dumps(result)

    # Delete Post
    @login_required
    def delete(self, post_id):
        post = Post.query.get(post_id)
        db.session.delete(post)
        db.session.commit()
        result = {'deletedsuccess': True}
        return json.dumps(result)


# urls for Post API
post_api_view = PostAPI.as_view('posts')
# Read all posts for a given page, Create a new post
app.add_url_rule('/photos/<any("home", "gallery", "profile", "login"):page_mark>/',
                 view_func=post_api_view, methods=["GET", "POST"])
# Update or Delete a single post
app.add_url_rule('/photos/detail/<int:post_id>/', view_func=post_api_view, methods=["PUT", "DELETE"])
# Read a single post (Non Restful)
app.add_url_rule('/photos/detail/<slug>/', view_func=post_api_view, methods=["GET"])


class SignupAPI(MethodView):
    def get(self, form=None):
        if g.user is not None and g.user.is_authenticated():
            return redirect(url_for('members'))
        signup_data = ViewData("signup", form=form)
        return render_template("base.html", **signup_data.context)

    def post(self):
        form = SignupForm()
コード例 #54
0
ファイル: routes.py プロジェクト: luanbqs/Gateway
from app import app

from werkzeug.routing import Rule

app.add_url_rule('/create-guest', methods=['POST'], endpoint='/create-guest')
app.add_url_rule('/search-guest', methods=['POST'], endpoint='/search-guest')
app.add_url_rule('/delet-guest', methods=['POST'], endpoint='/delete-guest')
app.add_url_rule('/update-guest', methods=['POST'], endpoint='/update-guest')
コード例 #55
0
ファイル: supplier.py プロジェクト: ztybuaa/amc
# -*- coding: utf-8 -*-

from app import app

from flask import Flask, render_template, views

from models import Supplier


class SupplierView(views.MethodView):
    
    def get(self):
        suppliers = Supplier.query.all()
        return render_template('supplier.html', suppliers=suppliers)


app.add_url_rule('/index/supplier/', view_func=SupplierView.as_view('show_suppliers'))
コード例 #56
0
@app.route('/image/<filename>')
def image_host(filename):
    """Returns raw image from the images/ directory
    """
    return send_from_directory(os.path.join("..", "images"), filename)


@app.route('/image/<filename>/h+w/<height>/<width>')
def image_host_resized(filename, height, width):
    """resize image at images/<filename> with the given
    width and height. Does not crop or change image aspect ratio.
    """
    path = os.path.join("images", filename)
    img_io = BytesIO()
    with open(path, "rb") as f:
        with Image.open(f) as image:
            resized_image = resizeimage.resize_contain(
                image, [int(width), int(height)])
            resized_image.save(img_io, 'PNG', quality=70)
            img_io.seek(0)
    return send_file(img_io, mimetype='image/png')


app.add_url_rule(
    '/graphql',
    view_func=FileUploadGraphQLView.as_view(
        'graphql',
        schema=schema,
        graphiql=True  # for having the GraphiQL interface
    ))
コード例 #57
0
ファイル: comment.py プロジェクト: publicscience/hive
        if form.validate():
            comment = Comment(issue=issue)
            form.populate_obj(comment)

            try:
                comment.process(request.files)
            except KeyError as e:
                return redirect(url_for('github_login', _method='GET'))

            return redirect(url_for('issue_api', slug=slug, id=issue.id, _method='GET'))

        return redirect(url_for('issue_api', slug=slug, id=issue.id, _method='GET'))

    @requires_login
    def put(self, slug, issue_id, id):
        comment = Comment.objects(id=id).first()
        form = self.form(request.form)
        form.populate_obj(comment)
        comment.process(request.files)
        return jsonify({'success':True, 'html':render_template('comment.html', current_user=current_user(), comment=comment)})

    @requires_login
    def delete(self, slug, issue_id, id):
        Comment.objects(id=id).first().delete()
        return jsonify({'success':True})

view_func = CommentAPI.as_view('comment_api')
app.add_url_rule('/p/<string:slug>/issues/<string:issue_id>/comments', view_func=view_func, methods=['POST'])
app.add_url_rule('/p/<string:slug>/issues/<string:issue_id>/comments/<string:id>', view_func=view_func, methods=['PUT', 'DELETE'])
コード例 #58
0
# -*- coding: utf-8 -*-
# @Date    : 2017-08-09 20:05:32
# @Author  :
'''url'''
from app.views import *
from app import app

app.add_url_rule('/load/<string:filename>', view_func=LoadView.as_view('load'))
app.add_url_rule('/getyongli', view_func=Getyongli.as_view('getyongli'))
コード例 #59
0
import flask, flask.views
from app import app

# Views
from login import Login 
from Logout import Logout
from profile import Profile
from feed import Feed
from challengeInfo import ChallengeInfo
from challengeCreate import ChallengeCreate
from shop import Shop
from accept import Accept
from profile import Profile
# Routes
app.add_url_rule('/logout',
	view_func=Logout.as_view('logout'),
	methods=['GET'])
app.add_url_rule('/',
	view_func=Login.as_view('login'),
	methods=['GET', 'POST'])
app.add_url_rule('/profile',
	view_func=Profile.as_view('profile'),
	methods=['GET', 'POST'])
app.add_url_rule('/feed',
	view_func=Feed.as_view('feed'),
	methods=['GET', 'POST'])
app.add_url_rule('/challengeInfo/<int:challengeId>',
	view_func=ChallengeInfo.as_view('challengeInfo'),
	methods=['GET', 'POST'])
app.add_url_rule('/challengeCreate',
	view_func=ChallengeCreate.as_view('challengeCreate'),