code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
@wraps(fnc)
def _wrapped(self, check, *args, **kwargs):
if not isinstance(check, CloudMonitorCheck):
# Must be the ID
check = self._check_manager.get(check)
return fnc(self, check, *args, **kwargs)
return _wrapped | def assure_check(fnc) | Converts an checkID passed as the check to a CloudMonitorCheck object. | 3.732359 | 2.450997 | 1.522792 |
@wraps(fnc)
def _wrapped(self, entity, *args, **kwargs):
if not isinstance(entity, CloudMonitorEntity):
# Must be the ID
entity = self._entity_manager.get(entity)
return fnc(self, entity, *args, **kwargs)
return _wrapped | def assure_entity(fnc) | Converts an entityID passed as the entity to a CloudMonitorEntity object. | 3.200038 | 2.372533 | 1.348785 |
self.manager.update_entity(self, agent=agent, metadata=metadata) | def update(self, agent=None, metadata=None) | Only the agent_id and metadata are able to be updated via the API. | 6.243993 | 5.854415 | 1.066544 |
chk = self._check_manager.get(check)
chk.set_entity(self)
return chk | def get_check(self, check) | Returns an instance of the specified check. | 8.243666 | 6.488963 | 1.270413 |
checks = self._check_manager.list(limit=limit, marker=marker,
return_next=return_next)
for check in checks:
check.set_entity(self)
return checks | def list_checks(self, limit=None, marker=None, return_next=False) | Returns a list of the checks defined for this account. By default the
number returned is limited to 100; you can define the number to return
by optionally passing a value for the 'limit' parameter. The value for
limit must be at least 1, and can be up to 1000.
For pagination, you must also specify the 'marker' parameter. This is
the ID of the first item to return. To get this, pass True for the
'return_next' parameter, and the response will be a 2-tuple, with the
first element being the list of checks, and the second the ID of the
next item. If there is no next item, the second element will be None. | 3.252069 | 5.325566 | 0.610652 |
checks = self._check_manager.find_all_checks(**kwargs)
for check in checks:
check.set_entity(self)
return checks | def find_all_checks(self, **kwargs) | Finds all checks for this entity with attributes matching ``**kwargs``.
This isn't very efficient: it loads the entire list then filters on
the Python side. | 3.877838 | 3.86776 | 1.002606 |
return self._check_manager.create_check(label=label, name=name,
check_type=check_type, disabled=disabled, metadata=metadata,
details=details, monitoring_zones_poll=monitoring_zones_poll,
timeout=timeout, period=period, target_alias=target_alias,
target_hostname=target_hostname,
target_receiver=target_receiver, test_only=test_only,
include_debug=include_debug) | def create_check(self, label=None, name=None, check_type=None,
disabled=False, metadata=None, details=None,
monitoring_zones_poll=None, timeout=None, period=None,
target_alias=None, target_hostname=None, target_receiver=None,
test_only=False, include_debug=False) | Creates a check on this entity with the specified attributes. The
'details' parameter should be a dict with the keys as the option name,
and the value as the desired setting. | 1.34998 | 1.438648 | 0.938367 |
return self._alarm_manager.create(check, notification_plan,
criteria=criteria, disabled=disabled, label=label, name=name,
metadata=metadata) | def create_alarm(self, check, notification_plan, criteria=None,
disabled=False, label=None, name=None, metadata=None) | Creates an alarm that binds the check on this entity with a
notification plan. | 2.372971 | 3.614237 | 0.656562 |
return self._alarm_manager.update(alarm, criteria=criteria,
disabled=disabled, label=label, name=name, metadata=metadata) | def update_alarm(self, alarm, criteria=None, disabled=False,
label=None, name=None, metadata=None) | Updates an existing alarm on this entity. | 2.561915 | 3.203042 | 0.799838 |
return self._alarm_manager.list(limit=limit, marker=marker,
return_next=return_next) | def list_alarms(self, limit=None, marker=None, return_next=False) | Returns a list of all the alarms created on this entity. | 3.521438 | 3.924628 | 0.897267 |
kwargs = {}
if return_next:
kwargs["other_keys"] = "metadata"
ret = super(_PaginationManager, self).list(limit=limit,
marker=marker, **kwargs)
if return_next:
ents, meta = ret
return (ents, meta[0].get("next_marker"))
else:
return ret | def list(self, limit=None, marker=None, return_next=False) | This is necessary to handle pagination correctly, as the Monitoring
service defines 'marker' differently than most other services. For
monitoring, 'marker' represents the first item in the next page,
whereas other services define it as the ID of the last item in the
current page. | 5.026362 | 5.196646 | 0.967232 |
uri = "/%s" % self.uri_base
body = {"label": label or name,
"type": utils.get_id(notification_type),
"details": details,
}
resp, resp_body = self.api.method_post(uri, body=body)
return self.get(resp.headers["x-object-id"]) | def create(self, notification_type, label=None, name=None, details=None) | Defines a notification for handling an alarm. | 3.483189 | 3.724571 | 0.935192 |
if isinstance(notification, CloudMonitorNotification):
nid = notification.id
ntyp = notification.type
else:
# Supplied an ID
nfcn = self.get(notification)
nid = notification
ntyp = nfcn.type
uri = "/%s/%s" % (self.uri_base, nid)
body = {"type": ntyp,
"details": details}
resp, resp_body = self.api.method_put(uri, body=body) | def update_notification(self, notification, details) | Updates the specified notification with the supplied details. | 4.670332 | 4.372484 | 1.068119 |
uri = "/notification_types"
resp, resp_body = self.api.method_get(uri)
return [CloudMonitorNotificationType(self, info)
for info in resp_body["values"]] | def list_types(self) | Returns a list of all available notification types. | 7.869695 | 5.975818 | 1.316923 |
uri = "/notification_types/%s" % utils.get_id(notification_type_id)
resp, resp_body = self.api.method_get(uri)
return CloudMonitorNotificationType(self, resp_body) | def get_type(self, notification_type_id) | Returns a CloudMonitorNotificationType object for the given ID. | 4.21337 | 2.949214 | 1.428642 |
uri = "/%s" % self.uri_base
body = {"label": label or name}
def make_list_of_ids(parameter):
params = utils.coerce_to_list(parameter)
return [utils.get_id(param) for param in params]
if critical_state:
critical_state = utils.coerce_to_list(critical_state)
body["critical_state"] = make_list_of_ids(critical_state)
if warning_state:
warning_state = utils.coerce_to_list(warning_state)
body["warning_state"] = make_list_of_ids(warning_state)
if ok_state:
ok_state = utils.coerce_to_list(ok_state)
body["ok_state"] = make_list_of_ids(ok_state)
resp, resp_body = self.api.method_post(uri, body=body)
return self.get(resp.headers["x-object-id"]) | def create(self, label=None, name=None, critical_state=None, ok_state=None,
warning_state=None) | Creates a notification plan to be executed when a monitoring check
triggers an alarm. You can optionally label (or name) the plan.
A plan consists of one or more notifications to be executed when an
associated alarm is triggered. You can have different lists of actions
for CRITICAL, WARNING or OK states. | 2.102131 | 2.15485 | 0.975535 |
allowed_resolutions = ("FULL", "MIN5", "MIN20", "MIN60", "MIN240",
"MIN1440")
if not (points or resolution):
raise exc.MissingMonitoringCheckGranularity("You must specify "
"either the 'points' or 'resolution' parameter when "
"fetching metrics.")
if resolution:
if resolution.upper() not in allowed_resolutions:
raise exc.InvalidMonitoringMetricsResolution("The specified "
"resolution '%s' is not valid. The valid values are: "
"%s." % (resolution, str(allowed_resolutions)))
start_tm = utils.to_timestamp(start)
end_tm = utils.to_timestamp(end)
# NOTE: For some odd reason, the timestamps required for this must be
# in milliseconds, instead of the UNIX standard for timestamps, which
# is in seconds. So the values here are multiplied by 1000 to make it
# work. If the API is ever corrected, the next two lines should be
# removed. GitHub #176.
start_tm *= 1000
end_tm *= 1000
qparms = []
# Timestamps with fractional seconds currently cause a 408 (timeout)
qparms.append("from=%s" % int(start_tm))
qparms.append("to=%s" % int(end_tm))
if points:
qparms.append("points=%s" % points)
if resolution:
qparms.append("resolution=%s" % resolution.upper())
if stats:
stats = utils.coerce_to_list(stats)
for stat in stats:
qparms.append("select=%s" % stat)
qparm = "&".join(qparms)
uri = "/%s/%s/plot?%s" % (self.uri_base, metric, qparm)
try:
resp, resp_body = self.api.method_get(uri)
except exc.BadRequest as e:
msg = e.message
dtls = e.details
if msg.startswith("Validation error"):
raise exc.InvalidMonitoringMetricsRequest("Your request was "
"invalid: '%s'" % dtls)
else:
raise
return resp_body["values"] | def get_metric_data_points(self, metric, start, end, points=None,
resolution=None, stats=None) | Returns the data points for a given metric for the given period. The
'start' and 'end' times must be specified; they can be be either Python
date/datetime values, or a Unix timestamp.
The 'points' parameter represents the number of points to return. The
'resolution' parameter represents the granularity of the data. You must
specify either 'points' or 'resolution'. The allowed values for
resolution are:
FULL
MIN5
MIN20
MIN60
MIN240
MIN1440
Finally, the 'stats' parameter specifies the stats you want returned.
By default only the 'average' is returned. You omit this parameter,
pass in a single value, or pass in a list of values. The allowed values
are:
average
variance
min
max | 3.41631 | 3.375257 | 1.012163 |
uri = "/%s" % self.uri_base
body = {"check_id": utils.get_id(check),
"notification_plan_id": utils.get_id(notification_plan),
}
if criteria:
body["criteria"] = criteria
if disabled is not None:
body["disabled"] = disabled
label_name = label or name
if label_name:
body["label"] = label_name
if metadata:
body["metadata"] = metadata
resp, resp_body = self.api.method_post(uri, body=body)
if resp.status_code == 201:
alarm_id = resp.headers["x-object-id"]
return self.get(alarm_id) | def create(self, check, notification_plan, criteria=None,
disabled=False, label=None, name=None, metadata=None) | Creates an alarm that binds the check on the given entity with a
notification plan.
Note that the 'criteria' parameter, if supplied, should be a string
representing the DSL for describing alerting conditions and their
output states. Pyrax does not do any validation of these criteria
statements; it is up to you as the developer to understand the language
and correctly form the statement. This alarm language is documented
online in the Cloud Monitoring section of http://docs.rackspace.com. | 2.281042 | 2.38419 | 0.956736 |
uri = "/%s/%s" % (self.uri_base, utils.get_id(alarm))
body = {}
if criteria:
body["criteria"] = criteria
if disabled is not None:
body["disabled"] = disabled
label_name = label or name
if label_name:
body["label"] = label_name
if metadata:
body["metadata"] = metadata
resp, resp_body = self.api.method_put(uri, body=body) | def update(self, alarm, criteria=None, disabled=False, label=None,
name=None, metadata=None) | Updates an existing alarm. See the comments on the 'create()' method
regarding the criteria parameter. | 2.350713 | 2.412089 | 0.974555 |
if details is None:
raise exc.MissingMonitoringCheckDetails("The required 'details' "
"parameter was not passed to the create_check() method.")
ctype = utils.get_id(check_type)
is_remote = ctype.startswith("remote")
monitoring_zones_poll = utils.coerce_to_list(monitoring_zones_poll)
monitoring_zones_poll = [utils.get_id(mzp)
for mzp in monitoring_zones_poll]
# only require monitoring_zones and targets for remote checks
if is_remote:
if not monitoring_zones_poll:
raise exc.MonitoringZonesPollMissing("You must specify the "
"'monitoring_zones_poll' parameter for remote checks.")
if not (target_alias or target_hostname):
raise exc.MonitoringCheckTargetNotSpecified("You must "
"specify either the 'target_alias' or 'target_hostname' "
"when creating a remote check.")
body = {"label": label or name,
"details": details,
"disabled": disabled,
"type": utils.get_id(check_type),
}
params = ("monitoring_zones_poll", "timeout", "period",
"target_alias", "target_hostname", "target_receiver")
body = _params_to_dict(params, body, locals())
if test_only:
uri = "/%s/test-check" % self.uri_base
if include_debug:
uri = "%s?debug=true" % uri
else:
uri = "/%s" % self.uri_base
try:
resp = self.api.method_post(uri, body=body)[0]
except exc.BadRequest as e:
msg = e.message
dtls = e.details
match = _invalid_key_pat.match(msg)
if match:
missing = match.groups()[0].replace("details.", "")
if missing in details:
errmsg = "".join(["The value passed for '%s' in the ",
"details parameter is not valid."]) % missing
else:
errmsg = "".join(["The required value for the '%s' ",
"setting is missing from the 'details' ",
"parameter."]) % missing
utils.update_exc(e, errmsg)
raise e
else:
if msg == "Validation error":
# Info is in the 'details'
raise exc.InvalidMonitoringCheckDetails("Validation "
"failed. Error: '%s'." % dtls)
# its something other than validation error; probably
# limits exceeded, but raise it instead of failing silently
raise e
else:
if resp.status_code == 201:
check_id = resp.headers["x-object-id"]
return self.get(check_id)
# don't fail silently here either; raise an error
# if we get an unexpected response code
raise exc.ClientException("Unknown response code creating check;"
" expected 201, got %s" % resp.status_code) | def create_check(self, label=None, name=None, check_type=None,
details=None, disabled=False, metadata=None,
monitoring_zones_poll=None, timeout=None, period=None,
target_alias=None, target_hostname=None, target_receiver=None,
test_only=False, include_debug=False) | Creates a check on the entity with the specified attributes. The
'details' parameter should be a dict with the keys as the option name,
and the value as the desired setting.
If the 'test_only' parameter is True, then the check is not created;
instead, the check is run and the results of the test run returned. If
'include_debug' is True, additional debug information is returned.
According to the current Cloud Monitoring docs:
"Currently debug information is only available for the
remote.http check and includes the response body." | 3.590092 | 3.57495 | 1.004236 |
found = []
searches = kwargs.items()
for obj in self.list():
try:
if all(getattr(obj, attr) == value
for (attr, value) in searches):
found.append(obj)
except AttributeError:
continue
return found | def find_all_checks(self, **kwargs) | Finds all checks for a given entity with attributes matching
``**kwargs``.
This isn't very efficient: it loads the entire list then filters on
the Python side. | 3.689764 | 3.249353 | 1.135538 |
uri = "/%s" % self.uri_base
if entity:
uri = "%s?entityId=%s" % (uri, utils.get_id(entity))
resp, resp_body = self._list(uri, return_raw=True)
return resp_body | def list(self, entity=None) | Returns a dictionary of data, optionally filtered for a given entity. | 4.236665 | 3.878043 | 1.092475 |
label = label or name
if ip_addresses is not None:
body = {"label": label}
if ip_addresses:
body["ip_addresses"] = ip_addresses
if agent:
body["agent_id"] = utils.get_id(agent)
if metadata:
body["metadata"] = metadata
return body | def _create_body(self, name, label=None, agent=None, ip_addresses=None,
metadata=None) | Used to create the dict required to create various resources. Accepts
either 'label' or 'name' as the keyword parameter for the label
attribute for entities. | 2.535202 | 2.602795 | 0.974031 |
body = {}
if agent:
body["agent_id"] = utils.get_id(agent)
if metadata:
body["metadata"] = metadata
if body:
uri = "/%s/%s" % (self.uri_base, utils.get_id(entity))
resp, body = self.api.method_put(uri, body=body) | def update_entity(self, entity, agent=None, metadata=None) | Updates the specified entity's values with the supplied parameters. | 2.492425 | 2.527913 | 0.985961 |
new = self.manager.get(self)
if new:
self._add_details(new._info) | def get(self) | Reloads the check with its current values. | 13.9001 | 10.297607 | 1.349838 |
self.manager.update(self, label=label, name=name,
disabled=disabled, metadata=metadata,
monitoring_zones_poll=monitoring_zones_poll, timeout=timeout,
period=period, target_alias=target_alias,
target_hostname=target_hostname,
target_receiver=target_receiver) | def update(self, label=None, name=None, disabled=None, metadata=None,
monitoring_zones_poll=None, timeout=None, period=None,
target_alias=None, target_hostname=None, target_receiver=None) | Updates an existing check with any of the parameters. | 1.546704 | 1.623804 | 0.952519 |
return self._metrics_manager.list(limit=limit, marker=marker,
return_next=return_next) | def list_metrics(self, limit=None, marker=None, return_next=False) | Returns a list of all the metrics associated with this check. | 3.721541 | 4.107228 | 0.906096 |
return self._metrics_manager.get_metric_data_points(metric, start, end,
points=points, resolution=resolution, stats=stats) | def get_metric_data_points(self, metric, start, end, points=None,
resolution=None, stats=None) | Returns the data points for a given metric for the given period. The
'start' and 'end' times must be specified; they can be be either Python
date/datetime values, or a Unix timestamp.
The 'points' parameter represents the number of points to return. The
'resolution' parameter represents the granularity of the data. You must
specify either 'points' or 'resolution'. The allowed values for
resolution are:
FULL
MIN5
MIN20
MIN60
MIN240
MIN1440
Finally, the 'stats' parameter specifies the stats you want returned.
By default only the 'average' is returned. You omit this parameter,
pass in a single value, or pass in a list of values. The allowed values
are:
average
variance
min
max | 2.500764 | 3.847956 | 0.649894 |
return self.manager.create_alarm(self.entity, self, notification_plan,
criteria=criteria, disabled=disabled, label=label, name=name,
metadata=metadata) | def create_alarm(self, notification_plan, criteria=None, disabled=False,
label=None, name=None, metadata=None) | Creates an alarm that binds this check with a notification plan. | 2.817472 | 3.086403 | 0.912866 |
new_alarm = self.entity.get_alarm(self)
if new_alarm:
self._add_details(new_alarm._info) | def get(self) | Fetches the current state of the alarm from the API and updates the
object. | 10.559251 | 8.076944 | 1.307332 |
self._entity_manager = CloudMonitorEntityManager(self,
uri_base="entities", resource_class=CloudMonitorEntity,
response_key=None, plural_response_key=None)
self._check_type_manager = _PaginationManager(self,
uri_base="check_types", resource_class=CloudMonitorCheckType,
response_key=None, plural_response_key=None)
self._monitoring_zone_manager = BaseManager(self,
uri_base="monitoring_zones", resource_class=CloudMonitorZone,
response_key=None, plural_response_key=None)
self._notification_manager = CloudMonitorNotificationManager(self,
uri_base="notifications",
resource_class=CloudMonitorNotification,
response_key=None, plural_response_key=None)
self._notification_plan_manager = CloudMonitorNotificationPlanManager(
self, uri_base="notification_plans",
resource_class=CloudMonitorNotificationPlan,
response_key=None, plural_response_key=None)
self._changelog_manager = _EntityFilteringManger(self,
uri_base="changelogs/alarms", resource_class=None,
response_key=None, plural_response_key=None)
self._overview_manager = _EntityFilteringManger(self,
uri_base="views/overview", resource_class=None,
response_key="value", plural_response_key=None)
self._token_manager = CloudMonitorTokenManager(self) | def _configure_manager(self) | Creates the Manager instances to handle monitoring. | 2.436919 | 2.362133 | 1.03166 |
self._entity_manager.update_entity(entity, agent=agent,
metadata=metadata) | def update_entity(self, entity, agent=None, metadata=None) | Only the agent_id and metadata are able to be updated via the API. | 4.737344 | 5.147027 | 0.920404 |
entity.update_check(check, label=label, name=name, disabled=disabled,
metadata=metadata, monitoring_zones_poll=monitoring_zones_poll,
timeout=timeout, period=period, target_alias=target_alias,
target_hostname=target_hostname,
target_receiver=target_receiver) | def update_check(self, entity, check, label=None, name=None, disabled=None,
metadata=None, monitoring_zones_poll=None, timeout=None,
period=None, target_alias=None, target_hostname=None,
target_receiver=None) | Updates an existing check with any of the parameters. | 1.434873 | 1.483148 | 0.967451 |
return entity.list_metrics(check, limit=limit, marker=marker,
return_next=return_next) | def list_metrics(self, entity, check, limit=None, marker=None,
return_next=False) | Returns a list of all the metrics associated with the specified check. | 2.958783 | 3.087637 | 0.958268 |
return self._notification_manager.create(notification_type,
label=label, name=name, details=details) | def create_notification(self, notification_type, label=None, name=None,
details=None) | Defines a notification for handling an alarm. | 3.050001 | 3.30829 | 0.921927 |
return self._notification_plan_manager.create(label=label, name=name,
critical_state=critical_state, ok_state=ok_state,
warning_state=warning_state) | def create_notification_plan(self, label=None, name=None,
critical_state=None, ok_state=None, warning_state=None) | Creates a notification plan to be executed when a monitoring check
triggers an alarm. | 2.031286 | 3.138469 | 0.647222 |
return entity.update_alarm(alarm, criteria=criteria, disabled=disabled,
label=label, name=name, metadata=metadata) | def update_alarm(self, entity, alarm, criteria=None, disabled=False,
label=None, name=None, metadata=None) | Updates an existing alarm on the given entity. | 2.208244 | 2.400903 | 0.919756 |
return entity.list_alarms(limit=limit, marker=marker,
return_next=return_next) | def list_alarms(self, entity, limit=None, marker=None, return_next=False) | Returns a list of all the alarms created on the specified entity. | 3.508859 | 3.732497 | 0.940083 |
req_method = req_methods[method.upper()]
raise_exception = kwargs.pop("raise_exception", True)
raw_content = kwargs.pop("raw_content", False)
kwargs["headers"] = kwargs.get("headers", {})
http_log_req(method, uri, args, kwargs)
data = None
if "data" in kwargs:
# The 'data' kwarg is used when you don't want json encoding.
data = kwargs.pop("data")
elif "body" in kwargs:
if "Content-Type" not in kwargs["headers"]:
kwargs["headers"]["Content-Type"] = "application/json"
data = json.dumps(kwargs.pop("body"))
if data:
resp = req_method(uri, data=data, **kwargs)
else:
resp = req_method(uri, **kwargs)
if raw_content:
body = resp.content
else:
try:
body = resp.json()
except ValueError:
# No JSON in response
body = resp.content
http_log_resp(resp, body)
if resp.status_code >= 400 and raise_exception:
raise exc.from_response(resp, body)
return resp, body | def request(method, uri, *args, **kwargs) | Handles all the common functionality required for API calls. Returns
the resulting response object.
Formats the request into a dict representing the headers
and body that will be used to make the API call. | 2.233132 | 2.372272 | 0.941347 |
if not pyrax.get_http_debug():
return
string_parts = ["curl -i -X %s" % method]
for element in args:
string_parts.append("%s" % element)
for element in kwargs["headers"]:
header = "-H '%s: %s'" % (element, kwargs["headers"][element])
string_parts.append(header)
string_parts.append(uri)
log = logging.getLogger("pyrax")
log.debug("\nREQ: %s\n" % " ".join(string_parts))
if "body" in kwargs:
pyrax._logger.debug("REQ BODY: %s\n" % (kwargs["body"]))
if "data" in kwargs:
pyrax._logger.debug("REQ DATA: %s\n" % (kwargs["data"])) | def http_log_req(method, uri, args, kwargs) | When pyrax.get_http_debug() is True, outputs the equivalent `curl`
command for the API request being made. | 2.498943 | 2.236676 | 1.117258 |
if not pyrax.get_http_debug():
return
log = logging.getLogger("pyrax")
log.debug("RESP: %s\n%s", resp, resp.headers)
if body:
log.debug("RESP BODY: %s", body) | def http_log_resp(resp, body) | When pyrax.get_http_debug() is True, outputs the response received
from the API request. | 4.19211 | 3.05744 | 1.371117 |
@wraps(fnc)
def _wrapped(self, container, *args, **kwargs):
if not isinstance(container, Container):
# Must be the name
container = self.get(container)
return fnc(self, container, *args, **kwargs)
return _wrapped | def assure_container(fnc) | Assures that whether a Container or a name of a container is passed, a
Container object is available. | 2.597459 | 2.427022 | 1.070225 |
lowprefix = prfx.lower()
ret = {}
for k, v in list(dct.items()):
if not k.lower().startswith(lowprefix):
k = "%s%s" % (prfx, k)
ret[k] = v
return ret | def _massage_metakeys(dct, prfx) | Returns a copy of the supplied dictionary, prefixing any keys that do
not begin with the specified prefix accordingly. | 2.545313 | 2.269399 | 1.12158 |
currpos = fileobj.tell()
fileobj.seek(0, 2)
total_size = fileobj.tell()
fileobj.seek(currpos)
return total_size | def get_file_size(fileobj) | Returns the size of a file-like object. | 2.236514 | 2.14479 | 1.042766 |
if self._cdn_enabled is FAULT:
self._cdn_enabled = False
self._cdn_uri = None
self._cdn_ttl = DEFAULT_CDN_TTL
self._cdn_ssl_uri = None
self._cdn_streaming_uri = None
self._cdn_ios_uri = None
self._cdn_log_retention = False | def _set_cdn_defaults(self) | Sets all the CDN-related attributes to default values. | 4.425142 | 3.832247 | 1.154712 |
if self._cdn_enabled is FAULT:
headers = self.manager.fetch_cdn_data(self)
else:
headers = {}
# Set defaults in case not all headers are present.
self._set_cdn_defaults()
if not headers:
# Not CDN enabled; return
return
else:
self._cdn_enabled = True
for key, value in headers.items():
low_key = key.lower()
if low_key == "x-cdn-uri":
self._cdn_uri = value
elif low_key == "x-ttl":
self._cdn_ttl = int(value)
elif low_key == "x-cdn-ssl-uri":
self._cdn_ssl_uri = value
elif low_key == "x-cdn-streaming-uri":
self._cdn_streaming_uri = value
elif low_key == "x-cdn-ios-uri":
self._cdn_ios_uri = value
elif low_key == "x-log-retention":
self._cdn_log_retention = (value == "True") | def _fetch_cdn_data(self) | Fetches the container's CDN data from the CDN service | 3.0801 | 2.9155 | 1.056457 |
return self.manager.set_metadata(self, metadata, clear=clear,
prefix=prefix) | def set_metadata(self, metadata, clear=False, prefix=None) | Accepts a dictionary of metadata key/value pairs and updates the
specified container metadata with them.
If 'clear' is True, any existing metadata is deleted and only the
passed metadata is retained. Otherwise, the values passed here update
the container's metadata.
The 'extra_info' parameter is included for backwards compatibility. It
is no longer used at all, and will not be modified with swiftclient
info, since swiftclient is not used any more.
By default, the standard container metadata prefix
('X-Container-Meta-') is prepended to the header name if it isn't
present. For non-standard headers, you must include a non-None prefix,
such as an empty string. | 4.866178 | 7.102906 | 0.685097 |
return self.object_manager.purge(obj, email_addresses=email_addresses) | def purge_cdn_object(self, obj, email_addresses=None) | Removes a CDN-enabled object from public access before the TTL expires.
Please note that there is a limit (at this time) of 25 such requests;
if you need to purge more than that, you must contact support.
If one or more email_addresses are included, an email confirming the
purge is sent to each address. | 4.713837 | 6.908374 | 0.682337 |
if isinstance(item, six.string_types):
item = self.object_manager.get(item)
return item | def get_object(self, item) | Returns a StorageObject matching the specified item. If no such object
exists, a NotFound exception is raised. If 'item' is not a string, that
item is returned unchanged. | 3.501474 | 3.960965 | 0.883995 |
if full_listing:
return self.list_all(prefix=prefix)
else:
return self.object_manager.list(marker=marker, limit=limit,
prefix=prefix, delimiter=delimiter, end_marker=end_marker,
return_raw=return_raw) | def list(self, marker=None, limit=None, prefix=None, delimiter=None,
end_marker=None, full_listing=False, return_raw=False) | List the objects in this container, using the parameters to control the
number and content of objects. Note that this is limited by the
absolute request limits of Swift (currently 10,000 objects). If you
need to list all objects in the container, use the `list_all()` method
instead. | 2.283573 | 2.406268 | 0.94901 |
if full_listing:
objects = self.list_all(prefix=prefix)
else:
objects = self.list(marker=marker, limit=limit, prefix=prefix,
delimiter=delimiter, end_marker=end_marker)
return [obj.name for obj in objects] | def list_object_names(self, marker=None, limit=None, prefix=None,
delimiter=None, end_marker=None, full_listing=False) | Returns a list of the names of all the objects in this container. The
same pagination parameters apply as in self.list(). | 2.040839 | 2.058083 | 0.991622 |
return self.object_manager.create(file_or_path=file_or_path,
data=data, obj_name=obj_name, content_type=content_type,
etag=etag, content_encoding=content_encoding,
content_length=content_length, ttl=ttl, chunked=chunked,
metadata=metadata, chunk_size=chunk_size, headers=headers,
return_none=return_none) | def create(self, file_or_path=None, data=None, obj_name=None,
content_type=None, etag=None, content_encoding=None,
content_length=None, ttl=None, chunked=False, metadata=None,
chunk_size=None, headers=None, return_none=False) | Creates or replaces a storage object in this container.
The content of the object can either be a stream of bytes (`data`), or
a file on disk (`file_or_path`). The disk file can be either an open
file-like object, or an absolute path to the file on disk.
When creating object from a data stream, you must specify the name of
the object to be created in the container via the `obj_name` parameter.
When working with a file, though, if no `obj_name` value is specified,
the file`s name will be used.
You may optionally set the `content_type` and `content_encoding`
parameters; pyrax will create the appropriate headers when the object
is stored. If no `content_type` is specified, the object storage system
will make an intelligent guess based on the content of the object.
If the size of the file is known, it can be passed as `content_length`.
If you wish for the object to be temporary, specify the time it should
be stored in seconds in the `ttl` parameter. If this is specified, the
object will be deleted after that number of seconds.
If you wish to store a stream of data (i.e., where you don't know the
total size in advance), set the `chunked` parameter to True, and omit
the `content_length` and `etag` parameters. This allows the data to be
streamed to the object in the container without having to be written to
disk first. | 1.397953 | 1.658199 | 0.843055 |
return self.create(obj_name=obj_name, data=data,
content_type=content_type, etag=etag,
content_encoding=content_encoding, ttl=ttl,
return_none=return_none, headers=headers) | def store_object(self, obj_name, data, content_type=None, etag=None,
content_encoding=None, ttl=None, return_none=False,
headers=None, extra_info=None) | Creates a new object in this container, and populates it with the given
data. A StorageObject reference to the uploaded file will be returned,
unless 'return_none' is set to True.
The 'extra_info' parameter is included for backwards compatibility. It
is no longer used at all, and will not be modified with swiftclient
info, since swiftclient is not used any more. | 1.778419 | 2.163383 | 0.822055 |
return self.create(file_or_path=file_or_path, obj_name=obj_name,
content_type=content_type, etag=etag,
content_encoding=content_encoding, headers=headers,
content_length=content_length, ttl=ttl,
return_none=return_none) | def upload_file(self, file_or_path, obj_name=None, content_type=None,
etag=None, return_none=False, content_encoding=None, ttl=None,
content_length=None, headers=None) | Uploads the specified file to this container. If no name is supplied,
the file's name will be used. Either a file path or an open file-like
object may be supplied. A StorageObject reference to the uploaded file
will be returned, unless 'return_none' is set to True.
You may optionally set the `content_type` and `content_encoding`
parameters; pyrax will create the appropriate headers when the object
is stored.
If the size of the file is known, it can be passed as `content_length`.
If you wish for the object to be temporary, specify the time it should
be stored in seconds in the `ttl` parameter. If this is specified, the
object will be deleted after that number of seconds.
The 'extra_info' parameter is included for backwards compatibility. It
is no longer used at all, and will not be modified with swiftclient
info, since swiftclient is not used any more. | 1.747714 | 2.17236 | 0.804523 |
return self.object_manager.fetch(obj, include_meta=include_meta,
chunk_size=chunk_size, size=size) | def fetch(self, obj, include_meta=False, chunk_size=None, size=None,
extra_info=None) | Fetches the object from storage.
If 'include_meta' is False, only the bytes representing the
stored object are returned.
Note: if 'chunk_size' is defined, you must fully read the object's
contents before making another request.
If 'size' is specified, only the first 'size' bytes of the object will
be returned. If the object if smaller than 'size', the entire object is
returned.
When 'include_meta' is True, what is returned from this method is a
2-tuple:
Element 0: a dictionary containing metadata about the file.
Element 1: a stream of bytes representing the object's contents.
The 'extra_info' parameter is included for backwards compatibility. It
is no longer used at all, and will not be modified with swiftclient
info, since swiftclient is not used any more. | 2.916407 | 3.760594 | 0.775518 |
return self.fetch(obj=obj_name, include_meta=include_meta,
chunk_size=chunk_size) | def fetch_object(self, obj_name, include_meta=False, chunk_size=None) | Alias for self.fetch(); included for backwards compatibility | 3.646492 | 2.892579 | 1.260637 |
return self.object_manager.download(obj, directory, structure=structure) | def download(self, obj, directory, structure=True) | Fetches the object from storage, and writes it to the specified
directory. The directory must exist before calling this method.
If the object name represents a nested folder structure, such as
"foo/bar/baz.txt", that folder structure will be created in the target
directory by default. If you do not want the nested folders to be
created, pass `structure=False` in the parameters. | 5.247533 | 7.174352 | 0.73143 |
return self.download(obj=obj_name, directory=directory,
structure=structure) | def download_object(self, obj_name, directory, structure=True) | Alias for self.download(); included for backwards compatibility | 5.642015 | 4.721846 | 1.194875 |
return self.manager.delete(self, del_objects=del_objects) | def delete(self, del_objects=False) | Deletes this Container. If the container contains objects, the
command will fail unless 'del_objects' is passed as True. In that
case, each object will be deleted first, and then the container. | 5.171308 | 4.855065 | 1.065137 |
return self.manager.delete_object_in_seconds(self, obj, seconds) | def delete_object_in_seconds(self, obj, seconds, extra_info=None) | Sets the object in this container to be deleted after the specified
number of seconds.
The 'extra_info' parameter is included for backwards compatibility. It
is no longer used at all, and will not be modified with swiftclient
info, since swiftclient is not used any more. | 4.988772 | 5.295601 | 0.94206 |
nms = self.list_object_names(full_listing=True)
return self.object_manager.delete_all_objects(nms, async_=async_) | def delete_all_objects(self, async_=False) | Deletes all objects from this container.
By default the call will block until all objects have been deleted. By
passing True for the 'async_' parameter, this method will not block, and
instead return an object that can be used to follow the progress of the
deletion. When deletion is complete the bulk deletion object's
'results' attribute will be populated with the information returned
from the API call. In synchronous mode this is the value that is
returned when the call completes. It is a dictionary with the following
keys:
deleted - the number of objects deleted
not_found - the number of objects not found
status - the HTTP return status code. '200 OK' indicates success
errors - a list of any errors returned by the bulk delete call | 5.836686 | 8.261683 | 0.706477 |
return self.manager.copy_object(self, obj, new_container,
new_obj_name=new_obj_name, content_type=content_type) | def copy_object(self, obj, new_container, new_obj_name=None,
content_type=None) | Copies the object to the new container, optionally giving it a new name.
If you copy to the same container, you must supply a different name. | 2.113438 | 2.258848 | 0.935626 |
return self.manager.move_object(self, obj, new_container,
new_obj_name=new_obj_name, new_reference=new_reference,
content_type=content_type) | def move_object(self, obj, new_container, new_obj_name=None,
new_reference=False, content_type=None, extra_info=None) | Works just like copy_object, except that the source object is deleted
after a successful copy.
You can optionally change the content_type of the object by supplying
that in the 'content_type' parameter.
NOTE: any references to the original object will no longer be valid;
you will have to get a reference to the new object by passing True for
the 'new_reference' parameter. When this is True, a reference to the
newly moved object is returned. Otherwise, the etag for the moved
object is returned.
The 'extra_info' parameter is included for backwards compatibility. It
is no longer used at all, and will not be modified with swiftclient
info, since swiftclient is not used any more. | 1.942966 | 2.362956 | 0.822261 |
return self.manager.change_object_content_type(self, obj, new_ctype,
guess=guess) | def change_object_content_type(self, obj, new_ctype, guess=False) | Copies object to itself, but applies a new content-type. The guess
feature requires this container to be CDN-enabled. If not, then the
content-type must be supplied. If using guess with a CDN-enabled
container, new_ctype can be set to None. Failure during the put will
result in an exception. | 3.628562 | 3.683116 | 0.985188 |
return self.manager.get_temp_url(self, obj, seconds, method=method,
key=key, cached=cached) | def get_temp_url(self, obj, seconds, method="GET", key=None, cached=True) | Given a storage object in this container, returns a URL that can be
used to access that object. The URL will expire after `seconds`
seconds.
The only methods supported are GET and PUT. Anything else will raise an
`InvalidTemporaryURLMethod` exception.
If you have your Temporary URL key, you can pass it in directly and
potentially save an API call to retrieve it. If you don't pass in the
key, and don't wish to use any cached value, pass `cached=False`. | 3.194319 | 3.619155 | 0.882614 |
return self.object_manager.set_metadata(obj, metadata, clear=clear,
prefix=prefix) | def set_object_metadata(self, obj, metadata, clear=False, extra_info=None,
prefix=None) | Accepts a dictionary of metadata key/value pairs and updates the
specified object metadata with them.
If 'clear' is True, any existing metadata is deleted and only the
passed metadata is retained. Otherwise, the values passed here update
the object's metadata.
The 'extra_info' parameter is included for backwards compatibility. It
is no longer used at all, and will not be modified with swiftclient
info, since swiftclient is not used any more.
By default, the standard object metadata prefix ('X-Object-Meta-') is
prepended to the header name if it isn't present. For non-standard
headers, you must include a non-None prefix, such as an empty string. | 3.691661 | 6.16546 | 0.598765 |
return self.manager.list_subdirs(self, marker=marker, limit=limit,
prefix=prefix, delimiter=delimiter, full_listing=full_listing) | def list_subdirs(self, marker=None, limit=None, prefix=None, delimiter=None,
full_listing=False) | Return a list of the namesrepresenting the pseudo-subdirectories in
this container. You can use the marker and limit params to handle
pagination, and the prefix param to filter the objects returned. The
delimiter param is there for backwards compatibility only, as the call
requires the delimiter to be '/'. | 2.195441 | 2.322937 | 0.945114 |
uri = "/%s" % self.uri_base
qs = utils.dict_to_qs({"marker": marker, "limit": limit,
"prefix": prefix, "end_marker": end_marker})
if qs:
uri = "%s?%s" % (uri, qs)
resp, resp_body = self.api.method_get(uri)
return [Container(self, res, loaded=False)
for res in resp_body if res] | def list(self, limit=None, marker=None, end_marker=None, prefix=None) | Swift doesn't return listings in the same format as the rest of
OpenStack, so this method has to be overriden. | 2.778885 | 2.826054 | 0.983309 |
name = utils.get_name(container)
uri = "/%s" % name
resp, resp_body = self.api.method_head(uri)
hdrs = resp.headers
data = {"total_bytes": int(hdrs.get("x-container-bytes-used", "0")),
"object_count": int(hdrs.get("x-container-object-count", "0")),
"name": name}
return Container(self, data, loaded=False) | def get(self, container) | Returns a Container matching the specified container name. If no such
container exists, a NoSuchContainer exception is raised. | 3.301518 | 3.108837 | 1.061979 |
uri = "/%s" % name
headers = {}
if prefix is None:
prefix = CONTAINER_META_PREFIX
if metadata:
metadata = _massage_metakeys(metadata, prefix)
headers = metadata
resp, resp_body = self.api.method_put(uri, headers=headers)
if resp.status_code in (201, 202):
hresp, hresp_body = self.api.method_head(uri)
num_obj = int(hresp.headers.get("x-container-object-count", "0"))
num_bytes = int(hresp.headers.get("x-container-bytes-used", "0"))
cont_info = {"name": name, "object_count": num_obj,
"total_bytes": num_bytes}
return Container(self, cont_info)
elif resp.status_code == 400:
raise exc.ClientException("Container creation failed: %s" %
resp_body) | def create(self, name, metadata=None, prefix=None, *args, **kwargs) | Creates a new container, and returns a Container object that represents
that contianer. If a container by the same name already exists, no
exception is raised; instead, a reference to that existing container is
returned. | 2.702878 | 2.641565 | 1.023211 |
if del_objects:
nms = self.list_object_names(container, full_listing=True)
self.api.bulk_delete(container, nms, async_=False)
uri = "/%s" % utils.get_name(container)
resp, resp_body = self.api.method_delete(uri) | def delete(self, container, del_objects=False) | Deletes the specified container. If the container contains objects, the
command will fail unless 'del_objects' is passed as True. In that case,
each object will be deleted first, and then the container. | 5.287499 | 5.452891 | 0.969669 |
name = utils.get_name(container)
uri = "/%s" % name
try:
resp, resp_body = self.api.cdn_request(uri, "HEAD")
except exc.NotCDNEnabled:
return {}
return resp.headers | def fetch_cdn_data(self, container) | Returns a dict containing the CDN information for the specified
container. If the container is not CDN-enabled, returns an empty dict. | 6.89507 | 5.785701 | 1.191743 |
uri = "/%s" % utils.get_name(container)
resp, resp_body = self.api.method_head(uri)
return resp.headers | def get_headers(self, container) | Return the headers for the specified container. | 6.793489 | 5.876706 | 1.156003 |
headers = self.get_account_headers()
if prefix is None:
prefix = ACCOUNT_META_PREFIX
low_prefix = prefix.lower()
ret = {}
for hkey, hval in list(headers.items()):
lowkey = hkey.lower()
if lowkey.startswith(low_prefix):
cleaned = hkey.replace(low_prefix, "").replace("-", "_")
ret[cleaned] = hval
return ret | def get_account_metadata(self, prefix=None) | Returns a dictionary containing metadata about the account. | 3.051358 | 3.002384 | 1.016312 |
# Add the metadata prefix, if needed.
if prefix is None:
prefix = ACCOUNT_META_PREFIX
massaged = _massage_metakeys(metadata, prefix)
new_meta = {}
if clear:
curr_meta = self.get_account_metadata(prefix=prefix)
for ckey in curr_meta:
new_meta[ckey] = ""
new_meta = _massage_metakeys(new_meta, prefix)
utils.case_insensitive_update(new_meta, massaged)
uri = "/"
resp, resp_body = self.api.method_post(uri, headers=new_meta)
return 200 <= resp.status_code <= 299 | def set_account_metadata(self, metadata, clear=False, prefix=None) | Accepts a dictionary of metadata key/value pairs and updates the
account metadata with them.
If 'clear' is True, any existing metadata is deleted and only the
passed metadata is retained. Otherwise, the values passed here update
the account's metadata.
By default, the standard account metadata prefix ('X-Account-Meta-') is
prepended to the header name if it isn't present. For non-standard
headers, you must include a non-None prefix, such as an empty string. | 3.615162 | 3.723364 | 0.97094 |
# Add the metadata prefix, if needed.
if prefix is None:
prefix = ACCOUNT_META_PREFIX
curr_meta = self.get_account_metadata(prefix=prefix)
for ckey in curr_meta:
curr_meta[ckey] = ""
new_meta = _massage_metakeys(curr_meta, prefix)
uri = "/"
resp, resp_body = self.api.method_post(uri, headers=new_meta)
return 200 <= resp.status_code <= 299 | def delete_account_metadata(self, prefix=None) | Removes all metadata matching the specified prefix from the account.
By default, the standard account metadata prefix ('X-Account-Meta-') is
prepended to the header name if it isn't present. For non-standard
headers, you must include a non-None prefix, such as an empty string. | 4.449277 | 4.086795 | 1.088696 |
headers = self.get_headers(container)
if prefix is None:
prefix = CONTAINER_META_PREFIX
low_prefix = prefix.lower()
ret = {}
for hkey, hval in list(headers.items()):
if hkey.lower().startswith(low_prefix):
cleaned = hkey.replace(low_prefix, "").replace("-", "_")
ret[cleaned] = hval
return ret | def get_metadata(self, container, prefix=None) | Returns a dictionary containing the metadata for the container. | 2.863051 | 2.7575 | 1.038278 |
# Add the metadata prefix, if needed.
if prefix is None:
prefix = CONTAINER_META_PREFIX
massaged = _massage_metakeys(metadata, prefix)
new_meta = {}
if clear:
curr_meta = self.api.get_container_metadata(container,
prefix=prefix)
for ckey in curr_meta:
new_meta[ckey] = ""
utils.case_insensitive_update(new_meta, massaged)
name = utils.get_name(container)
uri = "/%s" % name
resp, resp_body = self.api.method_post(uri, headers=new_meta)
return 200 <= resp.status_code <= 299 | def set_metadata(self, container, metadata, clear=False, prefix=None) | Accepts a dictionary of metadata key/value pairs and updates the
specified container metadata with them.
If 'clear' is True, any existing metadata is deleted and only the
passed metadata is retained. Otherwise, the values passed here update
the container's metadata.
By default, the standard container metadata prefix
('X-Container-Meta-') is prepended to the header name if it isn't
present. For non-standard headers, you must include a non-None prefix,
such as an empty string. | 4.075284 | 4.132328 | 0.986196 |
meta_dict = {key: ""}
return self.set_metadata(container, meta_dict) | def remove_metadata_key(self, container, key) | Removes the specified key from the container's metadata. If the key
does not exist in the metadata, nothing is done. | 5.882987 | 5.976465 | 0.984359 |
# Add the metadata prefix, if needed.
if prefix is None:
prefix = CONTAINER_META_PREFIX
new_meta = {}
curr_meta = self.get_metadata(container, prefix=prefix)
for ckey in curr_meta:
new_meta[ckey] = ""
uri = "/%s" % utils.get_name(container)
resp, resp_body = self.api.method_post(uri, headers=new_meta)
return 200 <= resp.status_code <= 299 | def delete_metadata(self, container, prefix=None) | Removes all of the container's metadata.
By default, all metadata beginning with the standard container metadata
prefix ('X-Container-Meta-') is removed. If you wish to remove all
metadata beginning with a different prefix, you must specify that
prefix. | 3.793293 | 3.743786 | 1.013224 |
uri = "%s/%s" % (self.uri_base, utils.get_name(container))
resp, resp_body = self.api.cdn_request(uri, "HEAD")
ret = dict(resp.headers)
# Remove non-CDN headers
ret.pop("content-length", None)
ret.pop("content-type", None)
ret.pop("date", None)
return ret | def get_cdn_metadata(self, container) | Returns a dictionary containing the CDN metadata for the container. If
the container does not exist, a NotFound exception is raised. If the
container exists, but is not CDN-enabled, a NotCDNEnabled exception is
raised. | 3.795366 | 3.62568 | 1.046801 |
allowed = ("x-log-retention", "x-cdn-enabled", "x-ttl")
hdrs = {}
bad = []
for mkey, mval in six.iteritems(metadata):
if mkey.lower() not in allowed:
bad.append(mkey)
continue
hdrs[mkey] = str(mval)
if bad:
raise exc.InvalidCDNMetadata("The only CDN metadata you can "
"update are: X-Log-Retention, X-CDN-enabled, and X-TTL. "
"Received the following illegal item(s): %s" %
", ".join(bad))
uri = "%s/%s" % (self.uri_base, utils.get_name(container))
resp, resp_body = self.api.cdn_request(uri, "POST", headers=hdrs)
return resp | def set_cdn_metadata(self, container, metadata) | Accepts a dictionary of metadata key/value pairs and updates
the specified container metadata with them.
NOTE: arbitrary metadata headers are not allowed. The only metadata
you can update are: X-Log-Retention, X-CDN-enabled, and X-TTL. | 3.735956 | 2.94172 | 1.26999 |
if not key:
key = self.api.get_temp_url_key(cached=cached)
if not key:
raise exc.MissingTemporaryURLKey("You must set the key for "
"Temporary URLs before you can generate them. This is "
"done via the `set_temp_url_key()` method.")
cname = utils.get_name(container)
oname = utils.get_name(obj)
mod_method = method.upper().strip()
if mod_method not in ("GET", "PUT"):
raise exc.InvalidTemporaryURLMethod("Method must be either 'GET' "
"or 'PUT'; received '%s'." % method)
mgt_url = self.api.management_url
mtch = re.search(r"/v\d/", mgt_url)
start = mtch.start()
base_url = mgt_url[:start]
path_parts = (mgt_url[start:], cname, oname)
cleaned = (part.strip("/\\") for part in path_parts)
pth = "/%s" % "/".join(cleaned)
expires = int(time.time() + int(seconds))
try:
key = key.encode("ascii")
hmac_body = b'\n'.join([
mod_method.encode("ascii"),
six.text_type(expires).encode("ascii"),
pth.encode("ascii")])
except UnicodeEncodeError:
raise exc.UnicodePathError("Due to a bug in Python, the TempURL "
"function only works with ASCII object paths.")
sig = hmac.new(key, hmac_body, hashlib.sha1).hexdigest()
temp_url = "%s%s?temp_url_sig=%s&temp_url_expires=%s" % (base_url, pth,
sig, expires)
return temp_url | def get_temp_url(self, container, obj, seconds, method="GET", key=None,
cached=True) | Given a storage object in a container, returns a URL that can be used
to access that object. The URL will expire after `seconds` seconds.
The only methods supported are GET and PUT. Anything else will raise
an `InvalidTemporaryURLMethod` exception.
If you have your Temporary URL key, you can pass it in directly and
potentially save an API call to retrieve it. If you don't pass in the
key, and don't wish to use any cached value, pass `cached=False`. | 3.133654 | 3.020355 | 1.037512 |
uri = ""
qs = utils.dict_to_qs({"limit": limit, "marker": marker})
if qs:
uri += "%s?%s" % (uri, qs)
resp, resp_body = self.api.method_get(uri)
return resp_body | def list_containers_info(self, limit=None, marker=None) | Returns a list of info on Containers.
For each container, a dict containing the following keys is returned:
\code
name - the name of the container
count - the number of objects in the container
bytes - the total bytes in the container | 3.327862 | 4.164642 | 0.799075 |
resp, resp_body = self.api.cdn_request("", "GET")
return [cont["name"] for cont in resp_body] | def list_public_containers(self) | Returns a list of the names of all CDN-enabled containers. | 10.030361 | 7.455032 | 1.345448 |
return self._set_cdn_access(container, public=True, ttl=ttl) | def make_public(self, container, ttl=None) | Enables CDN access for the specified container, and optionally sets the
TTL for the container. | 8.345279 | 7.100483 | 1.175311 |
headers = {"X-Cdn-Enabled": "%s" % public}
if public and ttl:
headers["X-Ttl"] = ttl
self.api.cdn_request("/%s" % utils.get_name(container), method="PUT",
headers=headers) | def _set_cdn_access(self, container, public, ttl=None) | Enables or disables CDN access for the specified container, and
optionally sets the TTL for the container when enabling access. | 5.409297 | 5.576882 | 0.96995 |
resp, resp_body = self.api.cdn_request("/%s" %
utils.get_name(container), method="HEAD")
return resp.headers.get("x-log-retention").lower() == "true" | def get_cdn_log_retention(self, container) | Returns the status of the setting for CDN log retention for the
specified container. | 7.484463 | 7.169077 | 1.043993 |
headers = {"X-Log-Retention": "%s" % enabled}
self.api.cdn_request("/%s" % utils.get_name(container), method="PUT",
headers=headers) | def set_cdn_log_retention(self, container, enabled) | Enables or disables whether CDN access logs for the specified container
are collected and stored on Cloud Files. | 7.241856 | 8.666462 | 0.835618 |
resp, resp_body = self.api.cdn_request("/%s" %
utils.get_name(container), method="HEAD")
return resp.headers.get("x-cdn-streaming-uri") | def get_container_streaming_uri(self, container) | Returns the URI for streaming content, or None if CDN is not enabled. | 6.720443 | 6.194709 | 1.084868 |
headers = {"X-Container-Meta-Web-Index": "%s" % page}
self.api.cdn_request("/%s" % utils.get_name(container), method="POST",
headers=headers) | def set_web_index_page(self, container, page) | Sets the header indicating the index page in a container
when creating a static website.
Note: the container must be CDN-enabled for this to have
any effect. | 6.746918 | 6.399907 | 1.054221 |
return container.purge_cdn_object(obj, email_addresses=email_addresses) | def purge_cdn_object(self, container, obj, email_addresses=None) | Removes a CDN-enabled object from public access before the TTL expires.
Please note that there is a limit (at this time) of 25 such requests;
if you need to purge more than that, you must contact support.
If one or more email_addresses are included, an email confirming the
purge is sent to each address. | 4.020076 | 4.791051 | 0.83908 |
if full_listing:
return container.list_all(prefix=prefix)
return container.list(limit=limit, marker=marker, prefix=prefix,
delimiter=delimiter, end_marker=end_marker) | def list_objects(self, container, limit=None, marker=None, prefix=None,
delimiter=None, end_marker=None, full_listing=False) | Return a list of StorageObjects representing the objects in this
container. You can use the marker, end_marker, and limit params to
handle pagination, and the prefix and delimiter params to filter the
objects returned. By default only the first 10,000 objects are
returned; if you need to access more than that, set the 'full_listing'
parameter to True. | 2.392389 | 2.538234 | 0.942541 |
return container.list_object_names(marker=marker, limit=limit,
prefix=prefix, delimiter=delimiter, end_marker=end_marker,
full_listing=full_listing) | def list_object_names(self, container, marker=None, limit=None, prefix=None,
delimiter=None, end_marker=None, full_listing=False) | Return a list of then names of the objects in this container. You can
use the marker, end_marker, and limit params to handle pagination, and
the prefix and delimiter params to filter the objects returned. By
default only the first 10,000 objects are returned; if you need to
access more than that, set the 'full_listing' parameter to True. | 1.832173 | 1.963629 | 0.933055 |
mthd = container.list_all if full_listing else container.list
objs = mthd(marker=marker, limit=limit, prefix=prefix, delimiter="/",
return_raw=True)
sdirs = [obj for obj in objs if "subdir" in obj]
mgr = container.object_manager
return [StorageObject(mgr, sdir) for sdir in sdirs] | def list_subdirs(self, container, marker=None, limit=None, prefix=None,
delimiter=None, full_listing=False) | Returns a list of StorageObjects representing the pseudo-subdirectories
in the specified container. You can use the marker and limit params to
handle pagination, and the prefix param to filter the objects returned.
The 'delimiter' parameter is ignored, as the only meaningful value is
'/'. | 4.586524 | 4.304384 | 1.065547 |
return container.download(obj, directory, structure=structure) | def download_object(self, container, obj, directory, structure=True) | Fetches the object from storage, and writes it to the specified
directory. The directory must exist before calling this method.
If the object name represents a nested folder structure, such as
"foo/bar/baz.txt", that folder structure will be created in the target
directory by default. If you do not want the nested folders to be
created, pass `structure=False` in the parameters. | 6.076825 | 10.470347 | 0.580384 |
nm = new_obj_name or utils.get_name(obj)
uri = "/%s/%s" % (utils.get_name(new_container), nm)
copy_from = "/%s/%s" % (utils.get_name(container), utils.get_name(obj))
headers = {"X-Copy-From": copy_from,
"Content-Length": "0"}
if content_type:
headers["Content-Type"] = content_type
resp, resp_body = self.api.method_put(uri, headers=headers)
return resp.headers.get("etag") | def copy_object(self, container, obj, new_container, new_obj_name=None,
content_type=None) | Copies the object to the new container, optionally giving it a new name.
If you copy to the same container, you must supply a different name.
Returns the etag of the newly-copied object.
You can optionally change the content_type of the object by supplying
that in the 'content_type' parameter. | 2.421523 | 2.536612 | 0.954629 |
new_obj_etag = self.copy_object(container, obj, new_container,
new_obj_name=new_obj_name, content_type=content_type)
if not new_obj_etag:
return
# Copy succeeded; delete the original.
self.delete_object(container, obj)
if new_reference:
nm = new_obj_name or utils.get_name(obj)
return self.get_object(new_container, nm)
return new_obj_etag | def move_object(self, container, obj, new_container, new_obj_name=None,
new_reference=False, content_type=None) | Works just like copy_object, except that the source object is deleted
after a successful copy.
You can optionally change the content_type of the object by supplying
that in the 'content_type' parameter.
NOTE: any references to the original object will no longer be valid;
you will have to get a reference to the new object by passing True for
the 'new_reference' parameter. When this is True, a reference to the
newly moved object is returned. Otherwise, the etag for the moved
object is returned. | 2.80613 | 2.695873 | 1.040899 |
cname = utils.get_name(container)
oname = utils.get_name(obj)
if guess and container.cdn_enabled:
# Test against the CDN url to guess the content-type.
obj_url = "%s/%s" % (container.cdn_uri, oname)
new_ctype = mimetypes.guess_type(obj_url)[0]
return self.copy_object(container, obj, container,
content_type=new_ctype) | def change_object_content_type(self, container, obj, new_ctype,
guess=False) | Copies object to itself, but applies a new content-type. The guess
feature requires the container to be CDN-enabled. If not, then the
content-type must be supplied. If using guess with a CDN-enabled
container, new_ctype can be set to None. Failure during the put will
result in an exception. | 3.886429 | 3.386973 | 1.147464 |
meta = {"X-Delete-After": seconds}
self.set_object_metadata(cont, obj, meta, clear=True, prefix="") | def delete_object_in_seconds(self, cont, obj, seconds, extra_info=None) | Sets the object in the specified container to be deleted after the
specified number of seconds.
The 'extra_info' parameter is included for backwards compatibility. It
is no longer used at all, and will not be modified with swiftclient
info, since swiftclient is not used any more. | 9.928046 | 6.792534 | 1.461611 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.