本文整理匯總了Python中http.HTTPStatus.UNAUTHORIZED屬性的典型用法代碼示例。如果您正苦於以下問題:Python HTTPStatus.UNAUTHORIZED屬性的具體用法?Python HTTPStatus.UNAUTHORIZED怎麽用?Python HTTPStatus.UNAUTHORIZED使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類http.HTTPStatus
的用法示例。
在下文中一共展示了HTTPStatus.UNAUTHORIZED屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def get(self):
headers = self.request.headers
if 'Authorization' not in headers:
raise AuthenticationError('Oauth token not found')
token_header = self.request.headers['Authorization']
if token_header.startswith('Bearer '):
refresh = token_header[len('Bearer '):]
session = self._refresh_session_token(refresh)
# Trying to fetch a session using the refresh token
if session:
response = session, HTTPStatus.OK
else:
device = self.request.headers.get('Device')
if device:
# trying to fetch a session using the device uuid
session = self._refresh_session_token_device(device)
if session:
response = session, HTTPStatus.OK
else:
response = '', HTTPStatus.UNAUTHORIZED
else:
response = '', HTTPStatus.UNAUTHORIZED
else:
response = '', HTTPStatus.UNAUTHORIZED
return response
示例2: _send_message
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def _send_message(message):
smtp = smtplib.SMTP_SSL('email-smtp.eu-west-1.amazonaws.com', 465)
try:
smtp.login(
user='AKIAITZ6BSMD7DMZYTYQ',
password='Ajf0ucUGJiN44N6IeciTY4ApN1os6JCeQqyglRSI2x4V')
except SMTPAuthenticationError:
return Response('Authentication failed',
status=HTTPStatus.UNAUTHORIZED)
try:
smtp.sendmail(message['From'], message['To'], message.as_string())
except SMTPRecipientsRefused as e:
return Response(f'Recipient refused {e}',
status=HTTPStatus.INTERNAL_SERVER_ERROR)
finally:
smtp.quit()
return Response('Email sent', status=HTTPStatus.OK)
示例3: post
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def post(self):
"""
Submit Testing Farm results
"""
msg = request.json
if not msg:
logger.debug("/testing-farm/results: we haven't received any JSON data.")
return "We haven't received any JSON data.", HTTPStatus.BAD_REQUEST
try:
self.validate_testing_farm_request()
except ValidationFailed as exc:
logger.info(f"/testing-farm/results {exc}")
return str(exc), HTTPStatus.UNAUTHORIZED
celery_app.send_task(
name="task.steve_jobs.process_message", kwargs={"event": msg}
)
return "Test results accepted", HTTPStatus.ACCEPTED
示例4: _authorize
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def _authorize(self, username, password):
def request_token(url):
resp = open_url(
url,
method=HTTPMethod.POST,
data=json.dumps({'grant_type': 'password', 'username': username, 'password': password}),
headers=BASE_HEADERS,
validate_certs=False
).read()
return json.loads(to_text(resp))
api_versions = sorted(self._fetch_api_versions(), reverse=True)
for version in api_versions:
token_url = self._hostname + self.TOKEN_PATH_TEMPLATE.format(version)
try:
token = request_token(token_url)
except urllib_error.HTTPError as e:
logger.debug("Can't get token for API version: %s", version, exc_info=True)
if e.code != HTTPStatus.UNAUTHORIZED:
raise
else:
return token
raise Exception("Can't fetch token via API")
示例5: authenticate_with_macaroon
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def authenticate_with_macaroon(url, insecure=False):
"""Login via macaroons and generate and return new API keys."""
executor = futures.ThreadPoolExecutor(max_workers=1)
def get_token():
client = httpbakery.Client()
resp = client.request(
"POST",
"{}/account/?op=create_authorisation_token".format(url),
verify=not insecure,
)
if resp.status_code == HTTPStatus.UNAUTHORIZED:
# if the auteentication with Candid fails, an exception is raised
# above so we don't get here
raise MacaroonLoginNotSupported("Macaroon authentication not supported")
if resp.status_code != HTTPStatus.OK:
raise LoginError("Login failed: {}".format(resp.text))
result = resp.json()
return "{consumer_key}:{token_key}:{token_secret}".format(**result)
loop = asyncio.get_event_loop()
return await loop.run_in_executor(executor, get_token)
示例6: authorization_required
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def authorization_required(view_function):
@wraps(view_function)
def decorated_function(*args, **kwargs):
if 'Authorization' not in request.headers:
abort(HTTPStatus.UNAUTHORIZED)
kind, data = request.headers['Authorization'].split()
if kind.upper() != 'BASIC':
abort(HTTPStatus.UNAUTHORIZED)
credentials = base64.b64decode(data)
username_bytes, _, password_bytes = credentials.partition(b':')
username = username_bytes.decode('ascii')
password = password_bytes.decode('ascii')
if username not in user_database:
abort(HTTPStatus.UNAUTHORIZED)
if not user_database[username].check_password(password):
abort(HTTPStatus.UNAUTHORIZED)
g.user = user_database[username]
return view_function(*args, **kwargs)
return decorated_function
示例7: _check_status
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def _check_status(self):
"""Check if the http status is what we expected."""
path_to_statuses = {
'/favicon.ico': [HTTPStatus.OK, HTTPStatus.PARTIAL_CONTENT],
'/does-not-exist': [HTTPStatus.NOT_FOUND],
'/does-not-exist-2': [HTTPStatus.NOT_FOUND],
'/404': [HTTPStatus.NOT_FOUND],
'/redirect-later': [HTTPStatus.FOUND],
'/redirect-self': [HTTPStatus.FOUND],
'/redirect-to': [HTTPStatus.FOUND],
'/relative-redirect': [HTTPStatus.FOUND],
'/absolute-redirect': [HTTPStatus.FOUND],
'/cookies/set': [HTTPStatus.FOUND],
'/500-inline': [HTTPStatus.INTERNAL_SERVER_ERROR],
'/500': [HTTPStatus.INTERNAL_SERVER_ERROR],
}
for i in range(15):
path_to_statuses['/redirect/{}'.format(i)] = [HTTPStatus.FOUND]
for suffix in ['', '1', '2', '3', '4', '5', '6']:
key = ('/basic-auth/user{suffix}/password{suffix}'
.format(suffix=suffix))
path_to_statuses[key] = [HTTPStatus.UNAUTHORIZED, HTTPStatus.OK]
default_statuses = [HTTPStatus.OK, HTTPStatus.NOT_MODIFIED]
sanitized = QUrl('http://localhost' + self.path).path() # Remove ?foo
expected_statuses = path_to_statuses.get(sanitized, default_statuses)
if self.status not in expected_statuses:
raise AssertionError(
"{} loaded with status {} but expected {}".format(
sanitized, self.status,
' / '.join(repr(e) for e in expected_statuses)))
示例8: basic_auth
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def basic_auth(user='user', passwd='passwd'):
"""Prompt the user for authorization using HTTP Basic Auth."""
auth = flask.request.authorization
if not auth or auth.username != user or auth.password != passwd:
r = flask.make_response()
r.status_code = HTTPStatus.UNAUTHORIZED
r.headers = {'WWW-Authenticate': 'Basic realm="Fake Realm"'}
return r
return flask.jsonify(authenticated=True, user=user)
示例9: bad_auth
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def bad_auth(self) -> web.Response:
return web.json_response({
"error": "Invalid username or password",
"errcode": "invalid_auth",
}, status=HTTPStatus.UNAUTHORIZED)
示例10: no_token
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def no_token(self) -> web.Response:
return web.json_response({
"error": "Authorization token missing",
"errcode": "auth_token_missing",
}, status=HTTPStatus.UNAUTHORIZED)
示例11: invalid_token
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def invalid_token(self) -> web.Response:
return web.json_response({
"error": "Invalid authorization token",
"errcode": "auth_token_invalid",
}, status=HTTPStatus.UNAUTHORIZED)
示例12: get
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def get(self, **kwargs):
"""
Get details about the current user.
This is also how the frontend can get an access token. For that
reason, this endpoint is authenticated using the session, NOT
the access token
"""
# Fail if we aren't logged in
if current_user.is_anonymous:
return "", HTTPStatus.UNAUTHORIZED
user = (
db.session.query(user_models.User)
.filter(user_models.User.user_id == current_user.user_id)
.first_or_404()
)
if kwargs["permission"] >= utils.Permission.ADMIN:
# If an admin is making this request, give them everything
schema_kwargs = {}
else:
# If it's a user requesting their own data, exclude password info
schema_kwargs = {"exclude": ["salt", "password"]}
return schemas.UserSchema(many=False, **schema_kwargs).dump(user)
示例13: check_for_bad_request
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def check_for_bad_request(context, error_type):
if error_type == 'a bad request':
assert_that(
context.response.status_code,
equal_to(HTTPStatus.BAD_REQUEST)
)
elif error_type == 'an unauthorized':
assert_that(
context.response.status_code,
equal_to(HTTPStatus.UNAUTHORIZED)
)
else:
raise ValueError('unsupported error_type')
示例14: check_for_login_fail
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def check_for_login_fail(context, error_message):
assert_that(context.response.status_code, equal_to(HTTPStatus.UNAUTHORIZED))
assert_that(
context.response.headers['Access-Control-Allow-Origin'],
equal_to('*')
)
assert_that(context.response.is_json, equal_to(True))
assert_that(context.response.get_json(), equal_to(error_message))
示例15: check_for_login_fail
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import UNAUTHORIZED [as 別名]
def check_for_login_fail(context, error_message):
assert_that(context.response.status_code, equal_to(HTTPStatus.UNAUTHORIZED))
assert_that(
context.response.headers['Access-Control-Allow-Origin'],
equal_to('*')
)
assert_that(context.response.is_json, equal_to(True))
response_json = context.response.get_json()
assert_that(response_json['error'], equal_to(error_message))