本文整理汇总了Python中r2.lib.base.abort函数的典型用法代码示例。如果您正苦于以下问题:Python abort函数的具体用法?Python abort怎么用?Python abort使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了abort函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: set_multireddit
def set_multireddit():
routes_dict = request.environ["pylons.routes_dict"]
if "multipath" in routes_dict:
multipath = routes_dict["multipath"].lower()
multi_id = None
if c.user_is_loggedin and routes_dict.get("my_multi"):
multi_id = "/user/%s/m/%s" % (c.user.name.lower(), multipath)
elif "username" in routes_dict:
username = routes_dict["username"].lower()
if c.user_is_loggedin:
# redirect /user/foo/m/... to /me/m/... for user foo.
if username == c.user.name.lower():
# trim off multi id
url_parts = request.path_qs.split("/")[5:]
url_parts.insert(0, "/me/m/%s" % multipath)
abort(302, location="/".join(url_parts))
multi_id = "/user/%s/m/%s" % (username, multipath)
if multi_id:
try:
c.site = LabeledMulti._byID(multi_id)
except tdb_cassandra.NotFound:
abort(404)
开发者ID:HerculesCE,项目名称:reddit,代码行数:26,代码来源:reddit_base.py
示例2: ratelimit_agent
def ratelimit_agent(agent):
key = "rate_agent_" + agent
if g.cache.get(key):
request.environ["retry_after"] = 1
abort(429)
else:
g.cache.set(key, "t", time=1)
开发者ID:rmoorman,项目名称:reddit,代码行数:7,代码来源:reddit_base.py
示例3: POST_message
def POST_message(self, level, logs):
# Whitelist tags to keep the frontend from creating too many keys in statsd
valid_frontend_log_tags = {
'unknown',
'jquery-migrate-bad-html',
}
# prevent simple CSRF by requiring a custom header
if not request.headers.get('X-Loggit'):
abort(403)
uid = c.user._id if c.user_is_loggedin else '-'
# only accept a maximum of 3 entries per request
for log in logs[:3]:
if 'msg' not in log or 'url' not in log:
continue
tag = 'unknown'
if log.get('tag') in valid_frontend_log_tags:
tag = log['tag']
g.stats.simple_event('frontend.error.' + tag)
g.log.warning('[web frontend] %s: %s | U: %s FP: %s UA: %s',
level, log['msg'], uid, log['url'],
request.user_agent)
VRatelimit.ratelimit(rate_user=False, rate_ip=True,
prefix="rate_weblog_", seconds=10)
开发者ID:GodOfConquest,项目名称:reddit,代码行数:31,代码来源:web.py
示例4: GET_policy_page
def GET_policy_page(self, page, requested_rev):
if c.render_style == 'compact':
self.redirect('/wiki/' + page)
if page == 'privacypolicy':
wiki_name = g.wiki_page_privacy_policy
pagename = _('privacy policy')
elif page == 'useragreement':
wiki_name = g.wiki_page_user_agreement
pagename = _('user agreement')
elif page == 'contentpolicy':
wiki_name = g.wiki_page_content_policy
pagename = _('content policy')
else:
abort(404)
wp = WikiPage.get(Frontpage, wiki_name)
revs = list(wp.get_revisions())
# collapse minor edits into revisions with reasons
rev_info = []
last_edit = None
for rev in revs:
if rev.is_hidden:
continue
if not last_edit:
last_edit = rev
if rev._get('reason'):
rev_info.append({
'id': str(last_edit._id),
'title': rev._get('reason'),
})
last_edit = None
if requested_rev:
try:
display_rev = WikiRevision.get(requested_rev, wp._id)
except (tdb_cassandra.NotFound, WikiBadRevision):
abort(404)
else:
display_rev = revs[0]
doc_html = wikimarkdown(display_rev.content, include_toc=False)
soup = BeautifulSoup(doc_html.decode('utf-8'))
toc = generate_table_of_contents(soup, prefix='section')
self._number_sections(soup)
self._linkify_headings(soup)
content = PolicyView(
body_html=unsafe(soup),
toc_html=unsafe(toc),
revs=rev_info,
display_rev=str(display_rev._id),
)
return PolicyPage(
pagename=pagename,
content=content,
).render()
开发者ID:My-Favorites,项目名称:reddit,代码行数:60,代码来源:policies.py
示例5: POST_message
def POST_message(self, level, logs):
# Whitelist tags to keep the frontend from creating too many keys in statsd
valid_frontend_log_tags = {"unknown", "jquery-migrate-bad-html"}
# prevent simple CSRF by requiring a custom header
if not request.headers.get("X-Loggit"):
abort(403)
uid = c.user._id if c.user_is_loggedin else "-"
# only accept a maximum of 3 entries per request
for log in logs[:3]:
if "msg" not in log or "url" not in log:
continue
tag = "unknown"
if log.get("tag") in valid_frontend_log_tags:
tag = log["tag"]
g.stats.simple_event("frontend.error." + tag)
g.log.warning(
"[web frontend] %s: %s | U: %s FP: %s UA: %s", level, log["msg"], uid, log["url"], request.user_agent
)
VRatelimit.ratelimit(rate_user=False, rate_ip=True, prefix="rate_weblog_", seconds=10)
开发者ID:annerajb,项目名称:reddit,代码行数:27,代码来源:web.py
示例6: ratelimit_agent
def ratelimit_agent(agent):
key = 'rate_agent_' + agent
if g.cache.get(key):
request.environ['retry_after'] = 1
abort(429)
else:
g.cache.set(key, 't', time = 1)
开发者ID:CryptArc,项目名称:reddit,代码行数:7,代码来源:reddit_base.py
示例7: abort_if_not_modified
def abort_if_not_modified(self, last_modified, private=True,
max_age=timedelta(0),
must_revalidate=True):
"""Check If-Modified-Since and abort(304) if appropriate."""
if c.user_is_loggedin and not c.allow_loggedin_cache:
return
# HTTP timestamps round to nearest second. truncate this value for
# comparisons.
last_modified = last_modified.replace(microsecond=0)
date_str = http_utils.http_date_str(last_modified)
response.headers['last-modified'] = date_str
cache_control = []
if private:
cache_control.append('private')
cache_control.append('max-age=%d' % max_age.total_seconds())
if must_revalidate:
cache_control.append('must-revalidate')
response.headers['cache-control'] = ', '.join(cache_control)
modified_since = request.if_modified_since
if modified_since and modified_since >= last_modified:
abort(304, 'not modified')
开发者ID:ChrisCinelli,项目名称:reddit,代码行数:26,代码来源:reddit_base.py
示例8: GET_crossdomain
def GET_crossdomain(self):
# Our middleware is weird and won't let us add a route for just
# '/crossdomain.xml'. Just 404 for other extensions.
if request.environ.get('extension', None) != 'xml':
abort(404)
response.content_type = "text/x-cross-domain-policy"
return CrossDomain().render(style='xml')
开发者ID:0xcd03,项目名称:reddit,代码行数:7,代码来源:robots.py
示例9: GET_authorize
def GET_authorize(self, response_type, client, redirect_uri, scope, state,
duration):
"""
First step in [OAuth 2.0](http://oauth.net/2/) authentication.
End users will be prompted for their credentials (username/password)
and asked if they wish to authorize the application identified by
the **client_id** parameter with the permissions specified by the
**scope** parameter. They are then redirected to the endpoint on
the client application's side specified by **redirect_uri**.
If the user granted permission to the application, the response will
contain a **code** parameter with a temporary authorization code
which can be exchanged for an access token at
[/api/v1/access_token](#api_method_access_token).
**redirect_uri** must match the URI configured for the client in the
[app preferences](/prefs/apps). All errors will show a 400 error
page along with some information on what option was wrong.
"""
self._check_employee_grants(client, scope)
# Check redirect URI first; it will ensure client exists
self._check_redirect_uri(client, redirect_uri)
self._check_response_type_and_scope(response_type, scope)
self._check_client_type_and_duration(response_type, client, duration)
if not c.errors:
return OAuth2AuthorizationPage(client, redirect_uri, scope, state,
duration, response_type).render()
else:
abort(BadRequestError(errors.INVALID_OPTION))
开发者ID:mishalzaman,项目名称:reddit,代码行数:34,代码来源:oauth2.py
示例10: ratelimit_agent
def ratelimit_agent(agent, limit=10, slice_size=10):
slice_size = min(slice_size, 60)
time_slice, retry_after = _get_ratelimit_timeslice(slice_size)
key = "rate_agent_" + agent + time.strftime("_%S", time_slice)
g.cache.add(key, 0, time=slice_size + 1)
if g.cache.incr(key) > limit:
request.environ['retry_after'] = retry_after
abort(429)
开发者ID:Bebetz,项目名称:reddit,代码行数:8,代码来源:reddit_base.py
示例11: handle_login
def handle_login(
controller, form, responder, user, rem=None, signature=None, **kwargs
):
# check captcha before login (if any) since its answer might
# change once c.user is set.
captcha_shown = not signature and need_provider_captcha("login")
def _event(error, captcha_shown=captcha_shown):
g.events.login_event(
'login_attempt',
error_msg=error,
user_name=request.urlvars.get('url_user'),
remember_me=rem,
signature=signature,
captcha_shown=captcha_shown,
request=request,
context=c)
if signature and not signature.is_valid():
_event(error="SIGNATURE")
abort(403)
hook_error = hooks.get_hook("account.login").call_until_return(
responder=responder,
request=request,
context=c,
)
# if any of the hooks returned an error, abort the login. The
# set_error in this case also needs to exist in the hook.
if hook_error:
_event(error=hook_error)
return
exempt_ua = (request.user_agent and
any(ua in request.user_agent for ua
in g.config.get('exempt_login_user_agents', ())))
if (errors.LOGGED_IN, None) in c.errors:
if user == c.user or exempt_ua:
# Allow funky clients to re-login as the current user.
c.errors.remove((errors.LOGGED_IN, None))
else:
_event(error='LOGGED_IN')
abort(reddit_http_error(409, errors.LOGGED_IN))
if responder.has_errors("ratelimit", errors.RATELIMIT):
_event(error='RATELIMIT')
elif responder.has_errors("passwd", errors.WRONG_PASSWORD):
_event(error='WRONG_PASSWORD')
# last but not least, we have to check the captcha
elif (not signature and not g.disable_captcha and
not valid_provider_captcha(responder, "login")):
_event(error='BAD_CAPTCHA')
else:
controller._login(responder, user, rem)
_event(error=None)
开发者ID:zeantsoi,项目名称:reddit,代码行数:58,代码来源:login.py
示例12: run_sitewide_ratelimits
def run_sitewide_ratelimits(self):
"""Ratelimit users and add ratelimit headers to the response.
Headers added are:
X-Ratelimit-Used: Number of requests used in this period
X-Ratelimit-Remaining: Number of requests left to use
X-Ratelimit-Reset: Approximate number of seconds to end of period
This function only has an effect if one of
g.RL_SITEWIDE_ENABLED or g.RL_OAUTH_SITEWIDE_ENABLED
are set to 'true' in the app configuration
If the ratelimit is exceeded, a 429 response will be sent,
unless the app configuration has g.ENFORCE_RATELIMIT off.
Headers will be sent even on aborted requests.
"""
if c.cdn_cacheable or not is_api():
# No ratelimiting or headers for:
# * Web requests (HTML)
# * CDN requests (logged out via www.reddit.com)
return
elif c.oauth_user and g.RL_OAUTH_SITEWIDE_ENABLED:
max_reqs = g.RL_OAUTH_MAX_REQS
period = g.RL_OAUTH_RESET_SECONDS
# Convert client_id to ascii str for use as memcache key
client_id = c.oauth2_access_token.client_id.encode("ascii")
# OAuth2 ratelimits are per user-app combination
key = 'siterl-oauth-' + c.user._id36 + ":" + client_id
elif g.RL_SITEWIDE_ENABLED:
max_reqs = g.RL_MAX_REQS
period = g.RL_RESET_SECONDS
# API (non-oauth) limits are per-ip
key = 'siterl-api-' + request.ip
else:
# Not in a context where sitewide ratelimits are on
return
period_start, retry_after = _get_ratelimit_timeslice(period)
key += time.strftime("-%H%M%S", period_start)
g.ratelimitcache.add(key, 0, time=retry_after + 1)
# Increment the key to track the current request
recent_reqs = g.ratelimitcache.incr(key)
reqs_remaining = max(0, max_reqs - recent_reqs)
c.ratelimit_headers = {
"X-Ratelimit-Used": str(recent_reqs),
"X-Ratelimit-Reset": str(retry_after),
"X-Ratelimit-Remaining": str(reqs_remaining),
}
if reqs_remaining <= 0 and g.ENFORCE_RATELIMIT:
# For non-abort situations, the headers will be added in post(),
# to avoid including them in a pagecache
response.headers.update(c.ratelimit_headers)
abort(429)
开发者ID:Bebetz,项目名称:reddit,代码行数:58,代码来源:reddit_base.py
示例13: abort_with_error
def abort_with_error(error, code=None):
if not code and not error.code:
raise ValueError("Error %r missing status code" % error)
abort(
reddit_http_error(
code=code or error.code, error_name=error.name, explanation=error.message, fields=error.fields
)
)
开发者ID:nderelli,项目名称:reddit,代码行数:9,代码来源:reddit_base.py
示例14: pre
def pre(self):
if g.disallow_db_writes:
abort(403)
set_extension(request.environ, "json")
MinimalController.pre(self)
require_https()
if request.method != "OPTIONS":
c.oauth2_client = self._get_client_auth()
开发者ID:AHAMED750,项目名称:reddit,代码行数:9,代码来源:oauth2.py
示例15: _check_client_type_and_duration
def _check_client_type_and_duration(self, response_type, client, duration):
if response_type == "token" and client.is_confidential():
# Prevent "confidential" clients from distributing tokens
# in a non-confidential manner
abort(BadRequestError(errors.OAUTH2_CONFIDENTIAL_TOKEN))
if response_type == "token" and duration != "temporary":
# implicit grant -> No refresh tokens allowed
abort(BadRequestError(errors.OAUTH2_NO_REFRESH_TOKENS_ALLOWED))
开发者ID:mishalzaman,项目名称:reddit,代码行数:9,代码来源:oauth2.py
示例16: ratelimit_agent
def ratelimit_agent(agent):
SLICE_SIZE = 10
slice, remainder = map(int, divmod(time.time(), SLICE_SIZE))
time_slice = time.gmtime(slice * SLICE_SIZE)
key = "rate_agent_" + agent + time.strftime("_%S", time_slice)
g.cache.add(key, 0, time=SLICE_SIZE + 1)
if g.cache.incr(key) > SLICE_SIZE:
request.environ['retry_after'] = SLICE_SIZE - remainder
abort(429)
开发者ID:ChrisCinelli,项目名称:reddit,代码行数:10,代码来源:reddit_base.py
示例17: redirect_to_host
def redirect_to_host(hostname, path=None):
"""Redirect (302) to the specified path and host."""
if path is None:
path = request.path
u = UrlParser(path)
u.hostname = hostname
# 307 redirect so request method is retained
abort(307, location=u.unparse())
开发者ID:13steinj,项目名称:reddit-plugin-betamode,代码行数:10,代码来源:betamode.py
示例18: _get_client_auth
def _get_client_auth(self):
auth = request.headers.get("Authorization")
try:
client_id, client_secret = parse_http_basic(auth)
client = OAuth2Client.get_token(client_id)
require(client)
require(constant_time_compare(client.secret, client_secret))
return client
except RequirementException:
abort(401, headers=[("WWW-Authenticate", 'Basic realm="reddit"')])
开发者ID:Bebetz,项目名称:reddit,代码行数:10,代码来源:oauth2.py
示例19: on_validation_error
def on_validation_error(self, error):
if not error.code:
raise ValueError('Error %r missing status code' % error)
abort(reddit_http_error(
code=error.code,
error_name=error.name,
explanation=error.message,
fields=error.fields,
))
开发者ID:ani625,项目名称:reddit,代码行数:10,代码来源:multi.py
示例20: ratelimit_agent
def ratelimit_agent(agent, limit=10, slice_size=10):
slice_size = min(slice_size, 60)
slice, remainder = map(int, divmod(time.time(), slice_size))
time_slice = time.gmtime(slice * slice_size)
key = "rate_agent_" + agent + time.strftime("_%S", time_slice)
g.cache.add(key, 0, time=slice_size + 1)
if g.cache.incr(key) > limit:
request.environ['retry_after'] = slice_size - remainder
abort(429)
开发者ID:HerculesCE,项目名称:reddit,代码行数:10,代码来源:reddit_base.py
注:本文中的r2.lib.base.abort函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论