本文整理汇总了Python中flask.request.endpoint方法的典型用法代码示例。如果您正苦于以下问题:Python request.endpoint方法的具体用法?Python request.endpoint怎么用?Python request.endpoint使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask.request
的用法示例。
在下文中一共展示了request.endpoint方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_handlers
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def load_handlers(self):
data_handlers = {
"basic": BasicDataHandler,
"anonymous": AnonymousDataHandler,
}
for mapping in self.__config.get("mapping"):
try:
security_type = "anonymous" if mapping.get("security") is None else mapping["security"]["type"].lower()
if security_type != "anonymous":
Users.add_user(mapping['endpoint'],
mapping['security']['username'],
mapping['security']['password'])
self._api.add_resource(data_handlers[security_type],
mapping['endpoint'],
endpoint=mapping['endpoint'],
resource_class_args=(self.collect_statistic_and_send,
self.get_name(),
self.endpoints[mapping["endpoint"]]))
except Exception as e:
log.error("Error on creating handlers - %s", str(e))
示例2: __init__
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def __init__(self, person: str = None, format_name: str = None) -> None:
query = match.Match.query
if person is not None:
query = query.filter(match.Match.players.any(db.User.name == person))
if format_name is not None:
fmt = db.get_format(format_name)
if fmt is not None:
query = query.filter(match.Match.format_id == fmt.id)
recent = query.order_by(match.Match.id.desc()).paginate()
self.matches = recent.items
self.has_next = recent.has_next
self.has_prev = recent.has_prev
self.has_pagination = self.has_next or self.has_prev
endpoint = request.endpoint
if endpoint is None:
return
if recent.has_next:
self.next_url = url_for(endpoint, person=person, format_name=format_name, page=recent.next_num)
if recent.has_prev:
self.prev_url = url_for(endpoint, person=person, format_name=format_name, page=recent.prev_num)
示例3: check_valid_login
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def check_valid_login():
user = db.session.query(User).first()
if any([request.endpoint.startswith('static'),
current_user.is_authenticated,
getattr(app.view_functions[request.endpoint],
'is_public', False)]):
return
elif user is None:
return redirect(url_for('user_system.register'))
else:
return redirect(url_for('user_system.login'))
# this was a fix to make sure images stored in the cache are deleted when
# a new image is uploaded
示例4: logout
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def logout(self):
"""
Request the browser to please forget the cookie we set, to clear the
current session.
Note that as described in [1], this will not log out in the case of a
browser that doesn't clear cookies when requested to, and the user
could be automatically logged in when they hit any authenticated
endpoint.
[1]: https://github.com/puiterwijk/flask-oidc/issues/5#issuecomment-86187023
.. versionadded:: 1.0
"""
# TODO: Add single logout
self._set_cookie_id_token(None)
# Below here is for resource servers to validate tokens
示例5: _verify_check_etag
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def _verify_check_etag(self):
"""Verify check_etag was called in resource code
Log a warning if ETag is enabled but check_etag was not called in
resource code in a PUT, PATCH or DELETE method.
Raise CheckEtagNotCalledError when in debug or testing mode.
This is called automatically. It is meant to warn the developer about
an issue in his ETag management.
"""
if request.method in self.METHODS_NEEDING_CHECK_ETAG:
if not _get_etag_ctx().get('etag_checked'):
message = (
'ETag not checked in endpoint {} on {} request.'
.format(request.endpoint, request.method))
app = current_app
app.logger.warning(message)
if app.debug or app.testing:
raise CheckEtagNotCalledError(message)
示例6: paginate
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def paginate(query, schema):
page = request.args.get("page", DEFAULT_PAGE_NUMBER)
per_page = request.args.get("page_size", DEFAULT_PAGE_SIZE)
page_obj = query.paginate(page=page, per_page=per_page)
next_ = url_for(
request.endpoint,
page=page_obj.next_num if page_obj.has_next else page_obj.page,
per_page=per_page,
**request.view_args
)
prev = url_for(
request.endpoint,
page=page_obj.prev_num if page_obj.has_prev else page_obj.page,
per_page=per_page,
**request.view_args
)
return {
"total": page_obj.total,
"pages": page_obj.pages,
"next": next_,
"prev": prev,
"results": schema.dump(page_obj.items),
}
示例7: response_minify
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def response_minify(self, response):
"""
minify response html to decrease traffic
"""
if response.content_type == u'text/html; charset=utf-8':
endpoint = request.endpoint or ''
view_func = current_app.view_functions.get(endpoint, None)
name = (
'%s.%s' % (view_func.__module__, view_func.__name__)
if view_func else ''
)
if name in self._exempt_routes:
return response
response.direct_passthrough = False
response.set_data(
self._html_minify.minify(response.get_data(as_text=True))
)
return response
return response
示例8: ratelimit
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def ratelimit(limit, per=300, send_x_headers=True,
over_limit=on_over_limit,
fp_func=lambda: request.form.get('fingerprint'),
ip_func=lambda: request.environ['REMOTE_ADDR'],
key_func=lambda: request.endpoint):
def decorator(f):
def rate_limited(*args, **kwargs):
ip_key = 'ip-limit/%s/%s/' % (key_func(), ip_func())
fp_key = 'fp-limit/%s/%s/' % (key_func(), fp_func())
rlimit = RateLimit(ip_key, fp_key, limit, per, send_x_headers)
g._view_rate_limit = rlimit
# check if IP has been used LIMIT times
if rlimit.over_ip_limit:
return over_limit(rlimit)
# IP is good, check fingerprint now
if not rlimit.over_ip_limit:
if rlimit.over_fp_limit:
return over_limit(rlimit)
return f(*args, **kwargs)
return update_wrapper(rate_limited, f)
return decorator
示例9: create_app
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def create_app():
app = Flask(__name__)
metrics.init_app(app)
with app.app_context():
setup_api(app)
metrics.register_default(
metrics.counter(
'by_path_counter', 'Request count by request paths',
labels={'path': lambda: request.path}
)
)
metrics.register_default(
metrics.counter(
'outside_context',
'Example default registration outside the app context',
labels={'endpoint': lambda: request.endpoint}
),
app=app
)
return app
示例10: start_http_server
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def start_http_server(self, port, host='0.0.0.0', endpoint='/metrics'):
"""
Start an HTTP server for exposing the metrics.
This will be an individual Flask application,
not the one registered with this class.
:param port: the HTTP port to expose the metrics endpoint on
:param host: the HTTP host to listen on (default: `0.0.0.0`)
:param endpoint: the URL path to expose the endpoint on
(default: `/metrics`)
"""
if is_running_from_reloader():
return
app = Flask('prometheus-flask-exporter-%d' % port)
self.register_endpoint(endpoint, app)
def run_app():
app.run(host=host, port=port)
thread = threading.Thread(target=run_app)
thread.setDaemon(True)
thread.start()
示例11: job_server_routing
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def job_server_routing(routing_type=0):
def _out_wrapper(func):
@functools.wraps(func)
def _wrapper(*args, **kwargs):
job_server = set()
jobs = query_job(job_id=request.json.get('job_id', None))
for job in jobs:
if job.f_run_ip:
job_server.add(job.f_run_ip)
if len(job_server) == 1:
execute_host = job_server.pop()
if execute_host != RuntimeConfig.JOB_SERVER_HOST:
if routing_type == 0:
return api_utils.request_execute_server(request=request, execute_host=execute_host)
else:
return redirect('http://{}{}'.format(execute_host, url_for(request.endpoint)), code=307)
return func(*args, **kwargs)
return _wrapper
return _out_wrapper
示例12: list_routes
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def list_routes():
import urllib
output = []
for rule in webapp.url_map.iter_rules():
options = {}
for arg in rule.arguments:
options[arg] = "[{0}]".format(arg)
methods = ','.join(rule.methods)
url = url_for(rule.endpoint, **options)
line = urllib.unquote(
"{:50s} {:20s} {}".format(rule.endpoint, methods, url))
output.append(line)
for line in sorted(output):
print(line)
return "<br>".join(output)
示例13: stop_timer
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def stop_timer(response):
# convert this into milliseconds for statsd
resp_time = (time.time() - request.start_time)*1000
key = REQUEST_LATENCY_METRIC_KEY_PATTERN.format(
request.endpoint,
request.method,
response.status_code,
)
statsd.timing(key, resp_time)
key = REQUEST_COUNT_METRIC_KEY_PATTERN.format(
request.endpoint,
request.method,
response.status_code,
)
statsd.incr(key)
return response
示例14: check_start
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def check_start(app, db):
from app.includes.start import _exist_config, exist_table, create_path, set_site
create_path(app)
app.start = False
if _exist_config(app):
from app.config import Config
app.config.from_object(Config)
if exist_table(app):
app.start = True
return
@app.before_request
def request_check_start():
if app.start:
return set_site(app)
ends = frozenset(["admin.setup", "admin.install", "static"])
if request.endpoint in ends:
return
if not _exist_config(app):
return redirect(url_for("admin.setup"))
return redirect(url_for("admin.install"))
示例15: is_active
# 需要导入模块: from flask import request [as 别名]
# 或者: from flask.request import endpoint [as 别名]
def is_active(endpoint_or_kwargs: Union[str, dict]):
endpoint = None
href = None
if isinstance(endpoint_or_kwargs, str):
if '/' in endpoint_or_kwargs:
href = endpoint_or_kwargs
else:
endpoint = endpoint_or_kwargs
elif isinstance(endpoint_or_kwargs, dict):
endpoint = endpoint_or_kwargs.get('endpoint')
href = endpoint_or_kwargs.get('href')
else:
raise TypeError('the first argument to is_active must be a str or dict')
if endpoint:
return endpoint == request.endpoint
return href in {request.path, request.url}