id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
226,500 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.hammingDistance | def hammingDistance(self, tree):
'''
Finds the Hamming distance between this tree and the one passed as argument.
'''
s1 = ' '.join(map(View.__str__, self.views))
s2 = ' '.join(map(View.__str__, tree))
return ViewClient.__hammingDistance(s1, s2) | python | def hammingDistance(self, tree):
'''
Finds the Hamming distance between this tree and the one passed as argument.
'''
s1 = ' '.join(map(View.__str__, self.views))
s2 = ' '.join(map(View.__str__, tree))
return ViewClient.__hammingDistance(s1, s2) | [
"def",
"hammingDistance",
"(",
"self",
",",
"tree",
")",
":",
"s1",
"=",
"' '",
".",
"join",
"(",
"map",
"(",
"View",
".",
"__str__",
",",
"self",
".",
"views",
")",
")",
"s2",
"=",
"' '",
".",
"join",
"(",
"map",
"(",
"View",
".",
"__str__",
"... | Finds the Hamming distance between this tree and the one passed as argument. | [
"Finds",
"the",
"Hamming",
"distance",
"between",
"this",
"tree",
"and",
"the",
"one",
"passed",
"as",
"argument",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L4234-L4242 |
226,501 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.__levenshteinDistance | def __levenshteinDistance(s, t):
'''
Find the Levenshtein distance between two Strings.
Python version of Levenshtein distance method implemented in Java at
U{http://www.java2s.com/Code/Java/Data-Type/FindtheLevenshteindistancebetweentwoStrings.htm}.
This is the number of changes needed to change one String into
another, where each change is a single character modification (deletion,
insertion or substitution).
The previous implementation of the Levenshtein distance algorithm
was from U{http://www.merriampark.com/ld.htm}
Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
which can occur when my Java implementation is used with very large strings.
This implementation of the Levenshtein distance algorithm
is from U{http://www.merriampark.com/ldjava.htm}::
StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
StringUtils.getLevenshteinDistance("","") = 0
StringUtils.getLevenshteinDistance("","a") = 1
StringUtils.getLevenshteinDistance("aaapppp", "") = 7
StringUtils.getLevenshteinDistance("frog", "fog") = 1
StringUtils.getLevenshteinDistance("fly", "ant") = 3
StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
StringUtils.getLevenshteinDistance("hello", "hallo") = 1
@param s: the first String, must not be null
@param t: the second String, must not be null
@return: result distance
@raise ValueError: if either String input C{null}
'''
if s is None or t is None:
raise ValueError("Strings must not be null")
n = len(s)
m = len(t)
if n == 0:
return m
elif m == 0:
return n
if n > m:
tmp = s
s = t
t = tmp
n = m;
m = len(t)
p = [None]*(n+1)
d = [None]*(n+1)
for i in range(0, n+1):
p[i] = i
for j in range(1, m+1):
if DEBUG_DISTANCE:
if j % 100 == 0:
print >>sys.stderr, "DEBUG:", int(j/(m+1.0)*100),"%\r",
t_j = t[j-1]
d[0] = j
for i in range(1, n+1):
cost = 0 if s[i-1] == t_j else 1
# minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = min(min(d[i-1]+1, p[i]+1), p[i-1]+cost)
_d = p
p = d
d = _d
if DEBUG_DISTANCE:
print >> sys.stderr, "\n"
return p[n] | python | def __levenshteinDistance(s, t):
'''
Find the Levenshtein distance between two Strings.
Python version of Levenshtein distance method implemented in Java at
U{http://www.java2s.com/Code/Java/Data-Type/FindtheLevenshteindistancebetweentwoStrings.htm}.
This is the number of changes needed to change one String into
another, where each change is a single character modification (deletion,
insertion or substitution).
The previous implementation of the Levenshtein distance algorithm
was from U{http://www.merriampark.com/ld.htm}
Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
which can occur when my Java implementation is used with very large strings.
This implementation of the Levenshtein distance algorithm
is from U{http://www.merriampark.com/ldjava.htm}::
StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
StringUtils.getLevenshteinDistance("","") = 0
StringUtils.getLevenshteinDistance("","a") = 1
StringUtils.getLevenshteinDistance("aaapppp", "") = 7
StringUtils.getLevenshteinDistance("frog", "fog") = 1
StringUtils.getLevenshteinDistance("fly", "ant") = 3
StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
StringUtils.getLevenshteinDistance("hello", "hallo") = 1
@param s: the first String, must not be null
@param t: the second String, must not be null
@return: result distance
@raise ValueError: if either String input C{null}
'''
if s is None or t is None:
raise ValueError("Strings must not be null")
n = len(s)
m = len(t)
if n == 0:
return m
elif m == 0:
return n
if n > m:
tmp = s
s = t
t = tmp
n = m;
m = len(t)
p = [None]*(n+1)
d = [None]*(n+1)
for i in range(0, n+1):
p[i] = i
for j in range(1, m+1):
if DEBUG_DISTANCE:
if j % 100 == 0:
print >>sys.stderr, "DEBUG:", int(j/(m+1.0)*100),"%\r",
t_j = t[j-1]
d[0] = j
for i in range(1, n+1):
cost = 0 if s[i-1] == t_j else 1
# minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = min(min(d[i-1]+1, p[i]+1), p[i-1]+cost)
_d = p
p = d
d = _d
if DEBUG_DISTANCE:
print >> sys.stderr, "\n"
return p[n] | [
"def",
"__levenshteinDistance",
"(",
"s",
",",
"t",
")",
":",
"if",
"s",
"is",
"None",
"or",
"t",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Strings must not be null\"",
")",
"n",
"=",
"len",
"(",
"s",
")",
"m",
"=",
"len",
"(",
"t",
")",
"i... | Find the Levenshtein distance between two Strings.
Python version of Levenshtein distance method implemented in Java at
U{http://www.java2s.com/Code/Java/Data-Type/FindtheLevenshteindistancebetweentwoStrings.htm}.
This is the number of changes needed to change one String into
another, where each change is a single character modification (deletion,
insertion or substitution).
The previous implementation of the Levenshtein distance algorithm
was from U{http://www.merriampark.com/ld.htm}
Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
which can occur when my Java implementation is used with very large strings.
This implementation of the Levenshtein distance algorithm
is from U{http://www.merriampark.com/ldjava.htm}::
StringUtils.getLevenshteinDistance(null, *) = IllegalArgumentException
StringUtils.getLevenshteinDistance(*, null) = IllegalArgumentException
StringUtils.getLevenshteinDistance("","") = 0
StringUtils.getLevenshteinDistance("","a") = 1
StringUtils.getLevenshteinDistance("aaapppp", "") = 7
StringUtils.getLevenshteinDistance("frog", "fog") = 1
StringUtils.getLevenshteinDistance("fly", "ant") = 3
StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
StringUtils.getLevenshteinDistance("hello", "hallo") = 1
@param s: the first String, must not be null
@param t: the second String, must not be null
@return: result distance
@raise ValueError: if either String input C{null} | [
"Find",
"the",
"Levenshtein",
"distance",
"between",
"two",
"Strings",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L4245-L4323 |
226,502 | dtmilano/AndroidViewClient | src/com/dtmilano/android/viewclient.py | ViewClient.levenshteinDistance | def levenshteinDistance(self, tree):
'''
Finds the Levenshtein distance between this tree and the one passed as argument.
'''
s1 = ' '.join(map(View.__microStr__, self.views))
s2 = ' '.join(map(View.__microStr__, tree))
return ViewClient.__levenshteinDistance(s1, s2) | python | def levenshteinDistance(self, tree):
'''
Finds the Levenshtein distance between this tree and the one passed as argument.
'''
s1 = ' '.join(map(View.__microStr__, self.views))
s2 = ' '.join(map(View.__microStr__, tree))
return ViewClient.__levenshteinDistance(s1, s2) | [
"def",
"levenshteinDistance",
"(",
"self",
",",
"tree",
")",
":",
"s1",
"=",
"' '",
".",
"join",
"(",
"map",
"(",
"View",
".",
"__microStr__",
",",
"self",
".",
"views",
")",
")",
"s2",
"=",
"' '",
".",
"join",
"(",
"map",
"(",
"View",
".",
"__mi... | Finds the Levenshtein distance between this tree and the one passed as argument. | [
"Finds",
"the",
"Levenshtein",
"distance",
"between",
"this",
"tree",
"and",
"the",
"one",
"passed",
"as",
"argument",
"."
] | 7e6e83fde63af99e5e4ab959712ecf94f9881aa2 | https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L4325-L4333 |
226,503 | minio/minio-py | minio/thread_pool.py | Worker.run | def run(self):
""" Continously receive tasks and execute them """
while True:
task = self.tasks_queue.get()
if task is None:
self.tasks_queue.task_done()
break
# No exception detected in any thread,
# continue the execution.
if self.exceptions_queue.empty():
try:
# Execute the task
func, args, kargs = task
result = func(*args, **kargs)
self.results_queue.put(result)
except Exception as e:
self.exceptions_queue.put(e)
# Mark this task as done, whether an exception happened or not
self.tasks_queue.task_done() | python | def run(self):
while True:
task = self.tasks_queue.get()
if task is None:
self.tasks_queue.task_done()
break
# No exception detected in any thread,
# continue the execution.
if self.exceptions_queue.empty():
try:
# Execute the task
func, args, kargs = task
result = func(*args, **kargs)
self.results_queue.put(result)
except Exception as e:
self.exceptions_queue.put(e)
# Mark this task as done, whether an exception happened or not
self.tasks_queue.task_done() | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"task",
"=",
"self",
".",
"tasks_queue",
".",
"get",
"(",
")",
"if",
"task",
"is",
"None",
":",
"self",
".",
"tasks_queue",
".",
"task_done",
"(",
")",
"break",
"# No exception detected in any th... | Continously receive tasks and execute them | [
"Continously",
"receive",
"tasks",
"and",
"execute",
"them"
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/thread_pool.py#L44-L62 |
226,504 | minio/minio-py | minio/thread_pool.py | ThreadPool.add_task | def add_task(self, func, *args, **kargs):
""" Add a task to the queue """
self.tasks_queue.put((func, args, kargs)) | python | def add_task(self, func, *args, **kargs):
self.tasks_queue.put((func, args, kargs)) | [
"def",
"add_task",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"self",
".",
"tasks_queue",
".",
"put",
"(",
"(",
"func",
",",
"args",
",",
"kargs",
")",
")"
] | Add a task to the queue | [
"Add",
"a",
"task",
"to",
"the",
"queue"
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/thread_pool.py#L73-L75 |
226,505 | minio/minio-py | minio/thread_pool.py | ThreadPool.start_parallel | def start_parallel(self):
""" Prepare threads to run tasks"""
for _ in range(self.num_threads):
Worker(self.tasks_queue, self.results_queue, self.exceptions_queue) | python | def start_parallel(self):
for _ in range(self.num_threads):
Worker(self.tasks_queue, self.results_queue, self.exceptions_queue) | [
"def",
"start_parallel",
"(",
"self",
")",
":",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"num_threads",
")",
":",
"Worker",
"(",
"self",
".",
"tasks_queue",
",",
"self",
".",
"results_queue",
",",
"self",
".",
"exceptions_queue",
")"
] | Prepare threads to run tasks | [
"Prepare",
"threads",
"to",
"run",
"tasks"
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/thread_pool.py#L77-L80 |
226,506 | minio/minio-py | minio/thread_pool.py | ThreadPool.result | def result(self):
""" Stop threads and return the result of all called tasks """
# Send None to all threads to cleanly stop them
for _ in range(self.num_threads):
self.tasks_queue.put(None)
# Wait for completion of all the tasks in the queue
self.tasks_queue.join()
# Check if one of the thread raised an exception, if yes
# raise it here in the function
if not self.exceptions_queue.empty():
raise self.exceptions_queue.get()
return self.results_queue | python | def result(self):
# Send None to all threads to cleanly stop them
for _ in range(self.num_threads):
self.tasks_queue.put(None)
# Wait for completion of all the tasks in the queue
self.tasks_queue.join()
# Check if one of the thread raised an exception, if yes
# raise it here in the function
if not self.exceptions_queue.empty():
raise self.exceptions_queue.get()
return self.results_queue | [
"def",
"result",
"(",
"self",
")",
":",
"# Send None to all threads to cleanly stop them",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"num_threads",
")",
":",
"self",
".",
"tasks_queue",
".",
"put",
"(",
"None",
")",
"# Wait for completion of all the tasks in the ... | Stop threads and return the result of all called tasks | [
"Stop",
"threads",
"and",
"return",
"the",
"result",
"of",
"all",
"called",
"tasks"
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/thread_pool.py#L82-L93 |
226,507 | minio/minio-py | minio/xml_marshal.py | xml_marshal_bucket_notifications | def xml_marshal_bucket_notifications(notifications):
"""
Marshals the notifications structure for sending to S3 compatible storage
:param notifications: Dictionary with following structure:
{
'TopicConfigurations': [
{
'Id': 'string',
'Arn': 'string',
'Events': [
's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated:Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:CompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|'s3:ObjectRemoved:DeleteMarkerCreated',
],
'Filter': {
'Key': {
'FilterRules': [
{
'Name': 'prefix'|'suffix',
'Value': 'string'
},
]
}
}
},
],
'QueueConfigurations': [
{
'Id': 'string',
'Arn': 'string',
'Events': [
's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated:Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:CompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|'s3:ObjectRemoved:DeleteMarkerCreated',
],
'Filter': {
'Key': {
'FilterRules': [
{
'Name': 'prefix'|'suffix',
'Value': 'string'
},
]
}
}
},
],
'CloudFunctionConfigurations': [
{
'Id': 'string',
'Arn': 'string',
'Events': [
's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated:Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:CompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|'s3:ObjectRemoved:DeleteMarkerCreated',
],
'Filter': {
'Key': {
'FilterRules': [
{
'Name': 'prefix'|'suffix',
'Value': 'string'
},
]
}
}
},
]
}
:return: Marshalled XML data
"""
root = s3_xml.Element('NotificationConfiguration', {'xmlns': _S3_NAMESPACE})
_add_notification_config_to_xml(
root,
'TopicConfiguration',
notifications.get('TopicConfigurations', [])
)
_add_notification_config_to_xml(
root,
'QueueConfiguration',
notifications.get('QueueConfigurations', [])
)
_add_notification_config_to_xml(
root,
'CloudFunctionConfiguration',
notifications.get('CloudFunctionConfigurations', [])
)
data = io.BytesIO()
s3_xml.ElementTree(root).write(data, encoding=None, xml_declaration=False)
return data.getvalue() | python | def xml_marshal_bucket_notifications(notifications):
root = s3_xml.Element('NotificationConfiguration', {'xmlns': _S3_NAMESPACE})
_add_notification_config_to_xml(
root,
'TopicConfiguration',
notifications.get('TopicConfigurations', [])
)
_add_notification_config_to_xml(
root,
'QueueConfiguration',
notifications.get('QueueConfigurations', [])
)
_add_notification_config_to_xml(
root,
'CloudFunctionConfiguration',
notifications.get('CloudFunctionConfigurations', [])
)
data = io.BytesIO()
s3_xml.ElementTree(root).write(data, encoding=None, xml_declaration=False)
return data.getvalue() | [
"def",
"xml_marshal_bucket_notifications",
"(",
"notifications",
")",
":",
"root",
"=",
"s3_xml",
".",
"Element",
"(",
"'NotificationConfiguration'",
",",
"{",
"'xmlns'",
":",
"_S3_NAMESPACE",
"}",
")",
"_add_notification_config_to_xml",
"(",
"root",
",",
"'TopicConfi... | Marshals the notifications structure for sending to S3 compatible storage
:param notifications: Dictionary with following structure:
{
'TopicConfigurations': [
{
'Id': 'string',
'Arn': 'string',
'Events': [
's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated:Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:CompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|'s3:ObjectRemoved:DeleteMarkerCreated',
],
'Filter': {
'Key': {
'FilterRules': [
{
'Name': 'prefix'|'suffix',
'Value': 'string'
},
]
}
}
},
],
'QueueConfigurations': [
{
'Id': 'string',
'Arn': 'string',
'Events': [
's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated:Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:CompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|'s3:ObjectRemoved:DeleteMarkerCreated',
],
'Filter': {
'Key': {
'FilterRules': [
{
'Name': 'prefix'|'suffix',
'Value': 'string'
},
]
}
}
},
],
'CloudFunctionConfigurations': [
{
'Id': 'string',
'Arn': 'string',
'Events': [
's3:ReducedRedundancyLostObject'|'s3:ObjectCreated:*'|'s3:ObjectCreated:Put'|'s3:ObjectCreated:Post'|'s3:ObjectCreated:Copy'|'s3:ObjectCreated:CompleteMultipartUpload'|'s3:ObjectRemoved:*'|'s3:ObjectRemoved:Delete'|'s3:ObjectRemoved:DeleteMarkerCreated',
],
'Filter': {
'Key': {
'FilterRules': [
{
'Name': 'prefix'|'suffix',
'Value': 'string'
},
]
}
}
},
]
}
:return: Marshalled XML data | [
"Marshals",
"the",
"notifications",
"structure",
"for",
"sending",
"to",
"S3",
"compatible",
"storage"
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/xml_marshal.py#L70-L157 |
226,508 | minio/minio-py | minio/xml_marshal.py | _add_notification_config_to_xml | def _add_notification_config_to_xml(node, element_name, configs):
"""
Internal function that builds the XML sub-structure for a given
kind of notification configuration.
"""
for config in configs:
config_node = s3_xml.SubElement(node, element_name)
if 'Id' in config:
id_node = s3_xml.SubElement(config_node, 'Id')
id_node.text = config['Id']
arn_node = s3_xml.SubElement(
config_node,
NOTIFICATIONS_ARN_FIELDNAME_MAP[element_name]
)
arn_node.text = config['Arn']
for event in config['Events']:
event_node = s3_xml.SubElement(config_node, 'Event')
event_node.text = event
filter_rules = config.get('Filter', {}).get(
'Key', {}).get('FilterRules', [])
if filter_rules:
filter_node = s3_xml.SubElement(config_node, 'Filter')
s3key_node = s3_xml.SubElement(filter_node, 'S3Key')
for filter_rule in filter_rules:
filter_rule_node = s3_xml.SubElement(s3key_node, 'FilterRule')
name_node = s3_xml.SubElement(filter_rule_node, 'Name')
name_node.text = filter_rule['Name']
value_node = s3_xml.SubElement(filter_rule_node, 'Value')
value_node.text = filter_rule['Value']
return node | python | def _add_notification_config_to_xml(node, element_name, configs):
for config in configs:
config_node = s3_xml.SubElement(node, element_name)
if 'Id' in config:
id_node = s3_xml.SubElement(config_node, 'Id')
id_node.text = config['Id']
arn_node = s3_xml.SubElement(
config_node,
NOTIFICATIONS_ARN_FIELDNAME_MAP[element_name]
)
arn_node.text = config['Arn']
for event in config['Events']:
event_node = s3_xml.SubElement(config_node, 'Event')
event_node.text = event
filter_rules = config.get('Filter', {}).get(
'Key', {}).get('FilterRules', [])
if filter_rules:
filter_node = s3_xml.SubElement(config_node, 'Filter')
s3key_node = s3_xml.SubElement(filter_node, 'S3Key')
for filter_rule in filter_rules:
filter_rule_node = s3_xml.SubElement(s3key_node, 'FilterRule')
name_node = s3_xml.SubElement(filter_rule_node, 'Name')
name_node.text = filter_rule['Name']
value_node = s3_xml.SubElement(filter_rule_node, 'Value')
value_node.text = filter_rule['Value']
return node | [
"def",
"_add_notification_config_to_xml",
"(",
"node",
",",
"element_name",
",",
"configs",
")",
":",
"for",
"config",
"in",
"configs",
":",
"config_node",
"=",
"s3_xml",
".",
"SubElement",
"(",
"node",
",",
"element_name",
")",
"if",
"'Id'",
"in",
"config",
... | Internal function that builds the XML sub-structure for a given
kind of notification configuration. | [
"Internal",
"function",
"that",
"builds",
"the",
"XML",
"sub",
"-",
"structure",
"for",
"a",
"given",
"kind",
"of",
"notification",
"configuration",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/xml_marshal.py#L165-L199 |
226,509 | minio/minio-py | minio/xml_marshal.py | xml_marshal_delete_objects | def xml_marshal_delete_objects(object_names):
"""
Marshal Multi-Object Delete request body from object names.
:param object_names: List of object keys to be deleted.
:return: Serialized XML string for multi-object delete request body.
"""
root = s3_xml.Element('Delete')
# use quiet mode in the request - this causes the S3 Server to
# limit its response to only object keys that had errors during
# the delete operation.
quiet = s3_xml.SubElement(root, 'Quiet')
quiet.text = "true"
# add each object to the request.
for object_name in object_names:
object_elt = s3_xml.SubElement(root, 'Object')
key_elt = s3_xml.SubElement(object_elt, 'Key')
key_elt.text = object_name
# return the marshalled xml.
data = io.BytesIO()
s3_xml.ElementTree(root).write(data, encoding=None, xml_declaration=False)
return data.getvalue() | python | def xml_marshal_delete_objects(object_names):
root = s3_xml.Element('Delete')
# use quiet mode in the request - this causes the S3 Server to
# limit its response to only object keys that had errors during
# the delete operation.
quiet = s3_xml.SubElement(root, 'Quiet')
quiet.text = "true"
# add each object to the request.
for object_name in object_names:
object_elt = s3_xml.SubElement(root, 'Object')
key_elt = s3_xml.SubElement(object_elt, 'Key')
key_elt.text = object_name
# return the marshalled xml.
data = io.BytesIO()
s3_xml.ElementTree(root).write(data, encoding=None, xml_declaration=False)
return data.getvalue() | [
"def",
"xml_marshal_delete_objects",
"(",
"object_names",
")",
":",
"root",
"=",
"s3_xml",
".",
"Element",
"(",
"'Delete'",
")",
"# use quiet mode in the request - this causes the S3 Server to",
"# limit its response to only object keys that had errors during",
"# the delete operatio... | Marshal Multi-Object Delete request body from object names.
:param object_names: List of object keys to be deleted.
:return: Serialized XML string for multi-object delete request body. | [
"Marshal",
"Multi",
"-",
"Object",
"Delete",
"request",
"body",
"from",
"object",
"names",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/xml_marshal.py#L201-L225 |
226,510 | minio/minio-py | minio/post_policy.py | PostPolicy.set_key | def set_key(self, key):
"""
Set key policy condition.
:param key: set key name.
"""
is_non_empty_string(key)
self.policies.append(('eq', '$key', key))
self.form_data['key'] = key
self.key = key | python | def set_key(self, key):
is_non_empty_string(key)
self.policies.append(('eq', '$key', key))
self.form_data['key'] = key
self.key = key | [
"def",
"set_key",
"(",
"self",
",",
"key",
")",
":",
"is_non_empty_string",
"(",
"key",
")",
"self",
".",
"policies",
".",
"append",
"(",
"(",
"'eq'",
",",
"'$key'",
",",
"key",
")",
")",
"self",
".",
"form_data",
"[",
"'key'",
"]",
"=",
"key",
"se... | Set key policy condition.
:param key: set key name. | [
"Set",
"key",
"policy",
"condition",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/post_policy.py#L62-L72 |
226,511 | minio/minio-py | minio/post_policy.py | PostPolicy.set_key_startswith | def set_key_startswith(self, key_startswith):
"""
Set key startswith policy condition.
:param key_startswith: set key prefix name.
"""
is_non_empty_string(key_startswith)
self.policies.append(('starts-with', '$key', key_startswith))
self.form_data['key'] = key_startswith | python | def set_key_startswith(self, key_startswith):
is_non_empty_string(key_startswith)
self.policies.append(('starts-with', '$key', key_startswith))
self.form_data['key'] = key_startswith | [
"def",
"set_key_startswith",
"(",
"self",
",",
"key_startswith",
")",
":",
"is_non_empty_string",
"(",
"key_startswith",
")",
"self",
".",
"policies",
".",
"append",
"(",
"(",
"'starts-with'",
",",
"'$key'",
",",
"key_startswith",
")",
")",
"self",
".",
"form_... | Set key startswith policy condition.
:param key_startswith: set key prefix name. | [
"Set",
"key",
"startswith",
"policy",
"condition",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/post_policy.py#L74-L83 |
226,512 | minio/minio-py | minio/post_policy.py | PostPolicy.set_bucket_name | def set_bucket_name(self, bucket_name):
"""
Set bucket name policy condition.
:param bucket_name: set bucket name.
"""
is_valid_bucket_name(bucket_name)
self.policies.append(('eq', '$bucket', bucket_name))
self.form_data['bucket'] = bucket_name
self.bucket_name = bucket_name | python | def set_bucket_name(self, bucket_name):
is_valid_bucket_name(bucket_name)
self.policies.append(('eq', '$bucket', bucket_name))
self.form_data['bucket'] = bucket_name
self.bucket_name = bucket_name | [
"def",
"set_bucket_name",
"(",
"self",
",",
"bucket_name",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"self",
".",
"policies",
".",
"append",
"(",
"(",
"'eq'",
",",
"'$bucket'",
",",
"bucket_name",
")",
")",
"self",
".",
"form_data",
"[",
"... | Set bucket name policy condition.
:param bucket_name: set bucket name. | [
"Set",
"bucket",
"name",
"policy",
"condition",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/post_policy.py#L85-L95 |
226,513 | minio/minio-py | minio/post_policy.py | PostPolicy.set_content_type | def set_content_type(self, content_type):
"""
Set content-type policy condition.
:param content_type: set content type name.
"""
self.policies.append(('eq', '$Content-Type', content_type))
self.form_data['Content-Type'] = content_type | python | def set_content_type(self, content_type):
self.policies.append(('eq', '$Content-Type', content_type))
self.form_data['Content-Type'] = content_type | [
"def",
"set_content_type",
"(",
"self",
",",
"content_type",
")",
":",
"self",
".",
"policies",
".",
"append",
"(",
"(",
"'eq'",
",",
"'$Content-Type'",
",",
"content_type",
")",
")",
"self",
".",
"form_data",
"[",
"'Content-Type'",
"]",
"=",
"content_type"
... | Set content-type policy condition.
:param content_type: set content type name. | [
"Set",
"content",
"-",
"type",
"policy",
"condition",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/post_policy.py#L97-L104 |
226,514 | minio/minio-py | minio/post_policy.py | PostPolicy.base64 | def base64(self, extras=()):
"""
Encode json into base64.
"""
s = self._marshal_json(extras=extras)
s_bytes = s if isinstance(s, bytes) else s.encode('utf-8')
b64enc = base64.b64encode(s_bytes)
return b64enc.decode('utf-8') if isinstance(b64enc, bytes) else b64enc | python | def base64(self, extras=()):
s = self._marshal_json(extras=extras)
s_bytes = s if isinstance(s, bytes) else s.encode('utf-8')
b64enc = base64.b64encode(s_bytes)
return b64enc.decode('utf-8') if isinstance(b64enc, bytes) else b64enc | [
"def",
"base64",
"(",
"self",
",",
"extras",
"=",
"(",
")",
")",
":",
"s",
"=",
"self",
".",
"_marshal_json",
"(",
"extras",
"=",
"extras",
")",
"s_bytes",
"=",
"s",
"if",
"isinstance",
"(",
"s",
",",
"bytes",
")",
"else",
"s",
".",
"encode",
"("... | Encode json into base64. | [
"Encode",
"json",
"into",
"base64",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/post_policy.py#L146-L153 |
226,515 | minio/minio-py | minio/post_policy.py | PostPolicy.is_valid | def is_valid(self):
"""
Validate for required parameters.
"""
if not isinstance(self._expiration, datetime.datetime):
raise InvalidArgumentError('Expiration datetime must be specified.')
if 'key' not in self.form_data:
raise InvalidArgumentError('object key must be specified.')
if 'bucket' not in self.form_data:
raise InvalidArgumentError('bucket name must be specified.') | python | def is_valid(self):
if not isinstance(self._expiration, datetime.datetime):
raise InvalidArgumentError('Expiration datetime must be specified.')
if 'key' not in self.form_data:
raise InvalidArgumentError('object key must be specified.')
if 'bucket' not in self.form_data:
raise InvalidArgumentError('bucket name must be specified.') | [
"def",
"is_valid",
"(",
"self",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_expiration",
",",
"datetime",
".",
"datetime",
")",
":",
"raise",
"InvalidArgumentError",
"(",
"'Expiration datetime must be specified.'",
")",
"if",
"'key'",
"not",
"in",
... | Validate for required parameters. | [
"Validate",
"for",
"required",
"parameters",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/post_policy.py#L155-L166 |
226,516 | minio/minio-py | minio/signer.py | post_presign_signature | def post_presign_signature(date, region, secret_key, policy_str):
"""
Calculates signature version '4' for POST policy string.
:param date: datetime formatted date.
:param region: region of the bucket for the policy.
:param secret_key: Amazon S3 secret access key.
:param policy_str: policy string.
:return: hexlified sha256 signature digest.
"""
signing_key = generate_signing_key(date, region, secret_key)
signature = hmac.new(signing_key, policy_str.encode('utf-8'),
hashlib.sha256).hexdigest()
return signature | python | def post_presign_signature(date, region, secret_key, policy_str):
signing_key = generate_signing_key(date, region, secret_key)
signature = hmac.new(signing_key, policy_str.encode('utf-8'),
hashlib.sha256).hexdigest()
return signature | [
"def",
"post_presign_signature",
"(",
"date",
",",
"region",
",",
"secret_key",
",",
"policy_str",
")",
":",
"signing_key",
"=",
"generate_signing_key",
"(",
"date",
",",
"region",
",",
"secret_key",
")",
"signature",
"=",
"hmac",
".",
"new",
"(",
"signing_key... | Calculates signature version '4' for POST policy string.
:param date: datetime formatted date.
:param region: region of the bucket for the policy.
:param secret_key: Amazon S3 secret access key.
:param policy_str: policy string.
:return: hexlified sha256 signature digest. | [
"Calculates",
"signature",
"version",
"4",
"for",
"POST",
"policy",
"string",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/signer.py#L44-L58 |
226,517 | minio/minio-py | minio/signer.py | presign_v4 | def presign_v4(method, url, access_key, secret_key, session_token=None,
region=None, headers=None, expires=None, response_headers=None,
request_date=None):
"""
Calculates signature version '4' for regular presigned URLs.
:param method: Method to be presigned examples 'PUT', 'GET'.
:param url: URL to be presigned.
:param access_key: Access key id for your AWS s3 account.
:param secret_key: Secret access key for your AWS s3 account.
:param session_token: Session token key set only for temporary
access credentials.
:param region: region of the bucket, it is optional.
:param headers: any additional HTTP request headers to
be presigned, it is optional.
:param expires: final expiration of the generated URL. Maximum is 7days.
:param response_headers: Specify additional query string parameters.
:param request_date: the date of the request.
"""
# Validate input arguments.
if not access_key or not secret_key:
raise InvalidArgumentError('Invalid access_key and secret_key.')
if region is None:
region = 'us-east-1'
if headers is None:
headers = {}
if expires is None:
expires = '604800'
if request_date is None:
request_date = datetime.utcnow()
parsed_url = urlsplit(url)
content_hash_hex = _UNSIGNED_PAYLOAD
host = parsed_url.netloc
headers['Host'] = host
iso8601Date = request_date.strftime("%Y%m%dT%H%M%SZ")
headers_to_sign = headers
# Construct queries.
query = {}
query['X-Amz-Algorithm'] = _SIGN_V4_ALGORITHM
query['X-Amz-Credential'] = generate_credential_string(access_key,
request_date,
region)
query['X-Amz-Date'] = iso8601Date
query['X-Amz-Expires'] = str(expires)
if session_token:
query['X-Amz-Security-Token'] = session_token
signed_headers = get_signed_headers(headers_to_sign)
query['X-Amz-SignedHeaders'] = ';'.join(signed_headers)
if response_headers is not None:
query.update(response_headers)
# URL components.
url_components = [parsed_url.geturl()]
if query is not None:
ordered_query = collections.OrderedDict(sorted(query.items()))
query_components = []
for component_key in ordered_query:
single_component = [component_key]
if ordered_query[component_key] is not None:
single_component.append('=')
single_component.append(
queryencode(ordered_query[component_key])
)
else:
single_component.append('=')
query_components.append(''.join(single_component))
query_string = '&'.join(query_components)
if query_string:
url_components.append('?')
url_components.append(query_string)
new_url = ''.join(url_components)
# new url constructor block ends.
new_parsed_url = urlsplit(new_url)
canonical_request = generate_canonical_request(method,
new_parsed_url,
headers_to_sign,
signed_headers,
content_hash_hex)
string_to_sign = generate_string_to_sign(request_date, region,
canonical_request)
signing_key = generate_signing_key(request_date, region, secret_key)
signature = hmac.new(signing_key, string_to_sign.encode('utf-8'),
hashlib.sha256).hexdigest()
new_parsed_url = urlsplit(new_url + "&X-Amz-Signature="+signature)
return new_parsed_url.geturl() | python | def presign_v4(method, url, access_key, secret_key, session_token=None,
region=None, headers=None, expires=None, response_headers=None,
request_date=None):
# Validate input arguments.
if not access_key or not secret_key:
raise InvalidArgumentError('Invalid access_key and secret_key.')
if region is None:
region = 'us-east-1'
if headers is None:
headers = {}
if expires is None:
expires = '604800'
if request_date is None:
request_date = datetime.utcnow()
parsed_url = urlsplit(url)
content_hash_hex = _UNSIGNED_PAYLOAD
host = parsed_url.netloc
headers['Host'] = host
iso8601Date = request_date.strftime("%Y%m%dT%H%M%SZ")
headers_to_sign = headers
# Construct queries.
query = {}
query['X-Amz-Algorithm'] = _SIGN_V4_ALGORITHM
query['X-Amz-Credential'] = generate_credential_string(access_key,
request_date,
region)
query['X-Amz-Date'] = iso8601Date
query['X-Amz-Expires'] = str(expires)
if session_token:
query['X-Amz-Security-Token'] = session_token
signed_headers = get_signed_headers(headers_to_sign)
query['X-Amz-SignedHeaders'] = ';'.join(signed_headers)
if response_headers is not None:
query.update(response_headers)
# URL components.
url_components = [parsed_url.geturl()]
if query is not None:
ordered_query = collections.OrderedDict(sorted(query.items()))
query_components = []
for component_key in ordered_query:
single_component = [component_key]
if ordered_query[component_key] is not None:
single_component.append('=')
single_component.append(
queryencode(ordered_query[component_key])
)
else:
single_component.append('=')
query_components.append(''.join(single_component))
query_string = '&'.join(query_components)
if query_string:
url_components.append('?')
url_components.append(query_string)
new_url = ''.join(url_components)
# new url constructor block ends.
new_parsed_url = urlsplit(new_url)
canonical_request = generate_canonical_request(method,
new_parsed_url,
headers_to_sign,
signed_headers,
content_hash_hex)
string_to_sign = generate_string_to_sign(request_date, region,
canonical_request)
signing_key = generate_signing_key(request_date, region, secret_key)
signature = hmac.new(signing_key, string_to_sign.encode('utf-8'),
hashlib.sha256).hexdigest()
new_parsed_url = urlsplit(new_url + "&X-Amz-Signature="+signature)
return new_parsed_url.geturl() | [
"def",
"presign_v4",
"(",
"method",
",",
"url",
",",
"access_key",
",",
"secret_key",
",",
"session_token",
"=",
"None",
",",
"region",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"expires",
"=",
"None",
",",
"response_headers",
"=",
"None",
",",
"req... | Calculates signature version '4' for regular presigned URLs.
:param method: Method to be presigned examples 'PUT', 'GET'.
:param url: URL to be presigned.
:param access_key: Access key id for your AWS s3 account.
:param secret_key: Secret access key for your AWS s3 account.
:param session_token: Session token key set only for temporary
access credentials.
:param region: region of the bucket, it is optional.
:param headers: any additional HTTP request headers to
be presigned, it is optional.
:param expires: final expiration of the generated URL. Maximum is 7days.
:param response_headers: Specify additional query string parameters.
:param request_date: the date of the request. | [
"Calculates",
"signature",
"version",
"4",
"for",
"regular",
"presigned",
"URLs",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/signer.py#L61-L156 |
226,518 | minio/minio-py | minio/signer.py | get_signed_headers | def get_signed_headers(headers):
"""
Get signed headers.
:param headers: input dictionary to be sorted.
"""
signed_headers = []
for header in headers:
signed_headers.append(header.lower().strip())
return sorted(signed_headers) | python | def get_signed_headers(headers):
signed_headers = []
for header in headers:
signed_headers.append(header.lower().strip())
return sorted(signed_headers) | [
"def",
"get_signed_headers",
"(",
"headers",
")",
":",
"signed_headers",
"=",
"[",
"]",
"for",
"header",
"in",
"headers",
":",
"signed_headers",
".",
"append",
"(",
"header",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
")",
"return",
"sorted",
"(",
... | Get signed headers.
:param headers: input dictionary to be sorted. | [
"Get",
"signed",
"headers",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/signer.py#L160-L169 |
226,519 | minio/minio-py | minio/signer.py | sign_v4 | def sign_v4(method, url, region, headers=None,
access_key=None,
secret_key=None,
session_token=None,
content_sha256=None):
"""
Signature version 4.
:param method: HTTP method used for signature.
:param url: Final url which needs to be signed.
:param region: Region should be set to bucket region.
:param headers: Optional headers for the method.
:param access_key: Optional access key, if not
specified no signature is needed.
:param secret_key: Optional secret key, if not
specified no signature is needed.
:param session_token: Optional session token, set
only for temporary credentials.
:param content_sha256: Optional body sha256.
"""
# If no access key or secret key is provided return headers.
if not access_key or not secret_key:
return headers
if headers is None:
headers = FoldCaseDict()
if region is None:
region = 'us-east-1'
parsed_url = urlsplit(url)
secure = parsed_url.scheme == 'https'
if secure:
content_sha256 = _UNSIGNED_PAYLOAD
if content_sha256 is None:
# with no payload, calculate sha256 for 0 length data.
content_sha256 = get_sha256_hexdigest('')
host = parsed_url.netloc
headers['Host'] = host
date = datetime.utcnow()
headers['X-Amz-Date'] = date.strftime("%Y%m%dT%H%M%SZ")
headers['X-Amz-Content-Sha256'] = content_sha256
if session_token:
headers['X-Amz-Security-Token'] = session_token
headers_to_sign = headers
signed_headers = get_signed_headers(headers_to_sign)
canonical_req = generate_canonical_request(method,
parsed_url,
headers_to_sign,
signed_headers,
content_sha256)
string_to_sign = generate_string_to_sign(date, region,
canonical_req)
signing_key = generate_signing_key(date, region, secret_key)
signature = hmac.new(signing_key, string_to_sign.encode('utf-8'),
hashlib.sha256).hexdigest()
authorization_header = generate_authorization_header(access_key,
date,
region,
signed_headers,
signature)
headers['Authorization'] = authorization_header
return headers | python | def sign_v4(method, url, region, headers=None,
access_key=None,
secret_key=None,
session_token=None,
content_sha256=None):
# If no access key or secret key is provided return headers.
if not access_key or not secret_key:
return headers
if headers is None:
headers = FoldCaseDict()
if region is None:
region = 'us-east-1'
parsed_url = urlsplit(url)
secure = parsed_url.scheme == 'https'
if secure:
content_sha256 = _UNSIGNED_PAYLOAD
if content_sha256 is None:
# with no payload, calculate sha256 for 0 length data.
content_sha256 = get_sha256_hexdigest('')
host = parsed_url.netloc
headers['Host'] = host
date = datetime.utcnow()
headers['X-Amz-Date'] = date.strftime("%Y%m%dT%H%M%SZ")
headers['X-Amz-Content-Sha256'] = content_sha256
if session_token:
headers['X-Amz-Security-Token'] = session_token
headers_to_sign = headers
signed_headers = get_signed_headers(headers_to_sign)
canonical_req = generate_canonical_request(method,
parsed_url,
headers_to_sign,
signed_headers,
content_sha256)
string_to_sign = generate_string_to_sign(date, region,
canonical_req)
signing_key = generate_signing_key(date, region, secret_key)
signature = hmac.new(signing_key, string_to_sign.encode('utf-8'),
hashlib.sha256).hexdigest()
authorization_header = generate_authorization_header(access_key,
date,
region,
signed_headers,
signature)
headers['Authorization'] = authorization_header
return headers | [
"def",
"sign_v4",
"(",
"method",
",",
"url",
",",
"region",
",",
"headers",
"=",
"None",
",",
"access_key",
"=",
"None",
",",
"secret_key",
"=",
"None",
",",
"session_token",
"=",
"None",
",",
"content_sha256",
"=",
"None",
")",
":",
"# If no access key or... | Signature version 4.
:param method: HTTP method used for signature.
:param url: Final url which needs to be signed.
:param region: Region should be set to bucket region.
:param headers: Optional headers for the method.
:param access_key: Optional access key, if not
specified no signature is needed.
:param secret_key: Optional secret key, if not
specified no signature is needed.
:param session_token: Optional session token, set
only for temporary credentials.
:param content_sha256: Optional body sha256. | [
"Signature",
"version",
"4",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/signer.py#L172-L242 |
226,520 | minio/minio-py | minio/signer.py | generate_canonical_request | def generate_canonical_request(method, parsed_url, headers, signed_headers, content_sha256):
"""
Generate canonical request.
:param method: HTTP method.
:param parsed_url: Parsed url is input from :func:`urlsplit`
:param headers: HTTP header dictionary.
:param content_sha256: Content sha256 hexdigest string.
"""
lines = [method, parsed_url.path, parsed_url.query]
# Headers added to canonical request.
header_lines = []
for header in signed_headers:
value = headers[header.title()]
value = str(value).strip()
header_lines.append(header + ':' + str(value))
lines = lines + header_lines
lines.append('')
lines.append(';'.join(signed_headers))
lines.append(content_sha256)
return '\n'.join(lines) | python | def generate_canonical_request(method, parsed_url, headers, signed_headers, content_sha256):
lines = [method, parsed_url.path, parsed_url.query]
# Headers added to canonical request.
header_lines = []
for header in signed_headers:
value = headers[header.title()]
value = str(value).strip()
header_lines.append(header + ':' + str(value))
lines = lines + header_lines
lines.append('')
lines.append(';'.join(signed_headers))
lines.append(content_sha256)
return '\n'.join(lines) | [
"def",
"generate_canonical_request",
"(",
"method",
",",
"parsed_url",
",",
"headers",
",",
"signed_headers",
",",
"content_sha256",
")",
":",
"lines",
"=",
"[",
"method",
",",
"parsed_url",
".",
"path",
",",
"parsed_url",
".",
"query",
"]",
"# Headers added to ... | Generate canonical request.
:param method: HTTP method.
:param parsed_url: Parsed url is input from :func:`urlsplit`
:param headers: HTTP header dictionary.
:param content_sha256: Content sha256 hexdigest string. | [
"Generate",
"canonical",
"request",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/signer.py#L245-L268 |
226,521 | minio/minio-py | minio/signer.py | generate_string_to_sign | def generate_string_to_sign(date, region, canonical_request):
"""
Generate string to sign.
:param date: Date is input from :meth:`datetime.datetime`
:param region: Region should be set to bucket region.
:param canonical_request: Canonical request generated previously.
"""
formatted_date_time = date.strftime("%Y%m%dT%H%M%SZ")
canonical_request_hasher = hashlib.sha256()
canonical_request_hasher.update(canonical_request.encode('utf-8'))
canonical_request_sha256 = canonical_request_hasher.hexdigest()
scope = generate_scope_string(date, region)
return '\n'.join([_SIGN_V4_ALGORITHM,
formatted_date_time,
scope,
canonical_request_sha256]) | python | def generate_string_to_sign(date, region, canonical_request):
formatted_date_time = date.strftime("%Y%m%dT%H%M%SZ")
canonical_request_hasher = hashlib.sha256()
canonical_request_hasher.update(canonical_request.encode('utf-8'))
canonical_request_sha256 = canonical_request_hasher.hexdigest()
scope = generate_scope_string(date, region)
return '\n'.join([_SIGN_V4_ALGORITHM,
formatted_date_time,
scope,
canonical_request_sha256]) | [
"def",
"generate_string_to_sign",
"(",
"date",
",",
"region",
",",
"canonical_request",
")",
":",
"formatted_date_time",
"=",
"date",
".",
"strftime",
"(",
"\"%Y%m%dT%H%M%SZ\"",
")",
"canonical_request_hasher",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"canonical_req... | Generate string to sign.
:param date: Date is input from :meth:`datetime.datetime`
:param region: Region should be set to bucket region.
:param canonical_request: Canonical request generated previously. | [
"Generate",
"string",
"to",
"sign",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/signer.py#L271-L289 |
226,522 | minio/minio-py | minio/signer.py | generate_signing_key | def generate_signing_key(date, region, secret_key):
"""
Generate signing key.
:param date: Date is input from :meth:`datetime.datetime`
:param region: Region should be set to bucket region.
:param secret_key: Secret access key.
"""
formatted_date = date.strftime("%Y%m%d")
key1_string = 'AWS4' + secret_key
key1 = key1_string.encode('utf-8')
key2 = hmac.new(key1, formatted_date.encode('utf-8'),
hashlib.sha256).digest()
key3 = hmac.new(key2, region.encode('utf-8'), hashlib.sha256).digest()
key4 = hmac.new(key3, 's3'.encode('utf-8'), hashlib.sha256).digest()
return hmac.new(key4, 'aws4_request'.encode('utf-8'),
hashlib.sha256).digest() | python | def generate_signing_key(date, region, secret_key):
formatted_date = date.strftime("%Y%m%d")
key1_string = 'AWS4' + secret_key
key1 = key1_string.encode('utf-8')
key2 = hmac.new(key1, formatted_date.encode('utf-8'),
hashlib.sha256).digest()
key3 = hmac.new(key2, region.encode('utf-8'), hashlib.sha256).digest()
key4 = hmac.new(key3, 's3'.encode('utf-8'), hashlib.sha256).digest()
return hmac.new(key4, 'aws4_request'.encode('utf-8'),
hashlib.sha256).digest() | [
"def",
"generate_signing_key",
"(",
"date",
",",
"region",
",",
"secret_key",
")",
":",
"formatted_date",
"=",
"date",
".",
"strftime",
"(",
"\"%Y%m%d\"",
")",
"key1_string",
"=",
"'AWS4'",
"+",
"secret_key",
"key1",
"=",
"key1_string",
".",
"encode",
"(",
"... | Generate signing key.
:param date: Date is input from :meth:`datetime.datetime`
:param region: Region should be set to bucket region.
:param secret_key: Secret access key. | [
"Generate",
"signing",
"key",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/signer.py#L292-L310 |
226,523 | minio/minio-py | minio/signer.py | generate_scope_string | def generate_scope_string(date, region):
"""
Generate scope string.
:param date: Date is input from :meth:`datetime.datetime`
:param region: Region should be set to bucket region.
"""
formatted_date = date.strftime("%Y%m%d")
scope = '/'.join([formatted_date,
region,
's3',
'aws4_request'])
return scope | python | def generate_scope_string(date, region):
formatted_date = date.strftime("%Y%m%d")
scope = '/'.join([formatted_date,
region,
's3',
'aws4_request'])
return scope | [
"def",
"generate_scope_string",
"(",
"date",
",",
"region",
")",
":",
"formatted_date",
"=",
"date",
".",
"strftime",
"(",
"\"%Y%m%d\"",
")",
"scope",
"=",
"'/'",
".",
"join",
"(",
"[",
"formatted_date",
",",
"region",
",",
"'s3'",
",",
"'aws4_request'",
"... | Generate scope string.
:param date: Date is input from :meth:`datetime.datetime`
:param region: Region should be set to bucket region. | [
"Generate",
"scope",
"string",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/signer.py#L313-L325 |
226,524 | minio/minio-py | minio/signer.py | generate_authorization_header | def generate_authorization_header(access_key, date, region,
signed_headers, signature):
"""
Generate authorization header.
:param access_key: Server access key.
:param date: Date is input from :meth:`datetime.datetime`
:param region: Region should be set to bucket region.
:param signed_headers: Signed headers.
:param signature: Calculated signature.
"""
signed_headers_string = ';'.join(signed_headers)
credential = generate_credential_string(access_key, date, region)
auth_header = [_SIGN_V4_ALGORITHM, 'Credential=' + credential + ',',
'SignedHeaders=' + signed_headers_string + ',',
'Signature=' + signature]
return ' '.join(auth_header) | python | def generate_authorization_header(access_key, date, region,
signed_headers, signature):
signed_headers_string = ';'.join(signed_headers)
credential = generate_credential_string(access_key, date, region)
auth_header = [_SIGN_V4_ALGORITHM, 'Credential=' + credential + ',',
'SignedHeaders=' + signed_headers_string + ',',
'Signature=' + signature]
return ' '.join(auth_header) | [
"def",
"generate_authorization_header",
"(",
"access_key",
",",
"date",
",",
"region",
",",
"signed_headers",
",",
"signature",
")",
":",
"signed_headers_string",
"=",
"';'",
".",
"join",
"(",
"signed_headers",
")",
"credential",
"=",
"generate_credential_string",
"... | Generate authorization header.
:param access_key: Server access key.
:param date: Date is input from :meth:`datetime.datetime`
:param region: Region should be set to bucket region.
:param signed_headers: Signed headers.
:param signature: Calculated signature. | [
"Generate",
"authorization",
"header",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/signer.py#L339-L355 |
226,525 | minio/minio-py | minio/parsers.py | parse_multipart_upload_result | def parse_multipart_upload_result(data):
"""
Parser for complete multipart upload response.
:param data: Response data for complete multipart upload.
:return: :class:`MultipartUploadResult <MultipartUploadResult>`.
"""
root = S3Element.fromstring('CompleteMultipartUploadResult', data)
return MultipartUploadResult(
root.get_child_text('Bucket'),
root.get_child_text('Key'),
root.get_child_text('Location'),
root.get_etag_elem()
) | python | def parse_multipart_upload_result(data):
root = S3Element.fromstring('CompleteMultipartUploadResult', data)
return MultipartUploadResult(
root.get_child_text('Bucket'),
root.get_child_text('Key'),
root.get_child_text('Location'),
root.get_etag_elem()
) | [
"def",
"parse_multipart_upload_result",
"(",
"data",
")",
":",
"root",
"=",
"S3Element",
".",
"fromstring",
"(",
"'CompleteMultipartUploadResult'",
",",
"data",
")",
"return",
"MultipartUploadResult",
"(",
"root",
".",
"get_child_text",
"(",
"'Bucket'",
")",
",",
... | Parser for complete multipart upload response.
:param data: Response data for complete multipart upload.
:return: :class:`MultipartUploadResult <MultipartUploadResult>`. | [
"Parser",
"for",
"complete",
"multipart",
"upload",
"response",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L155-L169 |
226,526 | minio/minio-py | minio/parsers.py | parse_copy_object | def parse_copy_object(bucket_name, object_name, data):
"""
Parser for copy object response.
:param data: Response data for copy object.
:return: :class:`CopyObjectResult <CopyObjectResult>`
"""
root = S3Element.fromstring('CopyObjectResult', data)
return CopyObjectResult(
bucket_name, object_name,
root.get_etag_elem(),
root.get_localized_time_elem('LastModified')
) | python | def parse_copy_object(bucket_name, object_name, data):
root = S3Element.fromstring('CopyObjectResult', data)
return CopyObjectResult(
bucket_name, object_name,
root.get_etag_elem(),
root.get_localized_time_elem('LastModified')
) | [
"def",
"parse_copy_object",
"(",
"bucket_name",
",",
"object_name",
",",
"data",
")",
":",
"root",
"=",
"S3Element",
".",
"fromstring",
"(",
"'CopyObjectResult'",
",",
"data",
")",
"return",
"CopyObjectResult",
"(",
"bucket_name",
",",
"object_name",
",",
"root"... | Parser for copy object response.
:param data: Response data for copy object.
:return: :class:`CopyObjectResult <CopyObjectResult>` | [
"Parser",
"for",
"copy",
"object",
"response",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L171-L184 |
226,527 | minio/minio-py | minio/parsers.py | parse_list_buckets | def parse_list_buckets(data):
"""
Parser for list buckets response.
:param data: Response data for list buckets.
:return: List of :class:`Bucket <Bucket>`.
"""
root = S3Element.fromstring('ListBucketsResult', data)
return [
Bucket(bucket.get_child_text('Name'),
bucket.get_localized_time_elem('CreationDate'))
for buckets in root.findall('Buckets')
for bucket in buckets.findall('Bucket')
] | python | def parse_list_buckets(data):
root = S3Element.fromstring('ListBucketsResult', data)
return [
Bucket(bucket.get_child_text('Name'),
bucket.get_localized_time_elem('CreationDate'))
for buckets in root.findall('Buckets')
for bucket in buckets.findall('Bucket')
] | [
"def",
"parse_list_buckets",
"(",
"data",
")",
":",
"root",
"=",
"S3Element",
".",
"fromstring",
"(",
"'ListBucketsResult'",
",",
"data",
")",
"return",
"[",
"Bucket",
"(",
"bucket",
".",
"get_child_text",
"(",
"'Name'",
")",
",",
"bucket",
".",
"get_localiz... | Parser for list buckets response.
:param data: Response data for list buckets.
:return: List of :class:`Bucket <Bucket>`. | [
"Parser",
"for",
"list",
"buckets",
"response",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L186-L200 |
226,528 | minio/minio-py | minio/parsers.py | _parse_objects_from_xml_elts | def _parse_objects_from_xml_elts(bucket_name, contents, common_prefixes):
"""Internal function that extracts objects and common prefixes from
list_objects responses.
"""
objects = [
Object(bucket_name,
content.get_child_text('Key'),
content.get_localized_time_elem('LastModified'),
content.get_etag_elem(strict=False),
content.get_int_elem('Size'),
is_dir=content.is_dir())
for content in contents
]
object_dirs = [
Object(bucket_name, dir_elt.text(), None, '',
0, is_dir=True)
for dirs_elt in common_prefixes
for dir_elt in dirs_elt.findall('Prefix')
]
return objects, object_dirs | python | def _parse_objects_from_xml_elts(bucket_name, contents, common_prefixes):
objects = [
Object(bucket_name,
content.get_child_text('Key'),
content.get_localized_time_elem('LastModified'),
content.get_etag_elem(strict=False),
content.get_int_elem('Size'),
is_dir=content.is_dir())
for content in contents
]
object_dirs = [
Object(bucket_name, dir_elt.text(), None, '',
0, is_dir=True)
for dirs_elt in common_prefixes
for dir_elt in dirs_elt.findall('Prefix')
]
return objects, object_dirs | [
"def",
"_parse_objects_from_xml_elts",
"(",
"bucket_name",
",",
"contents",
",",
"common_prefixes",
")",
":",
"objects",
"=",
"[",
"Object",
"(",
"bucket_name",
",",
"content",
".",
"get_child_text",
"(",
"'Key'",
")",
",",
"content",
".",
"get_localized_time_elem... | Internal function that extracts objects and common prefixes from
list_objects responses. | [
"Internal",
"function",
"that",
"extracts",
"objects",
"and",
"common",
"prefixes",
"from",
"list_objects",
"responses",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L202-L223 |
226,529 | minio/minio-py | minio/parsers.py | parse_list_objects | def parse_list_objects(data, bucket_name):
"""
Parser for list objects response.
:param data: Response data for list objects.
:param bucket_name: Response for the bucket.
:return: Replies back three distinctive components.
- List of :class:`Object <Object>`
- True if list is truncated, False otherwise.
- Object name marker for the next request.
"""
root = S3Element.fromstring('ListObjectResult', data)
is_truncated = root.get_child_text('IsTruncated').lower() == 'true'
# NextMarker element need not be present.
marker = root.get_urldecoded_elem_text('NextMarker', strict=False)
objects, object_dirs = _parse_objects_from_xml_elts(
bucket_name,
root.findall('Contents'),
root.findall('CommonPrefixes')
)
if is_truncated and marker is None:
marker = objects[-1].object_name
return objects + object_dirs, is_truncated, marker | python | def parse_list_objects(data, bucket_name):
root = S3Element.fromstring('ListObjectResult', data)
is_truncated = root.get_child_text('IsTruncated').lower() == 'true'
# NextMarker element need not be present.
marker = root.get_urldecoded_elem_text('NextMarker', strict=False)
objects, object_dirs = _parse_objects_from_xml_elts(
bucket_name,
root.findall('Contents'),
root.findall('CommonPrefixes')
)
if is_truncated and marker is None:
marker = objects[-1].object_name
return objects + object_dirs, is_truncated, marker | [
"def",
"parse_list_objects",
"(",
"data",
",",
"bucket_name",
")",
":",
"root",
"=",
"S3Element",
".",
"fromstring",
"(",
"'ListObjectResult'",
",",
"data",
")",
"is_truncated",
"=",
"root",
".",
"get_child_text",
"(",
"'IsTruncated'",
")",
".",
"lower",
"(",
... | Parser for list objects response.
:param data: Response data for list objects.
:param bucket_name: Response for the bucket.
:return: Replies back three distinctive components.
- List of :class:`Object <Object>`
- True if list is truncated, False otherwise.
- Object name marker for the next request. | [
"Parser",
"for",
"list",
"objects",
"response",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L225-L250 |
226,530 | minio/minio-py | minio/parsers.py | parse_list_objects_v2 | def parse_list_objects_v2(data, bucket_name):
"""
Parser for list objects version 2 response.
:param data: Response data for list objects.
:param bucket_name: Response for the bucket.
:return: Returns three distinct components:
- List of :class:`Object <Object>`
- True if list is truncated, False otherwise.
- Continuation Token for the next request.
"""
root = S3Element.fromstring('ListObjectV2Result', data)
is_truncated = root.get_child_text('IsTruncated').lower() == 'true'
# NextContinuationToken may not be present.
continuation_token = root.get_child_text('NextContinuationToken',
strict=False)
objects, object_dirs = _parse_objects_from_xml_elts(
bucket_name,
root.findall('Contents'),
root.findall('CommonPrefixes')
)
return objects + object_dirs, is_truncated, continuation_token | python | def parse_list_objects_v2(data, bucket_name):
root = S3Element.fromstring('ListObjectV2Result', data)
is_truncated = root.get_child_text('IsTruncated').lower() == 'true'
# NextContinuationToken may not be present.
continuation_token = root.get_child_text('NextContinuationToken',
strict=False)
objects, object_dirs = _parse_objects_from_xml_elts(
bucket_name,
root.findall('Contents'),
root.findall('CommonPrefixes')
)
return objects + object_dirs, is_truncated, continuation_token | [
"def",
"parse_list_objects_v2",
"(",
"data",
",",
"bucket_name",
")",
":",
"root",
"=",
"S3Element",
".",
"fromstring",
"(",
"'ListObjectV2Result'",
",",
"data",
")",
"is_truncated",
"=",
"root",
".",
"get_child_text",
"(",
"'IsTruncated'",
")",
".",
"lower",
... | Parser for list objects version 2 response.
:param data: Response data for list objects.
:param bucket_name: Response for the bucket.
:return: Returns three distinct components:
- List of :class:`Object <Object>`
- True if list is truncated, False otherwise.
- Continuation Token for the next request. | [
"Parser",
"for",
"list",
"objects",
"version",
"2",
"response",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L253-L276 |
226,531 | minio/minio-py | minio/parsers.py | parse_list_multipart_uploads | def parse_list_multipart_uploads(data, bucket_name):
"""
Parser for list multipart uploads response.
:param data: Response data for list multipart uploads.
:param bucket_name: Response for the bucket.
:return: Replies back four distinctive components.
- List of :class:`IncompleteUpload <IncompleteUpload>`
- True if list is truncated, False otherwise.
- Object name marker for the next request.
- Upload id marker for the next request.
"""
root = S3Element.fromstring('ListMultipartUploadsResult', data)
is_truncated = root.get_child_text('IsTruncated').lower() == 'true'
key_marker = root.get_urldecoded_elem_text('NextKeyMarker', strict=False)
upload_id_marker = root.get_child_text('NextUploadIdMarker', strict=False)
uploads = [
IncompleteUpload(bucket_name,
upload.get_urldecoded_elem_text('Key'),
upload.get_child_text('UploadId'),
upload.get_localized_time_elem('Initiated'))
for upload in root.findall('Upload')
]
return uploads, is_truncated, key_marker, upload_id_marker | python | def parse_list_multipart_uploads(data, bucket_name):
root = S3Element.fromstring('ListMultipartUploadsResult', data)
is_truncated = root.get_child_text('IsTruncated').lower() == 'true'
key_marker = root.get_urldecoded_elem_text('NextKeyMarker', strict=False)
upload_id_marker = root.get_child_text('NextUploadIdMarker', strict=False)
uploads = [
IncompleteUpload(bucket_name,
upload.get_urldecoded_elem_text('Key'),
upload.get_child_text('UploadId'),
upload.get_localized_time_elem('Initiated'))
for upload in root.findall('Upload')
]
return uploads, is_truncated, key_marker, upload_id_marker | [
"def",
"parse_list_multipart_uploads",
"(",
"data",
",",
"bucket_name",
")",
":",
"root",
"=",
"S3Element",
".",
"fromstring",
"(",
"'ListMultipartUploadsResult'",
",",
"data",
")",
"is_truncated",
"=",
"root",
".",
"get_child_text",
"(",
"'IsTruncated'",
")",
"."... | Parser for list multipart uploads response.
:param data: Response data for list multipart uploads.
:param bucket_name: Response for the bucket.
:return: Replies back four distinctive components.
- List of :class:`IncompleteUpload <IncompleteUpload>`
- True if list is truncated, False otherwise.
- Object name marker for the next request.
- Upload id marker for the next request. | [
"Parser",
"for",
"list",
"multipart",
"uploads",
"response",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L278-L303 |
226,532 | minio/minio-py | minio/parsers.py | parse_list_parts | def parse_list_parts(data, bucket_name, object_name, upload_id):
"""
Parser for list parts response.
:param data: Response data for list parts.
:param bucket_name: Response for the bucket.
:param object_name: Response for the object.
:param upload_id: Upload id of object name for
the active multipart session.
:return: Replies back three distinctive components.
- List of :class:`UploadPart <UploadPart>`.
- True if list is truncated, False otherwise.
- Next part marker for the next request if the
list was truncated.
"""
root = S3Element.fromstring('ListPartsResult', data)
is_truncated = root.get_child_text('IsTruncated').lower() == 'true'
part_marker = root.get_child_text('NextPartNumberMarker', strict=False)
parts = [
UploadPart(bucket_name, object_name, upload_id,
part.get_int_elem('PartNumber'),
part.get_etag_elem(),
part.get_localized_time_elem('LastModified'),
part.get_int_elem('Size'))
for part in root.findall('Part')
]
return parts, is_truncated, part_marker | python | def parse_list_parts(data, bucket_name, object_name, upload_id):
root = S3Element.fromstring('ListPartsResult', data)
is_truncated = root.get_child_text('IsTruncated').lower() == 'true'
part_marker = root.get_child_text('NextPartNumberMarker', strict=False)
parts = [
UploadPart(bucket_name, object_name, upload_id,
part.get_int_elem('PartNumber'),
part.get_etag_elem(),
part.get_localized_time_elem('LastModified'),
part.get_int_elem('Size'))
for part in root.findall('Part')
]
return parts, is_truncated, part_marker | [
"def",
"parse_list_parts",
"(",
"data",
",",
"bucket_name",
",",
"object_name",
",",
"upload_id",
")",
":",
"root",
"=",
"S3Element",
".",
"fromstring",
"(",
"'ListPartsResult'",
",",
"data",
")",
"is_truncated",
"=",
"root",
".",
"get_child_text",
"(",
"'IsTr... | Parser for list parts response.
:param data: Response data for list parts.
:param bucket_name: Response for the bucket.
:param object_name: Response for the object.
:param upload_id: Upload id of object name for
the active multipart session.
:return: Replies back three distinctive components.
- List of :class:`UploadPart <UploadPart>`.
- True if list is truncated, False otherwise.
- Next part marker for the next request if the
list was truncated. | [
"Parser",
"for",
"list",
"parts",
"response",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L306-L334 |
226,533 | minio/minio-py | minio/parsers.py | _iso8601_to_localized_time | def _iso8601_to_localized_time(date_string):
"""
Convert iso8601 date string into UTC time.
:param date_string: iso8601 formatted date string.
:return: :class:`datetime.datetime`
"""
parsed_date = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%fZ')
localized_time = pytz.utc.localize(parsed_date)
return localized_time | python | def _iso8601_to_localized_time(date_string):
parsed_date = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%fZ')
localized_time = pytz.utc.localize(parsed_date)
return localized_time | [
"def",
"_iso8601_to_localized_time",
"(",
"date_string",
")",
":",
"parsed_date",
"=",
"datetime",
".",
"strptime",
"(",
"date_string",
",",
"'%Y-%m-%dT%H:%M:%S.%fZ'",
")",
"localized_time",
"=",
"pytz",
".",
"utc",
".",
"localize",
"(",
"parsed_date",
")",
"retur... | Convert iso8601 date string into UTC time.
:param date_string: iso8601 formatted date string.
:return: :class:`datetime.datetime` | [
"Convert",
"iso8601",
"date",
"string",
"into",
"UTC",
"time",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L356-L365 |
226,534 | minio/minio-py | minio/parsers.py | parse_get_bucket_notification | def parse_get_bucket_notification(data):
"""
Parser for a get_bucket_notification response from S3.
:param data: Body of response from get_bucket_notification.
:return: Returns bucket notification configuration
"""
root = S3Element.fromstring('GetBucketNotificationResult', data)
notifications = _parse_add_notifying_service_config(
root, {},
'TopicConfigurations', 'TopicConfiguration'
)
notifications = _parse_add_notifying_service_config(
root, notifications,
'QueueConfigurations', 'QueueConfiguration'
)
notifications = _parse_add_notifying_service_config(
root, notifications,
'CloudFunctionConfigurations', 'CloudFunctionConfiguration'
)
return notifications | python | def parse_get_bucket_notification(data):
root = S3Element.fromstring('GetBucketNotificationResult', data)
notifications = _parse_add_notifying_service_config(
root, {},
'TopicConfigurations', 'TopicConfiguration'
)
notifications = _parse_add_notifying_service_config(
root, notifications,
'QueueConfigurations', 'QueueConfiguration'
)
notifications = _parse_add_notifying_service_config(
root, notifications,
'CloudFunctionConfigurations', 'CloudFunctionConfiguration'
)
return notifications | [
"def",
"parse_get_bucket_notification",
"(",
"data",
")",
":",
"root",
"=",
"S3Element",
".",
"fromstring",
"(",
"'GetBucketNotificationResult'",
",",
"data",
")",
"notifications",
"=",
"_parse_add_notifying_service_config",
"(",
"root",
",",
"{",
"}",
",",
"'TopicC... | Parser for a get_bucket_notification response from S3.
:param data: Body of response from get_bucket_notification.
:return: Returns bucket notification configuration | [
"Parser",
"for",
"a",
"get_bucket_notification",
"response",
"from",
"S3",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L367-L389 |
226,535 | minio/minio-py | minio/parsers.py | parse_multi_object_delete_response | def parse_multi_object_delete_response(data):
"""Parser for Multi-Object Delete API response.
:param data: XML response body content from service.
:return: Returns list of error objects for each delete object that
had an error.
"""
root = S3Element.fromstring('MultiObjectDeleteResult', data)
return [
MultiDeleteError(errtag.get_child_text('Key'),
errtag.get_child_text('Code'),
errtag.get_child_text('Message'))
for errtag in root.findall('Error')
] | python | def parse_multi_object_delete_response(data):
root = S3Element.fromstring('MultiObjectDeleteResult', data)
return [
MultiDeleteError(errtag.get_child_text('Key'),
errtag.get_child_text('Code'),
errtag.get_child_text('Message'))
for errtag in root.findall('Error')
] | [
"def",
"parse_multi_object_delete_response",
"(",
"data",
")",
":",
"root",
"=",
"S3Element",
".",
"fromstring",
"(",
"'MultiObjectDeleteResult'",
",",
"data",
")",
"return",
"[",
"MultiDeleteError",
"(",
"errtag",
".",
"get_child_text",
"(",
"'Key'",
")",
",",
... | Parser for Multi-Object Delete API response.
:param data: XML response body content from service.
:return: Returns list of error objects for each delete object that
had an error. | [
"Parser",
"for",
"Multi",
"-",
"Object",
"Delete",
"API",
"response",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L427-L442 |
226,536 | minio/minio-py | minio/parsers.py | S3Element.fromstring | def fromstring(cls, root_name, data):
"""Initialize S3Element from name and XML string data.
:param name: Name for XML data. Used in XML errors.
:param data: string data to be parsed.
:return: Returns an S3Element.
"""
try:
return cls(root_name, cElementTree.fromstring(data))
except _ETREE_EXCEPTIONS as error:
raise InvalidXMLError(
'"{}" XML is not parsable. Message: {}'.format(
root_name, error.message
)
) | python | def fromstring(cls, root_name, data):
try:
return cls(root_name, cElementTree.fromstring(data))
except _ETREE_EXCEPTIONS as error:
raise InvalidXMLError(
'"{}" XML is not parsable. Message: {}'.format(
root_name, error.message
)
) | [
"def",
"fromstring",
"(",
"cls",
",",
"root_name",
",",
"data",
")",
":",
"try",
":",
"return",
"cls",
"(",
"root_name",
",",
"cElementTree",
".",
"fromstring",
"(",
"data",
")",
")",
"except",
"_ETREE_EXCEPTIONS",
"as",
"error",
":",
"raise",
"InvalidXMLE... | Initialize S3Element from name and XML string data.
:param name: Name for XML data. Used in XML errors.
:param data: string data to be parsed.
:return: Returns an S3Element. | [
"Initialize",
"S3Element",
"from",
"name",
"and",
"XML",
"string",
"data",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L64-L78 |
226,537 | minio/minio-py | minio/parsers.py | S3Element.get_child_text | def get_child_text(self, name, strict=True):
"""Extract text of a child element. If strict, and child element is
not present, raises InvalidXMLError and otherwise returns
None.
"""
if strict:
try:
return self.element.find('s3:{}'.format(name), _S3_NS).text
except _ETREE_EXCEPTIONS as error:
raise InvalidXMLError(
('Invalid XML provided for "{}" - erroring tag <{}>. '
'Message: {}').format(self.root_name, name, error.message)
)
else:
return self.element.findtext('s3:{}'.format(name), None, _S3_NS) | python | def get_child_text(self, name, strict=True):
if strict:
try:
return self.element.find('s3:{}'.format(name), _S3_NS).text
except _ETREE_EXCEPTIONS as error:
raise InvalidXMLError(
('Invalid XML provided for "{}" - erroring tag <{}>. '
'Message: {}').format(self.root_name, name, error.message)
)
else:
return self.element.findtext('s3:{}'.format(name), None, _S3_NS) | [
"def",
"get_child_text",
"(",
"self",
",",
"name",
",",
"strict",
"=",
"True",
")",
":",
"if",
"strict",
":",
"try",
":",
"return",
"self",
".",
"element",
".",
"find",
"(",
"'s3:{}'",
".",
"format",
"(",
"name",
")",
",",
"_S3_NS",
")",
".",
"text... | Extract text of a child element. If strict, and child element is
not present, raises InvalidXMLError and otherwise returns
None. | [
"Extract",
"text",
"of",
"a",
"child",
"element",
".",
"If",
"strict",
"and",
"child",
"element",
"is",
"not",
"present",
"raises",
"InvalidXMLError",
"and",
"otherwise",
"returns",
"None",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/parsers.py#L96-L111 |
226,538 | minio/minio-py | minio/helpers.py | dump_http | def dump_http(method, url, request_headers, response, output_stream):
"""
Dump all headers and response headers into output_stream.
:param request_headers: Dictionary of HTTP request headers.
:param response_headers: Dictionary of HTTP response headers.
:param output_stream: Stream where the request is being dumped at.
"""
# Start header.
output_stream.write('---------START-HTTP---------\n')
# Get parsed url.
parsed_url = urlsplit(url)
# Dump all request headers recursively.
http_path = parsed_url.path
if parsed_url.query:
http_path = http_path + '?' + parsed_url.query
output_stream.write('{0} {1} HTTP/1.1\n'.format(method,
http_path))
for k, v in list(request_headers.items()):
if k is 'authorization':
# Redact signature header value from trace logs.
v = re.sub(r'Signature=([[0-9a-f]+)', 'Signature=*REDACTED*', v)
output_stream.write('{0}: {1}\n'.format(k.title(), v))
# Write a new line.
output_stream.write('\n')
# Write response status code.
output_stream.write('HTTP/1.1 {0}\n'.format(response.status))
# Dump all response headers recursively.
for k, v in list(response.getheaders().items()):
output_stream.write('{0}: {1}\n'.format(k.title(), v))
# For all errors write all the available response body.
if response.status != 200 and \
response.status != 204 and response.status != 206:
output_stream.write('{0}'.format(response.read()))
# End header.
output_stream.write('---------END-HTTP---------\n') | python | def dump_http(method, url, request_headers, response, output_stream):
# Start header.
output_stream.write('---------START-HTTP---------\n')
# Get parsed url.
parsed_url = urlsplit(url)
# Dump all request headers recursively.
http_path = parsed_url.path
if parsed_url.query:
http_path = http_path + '?' + parsed_url.query
output_stream.write('{0} {1} HTTP/1.1\n'.format(method,
http_path))
for k, v in list(request_headers.items()):
if k is 'authorization':
# Redact signature header value from trace logs.
v = re.sub(r'Signature=([[0-9a-f]+)', 'Signature=*REDACTED*', v)
output_stream.write('{0}: {1}\n'.format(k.title(), v))
# Write a new line.
output_stream.write('\n')
# Write response status code.
output_stream.write('HTTP/1.1 {0}\n'.format(response.status))
# Dump all response headers recursively.
for k, v in list(response.getheaders().items()):
output_stream.write('{0}: {1}\n'.format(k.title(), v))
# For all errors write all the available response body.
if response.status != 200 and \
response.status != 204 and response.status != 206:
output_stream.write('{0}'.format(response.read()))
# End header.
output_stream.write('---------END-HTTP---------\n') | [
"def",
"dump_http",
"(",
"method",
",",
"url",
",",
"request_headers",
",",
"response",
",",
"output_stream",
")",
":",
"# Start header.",
"output_stream",
".",
"write",
"(",
"'---------START-HTTP---------\\n'",
")",
"# Get parsed url.",
"parsed_url",
"=",
"urlsplit",... | Dump all headers and response headers into output_stream.
:param request_headers: Dictionary of HTTP request headers.
:param response_headers: Dictionary of HTTP response headers.
:param output_stream: Stream where the request is being dumped at. | [
"Dump",
"all",
"headers",
"and",
"response",
"headers",
"into",
"output_stream",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/helpers.py#L85-L130 |
226,539 | minio/minio-py | minio/helpers.py | read_full | def read_full(data, size):
"""
read_full reads exactly `size` bytes from reader. returns
`size` bytes.
:param data: Input stream to read from.
:param size: Number of bytes to read from `data`.
:return: Returns :bytes:`part_data`
"""
default_read_size = 32768 # 32KiB per read operation.
chunk = io.BytesIO()
chunk_size = 0
while chunk_size < size:
read_size = default_read_size
if (size - chunk_size) < default_read_size:
read_size = size - chunk_size
current_data = data.read(read_size)
if not current_data or len(current_data) == 0:
break
chunk.write(current_data)
chunk_size+= len(current_data)
return chunk.getvalue() | python | def read_full(data, size):
default_read_size = 32768 # 32KiB per read operation.
chunk = io.BytesIO()
chunk_size = 0
while chunk_size < size:
read_size = default_read_size
if (size - chunk_size) < default_read_size:
read_size = size - chunk_size
current_data = data.read(read_size)
if not current_data or len(current_data) == 0:
break
chunk.write(current_data)
chunk_size+= len(current_data)
return chunk.getvalue() | [
"def",
"read_full",
"(",
"data",
",",
"size",
")",
":",
"default_read_size",
"=",
"32768",
"# 32KiB per read operation.",
"chunk",
"=",
"io",
".",
"BytesIO",
"(",
")",
"chunk_size",
"=",
"0",
"while",
"chunk_size",
"<",
"size",
":",
"read_size",
"=",
"defaul... | read_full reads exactly `size` bytes from reader. returns
`size` bytes.
:param data: Input stream to read from.
:param size: Number of bytes to read from `data`.
:return: Returns :bytes:`part_data` | [
"read_full",
"reads",
"exactly",
"size",
"bytes",
"from",
"reader",
".",
"returns",
"size",
"bytes",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/helpers.py#L161-L184 |
226,540 | minio/minio-py | minio/helpers.py | get_target_url | def get_target_url(endpoint_url, bucket_name=None, object_name=None,
bucket_region='us-east-1', query=None):
"""
Construct final target url.
:param endpoint_url: Target endpoint url where request is served to.
:param bucket_name: Bucket component for the target url.
:param object_name: Object component for the target url.
:param bucket_region: Bucket region for the target url.
:param query: Query parameters as a *dict* for the target url.
:return: Returns final target url as *str*.
"""
# New url
url = None
# Parse url
parsed_url = urlsplit(endpoint_url)
# Get new host, scheme.
scheme = parsed_url.scheme
host = parsed_url.netloc
# Strip 80/443 ports since curl & browsers do not
# send them in Host header.
if (scheme == 'http' and parsed_url.port == 80) or\
(scheme == 'https' and parsed_url.port == 443):
host = parsed_url.hostname
if 's3.amazonaws.com' in host:
host = get_s3_endpoint(bucket_region)
url = scheme + '://' + host
if bucket_name:
# Save if target url will have buckets which suppport
# virtual host.
is_virtual_host_style = is_virtual_host(endpoint_url,
bucket_name)
if is_virtual_host_style:
url = (scheme + '://' + bucket_name + '.' + host)
else:
url = (scheme + '://' + host + '/' + bucket_name)
url_components = [url]
url_components.append('/')
if object_name:
object_name = encode_object_name(object_name)
url_components.append(object_name)
if query:
ordered_query = collections.OrderedDict(sorted(query.items()))
query_components = []
for component_key in ordered_query:
if isinstance(ordered_query[component_key], list):
for value in ordered_query[component_key]:
query_components.append(component_key+'='+
queryencode(value))
else:
query_components.append(
component_key+'='+
queryencode(ordered_query.get(component_key, '')))
query_string = '&'.join(query_components)
if query_string:
url_components.append('?')
url_components.append(query_string)
return ''.join(url_components) | python | def get_target_url(endpoint_url, bucket_name=None, object_name=None,
bucket_region='us-east-1', query=None):
# New url
url = None
# Parse url
parsed_url = urlsplit(endpoint_url)
# Get new host, scheme.
scheme = parsed_url.scheme
host = parsed_url.netloc
# Strip 80/443 ports since curl & browsers do not
# send them in Host header.
if (scheme == 'http' and parsed_url.port == 80) or\
(scheme == 'https' and parsed_url.port == 443):
host = parsed_url.hostname
if 's3.amazonaws.com' in host:
host = get_s3_endpoint(bucket_region)
url = scheme + '://' + host
if bucket_name:
# Save if target url will have buckets which suppport
# virtual host.
is_virtual_host_style = is_virtual_host(endpoint_url,
bucket_name)
if is_virtual_host_style:
url = (scheme + '://' + bucket_name + '.' + host)
else:
url = (scheme + '://' + host + '/' + bucket_name)
url_components = [url]
url_components.append('/')
if object_name:
object_name = encode_object_name(object_name)
url_components.append(object_name)
if query:
ordered_query = collections.OrderedDict(sorted(query.items()))
query_components = []
for component_key in ordered_query:
if isinstance(ordered_query[component_key], list):
for value in ordered_query[component_key]:
query_components.append(component_key+'='+
queryencode(value))
else:
query_components.append(
component_key+'='+
queryencode(ordered_query.get(component_key, '')))
query_string = '&'.join(query_components)
if query_string:
url_components.append('?')
url_components.append(query_string)
return ''.join(url_components) | [
"def",
"get_target_url",
"(",
"endpoint_url",
",",
"bucket_name",
"=",
"None",
",",
"object_name",
"=",
"None",
",",
"bucket_region",
"=",
"'us-east-1'",
",",
"query",
"=",
"None",
")",
":",
"# New url",
"url",
"=",
"None",
"# Parse url",
"parsed_url",
"=",
... | Construct final target url.
:param endpoint_url: Target endpoint url where request is served to.
:param bucket_name: Bucket component for the target url.
:param object_name: Object component for the target url.
:param bucket_region: Bucket region for the target url.
:param query: Query parameters as a *dict* for the target url.
:return: Returns final target url as *str*. | [
"Construct",
"final",
"target",
"url",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/helpers.py#L207-L274 |
226,541 | minio/minio-py | minio/helpers.py | is_valid_endpoint | def is_valid_endpoint(endpoint):
"""
Verify if endpoint is valid.
:type endpoint: string
:param endpoint: An endpoint. Must have at least a scheme and a hostname.
:return: True if the endpoint is valid. Raise :exc:`InvalidEndpointError`
otherwise.
"""
try:
if urlsplit(endpoint).scheme:
raise InvalidEndpointError('Hostname cannot have a scheme.')
hostname = endpoint.split(':')[0]
if hostname is None:
raise InvalidEndpointError('Hostname cannot be empty.')
if len(hostname) > 255:
raise InvalidEndpointError('Hostname cannot be greater than 255.')
if hostname[-1] == '.':
hostname = hostname[:-1]
if not _ALLOWED_HOSTNAME_REGEX.match(hostname):
raise InvalidEndpointError('Hostname does not meet URL standards.')
except AttributeError as error:
raise TypeError(error)
return True | python | def is_valid_endpoint(endpoint):
try:
if urlsplit(endpoint).scheme:
raise InvalidEndpointError('Hostname cannot have a scheme.')
hostname = endpoint.split(':')[0]
if hostname is None:
raise InvalidEndpointError('Hostname cannot be empty.')
if len(hostname) > 255:
raise InvalidEndpointError('Hostname cannot be greater than 255.')
if hostname[-1] == '.':
hostname = hostname[:-1]
if not _ALLOWED_HOSTNAME_REGEX.match(hostname):
raise InvalidEndpointError('Hostname does not meet URL standards.')
except AttributeError as error:
raise TypeError(error)
return True | [
"def",
"is_valid_endpoint",
"(",
"endpoint",
")",
":",
"try",
":",
"if",
"urlsplit",
"(",
"endpoint",
")",
".",
"scheme",
":",
"raise",
"InvalidEndpointError",
"(",
"'Hostname cannot have a scheme.'",
")",
"hostname",
"=",
"endpoint",
".",
"split",
"(",
"':'",
... | Verify if endpoint is valid.
:type endpoint: string
:param endpoint: An endpoint. Must have at least a scheme and a hostname.
:return: True if the endpoint is valid. Raise :exc:`InvalidEndpointError`
otherwise. | [
"Verify",
"if",
"endpoint",
"is",
"valid",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/helpers.py#L277-L306 |
226,542 | minio/minio-py | minio/helpers.py | is_virtual_host | def is_virtual_host(endpoint_url, bucket_name):
"""
Check to see if the ``bucket_name`` can be part of virtual host
style.
:param endpoint_url: Endpoint url which will be used for virtual host.
:param bucket_name: Bucket name to be validated against.
"""
is_valid_bucket_name(bucket_name)
parsed_url = urlsplit(endpoint_url)
# bucket_name can be valid but '.' in the hostname will fail
# SSL certificate validation. So do not use host-style for
# such buckets.
if 'https' in parsed_url.scheme and '.' in bucket_name:
return False
for host in ['s3.amazonaws.com', 'aliyuncs.com']:
if host in parsed_url.netloc:
return True
return False | python | def is_virtual_host(endpoint_url, bucket_name):
is_valid_bucket_name(bucket_name)
parsed_url = urlsplit(endpoint_url)
# bucket_name can be valid but '.' in the hostname will fail
# SSL certificate validation. So do not use host-style for
# such buckets.
if 'https' in parsed_url.scheme and '.' in bucket_name:
return False
for host in ['s3.amazonaws.com', 'aliyuncs.com']:
if host in parsed_url.netloc:
return True
return False | [
"def",
"is_virtual_host",
"(",
"endpoint_url",
",",
"bucket_name",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"parsed_url",
"=",
"urlsplit",
"(",
"endpoint_url",
")",
"# bucket_name can be valid but '.' in the hostname will fail",
"# SSL certificate validation. ... | Check to see if the ``bucket_name`` can be part of virtual host
style.
:param endpoint_url: Endpoint url which will be used for virtual host.
:param bucket_name: Bucket name to be validated against. | [
"Check",
"to",
"see",
"if",
"the",
"bucket_name",
"can",
"be",
"part",
"of",
"virtual",
"host",
"style",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/helpers.py#L308-L327 |
226,543 | minio/minio-py | minio/helpers.py | is_valid_bucket_name | def is_valid_bucket_name(bucket_name):
"""
Check to see if the ``bucket_name`` complies with the
restricted DNS naming conventions necessary to allow
access via virtual-hosting style.
:param bucket_name: Bucket name in *str*.
:return: True if the bucket is valid. Raise :exc:`InvalidBucketError`
otherwise.
"""
# Verify bucket name length.
if len(bucket_name) < 3:
raise InvalidBucketError('Bucket name cannot be less than'
' 3 characters.')
if len(bucket_name) > 63:
raise InvalidBucketError('Bucket name cannot be more than'
' 63 characters.')
if '..' in bucket_name:
raise InvalidBucketError('Bucket name cannot have successive'
' periods.')
match = _VALID_BUCKETNAME_REGEX.match(bucket_name)
if match is None or match.end() != len(bucket_name):
raise InvalidBucketError('Bucket name does not follow S3 standards.'
' Bucket: {0}'.format(bucket_name))
return True | python | def is_valid_bucket_name(bucket_name):
# Verify bucket name length.
if len(bucket_name) < 3:
raise InvalidBucketError('Bucket name cannot be less than'
' 3 characters.')
if len(bucket_name) > 63:
raise InvalidBucketError('Bucket name cannot be more than'
' 63 characters.')
if '..' in bucket_name:
raise InvalidBucketError('Bucket name cannot have successive'
' periods.')
match = _VALID_BUCKETNAME_REGEX.match(bucket_name)
if match is None or match.end() != len(bucket_name):
raise InvalidBucketError('Bucket name does not follow S3 standards.'
' Bucket: {0}'.format(bucket_name))
return True | [
"def",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
":",
"# Verify bucket name length.",
"if",
"len",
"(",
"bucket_name",
")",
"<",
"3",
":",
"raise",
"InvalidBucketError",
"(",
"'Bucket name cannot be less than'",
"' 3 characters.'",
")",
"if",
"len",
"(",
"bucke... | Check to see if the ``bucket_name`` complies with the
restricted DNS naming conventions necessary to allow
access via virtual-hosting style.
:param bucket_name: Bucket name in *str*.
:return: True if the bucket is valid. Raise :exc:`InvalidBucketError`
otherwise. | [
"Check",
"to",
"see",
"if",
"the",
"bucket_name",
"complies",
"with",
"the",
"restricted",
"DNS",
"naming",
"conventions",
"necessary",
"to",
"allow",
"access",
"via",
"virtual",
"-",
"hosting",
"style",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/helpers.py#L329-L355 |
226,544 | minio/minio-py | minio/helpers.py | is_non_empty_string | def is_non_empty_string(input_string):
"""
Validate if non empty string
:param input_string: Input is a *str*.
:return: True if input is string and non empty.
Raise :exc:`Exception` otherwise.
"""
try:
if not input_string.strip():
raise ValueError()
except AttributeError as error:
raise TypeError(error)
return True | python | def is_non_empty_string(input_string):
try:
if not input_string.strip():
raise ValueError()
except AttributeError as error:
raise TypeError(error)
return True | [
"def",
"is_non_empty_string",
"(",
"input_string",
")",
":",
"try",
":",
"if",
"not",
"input_string",
".",
"strip",
"(",
")",
":",
"raise",
"ValueError",
"(",
")",
"except",
"AttributeError",
"as",
"error",
":",
"raise",
"TypeError",
"(",
"error",
")",
"re... | Validate if non empty string
:param input_string: Input is a *str*.
:return: True if input is string and non empty.
Raise :exc:`Exception` otherwise. | [
"Validate",
"if",
"non",
"empty",
"string"
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/helpers.py#L358-L372 |
226,545 | minio/minio-py | minio/helpers.py | is_valid_policy_type | def is_valid_policy_type(policy):
"""
Validate if policy is type str
:param policy: S3 style Bucket policy.
:return: True if policy parameter is of a valid type, 'string'.
Raise :exc:`TypeError` otherwise.
"""
if _is_py3:
string_type = str,
elif _is_py2:
string_type = basestring
if not isinstance(policy, string_type):
raise TypeError('policy can only be of type str')
is_non_empty_string(policy)
return True | python | def is_valid_policy_type(policy):
if _is_py3:
string_type = str,
elif _is_py2:
string_type = basestring
if not isinstance(policy, string_type):
raise TypeError('policy can only be of type str')
is_non_empty_string(policy)
return True | [
"def",
"is_valid_policy_type",
"(",
"policy",
")",
":",
"if",
"_is_py3",
":",
"string_type",
"=",
"str",
",",
"elif",
"_is_py2",
":",
"string_type",
"=",
"basestring",
"if",
"not",
"isinstance",
"(",
"policy",
",",
"string_type",
")",
":",
"raise",
"TypeErro... | Validate if policy is type str
:param policy: S3 style Bucket policy.
:return: True if policy parameter is of a valid type, 'string'.
Raise :exc:`TypeError` otherwise. | [
"Validate",
"if",
"policy",
"is",
"type",
"str"
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/helpers.py#L374-L392 |
226,546 | minio/minio-py | minio/helpers.py | is_valid_sse_object | def is_valid_sse_object(sse):
"""
Validate the SSE object and type
:param sse: SSE object defined.
"""
if sse and sse.type() != "SSE-C" and sse.type() != "SSE-KMS" and sse.type() != "SSE-S3":
raise InvalidArgumentError("unsuported type of sse argument in put_object") | python | def is_valid_sse_object(sse):
if sse and sse.type() != "SSE-C" and sse.type() != "SSE-KMS" and sse.type() != "SSE-S3":
raise InvalidArgumentError("unsuported type of sse argument in put_object") | [
"def",
"is_valid_sse_object",
"(",
"sse",
")",
":",
"if",
"sse",
"and",
"sse",
".",
"type",
"(",
")",
"!=",
"\"SSE-C\"",
"and",
"sse",
".",
"type",
"(",
")",
"!=",
"\"SSE-KMS\"",
"and",
"sse",
".",
"type",
"(",
")",
"!=",
"\"SSE-S3\"",
":",
"raise",
... | Validate the SSE object and type
:param sse: SSE object defined. | [
"Validate",
"the",
"SSE",
"object",
"and",
"type"
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/helpers.py#L533-L540 |
226,547 | minio/minio-py | minio/helpers.py | optimal_part_info | def optimal_part_info(length, part_size):
"""
Calculate optimal part size for multipart uploads.
:param length: Input length to calculate part size of.
:return: Optimal part size.
"""
# object size is '-1' set it to 5TiB.
if length == -1:
length = MAX_MULTIPART_OBJECT_SIZE
if length > MAX_MULTIPART_OBJECT_SIZE:
raise InvalidArgumentError('Input content size is bigger '
' than allowed maximum of 5TiB.')
# honor user configured size
if part_size != MIN_PART_SIZE:
part_size_float = float(part_size)
else:
# Use floats for part size for all calculations to avoid
# overflows during float64 to int64 conversions.
part_size_float = math.ceil(length/MAX_MULTIPART_COUNT)
part_size_float = (math.ceil(part_size_float/part_size)
* part_size)
# Total parts count.
total_parts_count = int(math.ceil(length/part_size_float))
# Part size.
part_size = int(part_size_float)
# Last part size.
last_part_size = length - int(total_parts_count-1)*part_size
return total_parts_count, part_size, last_part_size | python | def optimal_part_info(length, part_size):
# object size is '-1' set it to 5TiB.
if length == -1:
length = MAX_MULTIPART_OBJECT_SIZE
if length > MAX_MULTIPART_OBJECT_SIZE:
raise InvalidArgumentError('Input content size is bigger '
' than allowed maximum of 5TiB.')
# honor user configured size
if part_size != MIN_PART_SIZE:
part_size_float = float(part_size)
else:
# Use floats for part size for all calculations to avoid
# overflows during float64 to int64 conversions.
part_size_float = math.ceil(length/MAX_MULTIPART_COUNT)
part_size_float = (math.ceil(part_size_float/part_size)
* part_size)
# Total parts count.
total_parts_count = int(math.ceil(length/part_size_float))
# Part size.
part_size = int(part_size_float)
# Last part size.
last_part_size = length - int(total_parts_count-1)*part_size
return total_parts_count, part_size, last_part_size | [
"def",
"optimal_part_info",
"(",
"length",
",",
"part_size",
")",
":",
"# object size is '-1' set it to 5TiB.",
"if",
"length",
"==",
"-",
"1",
":",
"length",
"=",
"MAX_MULTIPART_OBJECT_SIZE",
"if",
"length",
">",
"MAX_MULTIPART_OBJECT_SIZE",
":",
"raise",
"InvalidArg... | Calculate optimal part size for multipart uploads.
:param length: Input length to calculate part size of.
:return: Optimal part size. | [
"Calculate",
"optimal",
"part",
"size",
"for",
"multipart",
"uploads",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/helpers.py#L621-L650 |
226,548 | minio/minio-py | minio/compat.py | urlencode | def urlencode(resource):
"""
This implementation of urlencode supports all unicode characters
:param: resource: Resource value to be url encoded.
"""
if isinstance(resource, str):
return _urlencode(resource.encode('utf-8'))
return _urlencode(resource) | python | def urlencode(resource):
if isinstance(resource, str):
return _urlencode(resource.encode('utf-8'))
return _urlencode(resource) | [
"def",
"urlencode",
"(",
"resource",
")",
":",
"if",
"isinstance",
"(",
"resource",
",",
"str",
")",
":",
"return",
"_urlencode",
"(",
"resource",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"return",
"_urlencode",
"(",
"resource",
")"
] | This implementation of urlencode supports all unicode characters
:param: resource: Resource value to be url encoded. | [
"This",
"implementation",
"of",
"urlencode",
"supports",
"all",
"unicode",
"characters"
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/compat.py#L96-L105 |
226,549 | minio/minio-py | minio/error.py | ResponseError.get_exception | def get_exception(self):
"""
Gets the error exception derived from the initialization of
an ErrorResponse object
:return: The derived exception or ResponseError exception
"""
exception = known_errors.get(self.code)
if exception:
return exception(self)
else:
return self | python | def get_exception(self):
exception = known_errors.get(self.code)
if exception:
return exception(self)
else:
return self | [
"def",
"get_exception",
"(",
"self",
")",
":",
"exception",
"=",
"known_errors",
".",
"get",
"(",
"self",
".",
"code",
")",
"if",
"exception",
":",
"return",
"exception",
"(",
"self",
")",
"else",
":",
"return",
"self"
] | Gets the error exception derived from the initialization of
an ErrorResponse object
:return: The derived exception or ResponseError exception | [
"Gets",
"the",
"error",
"exception",
"derived",
"from",
"the",
"initialization",
"of",
"an",
"ErrorResponse",
"object"
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/error.py#L144-L155 |
226,550 | minio/minio-py | minio/error.py | ResponseError._handle_error_response | def _handle_error_response(self, bucket_name=None):
"""
Sets error response uses xml body if available, otherwise
relies on HTTP headers.
"""
if not self._response.data:
self._set_error_response_without_body(bucket_name)
else:
self._set_error_response_with_body(bucket_name) | python | def _handle_error_response(self, bucket_name=None):
if not self._response.data:
self._set_error_response_without_body(bucket_name)
else:
self._set_error_response_with_body(bucket_name) | [
"def",
"_handle_error_response",
"(",
"self",
",",
"bucket_name",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_response",
".",
"data",
":",
"self",
".",
"_set_error_response_without_body",
"(",
"bucket_name",
")",
"else",
":",
"self",
".",
"_set_error_re... | Sets error response uses xml body if available, otherwise
relies on HTTP headers. | [
"Sets",
"error",
"response",
"uses",
"xml",
"body",
"if",
"available",
"otherwise",
"relies",
"on",
"HTTP",
"headers",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/error.py#L157-L165 |
226,551 | minio/minio-py | minio/error.py | ResponseError._set_error_response_without_body | def _set_error_response_without_body(self, bucket_name=None):
"""
Sets all the error response fields from response headers.
"""
if self._response.status == 404:
if bucket_name:
if self.object_name:
self.code = 'NoSuchKey'
self.message = self._response.reason
else:
self.code = 'NoSuchBucket'
self.message = self._response.reason
elif self._response.status == 409:
self.code = 'Conflict'
self.message = 'The bucket you tried to delete is not empty.'
elif self._response.status == 403:
self.code = 'AccessDenied'
self.message = self._response.reason
elif self._response.status == 400:
self.code = 'BadRequest'
self.message = self._response.reason
elif self._response.status == 301:
self.code = 'PermanentRedirect'
self.message = self._response.reason
elif self._response.status == 307:
self.code = 'Redirect'
self.message = self._response.reason
elif self._response.status in [405, 501]:
self.code = 'MethodNotAllowed'
self.message = self._response.reason
elif self._response.status == 500:
self.code = 'InternalError'
self.message = 'Internal Server Error.'
else:
self.code = 'UnknownException'
self.message = self._response.reason
# Set amz headers.
self._set_amz_headers() | python | def _set_error_response_without_body(self, bucket_name=None):
if self._response.status == 404:
if bucket_name:
if self.object_name:
self.code = 'NoSuchKey'
self.message = self._response.reason
else:
self.code = 'NoSuchBucket'
self.message = self._response.reason
elif self._response.status == 409:
self.code = 'Conflict'
self.message = 'The bucket you tried to delete is not empty.'
elif self._response.status == 403:
self.code = 'AccessDenied'
self.message = self._response.reason
elif self._response.status == 400:
self.code = 'BadRequest'
self.message = self._response.reason
elif self._response.status == 301:
self.code = 'PermanentRedirect'
self.message = self._response.reason
elif self._response.status == 307:
self.code = 'Redirect'
self.message = self._response.reason
elif self._response.status in [405, 501]:
self.code = 'MethodNotAllowed'
self.message = self._response.reason
elif self._response.status == 500:
self.code = 'InternalError'
self.message = 'Internal Server Error.'
else:
self.code = 'UnknownException'
self.message = self._response.reason
# Set amz headers.
self._set_amz_headers() | [
"def",
"_set_error_response_without_body",
"(",
"self",
",",
"bucket_name",
"=",
"None",
")",
":",
"if",
"self",
".",
"_response",
".",
"status",
"==",
"404",
":",
"if",
"bucket_name",
":",
"if",
"self",
".",
"object_name",
":",
"self",
".",
"code",
"=",
... | Sets all the error response fields from response headers. | [
"Sets",
"all",
"the",
"error",
"response",
"fields",
"from",
"response",
"headers",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/error.py#L200-L237 |
226,552 | minio/minio-py | minio/api.py | Minio.set_app_info | def set_app_info(self, app_name, app_version):
"""
Sets your application name and version to
default user agent in the following format.
MinIO (OS; ARCH) LIB/VER APP/VER
Example:
client.set_app_info('my_app', '1.0.2')
:param app_name: application name.
:param app_version: application version.
"""
if not (app_name and app_version):
raise ValueError('app_name and app_version cannot be empty.')
app_info = _APP_INFO.format(app_name,
app_version)
self._user_agent = ' '.join([_DEFAULT_USER_AGENT, app_info]) | python | def set_app_info(self, app_name, app_version):
if not (app_name and app_version):
raise ValueError('app_name and app_version cannot be empty.')
app_info = _APP_INFO.format(app_name,
app_version)
self._user_agent = ' '.join([_DEFAULT_USER_AGENT, app_info]) | [
"def",
"set_app_info",
"(",
"self",
",",
"app_name",
",",
"app_version",
")",
":",
"if",
"not",
"(",
"app_name",
"and",
"app_version",
")",
":",
"raise",
"ValueError",
"(",
"'app_name and app_version cannot be empty.'",
")",
"app_info",
"=",
"_APP_INFO",
".",
"f... | Sets your application name and version to
default user agent in the following format.
MinIO (OS; ARCH) LIB/VER APP/VER
Example:
client.set_app_info('my_app', '1.0.2')
:param app_name: application name.
:param app_version: application version. | [
"Sets",
"your",
"application",
"name",
"and",
"version",
"to",
"default",
"user",
"agent",
"in",
"the",
"following",
"format",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L199-L217 |
226,553 | minio/minio-py | minio/api.py | Minio.make_bucket | def make_bucket(self, bucket_name, location='us-east-1'):
"""
Make a new bucket on the server.
Optionally include Location.
['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'eu-west-1',
'eu-west-2', 'ca-central-1', 'eu-central-1', 'sa-east-1',
'cn-north-1', 'ap-southeast-1', 'ap-southeast-2',
'ap-northeast-1', 'ap-northeast-2']
Examples:
minio.make_bucket('foo')
minio.make_bucket('foo', 'us-west-1')
:param bucket_name: Bucket to create on server
:param location: Location to create bucket on
"""
is_valid_bucket_name(bucket_name)
# Default region for all requests.
region = 'us-east-1'
if self._region:
region = self._region
# Validate if caller requested bucket location is same as current region
if self._region != location:
raise InvalidArgumentError("Configured region {0}, requested"
" {1}".format(self._region,
location))
method = 'PUT'
# Set user agent once before the request.
headers = {'User-Agent': self._user_agent}
content = None
if location and location != 'us-east-1':
content = xml_marshal_bucket_constraint(location)
headers['Content-Length'] = str(len(content))
content_sha256_hex = get_sha256_hexdigest(content)
if content:
headers['Content-Md5'] = get_md5_base64digest(content)
# In case of Amazon S3. The make bucket issued on already
# existing bucket would fail with 'AuthorizationMalformed'
# error if virtual style is used. So we default to 'path
# style' as that is the preferred method here. The final
# location of the 'bucket' is provided through XML
# LocationConstraint data with the request.
# Construct target url.
url = self._endpoint_url + '/' + bucket_name + '/'
# Get signature headers if any.
headers = sign_v4(method, url, region,
headers, self._access_key,
self._secret_key,
self._session_token,
content_sha256_hex)
response = self._http.urlopen(method, url,
body=content,
headers=headers)
if response.status != 200:
raise ResponseError(response, method, bucket_name).get_exception()
self._set_bucket_region(bucket_name, region=location) | python | def make_bucket(self, bucket_name, location='us-east-1'):
is_valid_bucket_name(bucket_name)
# Default region for all requests.
region = 'us-east-1'
if self._region:
region = self._region
# Validate if caller requested bucket location is same as current region
if self._region != location:
raise InvalidArgumentError("Configured region {0}, requested"
" {1}".format(self._region,
location))
method = 'PUT'
# Set user agent once before the request.
headers = {'User-Agent': self._user_agent}
content = None
if location and location != 'us-east-1':
content = xml_marshal_bucket_constraint(location)
headers['Content-Length'] = str(len(content))
content_sha256_hex = get_sha256_hexdigest(content)
if content:
headers['Content-Md5'] = get_md5_base64digest(content)
# In case of Amazon S3. The make bucket issued on already
# existing bucket would fail with 'AuthorizationMalformed'
# error if virtual style is used. So we default to 'path
# style' as that is the preferred method here. The final
# location of the 'bucket' is provided through XML
# LocationConstraint data with the request.
# Construct target url.
url = self._endpoint_url + '/' + bucket_name + '/'
# Get signature headers if any.
headers = sign_v4(method, url, region,
headers, self._access_key,
self._secret_key,
self._session_token,
content_sha256_hex)
response = self._http.urlopen(method, url,
body=content,
headers=headers)
if response.status != 200:
raise ResponseError(response, method, bucket_name).get_exception()
self._set_bucket_region(bucket_name, region=location) | [
"def",
"make_bucket",
"(",
"self",
",",
"bucket_name",
",",
"location",
"=",
"'us-east-1'",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"# Default region for all requests.",
"region",
"=",
"'us-east-1'",
"if",
"self",
".",
"_region",
":",
"region",
... | Make a new bucket on the server.
Optionally include Location.
['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'eu-west-1',
'eu-west-2', 'ca-central-1', 'eu-central-1', 'sa-east-1',
'cn-north-1', 'ap-southeast-1', 'ap-southeast-2',
'ap-northeast-1', 'ap-northeast-2']
Examples:
minio.make_bucket('foo')
minio.make_bucket('foo', 'us-west-1')
:param bucket_name: Bucket to create on server
:param location: Location to create bucket on | [
"Make",
"a",
"new",
"bucket",
"on",
"the",
"server",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L239-L304 |
226,554 | minio/minio-py | minio/api.py | Minio.list_buckets | def list_buckets(self):
"""
List all buckets owned by the user.
Example:
bucket_list = minio.list_buckets()
for bucket in bucket_list:
print(bucket.name, bucket.created_date)
:return: An iterator of buckets owned by the current user.
"""
method = 'GET'
url = get_target_url(self._endpoint_url)
# Set user agent once before the request.
headers = {'User-Agent': self._user_agent}
# default for all requests.
region = 'us-east-1'
# region is set then use the region.
if self._region:
region = self._region
# Get signature headers if any.
headers = sign_v4(method, url, region,
headers, self._access_key,
self._secret_key,
self._session_token,
None)
response = self._http.urlopen(method, url,
body=None,
headers=headers)
if self._trace_output_stream:
dump_http(method, url, headers, response,
self._trace_output_stream)
if response.status != 200:
raise ResponseError(response, method).get_exception()
try:
return parse_list_buckets(response.data)
except InvalidXMLError:
if self._endpoint_url.endswith("s3.amazonaws.com") and (not self._access_key or not self._secret_key):
raise AccessDenied(response) | python | def list_buckets(self):
method = 'GET'
url = get_target_url(self._endpoint_url)
# Set user agent once before the request.
headers = {'User-Agent': self._user_agent}
# default for all requests.
region = 'us-east-1'
# region is set then use the region.
if self._region:
region = self._region
# Get signature headers if any.
headers = sign_v4(method, url, region,
headers, self._access_key,
self._secret_key,
self._session_token,
None)
response = self._http.urlopen(method, url,
body=None,
headers=headers)
if self._trace_output_stream:
dump_http(method, url, headers, response,
self._trace_output_stream)
if response.status != 200:
raise ResponseError(response, method).get_exception()
try:
return parse_list_buckets(response.data)
except InvalidXMLError:
if self._endpoint_url.endswith("s3.amazonaws.com") and (not self._access_key or not self._secret_key):
raise AccessDenied(response) | [
"def",
"list_buckets",
"(",
"self",
")",
":",
"method",
"=",
"'GET'",
"url",
"=",
"get_target_url",
"(",
"self",
".",
"_endpoint_url",
")",
"# Set user agent once before the request.",
"headers",
"=",
"{",
"'User-Agent'",
":",
"self",
".",
"_user_agent",
"}",
"#... | List all buckets owned by the user.
Example:
bucket_list = minio.list_buckets()
for bucket in bucket_list:
print(bucket.name, bucket.created_date)
:return: An iterator of buckets owned by the current user. | [
"List",
"all",
"buckets",
"owned",
"by",
"the",
"user",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L306-L350 |
226,555 | minio/minio-py | minio/api.py | Minio.bucket_exists | def bucket_exists(self, bucket_name):
"""
Check if the bucket exists and if the user has access to it.
:param bucket_name: To test the existence and user access.
:return: True on success.
"""
is_valid_bucket_name(bucket_name)
try:
self._url_open('HEAD', bucket_name=bucket_name)
# If the bucket has not been created yet, MinIO will return a "NoSuchBucket" error.
except NoSuchBucket:
return False
except ResponseError:
raise
return True | python | def bucket_exists(self, bucket_name):
is_valid_bucket_name(bucket_name)
try:
self._url_open('HEAD', bucket_name=bucket_name)
# If the bucket has not been created yet, MinIO will return a "NoSuchBucket" error.
except NoSuchBucket:
return False
except ResponseError:
raise
return True | [
"def",
"bucket_exists",
"(",
"self",
",",
"bucket_name",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"try",
":",
"self",
".",
"_url_open",
"(",
"'HEAD'",
",",
"bucket_name",
"=",
"bucket_name",
")",
"# If the bucket has not been created yet, MinIO will ... | Check if the bucket exists and if the user has access to it.
:param bucket_name: To test the existence and user access.
:return: True on success. | [
"Check",
"if",
"the",
"bucket",
"exists",
"and",
"if",
"the",
"user",
"has",
"access",
"to",
"it",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L352-L368 |
226,556 | minio/minio-py | minio/api.py | Minio.remove_bucket | def remove_bucket(self, bucket_name):
"""
Remove a bucket.
:param bucket_name: Bucket to remove
"""
is_valid_bucket_name(bucket_name)
self._url_open('DELETE', bucket_name=bucket_name)
# Make sure to purge bucket_name from region cache.
self._delete_bucket_region(bucket_name) | python | def remove_bucket(self, bucket_name):
is_valid_bucket_name(bucket_name)
self._url_open('DELETE', bucket_name=bucket_name)
# Make sure to purge bucket_name from region cache.
self._delete_bucket_region(bucket_name) | [
"def",
"remove_bucket",
"(",
"self",
",",
"bucket_name",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"self",
".",
"_url_open",
"(",
"'DELETE'",
",",
"bucket_name",
"=",
"bucket_name",
")",
"# Make sure to purge bucket_name from region cache.",
"self",
"... | Remove a bucket.
:param bucket_name: Bucket to remove | [
"Remove",
"a",
"bucket",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L370-L380 |
226,557 | minio/minio-py | minio/api.py | Minio.get_bucket_policy | def get_bucket_policy(self, bucket_name):
"""
Get bucket policy of given bucket name.
:param bucket_name: Bucket name.
"""
is_valid_bucket_name(bucket_name)
response = self._url_open("GET",
bucket_name=bucket_name,
query={"policy": ""})
return response.data | python | def get_bucket_policy(self, bucket_name):
is_valid_bucket_name(bucket_name)
response = self._url_open("GET",
bucket_name=bucket_name,
query={"policy": ""})
return response.data | [
"def",
"get_bucket_policy",
"(",
"self",
",",
"bucket_name",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"response",
"=",
"self",
".",
"_url_open",
"(",
"\"GET\"",
",",
"bucket_name",
"=",
"bucket_name",
",",
"query",
"=",
"{",
"\"policy\"",
":"... | Get bucket policy of given bucket name.
:param bucket_name: Bucket name. | [
"Get",
"bucket",
"policy",
"of",
"given",
"bucket",
"name",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L382-L393 |
226,558 | minio/minio-py | minio/api.py | Minio.set_bucket_policy | def set_bucket_policy(self, bucket_name, policy):
"""
Set bucket policy of given bucket name.
:param bucket_name: Bucket name.
:param policy: Access policy/ies in string format.
"""
is_valid_policy_type(policy)
is_valid_bucket_name(bucket_name)
headers = {
'Content-Length': str(len(policy)),
'Content-Md5': get_md5_base64digest(policy)
}
content_sha256_hex = get_sha256_hexdigest(policy)
self._url_open("PUT",
bucket_name=bucket_name,
query={"policy": ""},
headers=headers,
body=policy,
content_sha256=content_sha256_hex) | python | def set_bucket_policy(self, bucket_name, policy):
is_valid_policy_type(policy)
is_valid_bucket_name(bucket_name)
headers = {
'Content-Length': str(len(policy)),
'Content-Md5': get_md5_base64digest(policy)
}
content_sha256_hex = get_sha256_hexdigest(policy)
self._url_open("PUT",
bucket_name=bucket_name,
query={"policy": ""},
headers=headers,
body=policy,
content_sha256=content_sha256_hex) | [
"def",
"set_bucket_policy",
"(",
"self",
",",
"bucket_name",
",",
"policy",
")",
":",
"is_valid_policy_type",
"(",
"policy",
")",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"headers",
"=",
"{",
"'Content-Length'",
":",
"str",
"(",
"len",
"(",
"policy",
"... | Set bucket policy of given bucket name.
:param bucket_name: Bucket name.
:param policy: Access policy/ies in string format. | [
"Set",
"bucket",
"policy",
"of",
"given",
"bucket",
"name",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L400-L421 |
226,559 | minio/minio-py | minio/api.py | Minio.get_bucket_notification | def get_bucket_notification(self, bucket_name):
"""
Get notifications configured for the given bucket.
:param bucket_name: Bucket name.
"""
is_valid_bucket_name(bucket_name)
response = self._url_open(
"GET",
bucket_name=bucket_name,
query={"notification": ""},
)
data = response.data.decode('utf-8')
return parse_get_bucket_notification(data) | python | def get_bucket_notification(self, bucket_name):
is_valid_bucket_name(bucket_name)
response = self._url_open(
"GET",
bucket_name=bucket_name,
query={"notification": ""},
)
data = response.data.decode('utf-8')
return parse_get_bucket_notification(data) | [
"def",
"get_bucket_notification",
"(",
"self",
",",
"bucket_name",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"response",
"=",
"self",
".",
"_url_open",
"(",
"\"GET\"",
",",
"bucket_name",
"=",
"bucket_name",
",",
"query",
"=",
"{",
"\"notificati... | Get notifications configured for the given bucket.
:param bucket_name: Bucket name. | [
"Get",
"notifications",
"configured",
"for",
"the",
"given",
"bucket",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L423-L437 |
226,560 | minio/minio-py | minio/api.py | Minio.set_bucket_notification | def set_bucket_notification(self, bucket_name, notifications):
"""
Set the given notifications on the bucket.
:param bucket_name: Bucket name.
:param notifications: Notifications structure
"""
is_valid_bucket_name(bucket_name)
is_valid_bucket_notification_config(notifications)
content = xml_marshal_bucket_notifications(notifications)
headers = {
'Content-Length': str(len(content)),
'Content-Md5': get_md5_base64digest(content)
}
content_sha256_hex = get_sha256_hexdigest(content)
self._url_open(
'PUT',
bucket_name=bucket_name,
query={"notification": ""},
headers=headers,
body=content,
content_sha256=content_sha256_hex
) | python | def set_bucket_notification(self, bucket_name, notifications):
is_valid_bucket_name(bucket_name)
is_valid_bucket_notification_config(notifications)
content = xml_marshal_bucket_notifications(notifications)
headers = {
'Content-Length': str(len(content)),
'Content-Md5': get_md5_base64digest(content)
}
content_sha256_hex = get_sha256_hexdigest(content)
self._url_open(
'PUT',
bucket_name=bucket_name,
query={"notification": ""},
headers=headers,
body=content,
content_sha256=content_sha256_hex
) | [
"def",
"set_bucket_notification",
"(",
"self",
",",
"bucket_name",
",",
"notifications",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"is_valid_bucket_notification_config",
"(",
"notifications",
")",
"content",
"=",
"xml_marshal_bucket_notifications",
"(",
"... | Set the given notifications on the bucket.
:param bucket_name: Bucket name.
:param notifications: Notifications structure | [
"Set",
"the",
"given",
"notifications",
"on",
"the",
"bucket",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L439-L462 |
226,561 | minio/minio-py | minio/api.py | Minio.remove_all_bucket_notification | def remove_all_bucket_notification(self, bucket_name):
"""
Removes all bucket notification configs configured
previously, this call disable event notifications
on a bucket. This operation cannot be undone, to
set notifications again you should use
``set_bucket_notification``
:param bucket_name: Bucket name.
"""
is_valid_bucket_name(bucket_name)
content_bytes = xml_marshal_bucket_notifications({})
headers = {
'Content-Length': str(len(content_bytes)),
'Content-Md5': get_md5_base64digest(content_bytes)
}
content_sha256_hex = get_sha256_hexdigest(content_bytes)
self._url_open(
'PUT',
bucket_name=bucket_name,
query={"notification": ""},
headers=headers,
body=content_bytes,
content_sha256=content_sha256_hex
) | python | def remove_all_bucket_notification(self, bucket_name):
is_valid_bucket_name(bucket_name)
content_bytes = xml_marshal_bucket_notifications({})
headers = {
'Content-Length': str(len(content_bytes)),
'Content-Md5': get_md5_base64digest(content_bytes)
}
content_sha256_hex = get_sha256_hexdigest(content_bytes)
self._url_open(
'PUT',
bucket_name=bucket_name,
query={"notification": ""},
headers=headers,
body=content_bytes,
content_sha256=content_sha256_hex
) | [
"def",
"remove_all_bucket_notification",
"(",
"self",
",",
"bucket_name",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"content_bytes",
"=",
"xml_marshal_bucket_notifications",
"(",
"{",
"}",
")",
"headers",
"=",
"{",
"'Content-Length'",
":",
"str",
"(... | Removes all bucket notification configs configured
previously, this call disable event notifications
on a bucket. This operation cannot be undone, to
set notifications again you should use
``set_bucket_notification``
:param bucket_name: Bucket name. | [
"Removes",
"all",
"bucket",
"notification",
"configs",
"configured",
"previously",
"this",
"call",
"disable",
"event",
"notifications",
"on",
"a",
"bucket",
".",
"This",
"operation",
"cannot",
"be",
"undone",
"to",
"set",
"notifications",
"again",
"you",
"should",... | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L464-L489 |
226,562 | minio/minio-py | minio/api.py | Minio.listen_bucket_notification | def listen_bucket_notification(self, bucket_name, prefix='', suffix='',
events=['s3:ObjectCreated:*',
's3:ObjectRemoved:*',
's3:ObjectAccessed:*']):
"""
Yeilds new event notifications on a bucket, caller should iterate
to read new notifications.
NOTE: Notification is retried in case of `JSONDecodeError` otherwise
the function raises an exception.
:param bucket_name: Bucket name to listen event notifications from.
:param prefix: Object key prefix to filter notifications for.
:param suffix: Object key suffix to filter notifications for.
:param events: Enables notifications for specific event types.
of events.
"""
is_valid_bucket_name(bucket_name)
# If someone explicitly set prefix to None convert it to empty string.
if prefix is None:
prefix = ''
# If someone explicitly set suffix to None convert it to empty string.
if suffix is None:
suffix = ''
url_components = urlsplit(self._endpoint_url)
if url_components.hostname == 's3.amazonaws.com':
raise InvalidArgumentError(
'Listening for event notifications on a bucket is a MinIO '
'specific extension to bucket notification API. It is not '
'supported by Amazon S3')
query = {
'prefix': prefix,
'suffix': suffix,
'events': events,
}
while True:
response = self._url_open('GET', bucket_name=bucket_name,
query=query, preload_content=False)
try:
for line in response.stream():
if line.strip():
if hasattr(line, 'decode'):
line = line.decode('utf-8')
event = json.loads(line)
if event['Records'] is not None:
yield event
except JSONDecodeError:
response.close()
continue | python | def listen_bucket_notification(self, bucket_name, prefix='', suffix='',
events=['s3:ObjectCreated:*',
's3:ObjectRemoved:*',
's3:ObjectAccessed:*']):
is_valid_bucket_name(bucket_name)
# If someone explicitly set prefix to None convert it to empty string.
if prefix is None:
prefix = ''
# If someone explicitly set suffix to None convert it to empty string.
if suffix is None:
suffix = ''
url_components = urlsplit(self._endpoint_url)
if url_components.hostname == 's3.amazonaws.com':
raise InvalidArgumentError(
'Listening for event notifications on a bucket is a MinIO '
'specific extension to bucket notification API. It is not '
'supported by Amazon S3')
query = {
'prefix': prefix,
'suffix': suffix,
'events': events,
}
while True:
response = self._url_open('GET', bucket_name=bucket_name,
query=query, preload_content=False)
try:
for line in response.stream():
if line.strip():
if hasattr(line, 'decode'):
line = line.decode('utf-8')
event = json.loads(line)
if event['Records'] is not None:
yield event
except JSONDecodeError:
response.close()
continue | [
"def",
"listen_bucket_notification",
"(",
"self",
",",
"bucket_name",
",",
"prefix",
"=",
"''",
",",
"suffix",
"=",
"''",
",",
"events",
"=",
"[",
"'s3:ObjectCreated:*'",
",",
"'s3:ObjectRemoved:*'",
",",
"'s3:ObjectAccessed:*'",
"]",
")",
":",
"is_valid_bucket_na... | Yeilds new event notifications on a bucket, caller should iterate
to read new notifications.
NOTE: Notification is retried in case of `JSONDecodeError` otherwise
the function raises an exception.
:param bucket_name: Bucket name to listen event notifications from.
:param prefix: Object key prefix to filter notifications for.
:param suffix: Object key suffix to filter notifications for.
:param events: Enables notifications for specific event types.
of events. | [
"Yeilds",
"new",
"event",
"notifications",
"on",
"a",
"bucket",
"caller",
"should",
"iterate",
"to",
"read",
"new",
"notifications",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L491-L543 |
226,563 | minio/minio-py | minio/api.py | Minio.fget_object | def fget_object(self, bucket_name, object_name, file_path, request_headers=None, sse=None):
"""
Retrieves an object from a bucket and writes at file_path.
Examples:
minio.fget_object('foo', 'bar', 'localfile')
:param bucket_name: Bucket to read object from.
:param object_name: Name of the object to read.
:param file_path: Local file path to save the object.
:param request_headers: Any additional headers to be added with GET request.
"""
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
stat = self.stat_object(bucket_name, object_name, sse)
if os.path.isdir(file_path):
raise OSError("file is a directory.")
# Create top level directory if needed.
top_level_dir = os.path.dirname(file_path)
if top_level_dir:
mkdir_p(top_level_dir)
# Write to a temporary file "file_path.part.minio" before saving.
file_part_path = file_path + stat.etag + '.part.minio'
# Open file in 'write+append' mode.
with open(file_part_path, 'ab') as file_part_data:
# Save current file_part statinfo.
file_statinfo = os.stat(file_part_path)
# Get partial object.
response = self._get_partial_object(bucket_name, object_name,
offset=file_statinfo.st_size,
length=0,
request_headers=request_headers,
sse=sse)
# Save content_size to verify if we wrote more data.
content_size = int(response.headers['content-length'])
# Save total_written.
total_written = 0
for data in response.stream(amt=1024 * 1024):
file_part_data.write(data)
total_written += len(data)
# Release the connection from the response at this point.
response.release_conn()
# Verify if we wrote data properly.
if total_written < content_size:
msg = 'Data written {0} bytes is smaller than the' \
'specified size {1} bytes'.format(total_written,
content_size)
raise InvalidSizeError(msg)
if total_written > content_size:
msg = 'Data written {0} bytes is in excess than the' \
'specified size {1} bytes'.format(total_written,
content_size)
raise InvalidSizeError(msg)
#Delete existing file to be compatible with Windows
if os.path.exists(file_path):
os.remove(file_path)
#Rename with destination file path
os.rename(file_part_path, file_path)
# Return the stat
return stat | python | def fget_object(self, bucket_name, object_name, file_path, request_headers=None, sse=None):
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
stat = self.stat_object(bucket_name, object_name, sse)
if os.path.isdir(file_path):
raise OSError("file is a directory.")
# Create top level directory if needed.
top_level_dir = os.path.dirname(file_path)
if top_level_dir:
mkdir_p(top_level_dir)
# Write to a temporary file "file_path.part.minio" before saving.
file_part_path = file_path + stat.etag + '.part.minio'
# Open file in 'write+append' mode.
with open(file_part_path, 'ab') as file_part_data:
# Save current file_part statinfo.
file_statinfo = os.stat(file_part_path)
# Get partial object.
response = self._get_partial_object(bucket_name, object_name,
offset=file_statinfo.st_size,
length=0,
request_headers=request_headers,
sse=sse)
# Save content_size to verify if we wrote more data.
content_size = int(response.headers['content-length'])
# Save total_written.
total_written = 0
for data in response.stream(amt=1024 * 1024):
file_part_data.write(data)
total_written += len(data)
# Release the connection from the response at this point.
response.release_conn()
# Verify if we wrote data properly.
if total_written < content_size:
msg = 'Data written {0} bytes is smaller than the' \
'specified size {1} bytes'.format(total_written,
content_size)
raise InvalidSizeError(msg)
if total_written > content_size:
msg = 'Data written {0} bytes is in excess than the' \
'specified size {1} bytes'.format(total_written,
content_size)
raise InvalidSizeError(msg)
#Delete existing file to be compatible with Windows
if os.path.exists(file_path):
os.remove(file_path)
#Rename with destination file path
os.rename(file_part_path, file_path)
# Return the stat
return stat | [
"def",
"fget_object",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"file_path",
",",
"request_headers",
"=",
"None",
",",
"sse",
"=",
"None",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"is_non_empty_string",
"(",
"object_name",
")",
... | Retrieves an object from a bucket and writes at file_path.
Examples:
minio.fget_object('foo', 'bar', 'localfile')
:param bucket_name: Bucket to read object from.
:param object_name: Name of the object to read.
:param file_path: Local file path to save the object.
:param request_headers: Any additional headers to be added with GET request. | [
"Retrieves",
"an",
"object",
"from",
"a",
"bucket",
"and",
"writes",
"at",
"file_path",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L573-L645 |
226,564 | minio/minio-py | minio/api.py | Minio.copy_object | def copy_object(self, bucket_name, object_name, object_source,
conditions=None, source_sse=None, sse=None, metadata=None):
"""
Copy a source object on object storage server to a new object.
NOTE: Maximum object size supported by this API is 5GB.
Examples:
:param bucket_name: Bucket of new object.
:param object_name: Name of new object.
:param object_source: Source object to be copied.
:param conditions: :class:`CopyConditions` object. Collection of
supported CopyObject conditions.
:param metadata: Any user-defined metadata to be copied along with
destination object.
"""
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
is_non_empty_string(object_source)
headers = {}
# Preserving the user-defined metadata in headers
if metadata is not None:
headers = amzprefix_user_metadata(metadata)
headers["x-amz-metadata-directive"] = "REPLACE"
if conditions:
for k, v in conditions.items():
headers[k] = v
# Source argument to copy_object can only be of type copy_SSE_C
if source_sse:
is_valid_source_sse_object(source_sse)
headers.update(source_sse.marshal())
#Destination argument to copy_object cannot be of type copy_SSE_C
if sse:
is_valid_sse_object(sse)
headers.update(sse.marshal())
headers['X-Amz-Copy-Source'] = queryencode(object_source)
response = self._url_open('PUT',
bucket_name=bucket_name,
object_name=object_name,
headers=headers)
return parse_copy_object(bucket_name, object_name, response.data) | python | def copy_object(self, bucket_name, object_name, object_source,
conditions=None, source_sse=None, sse=None, metadata=None):
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
is_non_empty_string(object_source)
headers = {}
# Preserving the user-defined metadata in headers
if metadata is not None:
headers = amzprefix_user_metadata(metadata)
headers["x-amz-metadata-directive"] = "REPLACE"
if conditions:
for k, v in conditions.items():
headers[k] = v
# Source argument to copy_object can only be of type copy_SSE_C
if source_sse:
is_valid_source_sse_object(source_sse)
headers.update(source_sse.marshal())
#Destination argument to copy_object cannot be of type copy_SSE_C
if sse:
is_valid_sse_object(sse)
headers.update(sse.marshal())
headers['X-Amz-Copy-Source'] = queryencode(object_source)
response = self._url_open('PUT',
bucket_name=bucket_name,
object_name=object_name,
headers=headers)
return parse_copy_object(bucket_name, object_name, response.data) | [
"def",
"copy_object",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"object_source",
",",
"conditions",
"=",
"None",
",",
"source_sse",
"=",
"None",
",",
"sse",
"=",
"None",
",",
"metadata",
"=",
"None",
")",
":",
"is_valid_bucket_name",
"(",
"... | Copy a source object on object storage server to a new object.
NOTE: Maximum object size supported by this API is 5GB.
Examples:
:param bucket_name: Bucket of new object.
:param object_name: Name of new object.
:param object_source: Source object to be copied.
:param conditions: :class:`CopyConditions` object. Collection of
supported CopyObject conditions.
:param metadata: Any user-defined metadata to be copied along with
destination object. | [
"Copy",
"a",
"source",
"object",
"on",
"object",
"storage",
"server",
"to",
"a",
"new",
"object",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L708-L756 |
226,565 | minio/minio-py | minio/api.py | Minio.list_objects | def list_objects(self, bucket_name, prefix='', recursive=False):
"""
List objects in the given bucket.
Examples:
objects = minio.list_objects('foo')
for current_object in objects:
print(current_object)
# hello
# hello/
# hello/
# world/
objects = minio.list_objects('foo', prefix='hello/')
for current_object in objects:
print(current_object)
# hello/world/
objects = minio.list_objects('foo', recursive=True)
for current_object in objects:
print(current_object)
# hello/world/1
# world/world/2
# ...
objects = minio.list_objects('foo', prefix='hello/',
recursive=True)
for current_object in objects:
print(current_object)
# hello/world/1
# hello/world/2
:param bucket_name: Bucket to list objects from
:param prefix: String specifying objects returned must begin with
:param recursive: If yes, returns all objects for a specified prefix
:return: An iterator of objects in alphabetical order.
"""
is_valid_bucket_name(bucket_name)
# If someone explicitly set prefix to None convert it to empty string.
if prefix is None:
prefix = ''
method = 'GET'
# Initialize query parameters.
query = {
'max-keys': '1000',
'prefix': prefix
}
# Delimited by default.
if not recursive:
query['delimiter'] = '/'
marker = ''
is_truncated = True
while is_truncated:
if marker:
query['marker'] = marker
headers = {}
response = self._url_open(method,
bucket_name=bucket_name,
query=query,
headers=headers)
objects, is_truncated, marker = parse_list_objects(response.data,
bucket_name=bucket_name)
for obj in objects:
yield obj | python | def list_objects(self, bucket_name, prefix='', recursive=False):
is_valid_bucket_name(bucket_name)
# If someone explicitly set prefix to None convert it to empty string.
if prefix is None:
prefix = ''
method = 'GET'
# Initialize query parameters.
query = {
'max-keys': '1000',
'prefix': prefix
}
# Delimited by default.
if not recursive:
query['delimiter'] = '/'
marker = ''
is_truncated = True
while is_truncated:
if marker:
query['marker'] = marker
headers = {}
response = self._url_open(method,
bucket_name=bucket_name,
query=query,
headers=headers)
objects, is_truncated, marker = parse_list_objects(response.data,
bucket_name=bucket_name)
for obj in objects:
yield obj | [
"def",
"list_objects",
"(",
"self",
",",
"bucket_name",
",",
"prefix",
"=",
"''",
",",
"recursive",
"=",
"False",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"# If someone explicitly set prefix to None convert it to empty string.",
"if",
"prefix",
"is",
... | List objects in the given bucket.
Examples:
objects = minio.list_objects('foo')
for current_object in objects:
print(current_object)
# hello
# hello/
# hello/
# world/
objects = minio.list_objects('foo', prefix='hello/')
for current_object in objects:
print(current_object)
# hello/world/
objects = minio.list_objects('foo', recursive=True)
for current_object in objects:
print(current_object)
# hello/world/1
# world/world/2
# ...
objects = minio.list_objects('foo', prefix='hello/',
recursive=True)
for current_object in objects:
print(current_object)
# hello/world/1
# hello/world/2
:param bucket_name: Bucket to list objects from
:param prefix: String specifying objects returned must begin with
:param recursive: If yes, returns all objects for a specified prefix
:return: An iterator of objects in alphabetical order. | [
"List",
"objects",
"in",
"the",
"given",
"bucket",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L840-L908 |
226,566 | minio/minio-py | minio/api.py | Minio.list_objects_v2 | def list_objects_v2(self, bucket_name, prefix='', recursive=False):
"""
List objects in the given bucket using the List objects V2 API.
Examples:
objects = minio.list_objects_v2('foo')
for current_object in objects:
print(current_object)
# hello
# hello/
# hello/
# world/
objects = minio.list_objects_v2('foo', prefix='hello/')
for current_object in objects:
print(current_object)
# hello/world/
objects = minio.list_objects_v2('foo', recursive=True)
for current_object in objects:
print(current_object)
# hello/world/1
# world/world/2
# ...
objects = minio.list_objects_v2('foo', prefix='hello/',
recursive=True)
for current_object in objects:
print(current_object)
# hello/world/1
# hello/world/2
:param bucket_name: Bucket to list objects from
:param prefix: String specifying objects returned must begin with
:param recursive: If yes, returns all objects for a specified prefix
:return: An iterator of objects in alphabetical order.
"""
is_valid_bucket_name(bucket_name)
# If someone explicitly set prefix to None convert it to empty string.
if prefix is None:
prefix = ''
# Initialize query parameters.
query = {
'list-type': '2',
'prefix': prefix
}
# Delimited by default.
if not recursive:
query['delimiter'] = '/'
continuation_token = None
is_truncated = True
while is_truncated:
if continuation_token is not None:
query['continuation-token'] = continuation_token
response = self._url_open(method='GET',
bucket_name=bucket_name,
query=query)
objects, is_truncated, continuation_token = parse_list_objects_v2(
response.data, bucket_name=bucket_name
)
for obj in objects:
yield obj | python | def list_objects_v2(self, bucket_name, prefix='', recursive=False):
is_valid_bucket_name(bucket_name)
# If someone explicitly set prefix to None convert it to empty string.
if prefix is None:
prefix = ''
# Initialize query parameters.
query = {
'list-type': '2',
'prefix': prefix
}
# Delimited by default.
if not recursive:
query['delimiter'] = '/'
continuation_token = None
is_truncated = True
while is_truncated:
if continuation_token is not None:
query['continuation-token'] = continuation_token
response = self._url_open(method='GET',
bucket_name=bucket_name,
query=query)
objects, is_truncated, continuation_token = parse_list_objects_v2(
response.data, bucket_name=bucket_name
)
for obj in objects:
yield obj | [
"def",
"list_objects_v2",
"(",
"self",
",",
"bucket_name",
",",
"prefix",
"=",
"''",
",",
"recursive",
"=",
"False",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"# If someone explicitly set prefix to None convert it to empty string.",
"if",
"prefix",
"is"... | List objects in the given bucket using the List objects V2 API.
Examples:
objects = minio.list_objects_v2('foo')
for current_object in objects:
print(current_object)
# hello
# hello/
# hello/
# world/
objects = minio.list_objects_v2('foo', prefix='hello/')
for current_object in objects:
print(current_object)
# hello/world/
objects = minio.list_objects_v2('foo', recursive=True)
for current_object in objects:
print(current_object)
# hello/world/1
# world/world/2
# ...
objects = minio.list_objects_v2('foo', prefix='hello/',
recursive=True)
for current_object in objects:
print(current_object)
# hello/world/1
# hello/world/2
:param bucket_name: Bucket to list objects from
:param prefix: String specifying objects returned must begin with
:param recursive: If yes, returns all objects for a specified prefix
:return: An iterator of objects in alphabetical order. | [
"List",
"objects",
"in",
"the",
"given",
"bucket",
"using",
"the",
"List",
"objects",
"V2",
"API",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L910-L976 |
226,567 | minio/minio-py | minio/api.py | Minio.stat_object | def stat_object(self, bucket_name, object_name, sse=None):
"""
Check if an object exists.
:param bucket_name: Bucket of object.
:param object_name: Name of object
:return: Object metadata if object exists
"""
headers = {}
if sse:
is_valid_sse_c_object(sse=sse)
headers.update(sse.marshal())
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
response = self._url_open('HEAD', bucket_name=bucket_name,
object_name=object_name, headers=headers)
etag = response.headers.get('etag', '').replace('"', '')
size = int(response.headers.get('content-length', '0'))
content_type = response.headers.get('content-type', '')
last_modified = response.headers.get('last-modified')
## Capture only custom metadata.
custom_metadata = dict()
for k in response.headers:
if is_supported_header(k) or is_amz_header(k):
custom_metadata[k] = response.headers.get(k)
if last_modified:
last_modified = dateutil.parser.parse(last_modified).timetuple()
return Object(bucket_name, object_name, last_modified, etag, size,
content_type=content_type, metadata=custom_metadata) | python | def stat_object(self, bucket_name, object_name, sse=None):
headers = {}
if sse:
is_valid_sse_c_object(sse=sse)
headers.update(sse.marshal())
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
response = self._url_open('HEAD', bucket_name=bucket_name,
object_name=object_name, headers=headers)
etag = response.headers.get('etag', '').replace('"', '')
size = int(response.headers.get('content-length', '0'))
content_type = response.headers.get('content-type', '')
last_modified = response.headers.get('last-modified')
## Capture only custom metadata.
custom_metadata = dict()
for k in response.headers:
if is_supported_header(k) or is_amz_header(k):
custom_metadata[k] = response.headers.get(k)
if last_modified:
last_modified = dateutil.parser.parse(last_modified).timetuple()
return Object(bucket_name, object_name, last_modified, etag, size,
content_type=content_type, metadata=custom_metadata) | [
"def",
"stat_object",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"sse",
"=",
"None",
")",
":",
"headers",
"=",
"{",
"}",
"if",
"sse",
":",
"is_valid_sse_c_object",
"(",
"sse",
"=",
"sse",
")",
"headers",
".",
"update",
"(",
"sse",
".",
... | Check if an object exists.
:param bucket_name: Bucket of object.
:param object_name: Name of object
:return: Object metadata if object exists | [
"Check",
"if",
"an",
"object",
"exists",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L978-L1012 |
226,568 | minio/minio-py | minio/api.py | Minio.remove_object | def remove_object(self, bucket_name, object_name):
"""
Remove an object from the bucket.
:param bucket_name: Bucket of object to remove
:param object_name: Name of object to remove
:return: None
"""
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
# No reason to store successful response, for errors
# relevant exceptions are thrown.
self._url_open('DELETE', bucket_name=bucket_name,
object_name=object_name) | python | def remove_object(self, bucket_name, object_name):
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
# No reason to store successful response, for errors
# relevant exceptions are thrown.
self._url_open('DELETE', bucket_name=bucket_name,
object_name=object_name) | [
"def",
"remove_object",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"is_non_empty_string",
"(",
"object_name",
")",
"# No reason to store successful response, for errors",
"# relevant exceptions are thrown.",
... | Remove an object from the bucket.
:param bucket_name: Bucket of object to remove
:param object_name: Name of object to remove
:return: None | [
"Remove",
"an",
"object",
"from",
"the",
"bucket",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1014-L1028 |
226,569 | minio/minio-py | minio/api.py | Minio._process_remove_objects_batch | def _process_remove_objects_batch(self, bucket_name, objects_batch):
"""
Requester and response parser for remove_objects
"""
# assemble request content for objects_batch
content = xml_marshal_delete_objects(objects_batch)
# compute headers
headers = {
'Content-Md5': get_md5_base64digest(content),
'Content-Length': len(content)
}
query = {'delete': ''}
content_sha256_hex = get_sha256_hexdigest(content)
# send multi-object delete request
response = self._url_open(
'POST', bucket_name=bucket_name,
headers=headers, body=content,
query=query, content_sha256=content_sha256_hex,
)
# parse response to find delete errors
return parse_multi_object_delete_response(response.data) | python | def _process_remove_objects_batch(self, bucket_name, objects_batch):
# assemble request content for objects_batch
content = xml_marshal_delete_objects(objects_batch)
# compute headers
headers = {
'Content-Md5': get_md5_base64digest(content),
'Content-Length': len(content)
}
query = {'delete': ''}
content_sha256_hex = get_sha256_hexdigest(content)
# send multi-object delete request
response = self._url_open(
'POST', bucket_name=bucket_name,
headers=headers, body=content,
query=query, content_sha256=content_sha256_hex,
)
# parse response to find delete errors
return parse_multi_object_delete_response(response.data) | [
"def",
"_process_remove_objects_batch",
"(",
"self",
",",
"bucket_name",
",",
"objects_batch",
")",
":",
"# assemble request content for objects_batch",
"content",
"=",
"xml_marshal_delete_objects",
"(",
"objects_batch",
")",
"# compute headers",
"headers",
"=",
"{",
"'Cont... | Requester and response parser for remove_objects | [
"Requester",
"and",
"response",
"parser",
"for",
"remove_objects"
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1030-L1053 |
226,570 | minio/minio-py | minio/api.py | Minio.remove_objects | def remove_objects(self, bucket_name, objects_iter):
"""
Removes multiple objects from a bucket.
:param bucket_name: Bucket from which to remove objects
:param objects_iter: A list, tuple or iterator that provides
objects names to delete.
:return: An iterator of MultiDeleteError instances for each
object that had a delete error.
"""
is_valid_bucket_name(bucket_name)
if isinstance(objects_iter, basestring):
raise TypeError(
'objects_iter cannot be `str` or `bytes` instance. It must be '
'a list, tuple or iterator of object names'
)
# turn list like objects into an iterator.
objects_iter = itertools.chain(objects_iter)
obj_batch = []
exit_loop = False
while not exit_loop:
try:
object_name = next(objects_iter)
is_non_empty_string(object_name)
except StopIteration:
exit_loop = True
if not exit_loop:
obj_batch.append(object_name)
# if we have 1000 items in the batch, or we have to exit
# the loop, we have to make a request to delete objects.
if len(obj_batch) == 1000 or (exit_loop and len(obj_batch) > 0):
# send request and parse response
errs_result = self._process_remove_objects_batch(
bucket_name, obj_batch
)
# return the delete errors.
for err_result in errs_result:
yield err_result
# clear batch for next set of items
obj_batch = [] | python | def remove_objects(self, bucket_name, objects_iter):
is_valid_bucket_name(bucket_name)
if isinstance(objects_iter, basestring):
raise TypeError(
'objects_iter cannot be `str` or `bytes` instance. It must be '
'a list, tuple or iterator of object names'
)
# turn list like objects into an iterator.
objects_iter = itertools.chain(objects_iter)
obj_batch = []
exit_loop = False
while not exit_loop:
try:
object_name = next(objects_iter)
is_non_empty_string(object_name)
except StopIteration:
exit_loop = True
if not exit_loop:
obj_batch.append(object_name)
# if we have 1000 items in the batch, or we have to exit
# the loop, we have to make a request to delete objects.
if len(obj_batch) == 1000 or (exit_loop and len(obj_batch) > 0):
# send request and parse response
errs_result = self._process_remove_objects_batch(
bucket_name, obj_batch
)
# return the delete errors.
for err_result in errs_result:
yield err_result
# clear batch for next set of items
obj_batch = [] | [
"def",
"remove_objects",
"(",
"self",
",",
"bucket_name",
",",
"objects_iter",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"if",
"isinstance",
"(",
"objects_iter",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"'objects_iter cannot be `str` ... | Removes multiple objects from a bucket.
:param bucket_name: Bucket from which to remove objects
:param objects_iter: A list, tuple or iterator that provides
objects names to delete.
:return: An iterator of MultiDeleteError instances for each
object that had a delete error. | [
"Removes",
"multiple",
"objects",
"from",
"a",
"bucket",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1055-L1103 |
226,571 | minio/minio-py | minio/api.py | Minio.list_incomplete_uploads | def list_incomplete_uploads(self, bucket_name, prefix='',
recursive=False):
"""
List all in-complete uploads for a given bucket.
Examples:
incomplete_uploads = minio.list_incomplete_uploads('foo')
for current_upload in incomplete_uploads:
print(current_upload)
# hello
# hello/
# hello/
# world/
incomplete_uploads = minio.list_incomplete_uploads('foo',
prefix='hello/')
for current_upload in incomplete_uploads:
print(current_upload)
# hello/world/
incomplete_uploads = minio.list_incomplete_uploads('foo',
recursive=True)
for current_upload in incomplete_uploads:
print(current_upload)
# hello/world/1
# world/world/2
# ...
incomplete_uploads = minio.list_incomplete_uploads('foo',
prefix='hello/',
recursive=True)
for current_upload in incomplete_uploads:
print(current_upload)
# hello/world/1
# hello/world/2
:param bucket_name: Bucket to list incomplete uploads
:param prefix: String specifying objects returned must begin with.
:param recursive: If yes, returns all incomplete uploads for
a specified prefix.
:return: An generator of incomplete uploads in alphabetical order.
"""
is_valid_bucket_name(bucket_name)
return self._list_incomplete_uploads(bucket_name, prefix, recursive) | python | def list_incomplete_uploads(self, bucket_name, prefix='',
recursive=False):
is_valid_bucket_name(bucket_name)
return self._list_incomplete_uploads(bucket_name, prefix, recursive) | [
"def",
"list_incomplete_uploads",
"(",
"self",
",",
"bucket_name",
",",
"prefix",
"=",
"''",
",",
"recursive",
"=",
"False",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"return",
"self",
".",
"_list_incomplete_uploads",
"(",
"bucket_name",
",",
"p... | List all in-complete uploads for a given bucket.
Examples:
incomplete_uploads = minio.list_incomplete_uploads('foo')
for current_upload in incomplete_uploads:
print(current_upload)
# hello
# hello/
# hello/
# world/
incomplete_uploads = minio.list_incomplete_uploads('foo',
prefix='hello/')
for current_upload in incomplete_uploads:
print(current_upload)
# hello/world/
incomplete_uploads = minio.list_incomplete_uploads('foo',
recursive=True)
for current_upload in incomplete_uploads:
print(current_upload)
# hello/world/1
# world/world/2
# ...
incomplete_uploads = minio.list_incomplete_uploads('foo',
prefix='hello/',
recursive=True)
for current_upload in incomplete_uploads:
print(current_upload)
# hello/world/1
# hello/world/2
:param bucket_name: Bucket to list incomplete uploads
:param prefix: String specifying objects returned must begin with.
:param recursive: If yes, returns all incomplete uploads for
a specified prefix.
:return: An generator of incomplete uploads in alphabetical order. | [
"List",
"all",
"in",
"-",
"complete",
"uploads",
"for",
"a",
"given",
"bucket",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1105-L1149 |
226,572 | minio/minio-py | minio/api.py | Minio._list_incomplete_uploads | def _list_incomplete_uploads(self, bucket_name, prefix='',
recursive=False, is_aggregate_size=True):
"""
List incomplete uploads list all previously uploaded incomplete multipart objects.
:param bucket_name: Bucket name to list uploaded objects.
:param prefix: String specifying objects returned must begin with.
:param recursive: If yes, returns all incomplete objects for a specified prefix.
:return: An generator of incomplete uploads in alphabetical order.
"""
is_valid_bucket_name(bucket_name)
# If someone explicitly set prefix to None convert it to empty string.
if prefix is None:
prefix = ''
# Initialize query parameters.
query = {
'uploads': '',
'max-uploads': '1000',
'prefix': prefix
}
if not recursive:
query['delimiter'] = '/'
key_marker, upload_id_marker = '', ''
is_truncated = True
while is_truncated:
if key_marker:
query['key-marker'] = key_marker
if upload_id_marker:
query['upload-id-marker'] = upload_id_marker
response = self._url_open('GET',
bucket_name=bucket_name,
query=query)
(uploads, is_truncated, key_marker,
upload_id_marker) = parse_list_multipart_uploads(response.data,
bucket_name)
for upload in uploads:
if is_aggregate_size:
upload.size = self._get_total_multipart_upload_size(
upload.bucket_name,
upload.object_name,
upload.upload_id)
yield upload | python | def _list_incomplete_uploads(self, bucket_name, prefix='',
recursive=False, is_aggregate_size=True):
is_valid_bucket_name(bucket_name)
# If someone explicitly set prefix to None convert it to empty string.
if prefix is None:
prefix = ''
# Initialize query parameters.
query = {
'uploads': '',
'max-uploads': '1000',
'prefix': prefix
}
if not recursive:
query['delimiter'] = '/'
key_marker, upload_id_marker = '', ''
is_truncated = True
while is_truncated:
if key_marker:
query['key-marker'] = key_marker
if upload_id_marker:
query['upload-id-marker'] = upload_id_marker
response = self._url_open('GET',
bucket_name=bucket_name,
query=query)
(uploads, is_truncated, key_marker,
upload_id_marker) = parse_list_multipart_uploads(response.data,
bucket_name)
for upload in uploads:
if is_aggregate_size:
upload.size = self._get_total_multipart_upload_size(
upload.bucket_name,
upload.object_name,
upload.upload_id)
yield upload | [
"def",
"_list_incomplete_uploads",
"(",
"self",
",",
"bucket_name",
",",
"prefix",
"=",
"''",
",",
"recursive",
"=",
"False",
",",
"is_aggregate_size",
"=",
"True",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"# If someone explicitly set prefix to None ... | List incomplete uploads list all previously uploaded incomplete multipart objects.
:param bucket_name: Bucket name to list uploaded objects.
:param prefix: String specifying objects returned must begin with.
:param recursive: If yes, returns all incomplete objects for a specified prefix.
:return: An generator of incomplete uploads in alphabetical order. | [
"List",
"incomplete",
"uploads",
"list",
"all",
"previously",
"uploaded",
"incomplete",
"multipart",
"objects",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1151-L1197 |
226,573 | minio/minio-py | minio/api.py | Minio._get_total_multipart_upload_size | def _get_total_multipart_upload_size(self, bucket_name, object_name,
upload_id):
"""
Get total multipart upload size.
:param bucket_name: Bucket name to list parts for.
:param object_name: Object name to list parts for.
:param upload_id: Upload id of the previously uploaded object name.
"""
return sum(
[part.size for part in
self._list_object_parts(bucket_name, object_name, upload_id)]
) | python | def _get_total_multipart_upload_size(self, bucket_name, object_name,
upload_id):
return sum(
[part.size for part in
self._list_object_parts(bucket_name, object_name, upload_id)]
) | [
"def",
"_get_total_multipart_upload_size",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"upload_id",
")",
":",
"return",
"sum",
"(",
"[",
"part",
".",
"size",
"for",
"part",
"in",
"self",
".",
"_list_object_parts",
"(",
"bucket_name",
",",
"object... | Get total multipart upload size.
:param bucket_name: Bucket name to list parts for.
:param object_name: Object name to list parts for.
:param upload_id: Upload id of the previously uploaded object name. | [
"Get",
"total",
"multipart",
"upload",
"size",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1199-L1211 |
226,574 | minio/minio-py | minio/api.py | Minio._list_object_parts | def _list_object_parts(self, bucket_name, object_name, upload_id):
"""
List all parts.
:param bucket_name: Bucket name to list parts for.
:param object_name: Object name to list parts for.
:param upload_id: Upload id of the previously uploaded object name.
"""
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
is_non_empty_string(upload_id)
query = {
'uploadId': upload_id,
'max-parts': '1000'
}
is_truncated = True
part_number_marker = ''
while is_truncated:
if part_number_marker:
query['part-number-marker'] = str(part_number_marker)
response = self._url_open('GET',
bucket_name=bucket_name,
object_name=object_name,
query=query)
parts, is_truncated, part_number_marker = parse_list_parts(
response.data,
bucket_name=bucket_name,
object_name=object_name,
upload_id=upload_id
)
for part in parts:
yield part | python | def _list_object_parts(self, bucket_name, object_name, upload_id):
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
is_non_empty_string(upload_id)
query = {
'uploadId': upload_id,
'max-parts': '1000'
}
is_truncated = True
part_number_marker = ''
while is_truncated:
if part_number_marker:
query['part-number-marker'] = str(part_number_marker)
response = self._url_open('GET',
bucket_name=bucket_name,
object_name=object_name,
query=query)
parts, is_truncated, part_number_marker = parse_list_parts(
response.data,
bucket_name=bucket_name,
object_name=object_name,
upload_id=upload_id
)
for part in parts:
yield part | [
"def",
"_list_object_parts",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"upload_id",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"is_non_empty_string",
"(",
"object_name",
")",
"is_non_empty_string",
"(",
"upload_id",
")",
"query",
"=",... | List all parts.
:param bucket_name: Bucket name to list parts for.
:param object_name: Object name to list parts for.
:param upload_id: Upload id of the previously uploaded object name. | [
"List",
"all",
"parts",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1213-L1248 |
226,575 | minio/minio-py | minio/api.py | Minio.remove_incomplete_upload | def remove_incomplete_upload(self, bucket_name, object_name):
"""
Remove all in-complete uploads for a given bucket_name and object_name.
:param bucket_name: Bucket to drop incomplete uploads
:param object_name: Name of object to remove incomplete uploads
:return: None
"""
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
recursive = True
uploads = self._list_incomplete_uploads(bucket_name, object_name,
recursive,
is_aggregate_size=False)
for upload in uploads:
if object_name == upload.object_name:
self._remove_incomplete_upload(bucket_name, object_name,
upload.upload_id) | python | def remove_incomplete_upload(self, bucket_name, object_name):
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
recursive = True
uploads = self._list_incomplete_uploads(bucket_name, object_name,
recursive,
is_aggregate_size=False)
for upload in uploads:
if object_name == upload.object_name:
self._remove_incomplete_upload(bucket_name, object_name,
upload.upload_id) | [
"def",
"remove_incomplete_upload",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"is_non_empty_string",
"(",
"object_name",
")",
"recursive",
"=",
"True",
"uploads",
"=",
"self",
".",
"_list_incomplet... | Remove all in-complete uploads for a given bucket_name and object_name.
:param bucket_name: Bucket to drop incomplete uploads
:param object_name: Name of object to remove incomplete uploads
:return: None | [
"Remove",
"all",
"in",
"-",
"complete",
"uploads",
"for",
"a",
"given",
"bucket_name",
"and",
"object_name",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1250-L1268 |
226,576 | minio/minio-py | minio/api.py | Minio.presigned_url | def presigned_url(self, method,
bucket_name,
object_name,
expires=timedelta(days=7),
response_headers=None,
request_date=None):
"""
Presigns a method on an object and provides a url
Example:
from datetime import timedelta
presignedURL = presigned_url('GET',
'bucket_name',
'object_name',
expires=timedelta(days=7))
print(presignedURL)
:param bucket_name: Bucket for the presigned url.
:param object_name: Object for which presigned url is generated.
:param expires: Optional expires argument to specify timedelta.
Defaults to 7days.
:params response_headers: Optional response_headers argument to
specify response fields like date, size,
type of file, data about server, etc.
:params request_date: Optional request_date argument to
specify a different request date. Default is
current date.
:return: Presigned put object url.
"""
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
if expires.total_seconds() < 1 or \
expires.total_seconds() > _MAX_EXPIRY_TIME:
raise InvalidArgumentError('Expires param valid values'
' are between 1 sec to'
' {0} secs'.format(_MAX_EXPIRY_TIME))
region = self._get_bucket_region(bucket_name)
url = get_target_url(self._endpoint_url,
bucket_name=bucket_name,
object_name=object_name,
bucket_region=region)
return presign_v4(method, url,
self._access_key,
self._secret_key,
session_token=self._session_token,
region=region,
expires=int(expires.total_seconds()),
response_headers=response_headers,
request_date=request_date) | python | def presigned_url(self, method,
bucket_name,
object_name,
expires=timedelta(days=7),
response_headers=None,
request_date=None):
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
if expires.total_seconds() < 1 or \
expires.total_seconds() > _MAX_EXPIRY_TIME:
raise InvalidArgumentError('Expires param valid values'
' are between 1 sec to'
' {0} secs'.format(_MAX_EXPIRY_TIME))
region = self._get_bucket_region(bucket_name)
url = get_target_url(self._endpoint_url,
bucket_name=bucket_name,
object_name=object_name,
bucket_region=region)
return presign_v4(method, url,
self._access_key,
self._secret_key,
session_token=self._session_token,
region=region,
expires=int(expires.total_seconds()),
response_headers=response_headers,
request_date=request_date) | [
"def",
"presigned_url",
"(",
"self",
",",
"method",
",",
"bucket_name",
",",
"object_name",
",",
"expires",
"=",
"timedelta",
"(",
"days",
"=",
"7",
")",
",",
"response_headers",
"=",
"None",
",",
"request_date",
"=",
"None",
")",
":",
"is_valid_bucket_name"... | Presigns a method on an object and provides a url
Example:
from datetime import timedelta
presignedURL = presigned_url('GET',
'bucket_name',
'object_name',
expires=timedelta(days=7))
print(presignedURL)
:param bucket_name: Bucket for the presigned url.
:param object_name: Object for which presigned url is generated.
:param expires: Optional expires argument to specify timedelta.
Defaults to 7days.
:params response_headers: Optional response_headers argument to
specify response fields like date, size,
type of file, data about server, etc.
:params request_date: Optional request_date argument to
specify a different request date. Default is
current date.
:return: Presigned put object url. | [
"Presigns",
"a",
"method",
"on",
"an",
"object",
"and",
"provides",
"a",
"url"
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1270-L1322 |
226,577 | minio/minio-py | minio/api.py | Minio.presigned_get_object | def presigned_get_object(self, bucket_name, object_name,
expires=timedelta(days=7),
response_headers=None,
request_date=None):
"""
Presigns a get object request and provides a url
Example:
from datetime import timedelta
presignedURL = presigned_get_object('bucket_name',
'object_name',
timedelta(days=7))
print(presignedURL)
:param bucket_name: Bucket for the presigned url.
:param object_name: Object for which presigned url is generated.
:param expires: Optional expires argument to specify timedelta.
Defaults to 7days.
:params response_headers: Optional response_headers argument to
specify response fields like date, size,
type of file, data about server, etc.
:params request_date: Optional request_date argument to
specify a different request date. Default is
current date.
:return: Presigned url.
"""
return self.presigned_url('GET',
bucket_name,
object_name,
expires,
response_headers=response_headers,
request_date=request_date) | python | def presigned_get_object(self, bucket_name, object_name,
expires=timedelta(days=7),
response_headers=None,
request_date=None):
return self.presigned_url('GET',
bucket_name,
object_name,
expires,
response_headers=response_headers,
request_date=request_date) | [
"def",
"presigned_get_object",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"expires",
"=",
"timedelta",
"(",
"days",
"=",
"7",
")",
",",
"response_headers",
"=",
"None",
",",
"request_date",
"=",
"None",
")",
":",
"return",
"self",
".",
"pres... | Presigns a get object request and provides a url
Example:
from datetime import timedelta
presignedURL = presigned_get_object('bucket_name',
'object_name',
timedelta(days=7))
print(presignedURL)
:param bucket_name: Bucket for the presigned url.
:param object_name: Object for which presigned url is generated.
:param expires: Optional expires argument to specify timedelta.
Defaults to 7days.
:params response_headers: Optional response_headers argument to
specify response fields like date, size,
type of file, data about server, etc.
:params request_date: Optional request_date argument to
specify a different request date. Default is
current date.
:return: Presigned url. | [
"Presigns",
"a",
"get",
"object",
"request",
"and",
"provides",
"a",
"url"
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1324-L1358 |
226,578 | minio/minio-py | minio/api.py | Minio.presigned_put_object | def presigned_put_object(self, bucket_name, object_name,
expires=timedelta(days=7)):
"""
Presigns a put object request and provides a url
Example:
from datetime import timedelta
presignedURL = presigned_put_object('bucket_name',
'object_name',
timedelta(days=7))
print(presignedURL)
:param bucket_name: Bucket for the presigned url.
:param object_name: Object for which presigned url is generated.
:param expires: optional expires argument to specify timedelta.
Defaults to 7days.
:return: Presigned put object url.
"""
return self.presigned_url('PUT',
bucket_name,
object_name,
expires) | python | def presigned_put_object(self, bucket_name, object_name,
expires=timedelta(days=7)):
return self.presigned_url('PUT',
bucket_name,
object_name,
expires) | [
"def",
"presigned_put_object",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"expires",
"=",
"timedelta",
"(",
"days",
"=",
"7",
")",
")",
":",
"return",
"self",
".",
"presigned_url",
"(",
"'PUT'",
",",
"bucket_name",
",",
"object_name",
",",
"... | Presigns a put object request and provides a url
Example:
from datetime import timedelta
presignedURL = presigned_put_object('bucket_name',
'object_name',
timedelta(days=7))
print(presignedURL)
:param bucket_name: Bucket for the presigned url.
:param object_name: Object for which presigned url is generated.
:param expires: optional expires argument to specify timedelta.
Defaults to 7days.
:return: Presigned put object url. | [
"Presigns",
"a",
"put",
"object",
"request",
"and",
"provides",
"a",
"url"
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1360-L1383 |
226,579 | minio/minio-py | minio/api.py | Minio.presigned_post_policy | def presigned_post_policy(self, post_policy):
"""
Provides a POST form data that can be used for object uploads.
Example:
post_policy = PostPolicy()
post_policy.set_bucket_name('bucket_name')
post_policy.set_key_startswith('objectPrefix/')
expires_date = datetime.utcnow()+timedelta(days=10)
post_policy.set_expires(expires_date)
print(presigned_post_policy(post_policy))
:param post_policy: Post_Policy object.
:return: PostPolicy form dictionary to be used in curl or HTML forms.
"""
post_policy.is_valid()
date = datetime.utcnow()
iso8601_date = date.strftime("%Y%m%dT%H%M%SZ")
region = self._get_bucket_region(post_policy.form_data['bucket'])
credential_string = generate_credential_string(self._access_key,
date, region)
policy = [
('eq', '$x-amz-date', iso8601_date),
('eq', '$x-amz-algorithm', _SIGN_V4_ALGORITHM),
('eq', '$x-amz-credential', credential_string),
]
if self._session_token:
policy.add(('eq', '$x-amz-security-token', self._session_token))
post_policy_base64 = post_policy.base64(extras=policy)
signature = post_presign_signature(date, region,
self._secret_key,
post_policy_base64)
form_data = {
'policy': post_policy_base64,
'x-amz-algorithm': _SIGN_V4_ALGORITHM,
'x-amz-credential': credential_string,
'x-amz-date': iso8601_date,
'x-amz-signature': signature,
}
if self._session_token:
form_data['x-amz-security-token'] = self._session_token
post_policy.form_data.update(form_data)
url_str = get_target_url(self._endpoint_url,
bucket_name=post_policy.form_data['bucket'],
bucket_region=region)
return (url_str, post_policy.form_data) | python | def presigned_post_policy(self, post_policy):
post_policy.is_valid()
date = datetime.utcnow()
iso8601_date = date.strftime("%Y%m%dT%H%M%SZ")
region = self._get_bucket_region(post_policy.form_data['bucket'])
credential_string = generate_credential_string(self._access_key,
date, region)
policy = [
('eq', '$x-amz-date', iso8601_date),
('eq', '$x-amz-algorithm', _SIGN_V4_ALGORITHM),
('eq', '$x-amz-credential', credential_string),
]
if self._session_token:
policy.add(('eq', '$x-amz-security-token', self._session_token))
post_policy_base64 = post_policy.base64(extras=policy)
signature = post_presign_signature(date, region,
self._secret_key,
post_policy_base64)
form_data = {
'policy': post_policy_base64,
'x-amz-algorithm': _SIGN_V4_ALGORITHM,
'x-amz-credential': credential_string,
'x-amz-date': iso8601_date,
'x-amz-signature': signature,
}
if self._session_token:
form_data['x-amz-security-token'] = self._session_token
post_policy.form_data.update(form_data)
url_str = get_target_url(self._endpoint_url,
bucket_name=post_policy.form_data['bucket'],
bucket_region=region)
return (url_str, post_policy.form_data) | [
"def",
"presigned_post_policy",
"(",
"self",
",",
"post_policy",
")",
":",
"post_policy",
".",
"is_valid",
"(",
")",
"date",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"iso8601_date",
"=",
"date",
".",
"strftime",
"(",
"\"%Y%m%dT%H%M%SZ\"",
")",
"region",
"="... | Provides a POST form data that can be used for object uploads.
Example:
post_policy = PostPolicy()
post_policy.set_bucket_name('bucket_name')
post_policy.set_key_startswith('objectPrefix/')
expires_date = datetime.utcnow()+timedelta(days=10)
post_policy.set_expires(expires_date)
print(presigned_post_policy(post_policy))
:param post_policy: Post_Policy object.
:return: PostPolicy form dictionary to be used in curl or HTML forms. | [
"Provides",
"a",
"POST",
"form",
"data",
"that",
"can",
"be",
"used",
"for",
"object",
"uploads",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1385-L1436 |
226,580 | minio/minio-py | minio/api.py | Minio._do_put_object | def _do_put_object(self, bucket_name, object_name, part_data,
part_size, upload_id='', part_number=0,
metadata=None, sse=None, progress=None):
"""
Initiate a multipart PUT operation for a part number
or single PUT object.
:param bucket_name: Bucket name for the multipart request.
:param object_name: Object name for the multipart request.
:param part_metadata: Part-data and metadata for the multipart request.
:param upload_id: Upload id of the multipart request [OPTIONAL].
:param part_number: Part number of the data to be uploaded [OPTIONAL].
:param metadata: Any additional metadata to be uploaded along
with your object.
:param progress: A progress object
"""
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
# Accept only bytes - otherwise we need to know how to encode
# the data to bytes before storing in the object.
if not isinstance(part_data, bytes):
raise ValueError('Input data must be bytes type')
headers = {
'Content-Length': part_size,
}
md5_base64 = ''
sha256_hex = ''
if self._is_ssl:
md5_base64 = get_md5_base64digest(part_data)
sha256_hex = _UNSIGNED_PAYLOAD
else:
sha256_hex = get_sha256_hexdigest(part_data)
if md5_base64:
headers['Content-Md5'] = md5_base64
if metadata:
headers.update(metadata)
query = {}
if part_number > 0 and upload_id:
query = {
'uploadId': upload_id,
'partNumber': str(part_number),
}
# Encryption headers for multipart uploads should
# be set only in the case of SSE-C.
if sse and sse.type() == "SSE-C":
headers.update(sse.marshal())
elif sse:
headers.update(sse.marshal())
response = self._url_open(
'PUT',
bucket_name=bucket_name,
object_name=object_name,
query=query,
headers=headers,
body=io.BytesIO(part_data),
content_sha256=sha256_hex
)
if progress:
# Update the 'progress' object with uploaded 'part_size'.
progress.update(part_size)
return response.headers['etag'].replace('"', '') | python | def _do_put_object(self, bucket_name, object_name, part_data,
part_size, upload_id='', part_number=0,
metadata=None, sse=None, progress=None):
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
# Accept only bytes - otherwise we need to know how to encode
# the data to bytes before storing in the object.
if not isinstance(part_data, bytes):
raise ValueError('Input data must be bytes type')
headers = {
'Content-Length': part_size,
}
md5_base64 = ''
sha256_hex = ''
if self._is_ssl:
md5_base64 = get_md5_base64digest(part_data)
sha256_hex = _UNSIGNED_PAYLOAD
else:
sha256_hex = get_sha256_hexdigest(part_data)
if md5_base64:
headers['Content-Md5'] = md5_base64
if metadata:
headers.update(metadata)
query = {}
if part_number > 0 and upload_id:
query = {
'uploadId': upload_id,
'partNumber': str(part_number),
}
# Encryption headers for multipart uploads should
# be set only in the case of SSE-C.
if sse and sse.type() == "SSE-C":
headers.update(sse.marshal())
elif sse:
headers.update(sse.marshal())
response = self._url_open(
'PUT',
bucket_name=bucket_name,
object_name=object_name,
query=query,
headers=headers,
body=io.BytesIO(part_data),
content_sha256=sha256_hex
)
if progress:
# Update the 'progress' object with uploaded 'part_size'.
progress.update(part_size)
return response.headers['etag'].replace('"', '') | [
"def",
"_do_put_object",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"part_data",
",",
"part_size",
",",
"upload_id",
"=",
"''",
",",
"part_number",
"=",
"0",
",",
"metadata",
"=",
"None",
",",
"sse",
"=",
"None",
",",
"progress",
"=",
"Non... | Initiate a multipart PUT operation for a part number
or single PUT object.
:param bucket_name: Bucket name for the multipart request.
:param object_name: Object name for the multipart request.
:param part_metadata: Part-data and metadata for the multipart request.
:param upload_id: Upload id of the multipart request [OPTIONAL].
:param part_number: Part number of the data to be uploaded [OPTIONAL].
:param metadata: Any additional metadata to be uploaded along
with your object.
:param progress: A progress object | [
"Initiate",
"a",
"multipart",
"PUT",
"operation",
"for",
"a",
"part",
"number",
"or",
"single",
"PUT",
"object",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1489-L1557 |
226,581 | minio/minio-py | minio/api.py | Minio._stream_put_object | def _stream_put_object(self, bucket_name, object_name,
data, content_size,
metadata=None, sse=None,
progress=None, part_size=MIN_PART_SIZE):
"""
Streaming multipart upload operation.
:param bucket_name: Bucket name of the multipart upload.
:param object_name: Object name of the multipart upload.
:param content_size: Total size of the content to be uploaded.
:param content_type: Content type of of the multipart upload.
Defaults to 'application/octet-stream'.
:param metadata: Any additional metadata to be uploaded along
with your object.
:param progress: A progress object
:param part_size: Multipart part size
"""
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
if not callable(getattr(data, 'read')):
raise ValueError(
'Invalid input data does not implement a callable read() method')
# get upload id.
upload_id = self._new_multipart_upload(bucket_name, object_name,
metadata, sse)
# Initialize variables
total_uploaded = 0
uploaded_parts = {}
# Calculate optimal part info.
total_parts_count, part_size, last_part_size = optimal_part_info(
content_size, part_size)
# Instantiate a thread pool with 3 worker threads
pool = ThreadPool(_PARALLEL_UPLOADERS)
pool.start_parallel()
# Generate new parts and upload <= current_part_size until
# part_number reaches total_parts_count calculated for the
# given size. Additionally part_manager() also provides
# md5digest and sha256digest for the partitioned data.
for part_number in range(1, total_parts_count + 1):
current_part_size = (part_size if part_number < total_parts_count
else last_part_size)
part_data = read_full(data, current_part_size)
pool.add_task(self._upload_part_routine, (bucket_name, object_name, upload_id,
part_number, part_data, sse, progress))
try:
upload_result = pool.result()
except:
# Any exception that occurs sends an abort on the
# on-going multipart operation.
self._remove_incomplete_upload(bucket_name,
object_name,
upload_id)
raise
# Update uploaded_parts with the part uploads result
# and check total uploaded data.
while not upload_result.empty():
part_number, etag, total_read = upload_result.get()
uploaded_parts[part_number] = UploadPart(bucket_name,
object_name,
upload_id,
part_number,
etag,
None,
total_read)
total_uploaded += total_read
if total_uploaded != content_size:
msg = 'Data uploaded {0} is not equal input size ' \
'{1}'.format(total_uploaded, content_size)
# cleanup incomplete upload upon incorrect upload
# automatically
self._remove_incomplete_upload(bucket_name,
object_name,
upload_id)
raise InvalidSizeError(msg)
# Complete all multipart transactions if possible.
try:
mpart_result = self._complete_multipart_upload(bucket_name,
object_name,
upload_id,
uploaded_parts)
except:
# Any exception that occurs sends an abort on the
# on-going multipart operation.
self._remove_incomplete_upload(bucket_name,
object_name,
upload_id)
raise
# Return etag here.
return mpart_result.etag | python | def _stream_put_object(self, bucket_name, object_name,
data, content_size,
metadata=None, sse=None,
progress=None, part_size=MIN_PART_SIZE):
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
if not callable(getattr(data, 'read')):
raise ValueError(
'Invalid input data does not implement a callable read() method')
# get upload id.
upload_id = self._new_multipart_upload(bucket_name, object_name,
metadata, sse)
# Initialize variables
total_uploaded = 0
uploaded_parts = {}
# Calculate optimal part info.
total_parts_count, part_size, last_part_size = optimal_part_info(
content_size, part_size)
# Instantiate a thread pool with 3 worker threads
pool = ThreadPool(_PARALLEL_UPLOADERS)
pool.start_parallel()
# Generate new parts and upload <= current_part_size until
# part_number reaches total_parts_count calculated for the
# given size. Additionally part_manager() also provides
# md5digest and sha256digest for the partitioned data.
for part_number in range(1, total_parts_count + 1):
current_part_size = (part_size if part_number < total_parts_count
else last_part_size)
part_data = read_full(data, current_part_size)
pool.add_task(self._upload_part_routine, (bucket_name, object_name, upload_id,
part_number, part_data, sse, progress))
try:
upload_result = pool.result()
except:
# Any exception that occurs sends an abort on the
# on-going multipart operation.
self._remove_incomplete_upload(bucket_name,
object_name,
upload_id)
raise
# Update uploaded_parts with the part uploads result
# and check total uploaded data.
while not upload_result.empty():
part_number, etag, total_read = upload_result.get()
uploaded_parts[part_number] = UploadPart(bucket_name,
object_name,
upload_id,
part_number,
etag,
None,
total_read)
total_uploaded += total_read
if total_uploaded != content_size:
msg = 'Data uploaded {0} is not equal input size ' \
'{1}'.format(total_uploaded, content_size)
# cleanup incomplete upload upon incorrect upload
# automatically
self._remove_incomplete_upload(bucket_name,
object_name,
upload_id)
raise InvalidSizeError(msg)
# Complete all multipart transactions if possible.
try:
mpart_result = self._complete_multipart_upload(bucket_name,
object_name,
upload_id,
uploaded_parts)
except:
# Any exception that occurs sends an abort on the
# on-going multipart operation.
self._remove_incomplete_upload(bucket_name,
object_name,
upload_id)
raise
# Return etag here.
return mpart_result.etag | [
"def",
"_stream_put_object",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"data",
",",
"content_size",
",",
"metadata",
"=",
"None",
",",
"sse",
"=",
"None",
",",
"progress",
"=",
"None",
",",
"part_size",
"=",
"MIN_PART_SIZE",
")",
":",
"is_v... | Streaming multipart upload operation.
:param bucket_name: Bucket name of the multipart upload.
:param object_name: Object name of the multipart upload.
:param content_size: Total size of the content to be uploaded.
:param content_type: Content type of of the multipart upload.
Defaults to 'application/octet-stream'.
:param metadata: Any additional metadata to be uploaded along
with your object.
:param progress: A progress object
:param part_size: Multipart part size | [
"Streaming",
"multipart",
"upload",
"operation",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1569-L1669 |
226,582 | minio/minio-py | minio/api.py | Minio._remove_incomplete_upload | def _remove_incomplete_upload(self, bucket_name, object_name, upload_id):
"""
Remove incomplete multipart request.
:param bucket_name: Bucket name of the incomplete upload.
:param object_name: Object name of incomplete upload.
:param upload_id: Upload id of the incomplete upload.
"""
# No reason to store successful response, for errors
# relevant exceptions are thrown.
self._url_open('DELETE', bucket_name=bucket_name,
object_name=object_name, query={'uploadId': upload_id},
headers={}) | python | def _remove_incomplete_upload(self, bucket_name, object_name, upload_id):
# No reason to store successful response, for errors
# relevant exceptions are thrown.
self._url_open('DELETE', bucket_name=bucket_name,
object_name=object_name, query={'uploadId': upload_id},
headers={}) | [
"def",
"_remove_incomplete_upload",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"upload_id",
")",
":",
"# No reason to store successful response, for errors",
"# relevant exceptions are thrown.",
"self",
".",
"_url_open",
"(",
"'DELETE'",
",",
"bucket_name",
"... | Remove incomplete multipart request.
:param bucket_name: Bucket name of the incomplete upload.
:param object_name: Object name of incomplete upload.
:param upload_id: Upload id of the incomplete upload. | [
"Remove",
"incomplete",
"multipart",
"request",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1671-L1684 |
226,583 | minio/minio-py | minio/api.py | Minio._new_multipart_upload | def _new_multipart_upload(self, bucket_name, object_name,
metadata=None, sse=None):
"""
Initialize new multipart upload request.
:param bucket_name: Bucket name of the new multipart request.
:param object_name: Object name of the new multipart request.
:param metadata: Additional new metadata for the new object.
:return: Returns an upload id.
"""
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
headers = {}
if metadata:
headers.update(metadata)
if sse:
headers.update(sse.marshal())
response = self._url_open('POST', bucket_name=bucket_name,
object_name=object_name,
query={'uploads': ''},
headers=headers)
return parse_new_multipart_upload(response.data) | python | def _new_multipart_upload(self, bucket_name, object_name,
metadata=None, sse=None):
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
headers = {}
if metadata:
headers.update(metadata)
if sse:
headers.update(sse.marshal())
response = self._url_open('POST', bucket_name=bucket_name,
object_name=object_name,
query={'uploads': ''},
headers=headers)
return parse_new_multipart_upload(response.data) | [
"def",
"_new_multipart_upload",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"metadata",
"=",
"None",
",",
"sse",
"=",
"None",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"is_non_empty_string",
"(",
"object_name",
")",
"headers",
"=",... | Initialize new multipart upload request.
:param bucket_name: Bucket name of the new multipart request.
:param object_name: Object name of the new multipart request.
:param metadata: Additional new metadata for the new object.
:return: Returns an upload id. | [
"Initialize",
"new",
"multipart",
"upload",
"request",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1686-L1710 |
226,584 | minio/minio-py | minio/api.py | Minio._complete_multipart_upload | def _complete_multipart_upload(self, bucket_name, object_name,
upload_id, uploaded_parts):
"""
Complete an active multipart upload request.
:param bucket_name: Bucket name of the multipart request.
:param object_name: Object name of the multipart request.
:param upload_id: Upload id of the active multipart request.
:param uploaded_parts: Key, Value dictionary of uploaded parts.
"""
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
is_non_empty_string(upload_id)
# Order uploaded parts as required by S3 specification
ordered_parts = []
for part in sorted(uploaded_parts.keys()):
ordered_parts.append(uploaded_parts[part])
data = xml_marshal_complete_multipart_upload(ordered_parts)
sha256_hex = get_sha256_hexdigest(data)
md5_base64 = get_md5_base64digest(data)
headers = {
'Content-Length': len(data),
'Content-Type': 'application/xml',
'Content-Md5': md5_base64,
}
response = self._url_open('POST', bucket_name=bucket_name,
object_name=object_name,
query={'uploadId': upload_id},
headers=headers, body=data,
content_sha256=sha256_hex)
return parse_multipart_upload_result(response.data) | python | def _complete_multipart_upload(self, bucket_name, object_name,
upload_id, uploaded_parts):
is_valid_bucket_name(bucket_name)
is_non_empty_string(object_name)
is_non_empty_string(upload_id)
# Order uploaded parts as required by S3 specification
ordered_parts = []
for part in sorted(uploaded_parts.keys()):
ordered_parts.append(uploaded_parts[part])
data = xml_marshal_complete_multipart_upload(ordered_parts)
sha256_hex = get_sha256_hexdigest(data)
md5_base64 = get_md5_base64digest(data)
headers = {
'Content-Length': len(data),
'Content-Type': 'application/xml',
'Content-Md5': md5_base64,
}
response = self._url_open('POST', bucket_name=bucket_name,
object_name=object_name,
query={'uploadId': upload_id},
headers=headers, body=data,
content_sha256=sha256_hex)
return parse_multipart_upload_result(response.data) | [
"def",
"_complete_multipart_upload",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"upload_id",
",",
"uploaded_parts",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"is_non_empty_string",
"(",
"object_name",
")",
"is_non_empty_string",
"(",
"u... | Complete an active multipart upload request.
:param bucket_name: Bucket name of the multipart request.
:param object_name: Object name of the multipart request.
:param upload_id: Upload id of the active multipart request.
:param uploaded_parts: Key, Value dictionary of uploaded parts. | [
"Complete",
"an",
"active",
"multipart",
"upload",
"request",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1712-L1747 |
226,585 | minio/minio-py | minio/api.py | Minio._get_bucket_region | def _get_bucket_region(self, bucket_name):
"""
Get region based on the bucket name.
:param bucket_name: Bucket name for which region will be fetched.
:return: Region of bucket name.
"""
# Region set in constructor, return right here.
if self._region:
return self._region
# get bucket location for Amazon S3.
region = 'us-east-1' # default to US standard.
if bucket_name in self._region_map:
region = self._region_map[bucket_name]
else:
region = self._get_bucket_location(bucket_name)
self._region_map[bucket_name] = region
# Success.
return region | python | def _get_bucket_region(self, bucket_name):
# Region set in constructor, return right here.
if self._region:
return self._region
# get bucket location for Amazon S3.
region = 'us-east-1' # default to US standard.
if bucket_name in self._region_map:
region = self._region_map[bucket_name]
else:
region = self._get_bucket_location(bucket_name)
self._region_map[bucket_name] = region
# Success.
return region | [
"def",
"_get_bucket_region",
"(",
"self",
",",
"bucket_name",
")",
":",
"# Region set in constructor, return right here.",
"if",
"self",
".",
"_region",
":",
"return",
"self",
".",
"_region",
"# get bucket location for Amazon S3.",
"region",
"=",
"'us-east-1'",
"# default... | Get region based on the bucket name.
:param bucket_name: Bucket name for which region will be fetched.
:return: Region of bucket name. | [
"Get",
"region",
"based",
"on",
"the",
"bucket",
"name",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1768-L1789 |
226,586 | minio/minio-py | minio/api.py | Minio._get_bucket_location | def _get_bucket_location(self, bucket_name):
"""
Get bucket location.
:param bucket_name: Fetches location of the Bucket name.
:return: location of bucket name is returned.
"""
method = 'GET'
url = self._endpoint_url + '/' + bucket_name + '?location='
headers = {}
# default for all requests.
region = 'us-east-1'
# Region is set override.
if self._region:
return self._region
# For anonymous requests no need to get bucket location.
if self._access_key is None or self._secret_key is None:
return 'us-east-1'
# Get signature headers if any.
headers = sign_v4(method, url, region,
headers, self._access_key,
self._secret_key,
self._session_token,
None)
response = self._http.urlopen(method, url,
body=None,
headers=headers)
if self._trace_output_stream:
dump_http(method, url, headers, response,
self._trace_output_stream)
if response.status != 200:
raise ResponseError(response, method, bucket_name).get_exception()
location = parse_location_constraint(response.data)
# location is empty for 'US standard region'
if not location:
return 'us-east-1'
# location can be 'EU' convert it to meaningful 'eu-west-1'
if location == 'EU':
return 'eu-west-1'
return location | python | def _get_bucket_location(self, bucket_name):
method = 'GET'
url = self._endpoint_url + '/' + bucket_name + '?location='
headers = {}
# default for all requests.
region = 'us-east-1'
# Region is set override.
if self._region:
return self._region
# For anonymous requests no need to get bucket location.
if self._access_key is None or self._secret_key is None:
return 'us-east-1'
# Get signature headers if any.
headers = sign_v4(method, url, region,
headers, self._access_key,
self._secret_key,
self._session_token,
None)
response = self._http.urlopen(method, url,
body=None,
headers=headers)
if self._trace_output_stream:
dump_http(method, url, headers, response,
self._trace_output_stream)
if response.status != 200:
raise ResponseError(response, method, bucket_name).get_exception()
location = parse_location_constraint(response.data)
# location is empty for 'US standard region'
if not location:
return 'us-east-1'
# location can be 'EU' convert it to meaningful 'eu-west-1'
if location == 'EU':
return 'eu-west-1'
return location | [
"def",
"_get_bucket_location",
"(",
"self",
",",
"bucket_name",
")",
":",
"method",
"=",
"'GET'",
"url",
"=",
"self",
".",
"_endpoint_url",
"+",
"'/'",
"+",
"bucket_name",
"+",
"'?location='",
"headers",
"=",
"{",
"}",
"# default for all requests.",
"region",
... | Get bucket location.
:param bucket_name: Fetches location of the Bucket name.
:return: location of bucket name is returned. | [
"Get",
"bucket",
"location",
"."
] | 7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e | https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1791-L1837 |
226,587 | tsroten/pynlpir | pynlpir/__init__.py | open | def open(data_dir=nlpir.PACKAGE_DIR, encoding=ENCODING,
encoding_errors=ENCODING_ERRORS, license_code=None):
"""Initializes the NLPIR API.
This calls the function :func:`~pynlpir.nlpir.Init`.
:param str data_dir: The absolute path to the directory that has NLPIR's
`Data` directory (defaults to :data:`pynlpir.nlpir.PACKAGE_DIR`).
:param str encoding: The encoding that the Chinese source text will be in
(defaults to ``'utf_8'``). Possible values include ``'gbk'``,
``'utf_8'``, or ``'big5'``.
:param str encoding_errors: The desired encoding error handling scheme.
Possible values include ``'strict'``, ``'ignore'``, and ``'replace'``.
The default error handler is 'strict' meaning that encoding errors
raise :class:`ValueError` (or a more codec specific subclass, such
as :class:`UnicodeEncodeError`).
:param str license_code: The license code that should be used when
initializing NLPIR. This is generally only used by commercial users.
:raises RuntimeError: The NLPIR API failed to initialize. Sometimes, NLPIR
leaves an error log in the current working directory or NLPIR's
``Data`` directory that provides more detailed messages (but this isn't
always the case).
:raises LicenseError: The NLPIR license appears to be missing or expired.
"""
if license_code is None:
license_code = ''
global ENCODING
if encoding.lower() in ('utf_8', 'utf-8', 'u8', 'utf', 'utf8'):
ENCODING = 'utf_8'
encoding_constant = nlpir.UTF8_CODE
elif encoding.lower() in ('gbk', '936', 'cp936', 'ms936'):
ENCODING = 'gbk'
encoding_constant = nlpir.GBK_CODE
elif encoding.lower() in ('big5', 'big5-tw', 'csbig5'):
ENCODING = 'big5'
encoding_constant = nlpir.BIG5_CODE
else:
raise ValueError("encoding must be one of 'utf_8', 'big5', or 'gbk'.")
logger.debug("Initializing the NLPIR API: 'data_dir': '{}', 'encoding': "
"'{}', 'license_code': '{}'".format(
data_dir, encoding, license_code))
global ENCODING_ERRORS
if encoding_errors not in ('strict', 'ignore', 'replace'):
raise ValueError("encoding_errors must be one of 'strict', 'ignore', "
"or 'replace'.")
else:
ENCODING_ERRORS = encoding_errors
# Init in Python 3 expects bytes, not strings.
if is_python3 and isinstance(data_dir, str):
data_dir = _encode(data_dir)
if is_python3 and isinstance(license_code, str):
license_code = _encode(license_code)
if not nlpir.Init(data_dir, encoding_constant, license_code):
_attempt_to_raise_license_error(data_dir)
raise RuntimeError("NLPIR function 'NLPIR_Init' failed.")
else:
logger.debug("NLPIR API initialized.") | python | def open(data_dir=nlpir.PACKAGE_DIR, encoding=ENCODING,
encoding_errors=ENCODING_ERRORS, license_code=None):
if license_code is None:
license_code = ''
global ENCODING
if encoding.lower() in ('utf_8', 'utf-8', 'u8', 'utf', 'utf8'):
ENCODING = 'utf_8'
encoding_constant = nlpir.UTF8_CODE
elif encoding.lower() in ('gbk', '936', 'cp936', 'ms936'):
ENCODING = 'gbk'
encoding_constant = nlpir.GBK_CODE
elif encoding.lower() in ('big5', 'big5-tw', 'csbig5'):
ENCODING = 'big5'
encoding_constant = nlpir.BIG5_CODE
else:
raise ValueError("encoding must be one of 'utf_8', 'big5', or 'gbk'.")
logger.debug("Initializing the NLPIR API: 'data_dir': '{}', 'encoding': "
"'{}', 'license_code': '{}'".format(
data_dir, encoding, license_code))
global ENCODING_ERRORS
if encoding_errors not in ('strict', 'ignore', 'replace'):
raise ValueError("encoding_errors must be one of 'strict', 'ignore', "
"or 'replace'.")
else:
ENCODING_ERRORS = encoding_errors
# Init in Python 3 expects bytes, not strings.
if is_python3 and isinstance(data_dir, str):
data_dir = _encode(data_dir)
if is_python3 and isinstance(license_code, str):
license_code = _encode(license_code)
if not nlpir.Init(data_dir, encoding_constant, license_code):
_attempt_to_raise_license_error(data_dir)
raise RuntimeError("NLPIR function 'NLPIR_Init' failed.")
else:
logger.debug("NLPIR API initialized.") | [
"def",
"open",
"(",
"data_dir",
"=",
"nlpir",
".",
"PACKAGE_DIR",
",",
"encoding",
"=",
"ENCODING",
",",
"encoding_errors",
"=",
"ENCODING_ERRORS",
",",
"license_code",
"=",
"None",
")",
":",
"if",
"license_code",
"is",
"None",
":",
"license_code",
"=",
"''"... | Initializes the NLPIR API.
This calls the function :func:`~pynlpir.nlpir.Init`.
:param str data_dir: The absolute path to the directory that has NLPIR's
`Data` directory (defaults to :data:`pynlpir.nlpir.PACKAGE_DIR`).
:param str encoding: The encoding that the Chinese source text will be in
(defaults to ``'utf_8'``). Possible values include ``'gbk'``,
``'utf_8'``, or ``'big5'``.
:param str encoding_errors: The desired encoding error handling scheme.
Possible values include ``'strict'``, ``'ignore'``, and ``'replace'``.
The default error handler is 'strict' meaning that encoding errors
raise :class:`ValueError` (or a more codec specific subclass, such
as :class:`UnicodeEncodeError`).
:param str license_code: The license code that should be used when
initializing NLPIR. This is generally only used by commercial users.
:raises RuntimeError: The NLPIR API failed to initialize. Sometimes, NLPIR
leaves an error log in the current working directory or NLPIR's
``Data`` directory that provides more detailed messages (but this isn't
always the case).
:raises LicenseError: The NLPIR license appears to be missing or expired. | [
"Initializes",
"the",
"NLPIR",
"API",
"."
] | 8d5e994796a2b5d513f7db8d76d7d24a85d531b1 | https://github.com/tsroten/pynlpir/blob/8d5e994796a2b5d513f7db8d76d7d24a85d531b1/pynlpir/__init__.py#L50-L110 |
226,588 | tsroten/pynlpir | pynlpir/__init__.py | _attempt_to_raise_license_error | def _attempt_to_raise_license_error(data_dir):
"""Raise an error if NLPIR has detected a missing or expired license.
:param str data_dir: The directory containing NLPIR's `Data` directory.
:raises LicenseError: The NLPIR license appears to be missing or expired.
"""
if isinstance(data_dir, bytes):
data_dir = _decode(data_dir)
data_dir = os.path.join(data_dir, 'Data')
current_date = dt.date.today().strftime('%Y%m%d')
timestamp = dt.datetime.today().strftime('[%Y-%m-%d %H:%M:%S]')
data_files = os.listdir(data_dir)
for f in data_files:
if f == (current_date + '.err'):
file_name = os.path.join(data_dir, f)
with fopen(file_name) as error_file:
for line in error_file:
if not line.startswith(timestamp):
continue
if 'Not valid license' in line:
raise LicenseError('Your license appears to have '
'expired. Try running "pynlpir '
'update".')
elif 'Can not open License file' in line:
raise LicenseError('Your license appears to be '
'missing. Try running "pynlpir '
'update".') | python | def _attempt_to_raise_license_error(data_dir):
if isinstance(data_dir, bytes):
data_dir = _decode(data_dir)
data_dir = os.path.join(data_dir, 'Data')
current_date = dt.date.today().strftime('%Y%m%d')
timestamp = dt.datetime.today().strftime('[%Y-%m-%d %H:%M:%S]')
data_files = os.listdir(data_dir)
for f in data_files:
if f == (current_date + '.err'):
file_name = os.path.join(data_dir, f)
with fopen(file_name) as error_file:
for line in error_file:
if not line.startswith(timestamp):
continue
if 'Not valid license' in line:
raise LicenseError('Your license appears to have '
'expired. Try running "pynlpir '
'update".')
elif 'Can not open License file' in line:
raise LicenseError('Your license appears to be '
'missing. Try running "pynlpir '
'update".') | [
"def",
"_attempt_to_raise_license_error",
"(",
"data_dir",
")",
":",
"if",
"isinstance",
"(",
"data_dir",
",",
"bytes",
")",
":",
"data_dir",
"=",
"_decode",
"(",
"data_dir",
")",
"data_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"'Dat... | Raise an error if NLPIR has detected a missing or expired license.
:param str data_dir: The directory containing NLPIR's `Data` directory.
:raises LicenseError: The NLPIR license appears to be missing or expired. | [
"Raise",
"an",
"error",
"if",
"NLPIR",
"has",
"detected",
"a",
"missing",
"or",
"expired",
"license",
"."
] | 8d5e994796a2b5d513f7db8d76d7d24a85d531b1 | https://github.com/tsroten/pynlpir/blob/8d5e994796a2b5d513f7db8d76d7d24a85d531b1/pynlpir/__init__.py#L126-L155 |
226,589 | tsroten/pynlpir | pynlpir/cli.py | update_license_file | def update_license_file(data_dir):
"""Update NLPIR license file if it is out-of-date or missing.
:param str data_dir: The NLPIR data directory that houses the license.
:returns bool: Whether or not an update occurred.
"""
license_file = os.path.join(data_dir, LICENSE_FILENAME)
temp_dir = tempfile.mkdtemp()
gh_license_filename = os.path.join(temp_dir, LICENSE_FILENAME)
try:
_, headers = urlretrieve(LICENSE_URL, gh_license_filename)
except IOError as e:
# Python 2 uses the unhelpful IOError for this. Re-raise as the more
# appropriate URLError.
raise URLError(e.strerror)
with open(gh_license_filename, 'rb') as f:
github_license = f.read()
try:
with open(license_file, 'rb') as f:
current_license = f.read()
except (IOError, OSError):
current_license = b''
github_digest = hashlib.sha256(github_license).hexdigest()
current_digest = hashlib.sha256(current_license).hexdigest()
if github_digest == current_digest:
return False
shutil.copyfile(gh_license_filename, license_file)
shutil.rmtree(temp_dir, ignore_errors=True)
return True | python | def update_license_file(data_dir):
license_file = os.path.join(data_dir, LICENSE_FILENAME)
temp_dir = tempfile.mkdtemp()
gh_license_filename = os.path.join(temp_dir, LICENSE_FILENAME)
try:
_, headers = urlretrieve(LICENSE_URL, gh_license_filename)
except IOError as e:
# Python 2 uses the unhelpful IOError for this. Re-raise as the more
# appropriate URLError.
raise URLError(e.strerror)
with open(gh_license_filename, 'rb') as f:
github_license = f.read()
try:
with open(license_file, 'rb') as f:
current_license = f.read()
except (IOError, OSError):
current_license = b''
github_digest = hashlib.sha256(github_license).hexdigest()
current_digest = hashlib.sha256(current_license).hexdigest()
if github_digest == current_digest:
return False
shutil.copyfile(gh_license_filename, license_file)
shutil.rmtree(temp_dir, ignore_errors=True)
return True | [
"def",
"update_license_file",
"(",
"data_dir",
")",
":",
"license_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"LICENSE_FILENAME",
")",
"temp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"gh_license_filename",
"=",
"os",
".",
"path",... | Update NLPIR license file if it is out-of-date or missing.
:param str data_dir: The NLPIR data directory that houses the license.
:returns bool: Whether or not an update occurred. | [
"Update",
"NLPIR",
"license",
"file",
"if",
"it",
"is",
"out",
"-",
"of",
"-",
"date",
"or",
"missing",
"."
] | 8d5e994796a2b5d513f7db8d76d7d24a85d531b1 | https://github.com/tsroten/pynlpir/blob/8d5e994796a2b5d513f7db8d76d7d24a85d531b1/pynlpir/cli.py#L34-L68 |
226,590 | tsroten/pynlpir | pynlpir/cli.py | update | def update(data_dir):
"""Update NLPIR license."""
try:
license_updated = update_license_file(data_dir)
except URLError:
click.secho('Error: unable to fetch newest license.', fg='red')
exit(1)
except (IOError, OSError):
click.secho('Error: unable to move license to data directory.',
fg='red')
exit(1)
if license_updated:
click.echo('License updated.')
else:
click.echo('Your license is already up-to-date.') | python | def update(data_dir):
try:
license_updated = update_license_file(data_dir)
except URLError:
click.secho('Error: unable to fetch newest license.', fg='red')
exit(1)
except (IOError, OSError):
click.secho('Error: unable to move license to data directory.',
fg='red')
exit(1)
if license_updated:
click.echo('License updated.')
else:
click.echo('Your license is already up-to-date.') | [
"def",
"update",
"(",
"data_dir",
")",
":",
"try",
":",
"license_updated",
"=",
"update_license_file",
"(",
"data_dir",
")",
"except",
"URLError",
":",
"click",
".",
"secho",
"(",
"'Error: unable to fetch newest license.'",
",",
"fg",
"=",
"'red'",
")",
"exit",
... | Update NLPIR license. | [
"Update",
"NLPIR",
"license",
"."
] | 8d5e994796a2b5d513f7db8d76d7d24a85d531b1 | https://github.com/tsroten/pynlpir/blob/8d5e994796a2b5d513f7db8d76d7d24a85d531b1/pynlpir/cli.py#L75-L90 |
226,591 | tsroten/pynlpir | pynlpir/nlpir.py | load_library | def load_library(platform, is_64bit, lib_dir=LIB_DIR):
"""Loads the NLPIR library appropriate for the user's system.
This function is called automatically when this module is loaded.
:param str platform: The platform identifier for the user's system.
:param bool is_64bit: Whether or not the user's system is 64-bit.
:param str lib_dir: The directory that contains the library files
(defaults to :data:`LIB_DIR`).
:raises RuntimeError: The user's platform is not supported by NLPIR.
"""
logger.debug("Loading NLPIR library file from '{}'".format(lib_dir))
if platform.startswith('win') and is_64bit:
lib = os.path.join(lib_dir, 'NLPIR64')
logger.debug("Using library file for 64-bit Windows.")
elif platform.startswith('win'):
lib = os.path.join(lib_dir, 'NLPIR32')
logger.debug("Using library file for 32-bit Windows.")
elif platform.startswith('linux') and is_64bit:
lib = os.path.join(lib_dir, 'libNLPIR64.so')
logger.debug("Using library file for 64-bit GNU/Linux.")
elif platform.startswith('linux'):
lib = os.path.join(lib_dir, 'libNLPIR32.so')
logger.debug("Using library file for 32-bit GNU/Linux.")
elif platform == 'darwin':
lib = os.path.join(lib_dir, 'libNLPIRios.so')
logger.debug("Using library file for OSX/iOS.")
else:
raise RuntimeError("Platform '{}' is not supported by NLPIR.".format(
platform))
lib_nlpir = cdll.LoadLibrary(lib if is_python3 else lib.encode('utf-8'))
logger.debug("NLPIR library file '{}' loaded.".format(lib))
return lib_nlpir | python | def load_library(platform, is_64bit, lib_dir=LIB_DIR):
logger.debug("Loading NLPIR library file from '{}'".format(lib_dir))
if platform.startswith('win') and is_64bit:
lib = os.path.join(lib_dir, 'NLPIR64')
logger.debug("Using library file for 64-bit Windows.")
elif platform.startswith('win'):
lib = os.path.join(lib_dir, 'NLPIR32')
logger.debug("Using library file for 32-bit Windows.")
elif platform.startswith('linux') and is_64bit:
lib = os.path.join(lib_dir, 'libNLPIR64.so')
logger.debug("Using library file for 64-bit GNU/Linux.")
elif platform.startswith('linux'):
lib = os.path.join(lib_dir, 'libNLPIR32.so')
logger.debug("Using library file for 32-bit GNU/Linux.")
elif platform == 'darwin':
lib = os.path.join(lib_dir, 'libNLPIRios.so')
logger.debug("Using library file for OSX/iOS.")
else:
raise RuntimeError("Platform '{}' is not supported by NLPIR.".format(
platform))
lib_nlpir = cdll.LoadLibrary(lib if is_python3 else lib.encode('utf-8'))
logger.debug("NLPIR library file '{}' loaded.".format(lib))
return lib_nlpir | [
"def",
"load_library",
"(",
"platform",
",",
"is_64bit",
",",
"lib_dir",
"=",
"LIB_DIR",
")",
":",
"logger",
".",
"debug",
"(",
"\"Loading NLPIR library file from '{}'\"",
".",
"format",
"(",
"lib_dir",
")",
")",
"if",
"platform",
".",
"startswith",
"(",
"'win... | Loads the NLPIR library appropriate for the user's system.
This function is called automatically when this module is loaded.
:param str platform: The platform identifier for the user's system.
:param bool is_64bit: Whether or not the user's system is 64-bit.
:param str lib_dir: The directory that contains the library files
(defaults to :data:`LIB_DIR`).
:raises RuntimeError: The user's platform is not supported by NLPIR. | [
"Loads",
"the",
"NLPIR",
"library",
"appropriate",
"for",
"the",
"user",
"s",
"system",
"."
] | 8d5e994796a2b5d513f7db8d76d7d24a85d531b1 | https://github.com/tsroten/pynlpir/blob/8d5e994796a2b5d513f7db8d76d7d24a85d531b1/pynlpir/nlpir.py#L80-L113 |
226,592 | tsroten/pynlpir | pynlpir/nlpir.py | get_func | def get_func(name, argtypes=None, restype=c_int, lib=libNLPIR):
"""Retrieves the corresponding NLPIR function.
:param str name: The name of the NLPIR function to get.
:param list argtypes: A list of :mod:`ctypes` data types that correspond
to the function's argument types.
:param restype: A :mod:`ctypes` data type that corresponds to the
function's return type (only needed if the return type isn't
:class:`ctypes.c_int`).
:param lib: A :class:`ctypes.CDLL` instance for the NLPIR API library where
the function will be retrieved from (defaults to :data:`libNLPIR`).
:returns: The exported function. It can be called like any other Python
callable.
"""
logger.debug("Getting NLPIR API function: 'name': '{}', 'argtypes': '{}',"
" 'restype': '{}'.".format(name, argtypes, restype))
func = getattr(lib, name)
if argtypes is not None:
func.argtypes = argtypes
if restype is not c_int:
func.restype = restype
logger.debug("NLPIR API function '{}' retrieved.".format(name))
return func | python | def get_func(name, argtypes=None, restype=c_int, lib=libNLPIR):
logger.debug("Getting NLPIR API function: 'name': '{}', 'argtypes': '{}',"
" 'restype': '{}'.".format(name, argtypes, restype))
func = getattr(lib, name)
if argtypes is not None:
func.argtypes = argtypes
if restype is not c_int:
func.restype = restype
logger.debug("NLPIR API function '{}' retrieved.".format(name))
return func | [
"def",
"get_func",
"(",
"name",
",",
"argtypes",
"=",
"None",
",",
"restype",
"=",
"c_int",
",",
"lib",
"=",
"libNLPIR",
")",
":",
"logger",
".",
"debug",
"(",
"\"Getting NLPIR API function: 'name': '{}', 'argtypes': '{}',\"",
"\" 'restype': '{}'.\"",
".",
"format",... | Retrieves the corresponding NLPIR function.
:param str name: The name of the NLPIR function to get.
:param list argtypes: A list of :mod:`ctypes` data types that correspond
to the function's argument types.
:param restype: A :mod:`ctypes` data type that corresponds to the
function's return type (only needed if the return type isn't
:class:`ctypes.c_int`).
:param lib: A :class:`ctypes.CDLL` instance for the NLPIR API library where
the function will be retrieved from (defaults to :data:`libNLPIR`).
:returns: The exported function. It can be called like any other Python
callable. | [
"Retrieves",
"the",
"corresponding",
"NLPIR",
"function",
"."
] | 8d5e994796a2b5d513f7db8d76d7d24a85d531b1 | https://github.com/tsroten/pynlpir/blob/8d5e994796a2b5d513f7db8d76d7d24a85d531b1/pynlpir/nlpir.py#L122-L145 |
226,593 | adamzap/landslide | landslide/parser.py | Parser.parse | def parse(self, text):
"""Parses and renders a text as HTML regarding current format.
"""
if self.format == 'markdown':
try:
import markdown
except ImportError:
raise RuntimeError(u"Looks like markdown is not installed")
if text.startswith(u'\ufeff'): # check for unicode BOM
text = text[1:]
return markdown.markdown(text, extensions=self.md_extensions)
elif self.format == 'restructuredtext':
try:
from landslide.rst import html_body
except ImportError:
raise RuntimeError(u"Looks like docutils are not installed")
html = html_body(text, input_encoding=self.encoding)
# RST generates pretty much markup to be removed in our case
for (pattern, replacement, mode) in self.RST_REPLACEMENTS:
html = re.sub(re.compile(pattern, mode), replacement, html, 0)
return html.strip()
elif self.format == 'textile':
try:
import textile
except ImportError:
raise RuntimeError(u"Looks like textile is not installed")
text = text.replace('\n---\n', '\n<hr />\n')
return textile.textile(text, encoding=self.encoding)
else:
raise NotImplementedError(u"Unsupported format %s, cannot parse"
% self.format) | python | def parse(self, text):
if self.format == 'markdown':
try:
import markdown
except ImportError:
raise RuntimeError(u"Looks like markdown is not installed")
if text.startswith(u'\ufeff'): # check for unicode BOM
text = text[1:]
return markdown.markdown(text, extensions=self.md_extensions)
elif self.format == 'restructuredtext':
try:
from landslide.rst import html_body
except ImportError:
raise RuntimeError(u"Looks like docutils are not installed")
html = html_body(text, input_encoding=self.encoding)
# RST generates pretty much markup to be removed in our case
for (pattern, replacement, mode) in self.RST_REPLACEMENTS:
html = re.sub(re.compile(pattern, mode), replacement, html, 0)
return html.strip()
elif self.format == 'textile':
try:
import textile
except ImportError:
raise RuntimeError(u"Looks like textile is not installed")
text = text.replace('\n---\n', '\n<hr />\n')
return textile.textile(text, encoding=self.encoding)
else:
raise NotImplementedError(u"Unsupported format %s, cannot parse"
% self.format) | [
"def",
"parse",
"(",
"self",
",",
"text",
")",
":",
"if",
"self",
".",
"format",
"==",
"'markdown'",
":",
"try",
":",
"import",
"markdown",
"except",
"ImportError",
":",
"raise",
"RuntimeError",
"(",
"u\"Looks like markdown is not installed\"",
")",
"if",
"tex... | Parses and renders a text as HTML regarding current format. | [
"Parses",
"and",
"renders",
"a",
"text",
"as",
"HTML",
"regarding",
"current",
"format",
"."
] | 59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832 | https://github.com/adamzap/landslide/blob/59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832/landslide/parser.py#L49-L86 |
226,594 | adamzap/landslide | landslide/macro.py | CodeHighlightingMacro.descape | def descape(self, string, defs=None):
"""Decodes html entities from a given string"""
if defs is None:
defs = html_entities.entitydefs
f = lambda m: defs[m.group(1)] if len(m.groups()) > 0 else m.group(0)
return self.html_entity_re.sub(f, string) | python | def descape(self, string, defs=None):
if defs is None:
defs = html_entities.entitydefs
f = lambda m: defs[m.group(1)] if len(m.groups()) > 0 else m.group(0)
return self.html_entity_re.sub(f, string) | [
"def",
"descape",
"(",
"self",
",",
"string",
",",
"defs",
"=",
"None",
")",
":",
"if",
"defs",
"is",
"None",
":",
"defs",
"=",
"html_entities",
".",
"entitydefs",
"f",
"=",
"lambda",
"m",
":",
"defs",
"[",
"m",
".",
"group",
"(",
"1",
")",
"]",
... | Decodes html entities from a given string | [
"Decodes",
"html",
"entities",
"from",
"a",
"given",
"string"
] | 59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832 | https://github.com/adamzap/landslide/blob/59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832/landslide/macro.py#L41-L46 |
226,595 | adamzap/landslide | landslide/utils.py | get_path_url | def get_path_url(path, relative=False):
""" Returns an absolute or relative path url given a path
"""
if relative:
return os.path.relpath(path)
else:
return 'file://%s' % os.path.abspath(path) | python | def get_path_url(path, relative=False):
if relative:
return os.path.relpath(path)
else:
return 'file://%s' % os.path.abspath(path) | [
"def",
"get_path_url",
"(",
"path",
",",
"relative",
"=",
"False",
")",
":",
"if",
"relative",
":",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
")",
"else",
":",
"return",
"'file://%s'",
"%",
"os",
".",
"path",
".",
"abspath",
"(",
"pat... | Returns an absolute or relative path url given a path | [
"Returns",
"an",
"absolute",
"or",
"relative",
"path",
"url",
"given",
"a",
"path"
] | 59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832 | https://github.com/adamzap/landslide/blob/59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832/landslide/utils.py#L8-L14 |
226,596 | adamzap/landslide | landslide/rst.py | html_parts | def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=1, initial_header_level=1):
"""
Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>").
"""
overrides = {
'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level,
'report_level': 5
}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts | python | def html_parts(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=1, initial_header_level=1):
overrides = {
'input_encoding': input_encoding,
'doctitle_xform': doctitle,
'initial_header_level': initial_header_level,
'report_level': 5
}
parts = core.publish_parts(
source=input_string, source_path=source_path,
destination_path=destination_path,
writer_name='html', settings_overrides=overrides)
return parts | [
"def",
"html_parts",
"(",
"input_string",
",",
"source_path",
"=",
"None",
",",
"destination_path",
"=",
"None",
",",
"input_encoding",
"=",
"'unicode'",
",",
"doctitle",
"=",
"1",
",",
"initial_header_level",
"=",
"1",
")",
":",
"overrides",
"=",
"{",
"'inp... | Given an input string, returns a dictionary of HTML document parts.
Dictionary keys are the names of parts, and values are Unicode strings;
encoding is up to the client.
Parameters:
- `input_string`: A multi-line text string; required.
- `source_path`: Path to the source file or object. Optional, but useful
for diagnostic output (system messages).
- `destination_path`: Path to the file or object which will receive the
output; optional. Used for determining relative paths (stylesheets,
source links, etc.).
- `input_encoding`: The encoding of `input_string`. If it is an encoded
8-bit string, provide the correct encoding. If it is a Unicode string,
use "unicode", the default.
- `doctitle`: Disable the promotion of a lone top-level section title to
document title (and subsequent section title to document subtitle
promotion); enabled by default.
- `initial_header_level`: The initial level for header elements (e.g. 1
for "<h1>"). | [
"Given",
"an",
"input",
"string",
"returns",
"a",
"dictionary",
"of",
"HTML",
"document",
"parts",
"."
] | 59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832 | https://github.com/adamzap/landslide/blob/59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832/landslide/rst.py#L43-L79 |
226,597 | adamzap/landslide | landslide/rst.py | html_body | def html_body(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=1, initial_header_level=1):
"""
Given an input string, returns an HTML fragment as a string.
The return value is the contents of the <body> element.
Parameters (see `html_parts()` for the remainder):
- `output_encoding`: The desired encoding of the output. If a Unicode
string is desired, use the default value of "unicode" .
"""
parts = html_parts(
input_string=input_string, source_path=source_path,
destination_path=destination_path,
input_encoding=input_encoding, doctitle=doctitle,
initial_header_level=initial_header_level)
fragment = parts['html_body']
return fragment | python | def html_body(input_string, source_path=None, destination_path=None,
input_encoding='unicode', doctitle=1, initial_header_level=1):
parts = html_parts(
input_string=input_string, source_path=source_path,
destination_path=destination_path,
input_encoding=input_encoding, doctitle=doctitle,
initial_header_level=initial_header_level)
fragment = parts['html_body']
return fragment | [
"def",
"html_body",
"(",
"input_string",
",",
"source_path",
"=",
"None",
",",
"destination_path",
"=",
"None",
",",
"input_encoding",
"=",
"'unicode'",
",",
"doctitle",
"=",
"1",
",",
"initial_header_level",
"=",
"1",
")",
":",
"parts",
"=",
"html_parts",
"... | Given an input string, returns an HTML fragment as a string.
The return value is the contents of the <body> element.
Parameters (see `html_parts()` for the remainder):
- `output_encoding`: The desired encoding of the output. If a Unicode
string is desired, use the default value of "unicode" . | [
"Given",
"an",
"input",
"string",
"returns",
"an",
"HTML",
"fragment",
"as",
"a",
"string",
"."
] | 59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832 | https://github.com/adamzap/landslide/blob/59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832/landslide/rst.py#L82-L100 |
226,598 | adamzap/landslide | landslide/generator.py | Generator.add_user_css | def add_user_css(self, css_list):
""" Adds supplementary user css files to the presentation. The
``css_list`` arg can be either a ``list`` or a string.
"""
if isinstance(css_list, string_types):
css_list = [css_list]
for css_path in css_list:
if css_path and css_path not in self.user_css:
if not os.path.exists(css_path):
raise IOError('%s user css file not found' % (css_path,))
with codecs.open(css_path, encoding=self.encoding) as css_file:
self.user_css.append({
'path_url': utils.get_path_url(css_path,
self.relative),
'contents': css_file.read(),
}) | python | def add_user_css(self, css_list):
if isinstance(css_list, string_types):
css_list = [css_list]
for css_path in css_list:
if css_path and css_path not in self.user_css:
if not os.path.exists(css_path):
raise IOError('%s user css file not found' % (css_path,))
with codecs.open(css_path, encoding=self.encoding) as css_file:
self.user_css.append({
'path_url': utils.get_path_url(css_path,
self.relative),
'contents': css_file.read(),
}) | [
"def",
"add_user_css",
"(",
"self",
",",
"css_list",
")",
":",
"if",
"isinstance",
"(",
"css_list",
",",
"string_types",
")",
":",
"css_list",
"=",
"[",
"css_list",
"]",
"for",
"css_path",
"in",
"css_list",
":",
"if",
"css_path",
"and",
"css_path",
"not",
... | Adds supplementary user css files to the presentation. The
``css_list`` arg can be either a ``list`` or a string. | [
"Adds",
"supplementary",
"user",
"css",
"files",
"to",
"the",
"presentation",
".",
"The",
"css_list",
"arg",
"can",
"be",
"either",
"a",
"list",
"or",
"a",
"string",
"."
] | 59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832 | https://github.com/adamzap/landslide/blob/59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832/landslide/generator.py#L135-L151 |
226,599 | adamzap/landslide | landslide/generator.py | Generator.add_user_js | def add_user_js(self, js_list):
""" Adds supplementary user javascript files to the presentation. The
``js_list`` arg can be either a ``list`` or a string.
"""
if isinstance(js_list, string_types):
js_list = [js_list]
for js_path in js_list:
if js_path and js_path not in self.user_js:
if js_path.startswith("http:"):
self.user_js.append({
'path_url': js_path,
'contents': '',
})
elif not os.path.exists(js_path):
raise IOError('%s user js file not found' % (js_path,))
else:
with codecs.open(js_path,
encoding=self.encoding) as js_file:
self.user_js.append({
'path_url': utils.get_path_url(js_path,
self.relative),
'contents': js_file.read(),
}) | python | def add_user_js(self, js_list):
if isinstance(js_list, string_types):
js_list = [js_list]
for js_path in js_list:
if js_path and js_path not in self.user_js:
if js_path.startswith("http:"):
self.user_js.append({
'path_url': js_path,
'contents': '',
})
elif not os.path.exists(js_path):
raise IOError('%s user js file not found' % (js_path,))
else:
with codecs.open(js_path,
encoding=self.encoding) as js_file:
self.user_js.append({
'path_url': utils.get_path_url(js_path,
self.relative),
'contents': js_file.read(),
}) | [
"def",
"add_user_js",
"(",
"self",
",",
"js_list",
")",
":",
"if",
"isinstance",
"(",
"js_list",
",",
"string_types",
")",
":",
"js_list",
"=",
"[",
"js_list",
"]",
"for",
"js_path",
"in",
"js_list",
":",
"if",
"js_path",
"and",
"js_path",
"not",
"in",
... | Adds supplementary user javascript files to the presentation. The
``js_list`` arg can be either a ``list`` or a string. | [
"Adds",
"supplementary",
"user",
"javascript",
"files",
"to",
"the",
"presentation",
".",
"The",
"js_list",
"arg",
"can",
"be",
"either",
"a",
"list",
"or",
"a",
"string",
"."
] | 59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832 | https://github.com/adamzap/landslide/blob/59b0403d7a7cca4b8ff6ba7fb76efb9748b3f832/landslide/generator.py#L153-L175 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.