本文整理匯總了Python中http.HTTPStatus.OK屬性的典型用法代碼示例。如果您正苦於以下問題:Python HTTPStatus.OK屬性的具體用法?Python HTTPStatus.OK怎麽用?Python HTTPStatus.OK使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類http.HTTPStatus
的用法示例。
在下文中一共展示了HTTPStatus.OK屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: drip
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [as 別名]
def drip():
"""Drip data over a duration."""
duration = float(flask.request.args.get('duration'))
numbytes = int(flask.request.args.get('numbytes'))
pause = duration / numbytes
def generate_bytes():
for _ in range(numbytes):
yield "*".encode('utf-8')
time.sleep(pause)
response = flask.Response(generate_bytes(), headers={
"Content-Type": "application/octet-stream",
"Content-Length": str(numbytes),
})
response.status_code = HTTPStatus.OK
return response
示例2: get_report
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [as 別名]
def get_report(self, sha256_hash: str) -> dict:
sleep_interval = 8 # In seconds.
attempt = 1
max_attempts = 16
for attempt in range(1, max_attempts + 1):
report = self.get_vt_session().get_file_report(sha256_hash)
if 'response_code' in report and report['response_code'] == HTTPStatus.OK:
report_results_rc = report['results']['response_code']
if report_results_rc == 1:
return report
# Exponential backoff.
sleep_interval *= attempt
self.logger.warning('Attempt {0}/{1} (retrying in {2} s), complete result not yet available: {3}'
.format(attempt, max_attempts, sleep_interval, report))
time.sleep(sleep_interval)
self.logger.error('Maximum number of {0} attempts reached for "{1}"'.format(attempt, sha256_hash))
raise Exception('Maximum number of attempts reached')
示例3: _check_result
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [as 別名]
def _check_result(response):
body = await response.text()
if response.content_type != 'application/json':
log.error('Invalid response with content type %r: %r',
response.content_type, body)
exceptions.DialogsAPIError.detect(body)
try:
result_json = await response.json(loads=json.loads)
except ValueError:
result_json = {}
log.debug('Request result is %r', result_json)
if HTTPStatus.OK <= response.status <= HTTPStatus.IM_USED:
return result_json
if result_json and 'message' in result_json:
description = result_json['message']
else:
description = body
log.warning('Response status %r with description %r',
response.status, description)
exceptions.DialogsAPIError.detect(description)
示例4: validate_response
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [as 別名]
def validate_response(context):
assert_that(context.response.status_code, equal_to(HTTPStatus.OK))
response_data = json.loads(context.response.data)
expected_response = ['tell me a joke']
assert_that(response_data, equal_to(expected_response))
resources_dir = os.path.join(os.path.dirname(__file__), 'resources')
with open(os.path.join(resources_dir, 'test_stt.flac'), 'rb') as input_file:
input_file_content = input_file.read()
flac_file_path = _get_stt_result_file(context.account.id, '.flac')
assert_that(flac_file_path, not_none())
with open(flac_file_path, 'rb') as output_file:
output_file_content = output_file.read()
assert_that(input_file_content, equal_to(output_file_content))
stt_file_path = _get_stt_result_file(context.account.id, '.stt')
assert_that(stt_file_path, not_none())
with open(stt_file_path, 'rb') as output_file:
output_file_content = output_file.read()
assert_that(b'tell me a joke', equal_to(output_file_content))
示例5: put
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [as 別名]
def put(self, device_id):
self._authenticate(device_id)
payload = json.loads(self.request.data)
send_email = SendEmail(payload)
send_email.validate()
account = AccountRepository(self.db).get_account_by_device_id(device_id)
if account:
message = EmailMessage()
message['Subject'] = str(send_email.title)
message['From'] = str(send_email.sender)
message.set_content(str(send_email.body))
message['To'] = account.email_address
self._send_email(message)
response = '', HTTPStatus.OK
else:
response = '', HTTPStatus.NO_CONTENT
return response
示例6: get
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [as 別名]
def get(self, device_id):
self._authenticate(device_id)
self._validate_etag(device_etag_key(device_id))
device = DeviceRepository(self.db).get_device_by_id(device_id)
if device is not None:
response_data = dict(
uuid=device.id,
name=device.name,
description=device.placement,
coreVersion=device.core_version,
enclosureVersion=device.enclosure_version,
platform=device.platform,
user=dict(uuid=device.account_id)
)
response = response_data, HTTPStatus.OK
self._add_etag(device_etag_key(device_id))
else:
response = '', HTTPStatus.NO_CONTENT
return response
示例7: do_GET
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [as 別名]
def do_GET(self):
if 'crumbIssuer' in self.path:
self.send_response(HTTPStatus.OK)
self.end_headers()
self.wfile.write(CRUMBDATA)
return
if 'pluginManager' in self.path:
self.send_response(200)
self.end_headers()
self.wfile.write(PLUGINS)
return
try:
txData = self.server.getTxData()
txData=txData[self.path]
self.send_response(HTTPStatus.OK)
self.end_headers()
self.wfile.write(txData)
except KeyError:
self.send_response(404)
self.end_headers()
示例8: get_swagger_doc
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [as 別名]
def get_swagger_doc(cls, http_method):
"""
Create a swagger api model based on the sqlalchemy schema
if an instance exists in the DB, the first entry is used as example
"""
body = {}
responses = {}
object_name = cls.__name__
object_model = {}
responses = {HTTPStatus.OK.value: {"description": "{} object".format(object_name), "schema": object_model}}
if http_method.upper() in ("POST", "GET"):
responses = {
HTTPStatus.OK.value: {"description": HTTPStatus.OK.description},
HTTPStatus.NOT_FOUND.value: {"description": HTTPStatus.NOT_FOUND.description},
}
return body, responses
示例9: refresh_balance
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [as 別名]
def refresh_balance(account):
try:
balance_return = rpc.account_balance(account="{}".format(account))
balance_dict = {
'balance': balance_return[0],
'pending': balance_return[1]
}
response = Response(json.dumps(balance_dict))
response.headers['Access-Control-Allow-Credentials'] = True
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Content-Type'] = 'application/json'
return response, HTTPStatus.OK
except Exception as e:
logger.info("{}: ERROR in refresh_balance (webhooks.py): {}".format(datetime.now, e))
return e, HTTPStatus.BAD_REQUEST
示例10: upload_csv
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [as 別名]
def upload_csv() -> str:
"""Upload CSV example."""
submitted_file = request.files["file"]
if submitted_file and allowed_filename(submitted_file.filename):
filename = secure_filename(submitted_file.filename)
directory = os.path.join(app.config["UPLOAD_FOLDER"])
if not os.path.exists(directory):
os.mkdir(directory)
basedir = os.path.abspath(os.path.dirname(__file__))
submitted_file.save(
os.path.join(basedir, app.config["UPLOAD_FOLDER"], filename)
)
out = {
"status": HTTPStatus.OK,
"filename": filename,
"message": f"{filename} saved successful.",
}
return jsonify(out)
示例11: _send_message
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [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)
示例12: validate_token
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [as 別名]
def validate_token():
"""
https://docs.gitlab.com/ee/user/project/integrations/webhooks.html#secret-token
"""
if "X-Gitlab-Token" not in request.headers:
if config.validate_webhooks:
msg = "X-Gitlab-Token not in request.headers"
logger.warning(msg)
raise ValidationFailed(msg)
else:
# don't validate signatures when testing locally
logger.debug("Ain't validating token.")
return
token = request.headers["X-Gitlab-Token"]
# Find a better solution
if token not in config.gitlab_webhook_tokens:
raise ValidationFailed("Payload token validation failed.")
logger.debug("Payload token is OK.")
示例13: do_GET
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [as 別名]
def do_GET(self):
"""Serve a GET request from the fixtures directory"""
fn = p.join(p.dirname(__file__), 'fixtures', self.path[1:])
print("path=", fn)
try:
with open(fn, 'rb') as f:
stat = os.fstat(f.fileno())
content = f.read()
except OSError:
self.send_error(HTTPStatus.NOT_FOUND)
except IOError:
self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR)
self.send_response(HTTPStatus.OK)
self.send_header('Content-Type', self.guess_type(fn))
self.send_header('Content-Length', stat.st_size)
self.send_header('ETag', hashlib.sha1(content).hexdigest())
self.end_headers()
self.wfile.write(content)
示例14: do_POST
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [as 別名]
def do_POST(self): # type: () -> None
assert self.command == 'POST'
assert self.path == '/'
# Parse the request body, and post to the queue.
data = self.read_request_data()
itn_queue = self.server.itn_queue # type: ignore
itn_queue # type: Queue
itn_queue.put(data)
self.send_response(HTTPStatus.OK)
self.end_headers()
示例15: _create_invoke_response
# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import OK [as 別名]
def _create_invoke_response(body: object = None) -> InvokeResponse:
return InvokeResponse(status=int(HTTPStatus.OK), body=serializer_helper(body))