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 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
234,400
|
kylejusticemagnuson/pyti
|
pyti/directional_indicators.py
|
average_directional_index
|
def average_directional_index(close_data, high_data, low_data, period):
"""
Average Directional Index.
Formula:
ADX = 100 * SMMA(abs((+DI - -DI) / (+DI + -DI)))
"""
avg_di = (abs(
(positive_directional_index(
close_data, high_data, low_data, period) -
negative_directional_index(
close_data, high_data, low_data, period)) /
(positive_directional_index(
close_data, high_data, low_data, period) +
negative_directional_index(
close_data, high_data, low_data, period)))
)
adx = 100 * smma(avg_di, period)
return adx
|
python
|
def average_directional_index(close_data, high_data, low_data, period):
"""
Average Directional Index.
Formula:
ADX = 100 * SMMA(abs((+DI - -DI) / (+DI + -DI)))
"""
avg_di = (abs(
(positive_directional_index(
close_data, high_data, low_data, period) -
negative_directional_index(
close_data, high_data, low_data, period)) /
(positive_directional_index(
close_data, high_data, low_data, period) +
negative_directional_index(
close_data, high_data, low_data, period)))
)
adx = 100 * smma(avg_di, period)
return adx
|
[
"def",
"average_directional_index",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"period",
")",
":",
"avg_di",
"=",
"(",
"abs",
"(",
"(",
"positive_directional_index",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"period",
")",
"-",
"negative_directional_index",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"period",
")",
")",
"/",
"(",
"positive_directional_index",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"period",
")",
"+",
"negative_directional_index",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"period",
")",
")",
")",
")",
"adx",
"=",
"100",
"*",
"smma",
"(",
"avg_di",
",",
"period",
")",
"return",
"adx"
] |
Average Directional Index.
Formula:
ADX = 100 * SMMA(abs((+DI - -DI) / (+DI + -DI)))
|
[
"Average",
"Directional",
"Index",
"."
] |
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
|
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/directional_indicators.py#L107-L125
|
234,401
|
kylejusticemagnuson/pyti
|
pyti/linear_weighted_moving_average.py
|
linear_weighted_moving_average
|
def linear_weighted_moving_average(data, period):
"""
Linear Weighted Moving Average.
Formula:
LWMA = SUM(DATA[i]) * i / SUM(i)
"""
catch_errors.check_for_period_error(data, period)
idx_period = list(range(1, period+1))
lwma = [(sum([i * idx_period[data[idx-(period-1):idx+1].index(i)]
for i in data[idx-(period-1):idx+1]])) /
sum(range(1, len(data[idx+1-period:idx+1])+1)) for idx in range(period-1, len(data))]
lwma = fill_for_noncomputable_vals(data, lwma)
return lwma
|
python
|
def linear_weighted_moving_average(data, period):
"""
Linear Weighted Moving Average.
Formula:
LWMA = SUM(DATA[i]) * i / SUM(i)
"""
catch_errors.check_for_period_error(data, period)
idx_period = list(range(1, period+1))
lwma = [(sum([i * idx_period[data[idx-(period-1):idx+1].index(i)]
for i in data[idx-(period-1):idx+1]])) /
sum(range(1, len(data[idx+1-period:idx+1])+1)) for idx in range(period-1, len(data))]
lwma = fill_for_noncomputable_vals(data, lwma)
return lwma
|
[
"def",
"linear_weighted_moving_average",
"(",
"data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"idx_period",
"=",
"list",
"(",
"range",
"(",
"1",
",",
"period",
"+",
"1",
")",
")",
"lwma",
"=",
"[",
"(",
"sum",
"(",
"[",
"i",
"*",
"idx_period",
"[",
"data",
"[",
"idx",
"-",
"(",
"period",
"-",
"1",
")",
":",
"idx",
"+",
"1",
"]",
".",
"index",
"(",
"i",
")",
"]",
"for",
"i",
"in",
"data",
"[",
"idx",
"-",
"(",
"period",
"-",
"1",
")",
":",
"idx",
"+",
"1",
"]",
"]",
")",
")",
"/",
"sum",
"(",
"range",
"(",
"1",
",",
"len",
"(",
"data",
"[",
"idx",
"+",
"1",
"-",
"period",
":",
"idx",
"+",
"1",
"]",
")",
"+",
"1",
")",
")",
"for",
"idx",
"in",
"range",
"(",
"period",
"-",
"1",
",",
"len",
"(",
"data",
")",
")",
"]",
"lwma",
"=",
"fill_for_noncomputable_vals",
"(",
"data",
",",
"lwma",
")",
"return",
"lwma"
] |
Linear Weighted Moving Average.
Formula:
LWMA = SUM(DATA[i]) * i / SUM(i)
|
[
"Linear",
"Weighted",
"Moving",
"Average",
"."
] |
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
|
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/linear_weighted_moving_average.py#L7-L21
|
234,402
|
kylejusticemagnuson/pyti
|
pyti/volume_oscillator.py
|
volume_oscillator
|
def volume_oscillator(volume, short_period, long_period):
"""
Volume Oscillator.
Formula:
vo = 100 * (SMA(vol, short) - SMA(vol, long) / SMA(vol, long))
"""
catch_errors.check_for_period_error(volume, short_period)
catch_errors.check_for_period_error(volume, long_period)
vo = (100 * ((sma(volume, short_period) - sma(volume, long_period)) /
sma(volume, long_period)))
return vo
|
python
|
def volume_oscillator(volume, short_period, long_period):
"""
Volume Oscillator.
Formula:
vo = 100 * (SMA(vol, short) - SMA(vol, long) / SMA(vol, long))
"""
catch_errors.check_for_period_error(volume, short_period)
catch_errors.check_for_period_error(volume, long_period)
vo = (100 * ((sma(volume, short_period) - sma(volume, long_period)) /
sma(volume, long_period)))
return vo
|
[
"def",
"volume_oscillator",
"(",
"volume",
",",
"short_period",
",",
"long_period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"volume",
",",
"short_period",
")",
"catch_errors",
".",
"check_for_period_error",
"(",
"volume",
",",
"long_period",
")",
"vo",
"=",
"(",
"100",
"*",
"(",
"(",
"sma",
"(",
"volume",
",",
"short_period",
")",
"-",
"sma",
"(",
"volume",
",",
"long_period",
")",
")",
"/",
"sma",
"(",
"volume",
",",
"long_period",
")",
")",
")",
"return",
"vo"
] |
Volume Oscillator.
Formula:
vo = 100 * (SMA(vol, short) - SMA(vol, long) / SMA(vol, long))
|
[
"Volume",
"Oscillator",
"."
] |
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
|
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/volume_oscillator.py#L6-L18
|
234,403
|
kylejusticemagnuson/pyti
|
pyti/triple_exponential_moving_average.py
|
triple_exponential_moving_average
|
def triple_exponential_moving_average(data, period):
"""
Triple Exponential Moving Average.
Formula:
TEMA = (3*EMA - 3*EMA(EMA)) + EMA(EMA(EMA))
"""
catch_errors.check_for_period_error(data, period)
tema = ((3 * ema(data, period) - (3 * ema(ema(data, period), period))) +
ema(ema(ema(data, period), period), period)
)
return tema
|
python
|
def triple_exponential_moving_average(data, period):
"""
Triple Exponential Moving Average.
Formula:
TEMA = (3*EMA - 3*EMA(EMA)) + EMA(EMA(EMA))
"""
catch_errors.check_for_period_error(data, period)
tema = ((3 * ema(data, period) - (3 * ema(ema(data, period), period))) +
ema(ema(ema(data, period), period), period)
)
return tema
|
[
"def",
"triple_exponential_moving_average",
"(",
"data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"tema",
"=",
"(",
"(",
"3",
"*",
"ema",
"(",
"data",
",",
"period",
")",
"-",
"(",
"3",
"*",
"ema",
"(",
"ema",
"(",
"data",
",",
"period",
")",
",",
"period",
")",
")",
")",
"+",
"ema",
"(",
"ema",
"(",
"ema",
"(",
"data",
",",
"period",
")",
",",
"period",
")",
",",
"period",
")",
")",
"return",
"tema"
] |
Triple Exponential Moving Average.
Formula:
TEMA = (3*EMA - 3*EMA(EMA)) + EMA(EMA(EMA))
|
[
"Triple",
"Exponential",
"Moving",
"Average",
"."
] |
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
|
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/triple_exponential_moving_average.py#L8-L20
|
234,404
|
kylejusticemagnuson/pyti
|
pyti/money_flow.py
|
money_flow
|
def money_flow(close_data, high_data, low_data, volume):
"""
Money Flow.
Formula:
MF = VOLUME * TYPICAL PRICE
"""
catch_errors.check_for_input_len_diff(
close_data, high_data, low_data, volume
)
mf = volume * tp(close_data, high_data, low_data)
return mf
|
python
|
def money_flow(close_data, high_data, low_data, volume):
"""
Money Flow.
Formula:
MF = VOLUME * TYPICAL PRICE
"""
catch_errors.check_for_input_len_diff(
close_data, high_data, low_data, volume
)
mf = volume * tp(close_data, high_data, low_data)
return mf
|
[
"def",
"money_flow",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"volume",
")",
":",
"catch_errors",
".",
"check_for_input_len_diff",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
",",
"volume",
")",
"mf",
"=",
"volume",
"*",
"tp",
"(",
"close_data",
",",
"high_data",
",",
"low_data",
")",
"return",
"mf"
] |
Money Flow.
Formula:
MF = VOLUME * TYPICAL PRICE
|
[
"Money",
"Flow",
"."
] |
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
|
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/money_flow.py#L6-L17
|
234,405
|
mrooney/mintapi
|
mintapi/api.py
|
Mint.request_and_check
|
def request_and_check(self, url, method='get',
expected_content_type=None, **kwargs):
"""Performs a request, and checks that the status is OK, and that the
content-type matches expectations.
Args:
url: URL to request
method: either 'get' or 'post'
expected_content_type: prefix to match response content-type against
**kwargs: passed to the request method directly.
Raises:
RuntimeError if status_code does not match.
"""
assert method in ['get', 'post']
result = self.driver.request(method, url, **kwargs)
if result.status_code != requests.codes.ok:
raise RuntimeError('Error requesting %r, status = %d' %
(url, result.status_code))
if expected_content_type is not None:
content_type = result.headers.get('content-type', '')
if not re.match(expected_content_type, content_type):
raise RuntimeError(
'Error requesting %r, content type %r does not match %r' %
(url, content_type, expected_content_type))
return result
|
python
|
def request_and_check(self, url, method='get',
expected_content_type=None, **kwargs):
"""Performs a request, and checks that the status is OK, and that the
content-type matches expectations.
Args:
url: URL to request
method: either 'get' or 'post'
expected_content_type: prefix to match response content-type against
**kwargs: passed to the request method directly.
Raises:
RuntimeError if status_code does not match.
"""
assert method in ['get', 'post']
result = self.driver.request(method, url, **kwargs)
if result.status_code != requests.codes.ok:
raise RuntimeError('Error requesting %r, status = %d' %
(url, result.status_code))
if expected_content_type is not None:
content_type = result.headers.get('content-type', '')
if not re.match(expected_content_type, content_type):
raise RuntimeError(
'Error requesting %r, content type %r does not match %r' %
(url, content_type, expected_content_type))
return result
|
[
"def",
"request_and_check",
"(",
"self",
",",
"url",
",",
"method",
"=",
"'get'",
",",
"expected_content_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"method",
"in",
"[",
"'get'",
",",
"'post'",
"]",
"result",
"=",
"self",
".",
"driver",
".",
"request",
"(",
"method",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
"if",
"result",
".",
"status_code",
"!=",
"requests",
".",
"codes",
".",
"ok",
":",
"raise",
"RuntimeError",
"(",
"'Error requesting %r, status = %d'",
"%",
"(",
"url",
",",
"result",
".",
"status_code",
")",
")",
"if",
"expected_content_type",
"is",
"not",
"None",
":",
"content_type",
"=",
"result",
".",
"headers",
".",
"get",
"(",
"'content-type'",
",",
"''",
")",
"if",
"not",
"re",
".",
"match",
"(",
"expected_content_type",
",",
"content_type",
")",
":",
"raise",
"RuntimeError",
"(",
"'Error requesting %r, content type %r does not match %r'",
"%",
"(",
"url",
",",
"content_type",
",",
"expected_content_type",
")",
")",
"return",
"result"
] |
Performs a request, and checks that the status is OK, and that the
content-type matches expectations.
Args:
url: URL to request
method: either 'get' or 'post'
expected_content_type: prefix to match response content-type against
**kwargs: passed to the request method directly.
Raises:
RuntimeError if status_code does not match.
|
[
"Performs",
"a",
"request",
"and",
"checks",
"that",
"the",
"status",
"is",
"OK",
"and",
"that",
"the",
"content",
"-",
"type",
"matches",
"expectations",
"."
] |
44fddbeac79a68da657ad8118e02fcde968f8dfe
|
https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L394-L419
|
234,406
|
mrooney/mintapi
|
mintapi/api.py
|
Mint.get_transactions_json
|
def get_transactions_json(self, include_investment=False,
skip_duplicates=False, start_date=None, id=0):
"""Returns the raw JSON transaction data as downloaded from Mint. The JSON
transaction data includes some additional information missing from the
CSV data, such as whether the transaction is pending or completed, but
leaves off the year for current year transactions.
Warning: In order to reliably include or exclude duplicates, it is
necessary to change the user account property 'hide_duplicates' to the
appropriate value. This affects what is displayed in the web
interface. Note that the CSV transactions never exclude duplicates.
"""
# Warning: This is a global property for the user that we are changing.
self.set_user_property(
'hide_duplicates', 'T' if skip_duplicates else 'F')
# Converts the start date into datetime format - must be mm/dd/yy
try:
start_date = datetime.strptime(start_date, '%m/%d/%y')
except (TypeError, ValueError):
start_date = None
all_txns = []
offset = 0
# Mint only returns some of the transactions at once. To get all of
# them, we have to keep asking for more until we reach the end.
while 1:
url = MINT_ROOT_URL + '/getJsonData.xevent'
params = {
'queryNew': '',
'offset': offset,
'comparableType': '8',
'rnd': Mint.get_rnd(),
}
# Specifying accountId=0 causes Mint to return investment
# transactions as well. Otherwise they are skipped by
# default.
if id > 0 or include_investment:
params['id'] = id
if include_investment:
params['task'] = 'transactions'
else:
params['task'] = 'transactions,txnfilters'
params['filterType'] = 'cash'
result = self.request_and_check(
url, headers=JSON_HEADER, params=params,
expected_content_type='text/json|application/json')
data = json.loads(result.text)
txns = data['set'][0].get('data', [])
if not txns:
break
if start_date:
last_dt = json_date_to_datetime(txns[-1]['odate'])
if last_dt < start_date:
keep_txns = [
t for t in txns
if json_date_to_datetime(t['odate']) >= start_date]
all_txns.extend(keep_txns)
break
all_txns.extend(txns)
offset += len(txns)
return all_txns
|
python
|
def get_transactions_json(self, include_investment=False,
skip_duplicates=False, start_date=None, id=0):
"""Returns the raw JSON transaction data as downloaded from Mint. The JSON
transaction data includes some additional information missing from the
CSV data, such as whether the transaction is pending or completed, but
leaves off the year for current year transactions.
Warning: In order to reliably include or exclude duplicates, it is
necessary to change the user account property 'hide_duplicates' to the
appropriate value. This affects what is displayed in the web
interface. Note that the CSV transactions never exclude duplicates.
"""
# Warning: This is a global property for the user that we are changing.
self.set_user_property(
'hide_duplicates', 'T' if skip_duplicates else 'F')
# Converts the start date into datetime format - must be mm/dd/yy
try:
start_date = datetime.strptime(start_date, '%m/%d/%y')
except (TypeError, ValueError):
start_date = None
all_txns = []
offset = 0
# Mint only returns some of the transactions at once. To get all of
# them, we have to keep asking for more until we reach the end.
while 1:
url = MINT_ROOT_URL + '/getJsonData.xevent'
params = {
'queryNew': '',
'offset': offset,
'comparableType': '8',
'rnd': Mint.get_rnd(),
}
# Specifying accountId=0 causes Mint to return investment
# transactions as well. Otherwise they are skipped by
# default.
if id > 0 or include_investment:
params['id'] = id
if include_investment:
params['task'] = 'transactions'
else:
params['task'] = 'transactions,txnfilters'
params['filterType'] = 'cash'
result = self.request_and_check(
url, headers=JSON_HEADER, params=params,
expected_content_type='text/json|application/json')
data = json.loads(result.text)
txns = data['set'][0].get('data', [])
if not txns:
break
if start_date:
last_dt = json_date_to_datetime(txns[-1]['odate'])
if last_dt < start_date:
keep_txns = [
t for t in txns
if json_date_to_datetime(t['odate']) >= start_date]
all_txns.extend(keep_txns)
break
all_txns.extend(txns)
offset += len(txns)
return all_txns
|
[
"def",
"get_transactions_json",
"(",
"self",
",",
"include_investment",
"=",
"False",
",",
"skip_duplicates",
"=",
"False",
",",
"start_date",
"=",
"None",
",",
"id",
"=",
"0",
")",
":",
"# Warning: This is a global property for the user that we are changing.",
"self",
".",
"set_user_property",
"(",
"'hide_duplicates'",
",",
"'T'",
"if",
"skip_duplicates",
"else",
"'F'",
")",
"# Converts the start date into datetime format - must be mm/dd/yy",
"try",
":",
"start_date",
"=",
"datetime",
".",
"strptime",
"(",
"start_date",
",",
"'%m/%d/%y'",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"start_date",
"=",
"None",
"all_txns",
"=",
"[",
"]",
"offset",
"=",
"0",
"# Mint only returns some of the transactions at once. To get all of",
"# them, we have to keep asking for more until we reach the end.",
"while",
"1",
":",
"url",
"=",
"MINT_ROOT_URL",
"+",
"'/getJsonData.xevent'",
"params",
"=",
"{",
"'queryNew'",
":",
"''",
",",
"'offset'",
":",
"offset",
",",
"'comparableType'",
":",
"'8'",
",",
"'rnd'",
":",
"Mint",
".",
"get_rnd",
"(",
")",
",",
"}",
"# Specifying accountId=0 causes Mint to return investment",
"# transactions as well. Otherwise they are skipped by",
"# default.",
"if",
"id",
">",
"0",
"or",
"include_investment",
":",
"params",
"[",
"'id'",
"]",
"=",
"id",
"if",
"include_investment",
":",
"params",
"[",
"'task'",
"]",
"=",
"'transactions'",
"else",
":",
"params",
"[",
"'task'",
"]",
"=",
"'transactions,txnfilters'",
"params",
"[",
"'filterType'",
"]",
"=",
"'cash'",
"result",
"=",
"self",
".",
"request_and_check",
"(",
"url",
",",
"headers",
"=",
"JSON_HEADER",
",",
"params",
"=",
"params",
",",
"expected_content_type",
"=",
"'text/json|application/json'",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"result",
".",
"text",
")",
"txns",
"=",
"data",
"[",
"'set'",
"]",
"[",
"0",
"]",
".",
"get",
"(",
"'data'",
",",
"[",
"]",
")",
"if",
"not",
"txns",
":",
"break",
"if",
"start_date",
":",
"last_dt",
"=",
"json_date_to_datetime",
"(",
"txns",
"[",
"-",
"1",
"]",
"[",
"'odate'",
"]",
")",
"if",
"last_dt",
"<",
"start_date",
":",
"keep_txns",
"=",
"[",
"t",
"for",
"t",
"in",
"txns",
"if",
"json_date_to_datetime",
"(",
"t",
"[",
"'odate'",
"]",
")",
">=",
"start_date",
"]",
"all_txns",
".",
"extend",
"(",
"keep_txns",
")",
"break",
"all_txns",
".",
"extend",
"(",
"txns",
")",
"offset",
"+=",
"len",
"(",
"txns",
")",
"return",
"all_txns"
] |
Returns the raw JSON transaction data as downloaded from Mint. The JSON
transaction data includes some additional information missing from the
CSV data, such as whether the transaction is pending or completed, but
leaves off the year for current year transactions.
Warning: In order to reliably include or exclude duplicates, it is
necessary to change the user account property 'hide_duplicates' to the
appropriate value. This affects what is displayed in the web
interface. Note that the CSV transactions never exclude duplicates.
|
[
"Returns",
"the",
"raw",
"JSON",
"transaction",
"data",
"as",
"downloaded",
"from",
"Mint",
".",
"The",
"JSON",
"transaction",
"data",
"includes",
"some",
"additional",
"information",
"missing",
"from",
"the",
"CSV",
"data",
"such",
"as",
"whether",
"the",
"transaction",
"is",
"pending",
"or",
"completed",
"but",
"leaves",
"off",
"the",
"year",
"for",
"current",
"year",
"transactions",
"."
] |
44fddbeac79a68da657ad8118e02fcde968f8dfe
|
https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L533-L594
|
234,407
|
mrooney/mintapi
|
mintapi/api.py
|
Mint.get_detailed_transactions
|
def get_detailed_transactions(self, include_investment=False,
skip_duplicates=False,
remove_pending=True,
start_date=None):
"""Returns the JSON transaction data as a DataFrame, and converts
current year dates and prior year dates into consistent datetime
format, and reverses credit activity.
Note: start_date must be in format mm/dd/yy. If pulls take too long,
use a more recent start date. See json explanations of
include_investment and skip_duplicates.
Also note: Mint includes pending transactions, however these sometimes
change dates/amounts after the transactions post. They have been
removed by default in this pull, but can be included by changing
remove_pending to False
"""
assert_pd()
result = self.get_transactions_json(include_investment,
skip_duplicates, start_date)
df = pd.DataFrame(result)
df['odate'] = df['odate'].apply(json_date_to_datetime)
if remove_pending:
df = df[~df.isPending]
df.reset_index(drop=True, inplace=True)
df.amount = df.apply(reverse_credit_amount, axis=1)
return df
|
python
|
def get_detailed_transactions(self, include_investment=False,
skip_duplicates=False,
remove_pending=True,
start_date=None):
"""Returns the JSON transaction data as a DataFrame, and converts
current year dates and prior year dates into consistent datetime
format, and reverses credit activity.
Note: start_date must be in format mm/dd/yy. If pulls take too long,
use a more recent start date. See json explanations of
include_investment and skip_duplicates.
Also note: Mint includes pending transactions, however these sometimes
change dates/amounts after the transactions post. They have been
removed by default in this pull, but can be included by changing
remove_pending to False
"""
assert_pd()
result = self.get_transactions_json(include_investment,
skip_duplicates, start_date)
df = pd.DataFrame(result)
df['odate'] = df['odate'].apply(json_date_to_datetime)
if remove_pending:
df = df[~df.isPending]
df.reset_index(drop=True, inplace=True)
df.amount = df.apply(reverse_credit_amount, axis=1)
return df
|
[
"def",
"get_detailed_transactions",
"(",
"self",
",",
"include_investment",
"=",
"False",
",",
"skip_duplicates",
"=",
"False",
",",
"remove_pending",
"=",
"True",
",",
"start_date",
"=",
"None",
")",
":",
"assert_pd",
"(",
")",
"result",
"=",
"self",
".",
"get_transactions_json",
"(",
"include_investment",
",",
"skip_duplicates",
",",
"start_date",
")",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"result",
")",
"df",
"[",
"'odate'",
"]",
"=",
"df",
"[",
"'odate'",
"]",
".",
"apply",
"(",
"json_date_to_datetime",
")",
"if",
"remove_pending",
":",
"df",
"=",
"df",
"[",
"~",
"df",
".",
"isPending",
"]",
"df",
".",
"reset_index",
"(",
"drop",
"=",
"True",
",",
"inplace",
"=",
"True",
")",
"df",
".",
"amount",
"=",
"df",
".",
"apply",
"(",
"reverse_credit_amount",
",",
"axis",
"=",
"1",
")",
"return",
"df"
] |
Returns the JSON transaction data as a DataFrame, and converts
current year dates and prior year dates into consistent datetime
format, and reverses credit activity.
Note: start_date must be in format mm/dd/yy. If pulls take too long,
use a more recent start date. See json explanations of
include_investment and skip_duplicates.
Also note: Mint includes pending transactions, however these sometimes
change dates/amounts after the transactions post. They have been
removed by default in this pull, but can be included by changing
remove_pending to False
|
[
"Returns",
"the",
"JSON",
"transaction",
"data",
"as",
"a",
"DataFrame",
"and",
"converts",
"current",
"year",
"dates",
"and",
"prior",
"year",
"dates",
"into",
"consistent",
"datetime",
"format",
"and",
"reverses",
"credit",
"activity",
"."
] |
44fddbeac79a68da657ad8118e02fcde968f8dfe
|
https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L596-L627
|
234,408
|
mrooney/mintapi
|
mintapi/api.py
|
Mint.get_transactions_csv
|
def get_transactions_csv(self, include_investment=False, acct=0):
"""Returns the raw CSV transaction data as downloaded from Mint.
If include_investment == True, also includes transactions that Mint
classifies as investment-related. You may find that the investment
transaction data is not sufficiently detailed to actually be useful,
however.
"""
# Specifying accountId=0 causes Mint to return investment
# transactions as well. Otherwise they are skipped by
# default.
params = None
if include_investment or acct > 0:
params = {'accountId': acct}
result = self.request_and_check(
'{}/transactionDownload.event'.format(MINT_ROOT_URL),
params=params,
expected_content_type='text/csv')
return result.content
|
python
|
def get_transactions_csv(self, include_investment=False, acct=0):
"""Returns the raw CSV transaction data as downloaded from Mint.
If include_investment == True, also includes transactions that Mint
classifies as investment-related. You may find that the investment
transaction data is not sufficiently detailed to actually be useful,
however.
"""
# Specifying accountId=0 causes Mint to return investment
# transactions as well. Otherwise they are skipped by
# default.
params = None
if include_investment or acct > 0:
params = {'accountId': acct}
result = self.request_and_check(
'{}/transactionDownload.event'.format(MINT_ROOT_URL),
params=params,
expected_content_type='text/csv')
return result.content
|
[
"def",
"get_transactions_csv",
"(",
"self",
",",
"include_investment",
"=",
"False",
",",
"acct",
"=",
"0",
")",
":",
"# Specifying accountId=0 causes Mint to return investment",
"# transactions as well. Otherwise they are skipped by",
"# default.",
"params",
"=",
"None",
"if",
"include_investment",
"or",
"acct",
">",
"0",
":",
"params",
"=",
"{",
"'accountId'",
":",
"acct",
"}",
"result",
"=",
"self",
".",
"request_and_check",
"(",
"'{}/transactionDownload.event'",
".",
"format",
"(",
"MINT_ROOT_URL",
")",
",",
"params",
"=",
"params",
",",
"expected_content_type",
"=",
"'text/csv'",
")",
"return",
"result",
".",
"content"
] |
Returns the raw CSV transaction data as downloaded from Mint.
If include_investment == True, also includes transactions that Mint
classifies as investment-related. You may find that the investment
transaction data is not sufficiently detailed to actually be useful,
however.
|
[
"Returns",
"the",
"raw",
"CSV",
"transaction",
"data",
"as",
"downloaded",
"from",
"Mint",
"."
] |
44fddbeac79a68da657ad8118e02fcde968f8dfe
|
https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L629-L648
|
234,409
|
mrooney/mintapi
|
mintapi/api.py
|
Mint.get_transactions
|
def get_transactions(self, include_investment=False):
"""Returns the transaction data as a Pandas DataFrame."""
assert_pd()
s = StringIO(self.get_transactions_csv(
include_investment=include_investment))
s.seek(0)
df = pd.read_csv(s, parse_dates=['Date'])
df.columns = [c.lower().replace(' ', '_') for c in df.columns]
df.category = (df.category.str.lower()
.replace('uncategorized', pd.np.nan))
return df
|
python
|
def get_transactions(self, include_investment=False):
"""Returns the transaction data as a Pandas DataFrame."""
assert_pd()
s = StringIO(self.get_transactions_csv(
include_investment=include_investment))
s.seek(0)
df = pd.read_csv(s, parse_dates=['Date'])
df.columns = [c.lower().replace(' ', '_') for c in df.columns]
df.category = (df.category.str.lower()
.replace('uncategorized', pd.np.nan))
return df
|
[
"def",
"get_transactions",
"(",
"self",
",",
"include_investment",
"=",
"False",
")",
":",
"assert_pd",
"(",
")",
"s",
"=",
"StringIO",
"(",
"self",
".",
"get_transactions_csv",
"(",
"include_investment",
"=",
"include_investment",
")",
")",
"s",
".",
"seek",
"(",
"0",
")",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"s",
",",
"parse_dates",
"=",
"[",
"'Date'",
"]",
")",
"df",
".",
"columns",
"=",
"[",
"c",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
"for",
"c",
"in",
"df",
".",
"columns",
"]",
"df",
".",
"category",
"=",
"(",
"df",
".",
"category",
".",
"str",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'uncategorized'",
",",
"pd",
".",
"np",
".",
"nan",
")",
")",
"return",
"df"
] |
Returns the transaction data as a Pandas DataFrame.
|
[
"Returns",
"the",
"transaction",
"data",
"as",
"a",
"Pandas",
"DataFrame",
"."
] |
44fddbeac79a68da657ad8118e02fcde968f8dfe
|
https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L662-L672
|
234,410
|
StellarCN/py-stellar-base
|
stellar_base/address.py
|
Address.payments
|
def payments(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the payments JSON from this instance's Horizon server.
Retrieve the payments JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
"""
return self.horizon.account_payments(address=self.address, cursor=cursor, order=order, limit=limit, sse=sse)
|
python
|
def payments(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the payments JSON from this instance's Horizon server.
Retrieve the payments JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
"""
return self.horizon.account_payments(address=self.address, cursor=cursor, order=order, limit=limit, sse=sse)
|
[
"def",
"payments",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"return",
"self",
".",
"horizon",
".",
"account_payments",
"(",
"address",
"=",
"self",
".",
"address",
",",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
",",
"sse",
"=",
"sse",
")"
] |
Retrieve the payments JSON from this instance's Horizon server.
Retrieve the payments JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
|
[
"Retrieve",
"the",
"payments",
"JSON",
"from",
"this",
"instance",
"s",
"Horizon",
"server",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L95-L109
|
234,411
|
StellarCN/py-stellar-base
|
stellar_base/address.py
|
Address.offers
|
def offers(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the offers JSON from this instance's Horizon server.
Retrieve the offers JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
"""
return self.horizon.account_offers(self.address, cursor=cursor, order=order, limit=limit, sse=sse)
|
python
|
def offers(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the offers JSON from this instance's Horizon server.
Retrieve the offers JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
"""
return self.horizon.account_offers(self.address, cursor=cursor, order=order, limit=limit, sse=sse)
|
[
"def",
"offers",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"return",
"self",
".",
"horizon",
".",
"account_offers",
"(",
"self",
".",
"address",
",",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
",",
"sse",
"=",
"sse",
")"
] |
Retrieve the offers JSON from this instance's Horizon server.
Retrieve the offers JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
|
[
"Retrieve",
"the",
"offers",
"JSON",
"from",
"this",
"instance",
"s",
"Horizon",
"server",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L111-L125
|
234,412
|
StellarCN/py-stellar-base
|
stellar_base/address.py
|
Address.transactions
|
def transactions(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the transactions JSON from this instance's Horizon server.
Retrieve the transactions JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
"""
return self.horizon.account_transactions(
self.address, cursor=cursor, order=order, limit=limit, sse=sse)
|
python
|
def transactions(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the transactions JSON from this instance's Horizon server.
Retrieve the transactions JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
"""
return self.horizon.account_transactions(
self.address, cursor=cursor, order=order, limit=limit, sse=sse)
|
[
"def",
"transactions",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"return",
"self",
".",
"horizon",
".",
"account_transactions",
"(",
"self",
".",
"address",
",",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
",",
"sse",
"=",
"sse",
")"
] |
Retrieve the transactions JSON from this instance's Horizon server.
Retrieve the transactions JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
|
[
"Retrieve",
"the",
"transactions",
"JSON",
"from",
"this",
"instance",
"s",
"Horizon",
"server",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L127-L141
|
234,413
|
StellarCN/py-stellar-base
|
stellar_base/address.py
|
Address.operations
|
def operations(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the operations JSON from this instance's Horizon server.
Retrieve the operations JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon.
"""
return self.horizon.account_operations(
self.address, cursor=cursor, order=order, limit=limit, sse=sse)
|
python
|
def operations(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the operations JSON from this instance's Horizon server.
Retrieve the operations JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon.
"""
return self.horizon.account_operations(
self.address, cursor=cursor, order=order, limit=limit, sse=sse)
|
[
"def",
"operations",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"return",
"self",
".",
"horizon",
".",
"account_operations",
"(",
"self",
".",
"address",
",",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
",",
"sse",
"=",
"sse",
")"
] |
Retrieve the operations JSON from this instance's Horizon server.
Retrieve the operations JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon.
|
[
"Retrieve",
"the",
"operations",
"JSON",
"from",
"this",
"instance",
"s",
"Horizon",
"server",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L143-L158
|
234,414
|
StellarCN/py-stellar-base
|
stellar_base/address.py
|
Address.trades
|
def trades(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the trades JSON from this instance's Horizon server.
Retrieve the trades JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon.
"""
return self.horizon.account_trades(
self.address, cursor=cursor, order=order, limit=limit, sse=sse)
|
python
|
def trades(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the trades JSON from this instance's Horizon server.
Retrieve the trades JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon.
"""
return self.horizon.account_trades(
self.address, cursor=cursor, order=order, limit=limit, sse=sse)
|
[
"def",
"trades",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"return",
"self",
".",
"horizon",
".",
"account_trades",
"(",
"self",
".",
"address",
",",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
",",
"sse",
"=",
"sse",
")"
] |
Retrieve the trades JSON from this instance's Horizon server.
Retrieve the trades JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon.
|
[
"Retrieve",
"the",
"trades",
"JSON",
"from",
"this",
"instance",
"s",
"Horizon",
"server",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L160-L174
|
234,415
|
StellarCN/py-stellar-base
|
stellar_base/address.py
|
Address.effects
|
def effects(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the effects JSON from this instance's Horizon server.
Retrieve the effects JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon.
"""
return self.horizon.account_effects(
self.address, cursor=cursor, order=order, limit=limit, sse=sse)
|
python
|
def effects(self, cursor=None, order='asc', limit=10, sse=False):
"""Retrieve the effects JSON from this instance's Horizon server.
Retrieve the effects JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon.
"""
return self.horizon.account_effects(
self.address, cursor=cursor, order=order, limit=limit, sse=sse)
|
[
"def",
"effects",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"return",
"self",
".",
"horizon",
".",
"account_effects",
"(",
"self",
".",
"address",
",",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
",",
"sse",
"=",
"sse",
")"
] |
Retrieve the effects JSON from this instance's Horizon server.
Retrieve the effects JSON response for the account associated with
this :class:`Address`.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use the SSE client for connecting to Horizon.
|
[
"Retrieve",
"the",
"effects",
"JSON",
"from",
"this",
"instance",
"s",
"Horizon",
"server",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L176-L191
|
234,416
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.submit
|
def submit(self, te):
"""Submit the transaction using a pooled connection, and retry on failure.
`POST /transactions
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-create.html>`_
Uses form-encoded data to send over to Horizon.
:return: The JSON response indicating the success/failure of the
submitted transaction.
:rtype: dict
"""
params = {'tx': te}
url = urljoin(self.horizon_uri, 'transactions/')
# POST is not included in Retry's method_whitelist for a good reason.
# our custom retry mechanism follows
reply = None
retry_count = self.num_retries
while True:
try:
reply = self._session.post(
url, data=params, timeout=self.request_timeout)
return check_horizon_reply(reply.json())
except (RequestException, NewConnectionError, ValueError) as e:
if reply is not None:
msg = 'Horizon submit exception: {}, reply: [{}] {}'.format(
str(e), reply.status_code, reply.text)
else:
msg = 'Horizon submit exception: {}'.format(str(e))
logging.warning(msg)
if (reply is not None and reply.status_code not in self.status_forcelist) or retry_count <= 0:
if reply is None:
raise HorizonRequestError(e)
raise HorizonError('Invalid horizon reply: [{}] {}'.format(
reply.status_code, reply.text), reply.status_code)
retry_count -= 1
logging.warning('Submit retry attempt {}'.format(retry_count))
sleep(self.backoff_factor)
|
python
|
def submit(self, te):
"""Submit the transaction using a pooled connection, and retry on failure.
`POST /transactions
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-create.html>`_
Uses form-encoded data to send over to Horizon.
:return: The JSON response indicating the success/failure of the
submitted transaction.
:rtype: dict
"""
params = {'tx': te}
url = urljoin(self.horizon_uri, 'transactions/')
# POST is not included in Retry's method_whitelist for a good reason.
# our custom retry mechanism follows
reply = None
retry_count = self.num_retries
while True:
try:
reply = self._session.post(
url, data=params, timeout=self.request_timeout)
return check_horizon_reply(reply.json())
except (RequestException, NewConnectionError, ValueError) as e:
if reply is not None:
msg = 'Horizon submit exception: {}, reply: [{}] {}'.format(
str(e), reply.status_code, reply.text)
else:
msg = 'Horizon submit exception: {}'.format(str(e))
logging.warning(msg)
if (reply is not None and reply.status_code not in self.status_forcelist) or retry_count <= 0:
if reply is None:
raise HorizonRequestError(e)
raise HorizonError('Invalid horizon reply: [{}] {}'.format(
reply.status_code, reply.text), reply.status_code)
retry_count -= 1
logging.warning('Submit retry attempt {}'.format(retry_count))
sleep(self.backoff_factor)
|
[
"def",
"submit",
"(",
"self",
",",
"te",
")",
":",
"params",
"=",
"{",
"'tx'",
":",
"te",
"}",
"url",
"=",
"urljoin",
"(",
"self",
".",
"horizon_uri",
",",
"'transactions/'",
")",
"# POST is not included in Retry's method_whitelist for a good reason.",
"# our custom retry mechanism follows",
"reply",
"=",
"None",
"retry_count",
"=",
"self",
".",
"num_retries",
"while",
"True",
":",
"try",
":",
"reply",
"=",
"self",
".",
"_session",
".",
"post",
"(",
"url",
",",
"data",
"=",
"params",
",",
"timeout",
"=",
"self",
".",
"request_timeout",
")",
"return",
"check_horizon_reply",
"(",
"reply",
".",
"json",
"(",
")",
")",
"except",
"(",
"RequestException",
",",
"NewConnectionError",
",",
"ValueError",
")",
"as",
"e",
":",
"if",
"reply",
"is",
"not",
"None",
":",
"msg",
"=",
"'Horizon submit exception: {}, reply: [{}] {}'",
".",
"format",
"(",
"str",
"(",
"e",
")",
",",
"reply",
".",
"status_code",
",",
"reply",
".",
"text",
")",
"else",
":",
"msg",
"=",
"'Horizon submit exception: {}'",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
"logging",
".",
"warning",
"(",
"msg",
")",
"if",
"(",
"reply",
"is",
"not",
"None",
"and",
"reply",
".",
"status_code",
"not",
"in",
"self",
".",
"status_forcelist",
")",
"or",
"retry_count",
"<=",
"0",
":",
"if",
"reply",
"is",
"None",
":",
"raise",
"HorizonRequestError",
"(",
"e",
")",
"raise",
"HorizonError",
"(",
"'Invalid horizon reply: [{}] {}'",
".",
"format",
"(",
"reply",
".",
"status_code",
",",
"reply",
".",
"text",
")",
",",
"reply",
".",
"status_code",
")",
"retry_count",
"-=",
"1",
"logging",
".",
"warning",
"(",
"'Submit retry attempt {}'",
".",
"format",
"(",
"retry_count",
")",
")",
"sleep",
"(",
"self",
".",
"backoff_factor",
")"
] |
Submit the transaction using a pooled connection, and retry on failure.
`POST /transactions
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-create.html>`_
Uses form-encoded data to send over to Horizon.
:return: The JSON response indicating the success/failure of the
submitted transaction.
:rtype: dict
|
[
"Submit",
"the",
"transaction",
"using",
"a",
"pooled",
"connection",
"and",
"retry",
"on",
"failure",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L118-L158
|
234,417
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.account
|
def account(self, address):
"""Returns information and links relating to a single account.
`GET /accounts/{account}
<https://www.stellar.org/developers/horizon/reference/endpoints/accounts-single.html>`_
:param str address: The account ID to retrieve details about.
:return: The account details in a JSON response.
:rtype: dict
"""
endpoint = '/accounts/{account_id}'.format(account_id=address)
return self.query(endpoint)
|
python
|
def account(self, address):
"""Returns information and links relating to a single account.
`GET /accounts/{account}
<https://www.stellar.org/developers/horizon/reference/endpoints/accounts-single.html>`_
:param str address: The account ID to retrieve details about.
:return: The account details in a JSON response.
:rtype: dict
"""
endpoint = '/accounts/{account_id}'.format(account_id=address)
return self.query(endpoint)
|
[
"def",
"account",
"(",
"self",
",",
"address",
")",
":",
"endpoint",
"=",
"'/accounts/{account_id}'",
".",
"format",
"(",
"account_id",
"=",
"address",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
")"
] |
Returns information and links relating to a single account.
`GET /accounts/{account}
<https://www.stellar.org/developers/horizon/reference/endpoints/accounts-single.html>`_
:param str address: The account ID to retrieve details about.
:return: The account details in a JSON response.
:rtype: dict
|
[
"Returns",
"information",
"and",
"links",
"relating",
"to",
"a",
"single",
"account",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L188-L200
|
234,418
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.account_data
|
def account_data(self, address, key):
"""This endpoint represents a single data associated with a given
account.
`GET /accounts/{account}/data/{key}
<https://www.stellar.org/developers/horizon/reference/endpoints/data-for-account.html>`_
:param str address: The account ID to look up a data item from.
:param str key: The name of the key for the data item in question.
:return: The value of the data field for the given account and data key.
:rtype: dict
"""
endpoint = '/accounts/{account_id}/data/{data_key}'.format(
account_id=address, data_key=key)
return self.query(endpoint)
|
python
|
def account_data(self, address, key):
"""This endpoint represents a single data associated with a given
account.
`GET /accounts/{account}/data/{key}
<https://www.stellar.org/developers/horizon/reference/endpoints/data-for-account.html>`_
:param str address: The account ID to look up a data item from.
:param str key: The name of the key for the data item in question.
:return: The value of the data field for the given account and data key.
:rtype: dict
"""
endpoint = '/accounts/{account_id}/data/{data_key}'.format(
account_id=address, data_key=key)
return self.query(endpoint)
|
[
"def",
"account_data",
"(",
"self",
",",
"address",
",",
"key",
")",
":",
"endpoint",
"=",
"'/accounts/{account_id}/data/{data_key}'",
".",
"format",
"(",
"account_id",
"=",
"address",
",",
"data_key",
"=",
"key",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
")"
] |
This endpoint represents a single data associated with a given
account.
`GET /accounts/{account}/data/{key}
<https://www.stellar.org/developers/horizon/reference/endpoints/data-for-account.html>`_
:param str address: The account ID to look up a data item from.
:param str key: The name of the key for the data item in question.
:return: The value of the data field for the given account and data key.
:rtype: dict
|
[
"This",
"endpoint",
"represents",
"a",
"single",
"data",
"associated",
"with",
"a",
"given",
"account",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L202-L217
|
234,419
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.account_effects
|
def account_effects(self, address, cursor=None, order='asc', limit=10, sse=False):
"""This endpoint represents all effects that changed a given account.
`GET /accounts/{account}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-account.html>`_
:param str address: The account ID to look up effects for.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
:return: The list of effects in a JSON response.
:rtype: dict
"""
endpoint = '/accounts/{account_id}/effects'.format(account_id=address)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params, sse)
|
python
|
def account_effects(self, address, cursor=None, order='asc', limit=10, sse=False):
"""This endpoint represents all effects that changed a given account.
`GET /accounts/{account}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-account.html>`_
:param str address: The account ID to look up effects for.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
:return: The list of effects in a JSON response.
:rtype: dict
"""
endpoint = '/accounts/{account_id}/effects'.format(account_id=address)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params, sse)
|
[
"def",
"account_effects",
"(",
"self",
",",
"address",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"endpoint",
"=",
"'/accounts/{account_id}/effects'",
".",
"format",
"(",
"account_id",
"=",
"address",
")",
"params",
"=",
"self",
".",
"__query_params",
"(",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
",",
"params",
",",
"sse",
")"
] |
This endpoint represents all effects that changed a given account.
`GET /accounts/{account}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-account.html>`_
:param str address: The account ID to look up effects for.
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
:return: The list of effects in a JSON response.
:rtype: dict
|
[
"This",
"endpoint",
"represents",
"all",
"effects",
"that",
"changed",
"a",
"given",
"account",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L219-L238
|
234,420
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.assets
|
def assets(self, asset_code=None, asset_issuer=None, cursor=None, order='asc', limit=10):
"""This endpoint represents all assets. It will give you all the assets
in the system along with various statistics about each.
See the documentation below for details on query parameters that are
available.
`GET /assets{?asset_code,asset_issuer,cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/assets-all.html>`_
:param str asset_code: Code of the Asset to filter by.
:param str asset_issuer: Issuer of the Asset to filter by.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc",
ordered by asset_code then by asset_issuer.
:param int limit: Maximum number of records to return.
:return: A list of all valid payment operations
:rtype: dict
"""
endpoint = '/assets'
params = self.__query_params(asset_code=asset_code, asset_issuer=asset_issuer, cursor=cursor, order=order,
limit=limit)
return self.query(endpoint, params)
|
python
|
def assets(self, asset_code=None, asset_issuer=None, cursor=None, order='asc', limit=10):
"""This endpoint represents all assets. It will give you all the assets
in the system along with various statistics about each.
See the documentation below for details on query parameters that are
available.
`GET /assets{?asset_code,asset_issuer,cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/assets-all.html>`_
:param str asset_code: Code of the Asset to filter by.
:param str asset_issuer: Issuer of the Asset to filter by.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc",
ordered by asset_code then by asset_issuer.
:param int limit: Maximum number of records to return.
:return: A list of all valid payment operations
:rtype: dict
"""
endpoint = '/assets'
params = self.__query_params(asset_code=asset_code, asset_issuer=asset_issuer, cursor=cursor, order=order,
limit=limit)
return self.query(endpoint, params)
|
[
"def",
"assets",
"(",
"self",
",",
"asset_code",
"=",
"None",
",",
"asset_issuer",
"=",
"None",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/assets'",
"params",
"=",
"self",
".",
"__query_params",
"(",
"asset_code",
"=",
"asset_code",
",",
"asset_issuer",
"=",
"asset_issuer",
",",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
",",
"params",
")"
] |
This endpoint represents all assets. It will give you all the assets
in the system along with various statistics about each.
See the documentation below for details on query parameters that are
available.
`GET /assets{?asset_code,asset_issuer,cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/assets-all.html>`_
:param str asset_code: Code of the Asset to filter by.
:param str asset_issuer: Issuer of the Asset to filter by.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc",
ordered by asset_code then by asset_issuer.
:param int limit: Maximum number of records to return.
:return: A list of all valid payment operations
:rtype: dict
|
[
"This",
"endpoint",
"represents",
"all",
"assets",
".",
"It",
"will",
"give",
"you",
"all",
"the",
"assets",
"in",
"the",
"system",
"along",
"with",
"various",
"statistics",
"about",
"each",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L352-L376
|
234,421
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.transaction
|
def transaction(self, tx_hash):
"""The transaction details endpoint provides information on a single
transaction.
`GET /transactions/{hash}
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:return: A single transaction's details.
:rtype: dict
"""
endpoint = '/transactions/{tx_hash}'.format(tx_hash=tx_hash)
return self.query(endpoint)
|
python
|
def transaction(self, tx_hash):
"""The transaction details endpoint provides information on a single
transaction.
`GET /transactions/{hash}
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:return: A single transaction's details.
:rtype: dict
"""
endpoint = '/transactions/{tx_hash}'.format(tx_hash=tx_hash)
return self.query(endpoint)
|
[
"def",
"transaction",
"(",
"self",
",",
"tx_hash",
")",
":",
"endpoint",
"=",
"'/transactions/{tx_hash}'",
".",
"format",
"(",
"tx_hash",
"=",
"tx_hash",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
")"
] |
The transaction details endpoint provides information on a single
transaction.
`GET /transactions/{hash}
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:return: A single transaction's details.
:rtype: dict
|
[
"The",
"transaction",
"details",
"endpoint",
"provides",
"information",
"on",
"a",
"single",
"transaction",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L399-L412
|
234,422
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.transaction_operations
|
def transaction_operations(self, tx_hash, cursor=None, order='asc', include_failed=False, limit=10):
"""This endpoint represents all operations that are part of a given
transaction.
`GET /transactions/{hash}/operations{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-for-transaction.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include operations of failed transactions in results.
:return: A single transaction's operations.
:rtype: dict
"""
endpoint = '/transactions/{tx_hash}/operations'.format(tx_hash=tx_hash)
params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed)
return self.query(endpoint, params)
|
python
|
def transaction_operations(self, tx_hash, cursor=None, order='asc', include_failed=False, limit=10):
"""This endpoint represents all operations that are part of a given
transaction.
`GET /transactions/{hash}/operations{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-for-transaction.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include operations of failed transactions in results.
:return: A single transaction's operations.
:rtype: dict
"""
endpoint = '/transactions/{tx_hash}/operations'.format(tx_hash=tx_hash)
params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed)
return self.query(endpoint, params)
|
[
"def",
"transaction_operations",
"(",
"self",
",",
"tx_hash",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"include_failed",
"=",
"False",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/transactions/{tx_hash}/operations'",
".",
"format",
"(",
"tx_hash",
"=",
"tx_hash",
")",
"params",
"=",
"self",
".",
"__query_params",
"(",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
",",
"include_failed",
"=",
"include_failed",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
",",
"params",
")"
] |
This endpoint represents all operations that are part of a given
transaction.
`GET /transactions/{hash}/operations{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-for-transaction.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include operations of failed transactions in results.
:return: A single transaction's operations.
:rtype: dict
|
[
"This",
"endpoint",
"represents",
"all",
"operations",
"that",
"are",
"part",
"of",
"a",
"given",
"transaction",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L414-L432
|
234,423
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.transaction_effects
|
def transaction_effects(self, tx_hash, cursor=None, order='asc', limit=10):
"""This endpoint represents all effects that occurred as a result of a
given transaction.
`GET /transactions/{hash}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-transaction.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A single transaction's effects.
:rtype: dict
"""
endpoint = '/transactions/{tx_hash}/effects'.format(tx_hash=tx_hash)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params)
|
python
|
def transaction_effects(self, tx_hash, cursor=None, order='asc', limit=10):
"""This endpoint represents all effects that occurred as a result of a
given transaction.
`GET /transactions/{hash}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-transaction.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A single transaction's effects.
:rtype: dict
"""
endpoint = '/transactions/{tx_hash}/effects'.format(tx_hash=tx_hash)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params)
|
[
"def",
"transaction_effects",
"(",
"self",
",",
"tx_hash",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/transactions/{tx_hash}/effects'",
".",
"format",
"(",
"tx_hash",
"=",
"tx_hash",
")",
"params",
"=",
"self",
".",
"__query_params",
"(",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
",",
"params",
")"
] |
This endpoint represents all effects that occurred as a result of a
given transaction.
`GET /transactions/{hash}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-transaction.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A single transaction's effects.
:rtype: dict
|
[
"This",
"endpoint",
"represents",
"all",
"effects",
"that",
"occurred",
"as",
"a",
"result",
"of",
"a",
"given",
"transaction",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L434-L451
|
234,424
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.order_book
|
def order_book(self, selling_asset_code, buying_asset_code, selling_asset_issuer=None, buying_asset_issuer=None,
limit=10):
"""Return, for each orderbook, a summary of the orderbook and the bids
and asks associated with that orderbook.
See the external docs below for information on the arguments required.
`GET /order_book
<https://www.stellar.org/developers/horizon/reference/endpoints/orderbook-details.html>`_
:param str selling_asset_code: Code of the Asset being sold.
:param str buying_asset_code: Type of the Asset being bought.
:param str selling_asset_issuer: Account ID of the issuer of the Asset being sold,
if it is a native asset, let it be `None`.
:param str buying_asset_issuer: Account ID of the issuer of the Asset being bought,
if it is a native asset, let it be `None`.
:param int limit: Limit the number of items returned.
:return: A list of orderbook summaries as a JSON object.
:rtype: dict
"""
selling_asset = Asset(selling_asset_code, selling_asset_issuer)
buying_asset = Asset(buying_asset_code, buying_asset_issuer)
asset_params = {
'selling_asset_type': selling_asset.type,
'selling_asset_code': None if selling_asset.is_native() else selling_asset.code,
'selling_asset_issuer': selling_asset.issuer,
'buying_asset_type': buying_asset.type,
'buying_asset_code': None if buying_asset.is_native() else buying_asset.code,
'buying_asset_issuer': buying_asset.issuer,
}
endpoint = '/order_book'
params = self.__query_params(limit=limit, **asset_params)
return self.query(endpoint, params)
|
python
|
def order_book(self, selling_asset_code, buying_asset_code, selling_asset_issuer=None, buying_asset_issuer=None,
limit=10):
"""Return, for each orderbook, a summary of the orderbook and the bids
and asks associated with that orderbook.
See the external docs below for information on the arguments required.
`GET /order_book
<https://www.stellar.org/developers/horizon/reference/endpoints/orderbook-details.html>`_
:param str selling_asset_code: Code of the Asset being sold.
:param str buying_asset_code: Type of the Asset being bought.
:param str selling_asset_issuer: Account ID of the issuer of the Asset being sold,
if it is a native asset, let it be `None`.
:param str buying_asset_issuer: Account ID of the issuer of the Asset being bought,
if it is a native asset, let it be `None`.
:param int limit: Limit the number of items returned.
:return: A list of orderbook summaries as a JSON object.
:rtype: dict
"""
selling_asset = Asset(selling_asset_code, selling_asset_issuer)
buying_asset = Asset(buying_asset_code, buying_asset_issuer)
asset_params = {
'selling_asset_type': selling_asset.type,
'selling_asset_code': None if selling_asset.is_native() else selling_asset.code,
'selling_asset_issuer': selling_asset.issuer,
'buying_asset_type': buying_asset.type,
'buying_asset_code': None if buying_asset.is_native() else buying_asset.code,
'buying_asset_issuer': buying_asset.issuer,
}
endpoint = '/order_book'
params = self.__query_params(limit=limit, **asset_params)
return self.query(endpoint, params)
|
[
"def",
"order_book",
"(",
"self",
",",
"selling_asset_code",
",",
"buying_asset_code",
",",
"selling_asset_issuer",
"=",
"None",
",",
"buying_asset_issuer",
"=",
"None",
",",
"limit",
"=",
"10",
")",
":",
"selling_asset",
"=",
"Asset",
"(",
"selling_asset_code",
",",
"selling_asset_issuer",
")",
"buying_asset",
"=",
"Asset",
"(",
"buying_asset_code",
",",
"buying_asset_issuer",
")",
"asset_params",
"=",
"{",
"'selling_asset_type'",
":",
"selling_asset",
".",
"type",
",",
"'selling_asset_code'",
":",
"None",
"if",
"selling_asset",
".",
"is_native",
"(",
")",
"else",
"selling_asset",
".",
"code",
",",
"'selling_asset_issuer'",
":",
"selling_asset",
".",
"issuer",
",",
"'buying_asset_type'",
":",
"buying_asset",
".",
"type",
",",
"'buying_asset_code'",
":",
"None",
"if",
"buying_asset",
".",
"is_native",
"(",
")",
"else",
"buying_asset",
".",
"code",
",",
"'buying_asset_issuer'",
":",
"buying_asset",
".",
"issuer",
",",
"}",
"endpoint",
"=",
"'/order_book'",
"params",
"=",
"self",
".",
"__query_params",
"(",
"limit",
"=",
"limit",
",",
"*",
"*",
"asset_params",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
",",
"params",
")"
] |
Return, for each orderbook, a summary of the orderbook and the bids
and asks associated with that orderbook.
See the external docs below for information on the arguments required.
`GET /order_book
<https://www.stellar.org/developers/horizon/reference/endpoints/orderbook-details.html>`_
:param str selling_asset_code: Code of the Asset being sold.
:param str buying_asset_code: Type of the Asset being bought.
:param str selling_asset_issuer: Account ID of the issuer of the Asset being sold,
if it is a native asset, let it be `None`.
:param str buying_asset_issuer: Account ID of the issuer of the Asset being bought,
if it is a native asset, let it be `None`.
:param int limit: Limit the number of items returned.
:return: A list of orderbook summaries as a JSON object.
:rtype: dict
|
[
"Return",
"for",
"each",
"orderbook",
"a",
"summary",
"of",
"the",
"orderbook",
"and",
"the",
"bids",
"and",
"asks",
"associated",
"with",
"that",
"orderbook",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L472-L505
|
234,425
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.ledger
|
def ledger(self, ledger_id):
"""The ledger details endpoint provides information on a single ledger.
`GET /ledgers/{sequence}
<https://www.stellar.org/developers/horizon/reference/endpoints/ledgers-single.html>`_
:param int ledger_id: The id of the ledger to look up.
:return: The details of a single ledger.
:rtype: dict
"""
endpoint = '/ledgers/{ledger_id}'.format(ledger_id=ledger_id)
return self.query(endpoint)
|
python
|
def ledger(self, ledger_id):
"""The ledger details endpoint provides information on a single ledger.
`GET /ledgers/{sequence}
<https://www.stellar.org/developers/horizon/reference/endpoints/ledgers-single.html>`_
:param int ledger_id: The id of the ledger to look up.
:return: The details of a single ledger.
:rtype: dict
"""
endpoint = '/ledgers/{ledger_id}'.format(ledger_id=ledger_id)
return self.query(endpoint)
|
[
"def",
"ledger",
"(",
"self",
",",
"ledger_id",
")",
":",
"endpoint",
"=",
"'/ledgers/{ledger_id}'",
".",
"format",
"(",
"ledger_id",
"=",
"ledger_id",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
")"
] |
The ledger details endpoint provides information on a single ledger.
`GET /ledgers/{sequence}
<https://www.stellar.org/developers/horizon/reference/endpoints/ledgers-single.html>`_
:param int ledger_id: The id of the ledger to look up.
:return: The details of a single ledger.
:rtype: dict
|
[
"The",
"ledger",
"details",
"endpoint",
"provides",
"information",
"on",
"a",
"single",
"ledger",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L527-L539
|
234,426
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.ledger_effects
|
def ledger_effects(self, ledger_id, cursor=None, order='asc', limit=10):
"""This endpoint represents all effects that occurred in the given
ledger.
`GET /ledgers/{id}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-ledger.html>`_
:param int ledger_id: The id of the ledger to look up.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: The effects for a single ledger.
:rtype: dict
"""
endpoint = '/ledgers/{ledger_id}/effects'.format(ledger_id=ledger_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params)
|
python
|
def ledger_effects(self, ledger_id, cursor=None, order='asc', limit=10):
"""This endpoint represents all effects that occurred in the given
ledger.
`GET /ledgers/{id}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-ledger.html>`_
:param int ledger_id: The id of the ledger to look up.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: The effects for a single ledger.
:rtype: dict
"""
endpoint = '/ledgers/{ledger_id}/effects'.format(ledger_id=ledger_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params)
|
[
"def",
"ledger_effects",
"(",
"self",
",",
"ledger_id",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/ledgers/{ledger_id}/effects'",
".",
"format",
"(",
"ledger_id",
"=",
"ledger_id",
")",
"params",
"=",
"self",
".",
"__query_params",
"(",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
",",
"params",
")"
] |
This endpoint represents all effects that occurred in the given
ledger.
`GET /ledgers/{id}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-ledger.html>`_
:param int ledger_id: The id of the ledger to look up.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: The effects for a single ledger.
:rtype: dict
|
[
"This",
"endpoint",
"represents",
"all",
"effects",
"that",
"occurred",
"in",
"the",
"given",
"ledger",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L541-L558
|
234,427
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.ledger_transactions
|
def ledger_transactions(self, ledger_id, cursor=None, order='asc', include_failed=False, limit=10):
"""This endpoint represents all transactions in a given ledger.
`GET /ledgers/{id}/transactions{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-for-ledger.html>`_
:param int ledger_id: The id of the ledger to look up.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include failed transactions in results.
:return: The transactions contained in a single ledger.
:rtype: dict
"""
endpoint = '/ledgers/{ledger_id}/transactions'.format(
ledger_id=ledger_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed)
return self.query(endpoint, params)
|
python
|
def ledger_transactions(self, ledger_id, cursor=None, order='asc', include_failed=False, limit=10):
"""This endpoint represents all transactions in a given ledger.
`GET /ledgers/{id}/transactions{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-for-ledger.html>`_
:param int ledger_id: The id of the ledger to look up.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include failed transactions in results.
:return: The transactions contained in a single ledger.
:rtype: dict
"""
endpoint = '/ledgers/{ledger_id}/transactions'.format(
ledger_id=ledger_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed)
return self.query(endpoint, params)
|
[
"def",
"ledger_transactions",
"(",
"self",
",",
"ledger_id",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"include_failed",
"=",
"False",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/ledgers/{ledger_id}/transactions'",
".",
"format",
"(",
"ledger_id",
"=",
"ledger_id",
")",
"params",
"=",
"self",
".",
"__query_params",
"(",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
",",
"include_failed",
"=",
"include_failed",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
",",
"params",
")"
] |
This endpoint represents all transactions in a given ledger.
`GET /ledgers/{id}/transactions{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-for-ledger.html>`_
:param int ledger_id: The id of the ledger to look up.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include failed transactions in results.
:return: The transactions contained in a single ledger.
:rtype: dict
|
[
"This",
"endpoint",
"represents",
"all",
"transactions",
"in",
"a",
"given",
"ledger",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L600-L618
|
234,428
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.effects
|
def effects(self, cursor=None, order='asc', limit=10, sse=False):
"""This endpoint represents all effects.
`GET /effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-all.html>`_
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
:return: A list of all effects.
:rtype: dict
"""
endpoint = '/effects'
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params, sse)
|
python
|
def effects(self, cursor=None, order='asc', limit=10, sse=False):
"""This endpoint represents all effects.
`GET /effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-all.html>`_
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
:return: A list of all effects.
:rtype: dict
"""
endpoint = '/effects'
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params, sse)
|
[
"def",
"effects",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"sse",
"=",
"False",
")",
":",
"endpoint",
"=",
"'/effects'",
"params",
"=",
"self",
".",
"__query_params",
"(",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
",",
"params",
",",
"sse",
")"
] |
This endpoint represents all effects.
`GET /effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-all.html>`_
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool sse: Use server side events for streaming responses.
:return: A list of all effects.
:rtype: dict
|
[
"This",
"endpoint",
"represents",
"all",
"effects",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L620-L638
|
234,429
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.operations
|
def operations(self, cursor=None, order='asc', limit=10, include_failed=False, sse=False):
"""This endpoint represents all operations that are part of validated
transactions.
`GET /operations{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-all.html>`_
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include operations of failed transactions in results.
:param bool sse: Use server side events for streaming responses.
:return: A list of all operations.
:rtype: dict
"""
endpoint = '/operations'
params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed)
return self.query(endpoint, params, sse)
|
python
|
def operations(self, cursor=None, order='asc', limit=10, include_failed=False, sse=False):
"""This endpoint represents all operations that are part of validated
transactions.
`GET /operations{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-all.html>`_
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include operations of failed transactions in results.
:param bool sse: Use server side events for streaming responses.
:return: A list of all operations.
:rtype: dict
"""
endpoint = '/operations'
params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed)
return self.query(endpoint, params, sse)
|
[
"def",
"operations",
"(",
"self",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"include_failed",
"=",
"False",
",",
"sse",
"=",
"False",
")",
":",
"endpoint",
"=",
"'/operations'",
"params",
"=",
"self",
".",
"__query_params",
"(",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
",",
"include_failed",
"=",
"include_failed",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
",",
"params",
",",
"sse",
")"
] |
This endpoint represents all operations that are part of validated
transactions.
`GET /operations{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-all.html>`_
:param cursor: A paging token, specifying where to start returning records from.
When streaming this can be set to "now" to stream object created since your request time.
:type cursor: int, str
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param bool include_failed: Set to `True` to include operations of failed transactions in results.
:param bool sse: Use server side events for streaming responses.
:return: A list of all operations.
:rtype: dict
|
[
"This",
"endpoint",
"represents",
"all",
"operations",
"that",
"are",
"part",
"of",
"validated",
"transactions",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L640-L660
|
234,430
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.operation
|
def operation(self, op_id):
"""The operation details endpoint provides information on a single
operation.
`GET /operations/{id}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-single.html>`_
:param id op_id: The operation ID to get details on.
:return: Details on a single operation.
:rtype: dict
"""
endpoint = '/operations/{op_id}'.format(op_id=op_id)
return self.query(endpoint)
|
python
|
def operation(self, op_id):
"""The operation details endpoint provides information on a single
operation.
`GET /operations/{id}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-single.html>`_
:param id op_id: The operation ID to get details on.
:return: Details on a single operation.
:rtype: dict
"""
endpoint = '/operations/{op_id}'.format(op_id=op_id)
return self.query(endpoint)
|
[
"def",
"operation",
"(",
"self",
",",
"op_id",
")",
":",
"endpoint",
"=",
"'/operations/{op_id}'",
".",
"format",
"(",
"op_id",
"=",
"op_id",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
")"
] |
The operation details endpoint provides information on a single
operation.
`GET /operations/{id}
<https://www.stellar.org/developers/horizon/reference/endpoints/operations-single.html>`_
:param id op_id: The operation ID to get details on.
:return: Details on a single operation.
:rtype: dict
|
[
"The",
"operation",
"details",
"endpoint",
"provides",
"information",
"on",
"a",
"single",
"operation",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L662-L674
|
234,431
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.operation_effects
|
def operation_effects(self, op_id, cursor=None, order='asc', limit=10):
"""This endpoint represents all effects that occurred as a result of a
given operation.
`GET /operations/{id}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-operation.html>`_
:param int op_id: The operation ID to get effects on.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of effects on the given operation.
:rtype: dict
"""
endpoint = '/operations/{op_id}/effects'.format(op_id=op_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params)
|
python
|
def operation_effects(self, op_id, cursor=None, order='asc', limit=10):
"""This endpoint represents all effects that occurred as a result of a
given operation.
`GET /operations/{id}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-operation.html>`_
:param int op_id: The operation ID to get effects on.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of effects on the given operation.
:rtype: dict
"""
endpoint = '/operations/{op_id}/effects'.format(op_id=op_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params)
|
[
"def",
"operation_effects",
"(",
"self",
",",
"op_id",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/operations/{op_id}/effects'",
".",
"format",
"(",
"op_id",
"=",
"op_id",
")",
"params",
"=",
"self",
".",
"__query_params",
"(",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
",",
"params",
")"
] |
This endpoint represents all effects that occurred as a result of a
given operation.
`GET /operations/{id}/effects{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-operation.html>`_
:param int op_id: The operation ID to get effects on.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of effects on the given operation.
:rtype: dict
|
[
"This",
"endpoint",
"represents",
"all",
"effects",
"that",
"occurred",
"as",
"a",
"result",
"of",
"a",
"given",
"operation",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L676-L693
|
234,432
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.paths
|
def paths(self, destination_account, destination_amount, source_account, destination_asset_code,
destination_asset_issuer=None):
"""Load a list of assets available to the source account id and find
any payment paths from those source assets to the desired
destination asset.
See the below docs for more information on required and optional
parameters for further specifying your search.
`GET /paths
<https://www.stellar.org/developers/horizon/reference/endpoints/path-finding.html>`_
:param str destination_account: The destination account that any returned path should use.
:param str destination_amount: The amount, denominated in the destination asset,
that any returned path should be able to satisfy.
:param str source_account: The sender's account id. Any returned path must use a source that the sender can hold.
:param str destination_asset_code: The asset code for the destination.
:param destination_asset_issuer: The asset issuer for the destination, if it is a native asset, let it be `None`.
:type destination_asset_issuer: str, None
:return: A list of paths that can be used to complete a payment based
on a given query.
:rtype: dict
"""
destination_asset = Asset(destination_asset_code, destination_asset_issuer)
destination_asset_params = {
'destination_asset_type': destination_asset.type,
'destination_asset_code': None if destination_asset.is_native() else destination_asset.code,
'destination_asset_issuer': destination_asset.issuer
}
endpoint = '/paths'
params = self.__query_params(destination_account=destination_account,
source_account=source_account,
destination_amount=destination_amount,
**destination_asset_params
)
return self.query(endpoint, params)
|
python
|
def paths(self, destination_account, destination_amount, source_account, destination_asset_code,
destination_asset_issuer=None):
"""Load a list of assets available to the source account id and find
any payment paths from those source assets to the desired
destination asset.
See the below docs for more information on required and optional
parameters for further specifying your search.
`GET /paths
<https://www.stellar.org/developers/horizon/reference/endpoints/path-finding.html>`_
:param str destination_account: The destination account that any returned path should use.
:param str destination_amount: The amount, denominated in the destination asset,
that any returned path should be able to satisfy.
:param str source_account: The sender's account id. Any returned path must use a source that the sender can hold.
:param str destination_asset_code: The asset code for the destination.
:param destination_asset_issuer: The asset issuer for the destination, if it is a native asset, let it be `None`.
:type destination_asset_issuer: str, None
:return: A list of paths that can be used to complete a payment based
on a given query.
:rtype: dict
"""
destination_asset = Asset(destination_asset_code, destination_asset_issuer)
destination_asset_params = {
'destination_asset_type': destination_asset.type,
'destination_asset_code': None if destination_asset.is_native() else destination_asset.code,
'destination_asset_issuer': destination_asset.issuer
}
endpoint = '/paths'
params = self.__query_params(destination_account=destination_account,
source_account=source_account,
destination_amount=destination_amount,
**destination_asset_params
)
return self.query(endpoint, params)
|
[
"def",
"paths",
"(",
"self",
",",
"destination_account",
",",
"destination_amount",
",",
"source_account",
",",
"destination_asset_code",
",",
"destination_asset_issuer",
"=",
"None",
")",
":",
"destination_asset",
"=",
"Asset",
"(",
"destination_asset_code",
",",
"destination_asset_issuer",
")",
"destination_asset_params",
"=",
"{",
"'destination_asset_type'",
":",
"destination_asset",
".",
"type",
",",
"'destination_asset_code'",
":",
"None",
"if",
"destination_asset",
".",
"is_native",
"(",
")",
"else",
"destination_asset",
".",
"code",
",",
"'destination_asset_issuer'",
":",
"destination_asset",
".",
"issuer",
"}",
"endpoint",
"=",
"'/paths'",
"params",
"=",
"self",
".",
"__query_params",
"(",
"destination_account",
"=",
"destination_account",
",",
"source_account",
"=",
"source_account",
",",
"destination_amount",
"=",
"destination_amount",
",",
"*",
"*",
"destination_asset_params",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
",",
"params",
")"
] |
Load a list of assets available to the source account id and find
any payment paths from those source assets to the desired
destination asset.
See the below docs for more information on required and optional
parameters for further specifying your search.
`GET /paths
<https://www.stellar.org/developers/horizon/reference/endpoints/path-finding.html>`_
:param str destination_account: The destination account that any returned path should use.
:param str destination_amount: The amount, denominated in the destination asset,
that any returned path should be able to satisfy.
:param str source_account: The sender's account id. Any returned path must use a source that the sender can hold.
:param str destination_asset_code: The asset code for the destination.
:param destination_asset_issuer: The asset issuer for the destination, if it is a native asset, let it be `None`.
:type destination_asset_issuer: str, None
:return: A list of paths that can be used to complete a payment based
on a given query.
:rtype: dict
|
[
"Load",
"a",
"list",
"of",
"assets",
"available",
"to",
"the",
"source",
"account",
"id",
"and",
"find",
"any",
"payment",
"paths",
"from",
"those",
"source",
"assets",
"to",
"the",
"desired",
"destination",
"asset",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L716-L754
|
234,433
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.trades
|
def trades(self, base_asset_code=None, counter_asset_code=None, base_asset_issuer=None, counter_asset_issuer=None,
offer_id=None, cursor=None, order='asc', limit=10):
"""Load a list of trades, optionally filtered by an orderbook.
See the below docs for more information on required and optional
parameters for further specifying your search.
`GET /trades
<https://www.stellar.org/developers/horizon/reference/endpoints/trades.html>`_
:param str base_asset_code: Code of base asset.
:param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`.
:param str counter_asset_code: Code of counter asset.
:param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`.
:param int offer_id: Filter for by a specific offer id.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of trades filtered by a given query.
:rtype: dict
"""
base_asset = Asset(base_asset_code, base_asset_issuer)
counter_asset = Asset(counter_asset_code, counter_asset_issuer)
asset_params = {
'base_asset_type': base_asset.type,
'base_asset_code': None if base_asset.is_native() else base_asset.code,
'base_asset_issuer': base_asset.issuer,
'counter_asset_type': counter_asset.type,
'counter_asset_code': None if counter_asset.is_native() else counter_asset.code,
'counter_asset_issuer': counter_asset.issuer
}
endpoint = '/trades'
params = self.__query_params(offer_id=offer_id, cursor=cursor, order=order, limit=limit, **asset_params)
return self.query(endpoint, params)
|
python
|
def trades(self, base_asset_code=None, counter_asset_code=None, base_asset_issuer=None, counter_asset_issuer=None,
offer_id=None, cursor=None, order='asc', limit=10):
"""Load a list of trades, optionally filtered by an orderbook.
See the below docs for more information on required and optional
parameters for further specifying your search.
`GET /trades
<https://www.stellar.org/developers/horizon/reference/endpoints/trades.html>`_
:param str base_asset_code: Code of base asset.
:param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`.
:param str counter_asset_code: Code of counter asset.
:param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`.
:param int offer_id: Filter for by a specific offer id.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of trades filtered by a given query.
:rtype: dict
"""
base_asset = Asset(base_asset_code, base_asset_issuer)
counter_asset = Asset(counter_asset_code, counter_asset_issuer)
asset_params = {
'base_asset_type': base_asset.type,
'base_asset_code': None if base_asset.is_native() else base_asset.code,
'base_asset_issuer': base_asset.issuer,
'counter_asset_type': counter_asset.type,
'counter_asset_code': None if counter_asset.is_native() else counter_asset.code,
'counter_asset_issuer': counter_asset.issuer
}
endpoint = '/trades'
params = self.__query_params(offer_id=offer_id, cursor=cursor, order=order, limit=limit, **asset_params)
return self.query(endpoint, params)
|
[
"def",
"trades",
"(",
"self",
",",
"base_asset_code",
"=",
"None",
",",
"counter_asset_code",
"=",
"None",
",",
"base_asset_issuer",
"=",
"None",
",",
"counter_asset_issuer",
"=",
"None",
",",
"offer_id",
"=",
"None",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
")",
":",
"base_asset",
"=",
"Asset",
"(",
"base_asset_code",
",",
"base_asset_issuer",
")",
"counter_asset",
"=",
"Asset",
"(",
"counter_asset_code",
",",
"counter_asset_issuer",
")",
"asset_params",
"=",
"{",
"'base_asset_type'",
":",
"base_asset",
".",
"type",
",",
"'base_asset_code'",
":",
"None",
"if",
"base_asset",
".",
"is_native",
"(",
")",
"else",
"base_asset",
".",
"code",
",",
"'base_asset_issuer'",
":",
"base_asset",
".",
"issuer",
",",
"'counter_asset_type'",
":",
"counter_asset",
".",
"type",
",",
"'counter_asset_code'",
":",
"None",
"if",
"counter_asset",
".",
"is_native",
"(",
")",
"else",
"counter_asset",
".",
"code",
",",
"'counter_asset_issuer'",
":",
"counter_asset",
".",
"issuer",
"}",
"endpoint",
"=",
"'/trades'",
"params",
"=",
"self",
".",
"__query_params",
"(",
"offer_id",
"=",
"offer_id",
",",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
",",
"*",
"*",
"asset_params",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
",",
"params",
")"
] |
Load a list of trades, optionally filtered by an orderbook.
See the below docs for more information on required and optional
parameters for further specifying your search.
`GET /trades
<https://www.stellar.org/developers/horizon/reference/endpoints/trades.html>`_
:param str base_asset_code: Code of base asset.
:param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`.
:param str counter_asset_code: Code of counter asset.
:param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`.
:param int offer_id: Filter for by a specific offer id.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of trades filtered by a given query.
:rtype: dict
|
[
"Load",
"a",
"list",
"of",
"trades",
"optionally",
"filtered",
"by",
"an",
"orderbook",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L756-L790
|
234,434
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.trade_aggregations
|
def trade_aggregations(self, resolution, base_asset_code, counter_asset_code,
base_asset_issuer=None, counter_asset_issuer=None, start_time=None,
end_time=None, order='asc', limit=10, offset=0):
"""Load a list of aggregated historical trade data, optionally filtered
by an orderbook.
`GET /trade_aggregations
<https://www.stellar.org/developers/horizon/reference/endpoints/trade_aggregations.html>`_
:param int start_time: Lower time boundary represented as millis since epoch.
:param int end_time: Upper time boundary represented as millis since epoch.
:param int resolution: Segment duration as millis since epoch. Supported values
are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000),
1 day (86400000) and 1 week (604800000).
:param str base_asset_code: Code of base asset.
:param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`.
:param str counter_asset_code: Code of counter asset.
:param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param int offset: segments can be offset using this parameter.
Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour.
Value must be in whole hours, less than the provided resolution, and less than 24 hours.
:return: A list of collected trade aggregations.
:rtype: dict
"""
allowed_resolutions = (60000, 300000, 900000, 3600000, 86400000, 604800000)
if resolution not in allowed_resolutions:
raise NotValidParamError("resolution is invalid")
if offset > resolution or offset >= 24 * 3600000 or offset % 3600000 != 0:
raise NotValidParamError("offset is invalid")
base_asset = Asset(base_asset_code, base_asset_issuer)
counter_asset = Asset(counter_asset_code, counter_asset_issuer)
asset_params = {
'base_asset_type': base_asset.type,
'base_asset_code': None if base_asset.is_native() else base_asset.code,
'base_asset_issuer': base_asset.issuer,
'counter_asset_type': counter_asset.type,
'counter_asset_code': None if counter_asset.is_native() else counter_asset.code,
'counter_asset_issuer': counter_asset.issuer
}
endpoint = '/trade_aggregations'
params = self.__query_params(start_time=start_time, end_time=end_time, resolution=resolution, order=order,
limit=limit, offset=offset, **asset_params)
return self.query(endpoint, params)
|
python
|
def trade_aggregations(self, resolution, base_asset_code, counter_asset_code,
base_asset_issuer=None, counter_asset_issuer=None, start_time=None,
end_time=None, order='asc', limit=10, offset=0):
"""Load a list of aggregated historical trade data, optionally filtered
by an orderbook.
`GET /trade_aggregations
<https://www.stellar.org/developers/horizon/reference/endpoints/trade_aggregations.html>`_
:param int start_time: Lower time boundary represented as millis since epoch.
:param int end_time: Upper time boundary represented as millis since epoch.
:param int resolution: Segment duration as millis since epoch. Supported values
are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000),
1 day (86400000) and 1 week (604800000).
:param str base_asset_code: Code of base asset.
:param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`.
:param str counter_asset_code: Code of counter asset.
:param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param int offset: segments can be offset using this parameter.
Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour.
Value must be in whole hours, less than the provided resolution, and less than 24 hours.
:return: A list of collected trade aggregations.
:rtype: dict
"""
allowed_resolutions = (60000, 300000, 900000, 3600000, 86400000, 604800000)
if resolution not in allowed_resolutions:
raise NotValidParamError("resolution is invalid")
if offset > resolution or offset >= 24 * 3600000 or offset % 3600000 != 0:
raise NotValidParamError("offset is invalid")
base_asset = Asset(base_asset_code, base_asset_issuer)
counter_asset = Asset(counter_asset_code, counter_asset_issuer)
asset_params = {
'base_asset_type': base_asset.type,
'base_asset_code': None if base_asset.is_native() else base_asset.code,
'base_asset_issuer': base_asset.issuer,
'counter_asset_type': counter_asset.type,
'counter_asset_code': None if counter_asset.is_native() else counter_asset.code,
'counter_asset_issuer': counter_asset.issuer
}
endpoint = '/trade_aggregations'
params = self.__query_params(start_time=start_time, end_time=end_time, resolution=resolution, order=order,
limit=limit, offset=offset, **asset_params)
return self.query(endpoint, params)
|
[
"def",
"trade_aggregations",
"(",
"self",
",",
"resolution",
",",
"base_asset_code",
",",
"counter_asset_code",
",",
"base_asset_issuer",
"=",
"None",
",",
"counter_asset_issuer",
"=",
"None",
",",
"start_time",
"=",
"None",
",",
"end_time",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
",",
"offset",
"=",
"0",
")",
":",
"allowed_resolutions",
"=",
"(",
"60000",
",",
"300000",
",",
"900000",
",",
"3600000",
",",
"86400000",
",",
"604800000",
")",
"if",
"resolution",
"not",
"in",
"allowed_resolutions",
":",
"raise",
"NotValidParamError",
"(",
"\"resolution is invalid\"",
")",
"if",
"offset",
">",
"resolution",
"or",
"offset",
">=",
"24",
"*",
"3600000",
"or",
"offset",
"%",
"3600000",
"!=",
"0",
":",
"raise",
"NotValidParamError",
"(",
"\"offset is invalid\"",
")",
"base_asset",
"=",
"Asset",
"(",
"base_asset_code",
",",
"base_asset_issuer",
")",
"counter_asset",
"=",
"Asset",
"(",
"counter_asset_code",
",",
"counter_asset_issuer",
")",
"asset_params",
"=",
"{",
"'base_asset_type'",
":",
"base_asset",
".",
"type",
",",
"'base_asset_code'",
":",
"None",
"if",
"base_asset",
".",
"is_native",
"(",
")",
"else",
"base_asset",
".",
"code",
",",
"'base_asset_issuer'",
":",
"base_asset",
".",
"issuer",
",",
"'counter_asset_type'",
":",
"counter_asset",
".",
"type",
",",
"'counter_asset_code'",
":",
"None",
"if",
"counter_asset",
".",
"is_native",
"(",
")",
"else",
"counter_asset",
".",
"code",
",",
"'counter_asset_issuer'",
":",
"counter_asset",
".",
"issuer",
"}",
"endpoint",
"=",
"'/trade_aggregations'",
"params",
"=",
"self",
".",
"__query_params",
"(",
"start_time",
"=",
"start_time",
",",
"end_time",
"=",
"end_time",
",",
"resolution",
"=",
"resolution",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
",",
"offset",
"=",
"offset",
",",
"*",
"*",
"asset_params",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
",",
"params",
")"
] |
Load a list of aggregated historical trade data, optionally filtered
by an orderbook.
`GET /trade_aggregations
<https://www.stellar.org/developers/horizon/reference/endpoints/trade_aggregations.html>`_
:param int start_time: Lower time boundary represented as millis since epoch.
:param int end_time: Upper time boundary represented as millis since epoch.
:param int resolution: Segment duration as millis since epoch. Supported values
are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000),
1 day (86400000) and 1 week (604800000).
:param str base_asset_code: Code of base asset.
:param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`.
:param str counter_asset_code: Code of counter asset.
:param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:param int offset: segments can be offset using this parameter.
Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour.
Value must be in whole hours, less than the provided resolution, and less than 24 hours.
:return: A list of collected trade aggregations.
:rtype: dict
|
[
"Load",
"a",
"list",
"of",
"aggregated",
"historical",
"trade",
"data",
"optionally",
"filtered",
"by",
"an",
"orderbook",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L792-L839
|
234,435
|
StellarCN/py-stellar-base
|
stellar_base/horizon.py
|
Horizon.offer_trades
|
def offer_trades(self, offer_id, cursor=None, order='asc', limit=10):
"""This endpoint represents all trades for a given offer.
`GET /offers/{offer_id}/trades{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/trades-for-offer.html>`_
:param int offer_id: The offer ID to get trades on.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of effects on the given operation.
:rtype: dict
"""
endpoint = '/offers/{offer_id}/trades'.format(offer_id=offer_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params)
|
python
|
def offer_trades(self, offer_id, cursor=None, order='asc', limit=10):
"""This endpoint represents all trades for a given offer.
`GET /offers/{offer_id}/trades{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/trades-for-offer.html>`_
:param int offer_id: The offer ID to get trades on.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of effects on the given operation.
:rtype: dict
"""
endpoint = '/offers/{offer_id}/trades'.format(offer_id=offer_id)
params = self.__query_params(cursor=cursor, order=order, limit=limit)
return self.query(endpoint, params)
|
[
"def",
"offer_trades",
"(",
"self",
",",
"offer_id",
",",
"cursor",
"=",
"None",
",",
"order",
"=",
"'asc'",
",",
"limit",
"=",
"10",
")",
":",
"endpoint",
"=",
"'/offers/{offer_id}/trades'",
".",
"format",
"(",
"offer_id",
"=",
"offer_id",
")",
"params",
"=",
"self",
".",
"__query_params",
"(",
"cursor",
"=",
"cursor",
",",
"order",
"=",
"order",
",",
"limit",
"=",
"limit",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
",",
"params",
")"
] |
This endpoint represents all trades for a given offer.
`GET /offers/{offer_id}/trades{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/trades-for-offer.html>`_
:param int offer_id: The offer ID to get trades on.
:param int cursor: A paging token, specifying where to start returning records from.
:param str order: The order in which to return rows, "asc" or "desc".
:param int limit: Maximum number of records to return.
:return: A list of effects on the given operation.
:rtype: dict
|
[
"This",
"endpoint",
"represents",
"all",
"trades",
"for",
"a",
"given",
"offer",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L841-L857
|
234,436
|
StellarCN/py-stellar-base
|
stellar_base/transaction_envelope.py
|
TransactionEnvelope.sign
|
def sign(self, keypair):
"""Sign this transaction envelope with a given keypair.
Note that the signature must not already be in this instance's list of
signatures.
:param keypair: The keypair to use for signing this transaction
envelope.
:type keypair: :class:`Keypair <stellar_base.keypair.Keypair>`
:raises: :exc:`SignatureExistError
<stellar_base.utils.SignatureExistError>`
"""
assert isinstance(keypair, Keypair)
tx_hash = self.hash_meta()
sig = keypair.sign_decorated(tx_hash)
sig_dict = [signature.__dict__ for signature in self.signatures]
if sig.__dict__ in sig_dict:
raise SignatureExistError('The keypair has already signed')
else:
self.signatures.append(sig)
|
python
|
def sign(self, keypair):
"""Sign this transaction envelope with a given keypair.
Note that the signature must not already be in this instance's list of
signatures.
:param keypair: The keypair to use for signing this transaction
envelope.
:type keypair: :class:`Keypair <stellar_base.keypair.Keypair>`
:raises: :exc:`SignatureExistError
<stellar_base.utils.SignatureExistError>`
"""
assert isinstance(keypair, Keypair)
tx_hash = self.hash_meta()
sig = keypair.sign_decorated(tx_hash)
sig_dict = [signature.__dict__ for signature in self.signatures]
if sig.__dict__ in sig_dict:
raise SignatureExistError('The keypair has already signed')
else:
self.signatures.append(sig)
|
[
"def",
"sign",
"(",
"self",
",",
"keypair",
")",
":",
"assert",
"isinstance",
"(",
"keypair",
",",
"Keypair",
")",
"tx_hash",
"=",
"self",
".",
"hash_meta",
"(",
")",
"sig",
"=",
"keypair",
".",
"sign_decorated",
"(",
"tx_hash",
")",
"sig_dict",
"=",
"[",
"signature",
".",
"__dict__",
"for",
"signature",
"in",
"self",
".",
"signatures",
"]",
"if",
"sig",
".",
"__dict__",
"in",
"sig_dict",
":",
"raise",
"SignatureExistError",
"(",
"'The keypair has already signed'",
")",
"else",
":",
"self",
".",
"signatures",
".",
"append",
"(",
"sig",
")"
] |
Sign this transaction envelope with a given keypair.
Note that the signature must not already be in this instance's list of
signatures.
:param keypair: The keypair to use for signing this transaction
envelope.
:type keypair: :class:`Keypair <stellar_base.keypair.Keypair>`
:raises: :exc:`SignatureExistError
<stellar_base.utils.SignatureExistError>`
|
[
"Sign",
"this",
"transaction",
"envelope",
"with",
"a",
"given",
"keypair",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/transaction_envelope.py#L43-L63
|
234,437
|
StellarCN/py-stellar-base
|
stellar_base/transaction_envelope.py
|
TransactionEnvelope.signature_base
|
def signature_base(self):
"""Get the signature base of this transaction envelope.
Return the "signature base" of this transaction, which is the value
that, when hashed, should be signed to create a signature that
validators on the Stellar Network will accept.
It is composed of a 4 prefix bytes followed by the xdr-encoded form of
this transaction.
:return: The signature base of this transaction envelope.
"""
network_id = self.network_id
tx_type = Xdr.StellarXDRPacker()
tx_type.pack_EnvelopeType(Xdr.const.ENVELOPE_TYPE_TX)
tx_type = tx_type.get_buffer()
tx = Xdr.StellarXDRPacker()
tx.pack_Transaction(self.tx.to_xdr_object())
tx = tx.get_buffer()
return network_id + tx_type + tx
|
python
|
def signature_base(self):
"""Get the signature base of this transaction envelope.
Return the "signature base" of this transaction, which is the value
that, when hashed, should be signed to create a signature that
validators on the Stellar Network will accept.
It is composed of a 4 prefix bytes followed by the xdr-encoded form of
this transaction.
:return: The signature base of this transaction envelope.
"""
network_id = self.network_id
tx_type = Xdr.StellarXDRPacker()
tx_type.pack_EnvelopeType(Xdr.const.ENVELOPE_TYPE_TX)
tx_type = tx_type.get_buffer()
tx = Xdr.StellarXDRPacker()
tx.pack_Transaction(self.tx.to_xdr_object())
tx = tx.get_buffer()
return network_id + tx_type + tx
|
[
"def",
"signature_base",
"(",
"self",
")",
":",
"network_id",
"=",
"self",
".",
"network_id",
"tx_type",
"=",
"Xdr",
".",
"StellarXDRPacker",
"(",
")",
"tx_type",
".",
"pack_EnvelopeType",
"(",
"Xdr",
".",
"const",
".",
"ENVELOPE_TYPE_TX",
")",
"tx_type",
"=",
"tx_type",
".",
"get_buffer",
"(",
")",
"tx",
"=",
"Xdr",
".",
"StellarXDRPacker",
"(",
")",
"tx",
".",
"pack_Transaction",
"(",
"self",
".",
"tx",
".",
"to_xdr_object",
"(",
")",
")",
"tx",
"=",
"tx",
".",
"get_buffer",
"(",
")",
"return",
"network_id",
"+",
"tx_type",
"+",
"tx"
] |
Get the signature base of this transaction envelope.
Return the "signature base" of this transaction, which is the value
that, when hashed, should be signed to create a signature that
validators on the Stellar Network will accept.
It is composed of a 4 prefix bytes followed by the xdr-encoded form of
this transaction.
:return: The signature base of this transaction envelope.
|
[
"Get",
"the",
"signature",
"base",
"of",
"this",
"transaction",
"envelope",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/transaction_envelope.py#L99-L120
|
234,438
|
StellarCN/py-stellar-base
|
stellar_base/federation.py
|
get_federation_service
|
def get_federation_service(domain, allow_http=False):
"""Retrieve the FEDERATION_SERVER config from a domain's stellar.toml.
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return str: The FEDERATION_SERVER url.
"""
st = get_stellar_toml(domain, allow_http)
if not st:
return None
return st.get('FEDERATION_SERVER')
|
python
|
def get_federation_service(domain, allow_http=False):
"""Retrieve the FEDERATION_SERVER config from a domain's stellar.toml.
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return str: The FEDERATION_SERVER url.
"""
st = get_stellar_toml(domain, allow_http)
if not st:
return None
return st.get('FEDERATION_SERVER')
|
[
"def",
"get_federation_service",
"(",
"domain",
",",
"allow_http",
"=",
"False",
")",
":",
"st",
"=",
"get_stellar_toml",
"(",
"domain",
",",
"allow_http",
")",
"if",
"not",
"st",
":",
"return",
"None",
"return",
"st",
".",
"get",
"(",
"'FEDERATION_SERVER'",
")"
] |
Retrieve the FEDERATION_SERVER config from a domain's stellar.toml.
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return str: The FEDERATION_SERVER url.
|
[
"Retrieve",
"the",
"FEDERATION_SERVER",
"config",
"from",
"a",
"domain",
"s",
"stellar",
".",
"toml",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/federation.py#L76-L88
|
234,439
|
StellarCN/py-stellar-base
|
stellar_base/federation.py
|
get_auth_server
|
def get_auth_server(domain, allow_http=False):
"""Retrieve the AUTH_SERVER config from a domain's stellar.toml.
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return str: The AUTH_SERVER url.
"""
st = get_stellar_toml(domain, allow_http)
if not st:
return None
return st.get('AUTH_SERVER')
|
python
|
def get_auth_server(domain, allow_http=False):
"""Retrieve the AUTH_SERVER config from a domain's stellar.toml.
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return str: The AUTH_SERVER url.
"""
st = get_stellar_toml(domain, allow_http)
if not st:
return None
return st.get('AUTH_SERVER')
|
[
"def",
"get_auth_server",
"(",
"domain",
",",
"allow_http",
"=",
"False",
")",
":",
"st",
"=",
"get_stellar_toml",
"(",
"domain",
",",
"allow_http",
")",
"if",
"not",
"st",
":",
"return",
"None",
"return",
"st",
".",
"get",
"(",
"'AUTH_SERVER'",
")"
] |
Retrieve the AUTH_SERVER config from a domain's stellar.toml.
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return str: The AUTH_SERVER url.
|
[
"Retrieve",
"the",
"AUTH_SERVER",
"config",
"from",
"a",
"domain",
"s",
"stellar",
".",
"toml",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/federation.py#L91-L103
|
234,440
|
StellarCN/py-stellar-base
|
stellar_base/federation.py
|
get_stellar_toml
|
def get_stellar_toml(domain, allow_http=False):
"""Retrieve the stellar.toml file from a given domain.
Retrieve the stellar.toml file for information about interacting with
Stellar's federation protocol for a given Stellar Anchor (specified by a
domain).
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return: The stellar.toml file as a an object via :func:`toml.loads`.
"""
toml_link = '/.well-known/stellar.toml'
if allow_http:
protocol = 'http://'
else:
protocol = 'https://'
url_list = ['', 'www.', 'stellar.']
url_list = [protocol + url + domain + toml_link for url in url_list]
for url in url_list:
r = requests.get(url)
if r.status_code == 200:
return toml.loads(r.text)
return None
|
python
|
def get_stellar_toml(domain, allow_http=False):
"""Retrieve the stellar.toml file from a given domain.
Retrieve the stellar.toml file for information about interacting with
Stellar's federation protocol for a given Stellar Anchor (specified by a
domain).
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return: The stellar.toml file as a an object via :func:`toml.loads`.
"""
toml_link = '/.well-known/stellar.toml'
if allow_http:
protocol = 'http://'
else:
protocol = 'https://'
url_list = ['', 'www.', 'stellar.']
url_list = [protocol + url + domain + toml_link for url in url_list]
for url in url_list:
r = requests.get(url)
if r.status_code == 200:
return toml.loads(r.text)
return None
|
[
"def",
"get_stellar_toml",
"(",
"domain",
",",
"allow_http",
"=",
"False",
")",
":",
"toml_link",
"=",
"'/.well-known/stellar.toml'",
"if",
"allow_http",
":",
"protocol",
"=",
"'http://'",
"else",
":",
"protocol",
"=",
"'https://'",
"url_list",
"=",
"[",
"''",
",",
"'www.'",
",",
"'stellar.'",
"]",
"url_list",
"=",
"[",
"protocol",
"+",
"url",
"+",
"domain",
"+",
"toml_link",
"for",
"url",
"in",
"url_list",
"]",
"for",
"url",
"in",
"url_list",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"return",
"toml",
".",
"loads",
"(",
"r",
".",
"text",
")",
"return",
"None"
] |
Retrieve the stellar.toml file from a given domain.
Retrieve the stellar.toml file for information about interacting with
Stellar's federation protocol for a given Stellar Anchor (specified by a
domain).
:param str domain: The domain the .toml file is hosted at.
:param bool allow_http: Specifies whether the request should go over plain
HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS.
:return: The stellar.toml file as a an object via :func:`toml.loads`.
|
[
"Retrieve",
"the",
"stellar",
".",
"toml",
"file",
"from",
"a",
"given",
"domain",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/federation.py#L106-L132
|
234,441
|
StellarCN/py-stellar-base
|
stellar_base/keypair.py
|
Keypair.account_xdr_object
|
def account_xdr_object(self):
"""Create PublicKey XDR object via public key bytes.
:return: Serialized XDR of PublicKey type.
"""
return Xdr.types.PublicKey(Xdr.const.KEY_TYPE_ED25519,
self.verifying_key.to_bytes())
|
python
|
def account_xdr_object(self):
"""Create PublicKey XDR object via public key bytes.
:return: Serialized XDR of PublicKey type.
"""
return Xdr.types.PublicKey(Xdr.const.KEY_TYPE_ED25519,
self.verifying_key.to_bytes())
|
[
"def",
"account_xdr_object",
"(",
"self",
")",
":",
"return",
"Xdr",
".",
"types",
".",
"PublicKey",
"(",
"Xdr",
".",
"const",
".",
"KEY_TYPE_ED25519",
",",
"self",
".",
"verifying_key",
".",
"to_bytes",
"(",
")",
")"
] |
Create PublicKey XDR object via public key bytes.
:return: Serialized XDR of PublicKey type.
|
[
"Create",
"PublicKey",
"XDR",
"object",
"via",
"public",
"key",
"bytes",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/keypair.py#L154-L160
|
234,442
|
StellarCN/py-stellar-base
|
stellar_base/keypair.py
|
Keypair.xdr
|
def xdr(self):
"""Generate base64 encoded XDR PublicKey object.
Return a base64 encoded PublicKey XDR object, for sending over the wire
when interacting with stellar.
:return: The base64 encoded PublicKey XDR structure.
"""
kp = Xdr.StellarXDRPacker()
kp.pack_PublicKey(self.account_xdr_object())
return base64.b64encode(kp.get_buffer())
|
python
|
def xdr(self):
"""Generate base64 encoded XDR PublicKey object.
Return a base64 encoded PublicKey XDR object, for sending over the wire
when interacting with stellar.
:return: The base64 encoded PublicKey XDR structure.
"""
kp = Xdr.StellarXDRPacker()
kp.pack_PublicKey(self.account_xdr_object())
return base64.b64encode(kp.get_buffer())
|
[
"def",
"xdr",
"(",
"self",
")",
":",
"kp",
"=",
"Xdr",
".",
"StellarXDRPacker",
"(",
")",
"kp",
".",
"pack_PublicKey",
"(",
"self",
".",
"account_xdr_object",
"(",
")",
")",
"return",
"base64",
".",
"b64encode",
"(",
"kp",
".",
"get_buffer",
"(",
")",
")"
] |
Generate base64 encoded XDR PublicKey object.
Return a base64 encoded PublicKey XDR object, for sending over the wire
when interacting with stellar.
:return: The base64 encoded PublicKey XDR structure.
|
[
"Generate",
"base64",
"encoded",
"XDR",
"PublicKey",
"object",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/keypair.py#L162-L172
|
234,443
|
StellarCN/py-stellar-base
|
stellar_base/keypair.py
|
Keypair.verify
|
def verify(self, data, signature):
"""Verify the signature of a sequence of bytes.
Verify the signature of a sequence of bytes using the verifying
(public) key and the data that was originally signed, otherwise throws
an exception.
:param bytes data: A sequence of bytes that were previously signed by
the private key associated with this verifying key.
:param bytes signature: A sequence of bytes that comprised the
signature for the corresponding data.
"""
try:
return self.verifying_key.verify(signature, data)
except ed25519.BadSignatureError:
raise BadSignatureError("Signature verification failed.")
|
python
|
def verify(self, data, signature):
"""Verify the signature of a sequence of bytes.
Verify the signature of a sequence of bytes using the verifying
(public) key and the data that was originally signed, otherwise throws
an exception.
:param bytes data: A sequence of bytes that were previously signed by
the private key associated with this verifying key.
:param bytes signature: A sequence of bytes that comprised the
signature for the corresponding data.
"""
try:
return self.verifying_key.verify(signature, data)
except ed25519.BadSignatureError:
raise BadSignatureError("Signature verification failed.")
|
[
"def",
"verify",
"(",
"self",
",",
"data",
",",
"signature",
")",
":",
"try",
":",
"return",
"self",
".",
"verifying_key",
".",
"verify",
"(",
"signature",
",",
"data",
")",
"except",
"ed25519",
".",
"BadSignatureError",
":",
"raise",
"BadSignatureError",
"(",
"\"Signature verification failed.\"",
")"
] |
Verify the signature of a sequence of bytes.
Verify the signature of a sequence of bytes using the verifying
(public) key and the data that was originally signed, otherwise throws
an exception.
:param bytes data: A sequence of bytes that were previously signed by
the private key associated with this verifying key.
:param bytes signature: A sequence of bytes that comprised the
signature for the corresponding data.
|
[
"Verify",
"the",
"signature",
"of",
"a",
"sequence",
"of",
"bytes",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/keypair.py#L228-L243
|
234,444
|
StellarCN/py-stellar-base
|
stellar_base/keypair.py
|
Keypair.sign_decorated
|
def sign_decorated(self, data):
"""Sign a bytes-like object and return the decorated signature.
Sign a bytes-like object by signing the data using the signing
(private) key, and return a decorated signature, which includes the
last four bytes of the public key as a signature hint to go along with
the signature as an XDR DecoratedSignature object.
:param bytes data: A sequence of bytes to sign, typically a
transaction.
"""
signature = self.sign(data)
hint = self.signature_hint()
return Xdr.types.DecoratedSignature(hint, signature)
|
python
|
def sign_decorated(self, data):
"""Sign a bytes-like object and return the decorated signature.
Sign a bytes-like object by signing the data using the signing
(private) key, and return a decorated signature, which includes the
last four bytes of the public key as a signature hint to go along with
the signature as an XDR DecoratedSignature object.
:param bytes data: A sequence of bytes to sign, typically a
transaction.
"""
signature = self.sign(data)
hint = self.signature_hint()
return Xdr.types.DecoratedSignature(hint, signature)
|
[
"def",
"sign_decorated",
"(",
"self",
",",
"data",
")",
":",
"signature",
"=",
"self",
".",
"sign",
"(",
"data",
")",
"hint",
"=",
"self",
".",
"signature_hint",
"(",
")",
"return",
"Xdr",
".",
"types",
".",
"DecoratedSignature",
"(",
"hint",
",",
"signature",
")"
] |
Sign a bytes-like object and return the decorated signature.
Sign a bytes-like object by signing the data using the signing
(private) key, and return a decorated signature, which includes the
last four bytes of the public key as a signature hint to go along with
the signature as an XDR DecoratedSignature object.
:param bytes data: A sequence of bytes to sign, typically a
transaction.
|
[
"Sign",
"a",
"bytes",
"-",
"like",
"object",
"and",
"return",
"the",
"decorated",
"signature",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/keypair.py#L245-L259
|
234,445
|
StellarCN/py-stellar-base
|
stellar_base/utils.py
|
bytes_from_decode_data
|
def bytes_from_decode_data(s):
"""copy from base64._bytes_from_decode_data
"""
if isinstance(s, (str, unicode)):
try:
return s.encode('ascii')
except UnicodeEncodeError:
raise NotValidParamError(
'String argument should contain only ASCII characters')
if isinstance(s, bytes_types):
return s
try:
return memoryview(s).tobytes()
except TypeError:
raise suppress_context(
TypeError(
'Argument should be a bytes-like object or ASCII string, not '
'{!r}'.format(s.__class__.__name__)))
|
python
|
def bytes_from_decode_data(s):
"""copy from base64._bytes_from_decode_data
"""
if isinstance(s, (str, unicode)):
try:
return s.encode('ascii')
except UnicodeEncodeError:
raise NotValidParamError(
'String argument should contain only ASCII characters')
if isinstance(s, bytes_types):
return s
try:
return memoryview(s).tobytes()
except TypeError:
raise suppress_context(
TypeError(
'Argument should be a bytes-like object or ASCII string, not '
'{!r}'.format(s.__class__.__name__)))
|
[
"def",
"bytes_from_decode_data",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"try",
":",
"return",
"s",
".",
"encode",
"(",
"'ascii'",
")",
"except",
"UnicodeEncodeError",
":",
"raise",
"NotValidParamError",
"(",
"'String argument should contain only ASCII characters'",
")",
"if",
"isinstance",
"(",
"s",
",",
"bytes_types",
")",
":",
"return",
"s",
"try",
":",
"return",
"memoryview",
"(",
"s",
")",
".",
"tobytes",
"(",
")",
"except",
"TypeError",
":",
"raise",
"suppress_context",
"(",
"TypeError",
"(",
"'Argument should be a bytes-like object or ASCII string, not '",
"'{!r}'",
".",
"format",
"(",
"s",
".",
"__class__",
".",
"__name__",
")",
")",
")"
] |
copy from base64._bytes_from_decode_data
|
[
"copy",
"from",
"base64",
".",
"_bytes_from_decode_data"
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/utils.py#L75-L92
|
234,446
|
StellarCN/py-stellar-base
|
stellar_base/operation.py
|
Operation.to_xdr_amount
|
def to_xdr_amount(value):
"""Converts an amount to the appropriate value to send over the network
as a part of an XDR object.
Each asset amount is encoded as a signed 64-bit integer in the XDR
structures. An asset amount unit (that which is seen by end users) is
scaled down by a factor of ten million (10,000,000) to arrive at the
native 64-bit integer representation. For example, the integer amount
value 25,123,456 equals 2.5123456 units of the asset. This scaling
allows for seven decimal places of precision in human-friendly amount
units.
This static method correctly multiplies the value by the scaling factor
in order to come to the integer value used in XDR structures.
See `Stellar's documentation on Asset Precision
<https://www.stellar.org/developers/guides/concepts/assets.html#amount-precision-and-representation>`_
for more information.
:param str value: The amount to convert to an integer for XDR
serialization.
"""
if not isinstance(value, str):
raise NotValidParamError("Value of type '{}' must be of type String, but got {}".format(value, type(value)))
# throw exception if value * ONE has decimal places (it can't be
# represented as int64)
try:
amount = int((Decimal(value) * ONE).to_integral_exact(context=Context(traps=[Inexact])))
except decimal.Inexact:
raise NotValidParamError("Value of '{}' must have at most 7 digits after the decimal.".format(value))
except decimal.InvalidOperation:
raise NotValidParamError("Value of '{}' must represent a positive number.".format(value))
return amount
|
python
|
def to_xdr_amount(value):
"""Converts an amount to the appropriate value to send over the network
as a part of an XDR object.
Each asset amount is encoded as a signed 64-bit integer in the XDR
structures. An asset amount unit (that which is seen by end users) is
scaled down by a factor of ten million (10,000,000) to arrive at the
native 64-bit integer representation. For example, the integer amount
value 25,123,456 equals 2.5123456 units of the asset. This scaling
allows for seven decimal places of precision in human-friendly amount
units.
This static method correctly multiplies the value by the scaling factor
in order to come to the integer value used in XDR structures.
See `Stellar's documentation on Asset Precision
<https://www.stellar.org/developers/guides/concepts/assets.html#amount-precision-and-representation>`_
for more information.
:param str value: The amount to convert to an integer for XDR
serialization.
"""
if not isinstance(value, str):
raise NotValidParamError("Value of type '{}' must be of type String, but got {}".format(value, type(value)))
# throw exception if value * ONE has decimal places (it can't be
# represented as int64)
try:
amount = int((Decimal(value) * ONE).to_integral_exact(context=Context(traps=[Inexact])))
except decimal.Inexact:
raise NotValidParamError("Value of '{}' must have at most 7 digits after the decimal.".format(value))
except decimal.InvalidOperation:
raise NotValidParamError("Value of '{}' must represent a positive number.".format(value))
return amount
|
[
"def",
"to_xdr_amount",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"NotValidParamError",
"(",
"\"Value of type '{}' must be of type String, but got {}\"",
".",
"format",
"(",
"value",
",",
"type",
"(",
"value",
")",
")",
")",
"# throw exception if value * ONE has decimal places (it can't be",
"# represented as int64)",
"try",
":",
"amount",
"=",
"int",
"(",
"(",
"Decimal",
"(",
"value",
")",
"*",
"ONE",
")",
".",
"to_integral_exact",
"(",
"context",
"=",
"Context",
"(",
"traps",
"=",
"[",
"Inexact",
"]",
")",
")",
")",
"except",
"decimal",
".",
"Inexact",
":",
"raise",
"NotValidParamError",
"(",
"\"Value of '{}' must have at most 7 digits after the decimal.\"",
".",
"format",
"(",
"value",
")",
")",
"except",
"decimal",
".",
"InvalidOperation",
":",
"raise",
"NotValidParamError",
"(",
"\"Value of '{}' must represent a positive number.\"",
".",
"format",
"(",
"value",
")",
")",
"return",
"amount"
] |
Converts an amount to the appropriate value to send over the network
as a part of an XDR object.
Each asset amount is encoded as a signed 64-bit integer in the XDR
structures. An asset amount unit (that which is seen by end users) is
scaled down by a factor of ten million (10,000,000) to arrive at the
native 64-bit integer representation. For example, the integer amount
value 25,123,456 equals 2.5123456 units of the asset. This scaling
allows for seven decimal places of precision in human-friendly amount
units.
This static method correctly multiplies the value by the scaling factor
in order to come to the integer value used in XDR structures.
See `Stellar's documentation on Asset Precision
<https://www.stellar.org/developers/guides/concepts/assets.html#amount-precision-and-representation>`_
for more information.
:param str value: The amount to convert to an integer for XDR
serialization.
|
[
"Converts",
"an",
"amount",
"to",
"the",
"appropriate",
"value",
"to",
"send",
"over",
"the",
"network",
"as",
"a",
"part",
"of",
"an",
"XDR",
"object",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/operation.py#L71-L105
|
234,447
|
StellarCN/py-stellar-base
|
stellar_base/memo.py
|
TextMemo.to_xdr_object
|
def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_TEXT."""
return Xdr.types.Memo(type=Xdr.const.MEMO_TEXT, text=self.text)
|
python
|
def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_TEXT."""
return Xdr.types.Memo(type=Xdr.const.MEMO_TEXT, text=self.text)
|
[
"def",
"to_xdr_object",
"(",
"self",
")",
":",
"return",
"Xdr",
".",
"types",
".",
"Memo",
"(",
"type",
"=",
"Xdr",
".",
"const",
".",
"MEMO_TEXT",
",",
"text",
"=",
"self",
".",
"text",
")"
] |
Creates an XDR Memo object for a transaction with MEMO_TEXT.
|
[
"Creates",
"an",
"XDR",
"Memo",
"object",
"for",
"a",
"transaction",
"with",
"MEMO_TEXT",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/memo.py#L97-L99
|
234,448
|
StellarCN/py-stellar-base
|
stellar_base/memo.py
|
IdMemo.to_xdr_object
|
def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_ID."""
return Xdr.types.Memo(type=Xdr.const.MEMO_ID, id=self.memo_id)
|
python
|
def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_ID."""
return Xdr.types.Memo(type=Xdr.const.MEMO_ID, id=self.memo_id)
|
[
"def",
"to_xdr_object",
"(",
"self",
")",
":",
"return",
"Xdr",
".",
"types",
".",
"Memo",
"(",
"type",
"=",
"Xdr",
".",
"const",
".",
"MEMO_ID",
",",
"id",
"=",
"self",
".",
"memo_id",
")"
] |
Creates an XDR Memo object for a transaction with MEMO_ID.
|
[
"Creates",
"an",
"XDR",
"Memo",
"object",
"for",
"a",
"transaction",
"with",
"MEMO_ID",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/memo.py#L112-L114
|
234,449
|
StellarCN/py-stellar-base
|
stellar_base/memo.py
|
HashMemo.to_xdr_object
|
def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_HASH."""
return Xdr.types.Memo(type=Xdr.const.MEMO_HASH, hash=self.memo_hash)
|
python
|
def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_HASH."""
return Xdr.types.Memo(type=Xdr.const.MEMO_HASH, hash=self.memo_hash)
|
[
"def",
"to_xdr_object",
"(",
"self",
")",
":",
"return",
"Xdr",
".",
"types",
".",
"Memo",
"(",
"type",
"=",
"Xdr",
".",
"const",
".",
"MEMO_HASH",
",",
"hash",
"=",
"self",
".",
"memo_hash",
")"
] |
Creates an XDR Memo object for a transaction with MEMO_HASH.
|
[
"Creates",
"an",
"XDR",
"Memo",
"object",
"for",
"a",
"transaction",
"with",
"MEMO_HASH",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/memo.py#L127-L129
|
234,450
|
StellarCN/py-stellar-base
|
stellar_base/memo.py
|
RetHashMemo.to_xdr_object
|
def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_RETURN."""
return Xdr.types.Memo(
type=Xdr.const.MEMO_RETURN, retHash=self.memo_return)
|
python
|
def to_xdr_object(self):
"""Creates an XDR Memo object for a transaction with MEMO_RETURN."""
return Xdr.types.Memo(
type=Xdr.const.MEMO_RETURN, retHash=self.memo_return)
|
[
"def",
"to_xdr_object",
"(",
"self",
")",
":",
"return",
"Xdr",
".",
"types",
".",
"Memo",
"(",
"type",
"=",
"Xdr",
".",
"const",
".",
"MEMO_RETURN",
",",
"retHash",
"=",
"self",
".",
"memo_return",
")"
] |
Creates an XDR Memo object for a transaction with MEMO_RETURN.
|
[
"Creates",
"an",
"XDR",
"Memo",
"object",
"for",
"a",
"transaction",
"with",
"MEMO_RETURN",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/memo.py#L148-L151
|
234,451
|
StellarCN/py-stellar-base
|
stellar_base/builder.py
|
Builder.append_hashx_signer
|
def append_hashx_signer(self, hashx, signer_weight, source=None):
"""Add a HashX signer to an account.
Add a HashX signer to an account via a :class:`SetOptions
<stellar_base.operation.SetOptions` operation. This is a helper
function for :meth:`append_set_options_op`.
:param hashx: The address of the new hashX signer.
:type hashx: str, bytes
:param int signer_weight: The weight of the new signer.
:param str source: The source account that is adding a signer to its
list of signers.
:return: This builder instance.
"""
return self.append_set_options_op(
signer_address=hashx,
signer_type='hashX',
signer_weight=signer_weight,
source=source)
|
python
|
def append_hashx_signer(self, hashx, signer_weight, source=None):
"""Add a HashX signer to an account.
Add a HashX signer to an account via a :class:`SetOptions
<stellar_base.operation.SetOptions` operation. This is a helper
function for :meth:`append_set_options_op`.
:param hashx: The address of the new hashX signer.
:type hashx: str, bytes
:param int signer_weight: The weight of the new signer.
:param str source: The source account that is adding a signer to its
list of signers.
:return: This builder instance.
"""
return self.append_set_options_op(
signer_address=hashx,
signer_type='hashX',
signer_weight=signer_weight,
source=source)
|
[
"def",
"append_hashx_signer",
"(",
"self",
",",
"hashx",
",",
"signer_weight",
",",
"source",
"=",
"None",
")",
":",
"return",
"self",
".",
"append_set_options_op",
"(",
"signer_address",
"=",
"hashx",
",",
"signer_type",
"=",
"'hashX'",
",",
"signer_weight",
"=",
"signer_weight",
",",
"source",
"=",
"source",
")"
] |
Add a HashX signer to an account.
Add a HashX signer to an account via a :class:`SetOptions
<stellar_base.operation.SetOptions` operation. This is a helper
function for :meth:`append_set_options_op`.
:param hashx: The address of the new hashX signer.
:type hashx: str, bytes
:param int signer_weight: The weight of the new signer.
:param str source: The source account that is adding a signer to its
list of signers.
:return: This builder instance.
|
[
"Add",
"a",
"HashX",
"signer",
"to",
"an",
"account",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/builder.py#L323-L342
|
234,452
|
StellarCN/py-stellar-base
|
stellar_base/builder.py
|
Builder.append_pre_auth_tx_signer
|
def append_pre_auth_tx_signer(self,
pre_auth_tx,
signer_weight,
source=None):
"""Add a PreAuthTx signer to an account.
Add a PreAuthTx signer to an account via a :class:`SetOptions
<stellar_base.operation.SetOptions` operation. This is a helper
function for :meth:`append_set_options_op`.
:param pre_auth_tx: The address of the new preAuthTx signer - obtained by calling `hash_meta` on the TransactionEnvelope.
:type pre_auth_tx: str, bytes
:param int signer_weight: The weight of the new signer.
:param str source: The source account that is adding a signer to its
list of signers.
:return: This builder instance.
"""
return self.append_set_options_op(
signer_address=pre_auth_tx,
signer_type='preAuthTx',
signer_weight=signer_weight,
source=source)
|
python
|
def append_pre_auth_tx_signer(self,
pre_auth_tx,
signer_weight,
source=None):
"""Add a PreAuthTx signer to an account.
Add a PreAuthTx signer to an account via a :class:`SetOptions
<stellar_base.operation.SetOptions` operation. This is a helper
function for :meth:`append_set_options_op`.
:param pre_auth_tx: The address of the new preAuthTx signer - obtained by calling `hash_meta` on the TransactionEnvelope.
:type pre_auth_tx: str, bytes
:param int signer_weight: The weight of the new signer.
:param str source: The source account that is adding a signer to its
list of signers.
:return: This builder instance.
"""
return self.append_set_options_op(
signer_address=pre_auth_tx,
signer_type='preAuthTx',
signer_weight=signer_weight,
source=source)
|
[
"def",
"append_pre_auth_tx_signer",
"(",
"self",
",",
"pre_auth_tx",
",",
"signer_weight",
",",
"source",
"=",
"None",
")",
":",
"return",
"self",
".",
"append_set_options_op",
"(",
"signer_address",
"=",
"pre_auth_tx",
",",
"signer_type",
"=",
"'preAuthTx'",
",",
"signer_weight",
"=",
"signer_weight",
",",
"source",
"=",
"source",
")"
] |
Add a PreAuthTx signer to an account.
Add a PreAuthTx signer to an account via a :class:`SetOptions
<stellar_base.operation.SetOptions` operation. This is a helper
function for :meth:`append_set_options_op`.
:param pre_auth_tx: The address of the new preAuthTx signer - obtained by calling `hash_meta` on the TransactionEnvelope.
:type pre_auth_tx: str, bytes
:param int signer_weight: The weight of the new signer.
:param str source: The source account that is adding a signer to its
list of signers.
:return: This builder instance.
|
[
"Add",
"a",
"PreAuthTx",
"signer",
"to",
"an",
"account",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/builder.py#L344-L366
|
234,453
|
StellarCN/py-stellar-base
|
stellar_base/builder.py
|
Builder.next_builder
|
def next_builder(self):
"""Create a new builder based off of this one with its sequence number
incremented.
:return: A new Builder instance
:rtype: :class:`Builder`
"""
sequence = self.sequence + 1
next_builder = Builder(
horizon_uri=self.horizon.horizon_uri,
address=self.address,
network=self.network,
sequence=sequence,
fee=self.fee)
next_builder.keypair = self.keypair
return next_builder
|
python
|
def next_builder(self):
"""Create a new builder based off of this one with its sequence number
incremented.
:return: A new Builder instance
:rtype: :class:`Builder`
"""
sequence = self.sequence + 1
next_builder = Builder(
horizon_uri=self.horizon.horizon_uri,
address=self.address,
network=self.network,
sequence=sequence,
fee=self.fee)
next_builder.keypair = self.keypair
return next_builder
|
[
"def",
"next_builder",
"(",
"self",
")",
":",
"sequence",
"=",
"self",
".",
"sequence",
"+",
"1",
"next_builder",
"=",
"Builder",
"(",
"horizon_uri",
"=",
"self",
".",
"horizon",
".",
"horizon_uri",
",",
"address",
"=",
"self",
".",
"address",
",",
"network",
"=",
"self",
".",
"network",
",",
"sequence",
"=",
"sequence",
",",
"fee",
"=",
"self",
".",
"fee",
")",
"next_builder",
".",
"keypair",
"=",
"self",
".",
"keypair",
"return",
"next_builder"
] |
Create a new builder based off of this one with its sequence number
incremented.
:return: A new Builder instance
:rtype: :class:`Builder`
|
[
"Create",
"a",
"new",
"builder",
"based",
"off",
"of",
"this",
"one",
"with",
"its",
"sequence",
"number",
"incremented",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/builder.py#L786-L802
|
234,454
|
StellarCN/py-stellar-base
|
stellar_base/builder.py
|
Builder.get_sequence
|
def get_sequence(self):
"""Get the sequence number for a given account via Horizon.
:return: The current sequence number for a given account
:rtype: int
"""
if not self.address:
raise StellarAddressInvalidError('No address provided.')
address = self.horizon.account(self.address)
return int(address.get('sequence'))
|
python
|
def get_sequence(self):
"""Get the sequence number for a given account via Horizon.
:return: The current sequence number for a given account
:rtype: int
"""
if not self.address:
raise StellarAddressInvalidError('No address provided.')
address = self.horizon.account(self.address)
return int(address.get('sequence'))
|
[
"def",
"get_sequence",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"address",
":",
"raise",
"StellarAddressInvalidError",
"(",
"'No address provided.'",
")",
"address",
"=",
"self",
".",
"horizon",
".",
"account",
"(",
"self",
".",
"address",
")",
"return",
"int",
"(",
"address",
".",
"get",
"(",
"'sequence'",
")",
")"
] |
Get the sequence number for a given account via Horizon.
:return: The current sequence number for a given account
:rtype: int
|
[
"Get",
"the",
"sequence",
"number",
"for",
"a",
"given",
"account",
"via",
"Horizon",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/builder.py#L804-L814
|
234,455
|
StellarCN/py-stellar-base
|
stellar_base/asset.py
|
Asset.to_dict
|
def to_dict(self):
"""Generate a dict for this object's attributes.
:return: A dict representing an :class:`Asset`
"""
rv = {'code': self.code}
if not self.is_native():
rv['issuer'] = self.issuer
rv['type'] = self.type
else:
rv['type'] = 'native'
return rv
|
python
|
def to_dict(self):
"""Generate a dict for this object's attributes.
:return: A dict representing an :class:`Asset`
"""
rv = {'code': self.code}
if not self.is_native():
rv['issuer'] = self.issuer
rv['type'] = self.type
else:
rv['type'] = 'native'
return rv
|
[
"def",
"to_dict",
"(",
"self",
")",
":",
"rv",
"=",
"{",
"'code'",
":",
"self",
".",
"code",
"}",
"if",
"not",
"self",
".",
"is_native",
"(",
")",
":",
"rv",
"[",
"'issuer'",
"]",
"=",
"self",
".",
"issuer",
"rv",
"[",
"'type'",
"]",
"=",
"self",
".",
"type",
"else",
":",
"rv",
"[",
"'type'",
"]",
"=",
"'native'",
"return",
"rv"
] |
Generate a dict for this object's attributes.
:return: A dict representing an :class:`Asset`
|
[
"Generate",
"a",
"dict",
"for",
"this",
"object",
"s",
"attributes",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/asset.py#L61-L72
|
234,456
|
StellarCN/py-stellar-base
|
stellar_base/stellarxdr/xdrgen.py
|
id_unique
|
def id_unique(dict_id, name, lineno):
"""Returns True if dict_id not already used. Otherwise, invokes error"""
if dict_id in name_dict:
global error_occurred
error_occurred = True
print(
"ERROR - {0:s} definition {1:s} at line {2:d} conflicts with {3:s}"
.format(name, dict_id, lineno, name_dict[dict_id]))
return False
else:
return True
|
python
|
def id_unique(dict_id, name, lineno):
"""Returns True if dict_id not already used. Otherwise, invokes error"""
if dict_id in name_dict:
global error_occurred
error_occurred = True
print(
"ERROR - {0:s} definition {1:s} at line {2:d} conflicts with {3:s}"
.format(name, dict_id, lineno, name_dict[dict_id]))
return False
else:
return True
|
[
"def",
"id_unique",
"(",
"dict_id",
",",
"name",
",",
"lineno",
")",
":",
"if",
"dict_id",
"in",
"name_dict",
":",
"global",
"error_occurred",
"error_occurred",
"=",
"True",
"print",
"(",
"\"ERROR - {0:s} definition {1:s} at line {2:d} conflicts with {3:s}\"",
".",
"format",
"(",
"name",
",",
"dict_id",
",",
"lineno",
",",
"name_dict",
"[",
"dict_id",
"]",
")",
")",
"return",
"False",
"else",
":",
"return",
"True"
] |
Returns True if dict_id not already used. Otherwise, invokes error
|
[
"Returns",
"True",
"if",
"dict_id",
"not",
"already",
"used",
".",
"Otherwise",
"invokes",
"error"
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/stellarxdr/xdrgen.py#L770-L780
|
234,457
|
StellarCN/py-stellar-base
|
stellar_base/base58.py
|
main
|
def main():
'''Base58 encode or decode FILE, or standard input, to standard output.'''
import sys
import argparse
stdout = buffer(sys.stdout)
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument(
'file',
metavar='FILE',
nargs='?',
type=argparse.FileType('r'),
default='-')
parser.add_argument(
'-d', '--decode', action='store_true', help='decode data')
parser.add_argument(
'-c',
'--check',
action='store_true',
help='append a checksum before encoding')
args = parser.parse_args()
fun = {
(False, False): b58encode,
(False, True): b58encode_check,
(True, False): b58decode,
(True, True): b58decode_check
}[(args.decode, args.check)]
data = buffer(args.file).read().rstrip(b'\n')
try:
result = fun(data)
except Exception as e:
sys.exit(e)
if not isinstance(result, bytes):
result = result.encode('ascii')
stdout.write(result)
|
python
|
def main():
'''Base58 encode or decode FILE, or standard input, to standard output.'''
import sys
import argparse
stdout = buffer(sys.stdout)
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument(
'file',
metavar='FILE',
nargs='?',
type=argparse.FileType('r'),
default='-')
parser.add_argument(
'-d', '--decode', action='store_true', help='decode data')
parser.add_argument(
'-c',
'--check',
action='store_true',
help='append a checksum before encoding')
args = parser.parse_args()
fun = {
(False, False): b58encode,
(False, True): b58encode_check,
(True, False): b58decode,
(True, True): b58decode_check
}[(args.decode, args.check)]
data = buffer(args.file).read().rstrip(b'\n')
try:
result = fun(data)
except Exception as e:
sys.exit(e)
if not isinstance(result, bytes):
result = result.encode('ascii')
stdout.write(result)
|
[
"def",
"main",
"(",
")",
":",
"import",
"sys",
"import",
"argparse",
"stdout",
"=",
"buffer",
"(",
"sys",
".",
"stdout",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"main",
".",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'file'",
",",
"metavar",
"=",
"'FILE'",
",",
"nargs",
"=",
"'?'",
",",
"type",
"=",
"argparse",
".",
"FileType",
"(",
"'r'",
")",
",",
"default",
"=",
"'-'",
")",
"parser",
".",
"add_argument",
"(",
"'-d'",
",",
"'--decode'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'decode data'",
")",
"parser",
".",
"add_argument",
"(",
"'-c'",
",",
"'--check'",
",",
"action",
"=",
"'store_true'",
",",
"help",
"=",
"'append a checksum before encoding'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"fun",
"=",
"{",
"(",
"False",
",",
"False",
")",
":",
"b58encode",
",",
"(",
"False",
",",
"True",
")",
":",
"b58encode_check",
",",
"(",
"True",
",",
"False",
")",
":",
"b58decode",
",",
"(",
"True",
",",
"True",
")",
":",
"b58decode_check",
"}",
"[",
"(",
"args",
".",
"decode",
",",
"args",
".",
"check",
")",
"]",
"data",
"=",
"buffer",
"(",
"args",
".",
"file",
")",
".",
"read",
"(",
")",
".",
"rstrip",
"(",
"b'\\n'",
")",
"try",
":",
"result",
"=",
"fun",
"(",
"data",
")",
"except",
"Exception",
"as",
"e",
":",
"sys",
".",
"exit",
"(",
"e",
")",
"if",
"not",
"isinstance",
"(",
"result",
",",
"bytes",
")",
":",
"result",
"=",
"result",
".",
"encode",
"(",
"'ascii'",
")",
"stdout",
".",
"write",
"(",
"result",
")"
] |
Base58 encode or decode FILE, or standard input, to standard output.
|
[
"Base58",
"encode",
"or",
"decode",
"FILE",
"or",
"standard",
"input",
"to",
"standard",
"output",
"."
] |
cce2e782064fb3955c85e1696e630d67b1010848
|
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/base58.py#L93-L134
|
234,458
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/distro_lib/sles_11/utils.py
|
Utils._Dhcpcd
|
def _Dhcpcd(self, interfaces, logger):
"""Use dhcpcd to activate the interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
"""
for interface in interfaces:
dhcpcd = ['/sbin/dhcpcd']
try:
subprocess.check_call(dhcpcd + ['-x', interface])
except subprocess.CalledProcessError:
# Dhcpcd not yet running for this device.
logger.info('Dhcpcd not yet running for interface %s.', interface)
try:
subprocess.check_call(dhcpcd + [interface])
except subprocess.CalledProcessError:
# The interface is already active.
logger.warning('Could not activate interface %s.', interface)
|
python
|
def _Dhcpcd(self, interfaces, logger):
"""Use dhcpcd to activate the interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
"""
for interface in interfaces:
dhcpcd = ['/sbin/dhcpcd']
try:
subprocess.check_call(dhcpcd + ['-x', interface])
except subprocess.CalledProcessError:
# Dhcpcd not yet running for this device.
logger.info('Dhcpcd not yet running for interface %s.', interface)
try:
subprocess.check_call(dhcpcd + [interface])
except subprocess.CalledProcessError:
# The interface is already active.
logger.warning('Could not activate interface %s.', interface)
|
[
"def",
"_Dhcpcd",
"(",
"self",
",",
"interfaces",
",",
"logger",
")",
":",
"for",
"interface",
"in",
"interfaces",
":",
"dhcpcd",
"=",
"[",
"'/sbin/dhcpcd'",
"]",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"dhcpcd",
"+",
"[",
"'-x'",
",",
"interface",
"]",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"# Dhcpcd not yet running for this device.",
"logger",
".",
"info",
"(",
"'Dhcpcd not yet running for interface %s.'",
",",
"interface",
")",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"dhcpcd",
"+",
"[",
"interface",
"]",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"# The interface is already active.",
"logger",
".",
"warning",
"(",
"'Could not activate interface %s.'",
",",
"interface",
")"
] |
Use dhcpcd to activate the interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
|
[
"Use",
"dhcpcd",
"to",
"activate",
"the",
"interfaces",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/sles_11/utils.py#L44-L62
|
234,459
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_manager.py
|
_CreateTempDir
|
def _CreateTempDir(prefix, run_dir=None):
"""Context manager for creating a temporary directory.
Args:
prefix: string, the prefix for the temporary directory.
run_dir: string, the base directory location of the temporary directory.
Yields:
string, the temporary directory created.
"""
temp_dir = tempfile.mkdtemp(prefix=prefix + '-', dir=run_dir)
try:
yield temp_dir
finally:
shutil.rmtree(temp_dir)
|
python
|
def _CreateTempDir(prefix, run_dir=None):
"""Context manager for creating a temporary directory.
Args:
prefix: string, the prefix for the temporary directory.
run_dir: string, the base directory location of the temporary directory.
Yields:
string, the temporary directory created.
"""
temp_dir = tempfile.mkdtemp(prefix=prefix + '-', dir=run_dir)
try:
yield temp_dir
finally:
shutil.rmtree(temp_dir)
|
[
"def",
"_CreateTempDir",
"(",
"prefix",
",",
"run_dir",
"=",
"None",
")",
":",
"temp_dir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"prefix",
"+",
"'-'",
",",
"dir",
"=",
"run_dir",
")",
"try",
":",
"yield",
"temp_dir",
"finally",
":",
"shutil",
".",
"rmtree",
"(",
"temp_dir",
")"
] |
Context manager for creating a temporary directory.
Args:
prefix: string, the prefix for the temporary directory.
run_dir: string, the base directory location of the temporary directory.
Yields:
string, the temporary directory created.
|
[
"Context",
"manager",
"for",
"creating",
"a",
"temporary",
"directory",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_manager.py#L31-L45
|
234,460
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_manager.py
|
ScriptManager._RunScripts
|
def _RunScripts(self, run_dir=None):
"""Retrieve metadata scripts and execute them.
Args:
run_dir: string, the base directory location of the temporary directory.
"""
with _CreateTempDir(self.script_type, run_dir=run_dir) as dest_dir:
try:
self.logger.info('Starting %s scripts.', self.script_type)
script_dict = self.retriever.GetScripts(dest_dir)
self.executor.RunScripts(script_dict)
finally:
self.logger.info('Finished running %s scripts.', self.script_type)
|
python
|
def _RunScripts(self, run_dir=None):
"""Retrieve metadata scripts and execute them.
Args:
run_dir: string, the base directory location of the temporary directory.
"""
with _CreateTempDir(self.script_type, run_dir=run_dir) as dest_dir:
try:
self.logger.info('Starting %s scripts.', self.script_type)
script_dict = self.retriever.GetScripts(dest_dir)
self.executor.RunScripts(script_dict)
finally:
self.logger.info('Finished running %s scripts.', self.script_type)
|
[
"def",
"_RunScripts",
"(",
"self",
",",
"run_dir",
"=",
"None",
")",
":",
"with",
"_CreateTempDir",
"(",
"self",
".",
"script_type",
",",
"run_dir",
"=",
"run_dir",
")",
"as",
"dest_dir",
":",
"try",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Starting %s scripts.'",
",",
"self",
".",
"script_type",
")",
"script_dict",
"=",
"self",
".",
"retriever",
".",
"GetScripts",
"(",
"dest_dir",
")",
"self",
".",
"executor",
".",
"RunScripts",
"(",
"script_dict",
")",
"finally",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Finished running %s scripts.'",
",",
"self",
".",
"script_type",
")"
] |
Retrieve metadata scripts and execute them.
Args:
run_dir: string, the base directory location of the temporary directory.
|
[
"Retrieve",
"metadata",
"scripts",
"and",
"execute",
"them",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_manager.py#L71-L83
|
234,461
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py
|
InstanceSetup._GetInstanceConfig
|
def _GetInstanceConfig(self):
"""Get the instance configuration specified in metadata.
Returns:
string, the instance configuration data.
"""
try:
instance_data = self.metadata_dict['instance']['attributes']
except KeyError:
instance_data = {}
self.logger.warning('Instance attributes were not found.')
try:
project_data = self.metadata_dict['project']['attributes']
except KeyError:
project_data = {}
self.logger.warning('Project attributes were not found.')
return (instance_data.get('google-instance-configs')
or project_data.get('google-instance-configs'))
|
python
|
def _GetInstanceConfig(self):
"""Get the instance configuration specified in metadata.
Returns:
string, the instance configuration data.
"""
try:
instance_data = self.metadata_dict['instance']['attributes']
except KeyError:
instance_data = {}
self.logger.warning('Instance attributes were not found.')
try:
project_data = self.metadata_dict['project']['attributes']
except KeyError:
project_data = {}
self.logger.warning('Project attributes were not found.')
return (instance_data.get('google-instance-configs')
or project_data.get('google-instance-configs'))
|
[
"def",
"_GetInstanceConfig",
"(",
"self",
")",
":",
"try",
":",
"instance_data",
"=",
"self",
".",
"metadata_dict",
"[",
"'instance'",
"]",
"[",
"'attributes'",
"]",
"except",
"KeyError",
":",
"instance_data",
"=",
"{",
"}",
"self",
".",
"logger",
".",
"warning",
"(",
"'Instance attributes were not found.'",
")",
"try",
":",
"project_data",
"=",
"self",
".",
"metadata_dict",
"[",
"'project'",
"]",
"[",
"'attributes'",
"]",
"except",
"KeyError",
":",
"project_data",
"=",
"{",
"}",
"self",
".",
"logger",
".",
"warning",
"(",
"'Project attributes were not found.'",
")",
"return",
"(",
"instance_data",
".",
"get",
"(",
"'google-instance-configs'",
")",
"or",
"project_data",
".",
"get",
"(",
"'google-instance-configs'",
")",
")"
] |
Get the instance configuration specified in metadata.
Returns:
string, the instance configuration data.
|
[
"Get",
"the",
"instance",
"configuration",
"specified",
"in",
"metadata",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py#L72-L91
|
234,462
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py
|
InstanceSetup._GenerateSshKey
|
def _GenerateSshKey(self, key_type, key_dest):
"""Generate a new SSH key.
Args:
key_type: string, the type of the SSH key.
key_dest: string, a file location to store the SSH key.
"""
# Create a temporary file to save the created RSA keys.
with tempfile.NamedTemporaryFile(prefix=key_type, delete=True) as temp:
temp_key = temp.name
command = ['ssh-keygen', '-t', key_type, '-f', temp_key, '-N', '', '-q']
try:
self.logger.info('Generating SSH key %s.', key_dest)
subprocess.check_call(command)
except subprocess.CalledProcessError:
self.logger.warning('Could not create SSH key %s.', key_dest)
return
shutil.move(temp_key, key_dest)
shutil.move('%s.pub' % temp_key, '%s.pub' % key_dest)
file_utils.SetPermissions(key_dest, mode=0o600)
file_utils.SetPermissions('%s.pub' % key_dest, mode=0o644)
|
python
|
def _GenerateSshKey(self, key_type, key_dest):
"""Generate a new SSH key.
Args:
key_type: string, the type of the SSH key.
key_dest: string, a file location to store the SSH key.
"""
# Create a temporary file to save the created RSA keys.
with tempfile.NamedTemporaryFile(prefix=key_type, delete=True) as temp:
temp_key = temp.name
command = ['ssh-keygen', '-t', key_type, '-f', temp_key, '-N', '', '-q']
try:
self.logger.info('Generating SSH key %s.', key_dest)
subprocess.check_call(command)
except subprocess.CalledProcessError:
self.logger.warning('Could not create SSH key %s.', key_dest)
return
shutil.move(temp_key, key_dest)
shutil.move('%s.pub' % temp_key, '%s.pub' % key_dest)
file_utils.SetPermissions(key_dest, mode=0o600)
file_utils.SetPermissions('%s.pub' % key_dest, mode=0o644)
|
[
"def",
"_GenerateSshKey",
"(",
"self",
",",
"key_type",
",",
"key_dest",
")",
":",
"# Create a temporary file to save the created RSA keys.",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"prefix",
"=",
"key_type",
",",
"delete",
"=",
"True",
")",
"as",
"temp",
":",
"temp_key",
"=",
"temp",
".",
"name",
"command",
"=",
"[",
"'ssh-keygen'",
",",
"'-t'",
",",
"key_type",
",",
"'-f'",
",",
"temp_key",
",",
"'-N'",
",",
"''",
",",
"'-q'",
"]",
"try",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Generating SSH key %s.'",
",",
"key_dest",
")",
"subprocess",
".",
"check_call",
"(",
"command",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Could not create SSH key %s.'",
",",
"key_dest",
")",
"return",
"shutil",
".",
"move",
"(",
"temp_key",
",",
"key_dest",
")",
"shutil",
".",
"move",
"(",
"'%s.pub'",
"%",
"temp_key",
",",
"'%s.pub'",
"%",
"key_dest",
")",
"file_utils",
".",
"SetPermissions",
"(",
"key_dest",
",",
"mode",
"=",
"0o600",
")",
"file_utils",
".",
"SetPermissions",
"(",
"'%s.pub'",
"%",
"key_dest",
",",
"mode",
"=",
"0o644",
")"
] |
Generate a new SSH key.
Args:
key_type: string, the type of the SSH key.
key_dest: string, a file location to store the SSH key.
|
[
"Generate",
"a",
"new",
"SSH",
"key",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py#L119-L142
|
234,463
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py
|
InstanceSetup._StartSshd
|
def _StartSshd(self):
"""Initialize the SSH daemon."""
# Exit as early as possible.
# Instance setup systemd scripts block sshd from starting.
if os.path.exists(constants.LOCALBASE + '/bin/systemctl'):
return
elif (os.path.exists('/etc/init.d/ssh')
or os.path.exists('/etc/init/ssh.conf')):
subprocess.call(['service', 'ssh', 'start'])
subprocess.call(['service', 'ssh', 'reload'])
elif (os.path.exists('/etc/init.d/sshd')
or os.path.exists('/etc/init/sshd.conf')):
subprocess.call(['service', 'sshd', 'start'])
subprocess.call(['service', 'sshd', 'reload'])
|
python
|
def _StartSshd(self):
"""Initialize the SSH daemon."""
# Exit as early as possible.
# Instance setup systemd scripts block sshd from starting.
if os.path.exists(constants.LOCALBASE + '/bin/systemctl'):
return
elif (os.path.exists('/etc/init.d/ssh')
or os.path.exists('/etc/init/ssh.conf')):
subprocess.call(['service', 'ssh', 'start'])
subprocess.call(['service', 'ssh', 'reload'])
elif (os.path.exists('/etc/init.d/sshd')
or os.path.exists('/etc/init/sshd.conf')):
subprocess.call(['service', 'sshd', 'start'])
subprocess.call(['service', 'sshd', 'reload'])
|
[
"def",
"_StartSshd",
"(",
"self",
")",
":",
"# Exit as early as possible.",
"# Instance setup systemd scripts block sshd from starting.",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"constants",
".",
"LOCALBASE",
"+",
"'/bin/systemctl'",
")",
":",
"return",
"elif",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"'/etc/init.d/ssh'",
")",
"or",
"os",
".",
"path",
".",
"exists",
"(",
"'/etc/init/ssh.conf'",
")",
")",
":",
"subprocess",
".",
"call",
"(",
"[",
"'service'",
",",
"'ssh'",
",",
"'start'",
"]",
")",
"subprocess",
".",
"call",
"(",
"[",
"'service'",
",",
"'ssh'",
",",
"'reload'",
"]",
")",
"elif",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"'/etc/init.d/sshd'",
")",
"or",
"os",
".",
"path",
".",
"exists",
"(",
"'/etc/init/sshd.conf'",
")",
")",
":",
"subprocess",
".",
"call",
"(",
"[",
"'service'",
",",
"'sshd'",
",",
"'start'",
"]",
")",
"subprocess",
".",
"call",
"(",
"[",
"'service'",
",",
"'sshd'",
",",
"'reload'",
"]",
")"
] |
Initialize the SSH daemon.
|
[
"Initialize",
"the",
"SSH",
"daemon",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py#L144-L157
|
234,464
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py
|
InstanceSetup._SetSshHostKeys
|
def _SetSshHostKeys(self, host_key_types=None):
"""Regenerates SSH host keys when the VM is restarted with a new IP address.
Booting a VM from an image with a known SSH key allows a number of attacks.
This function will regenerating the host key whenever the IP address
changes. This applies the first time the instance is booted, and each time
the disk is used to boot a new instance.
Args:
host_key_types: string, a comma separated list of host key types.
"""
section = 'Instance'
instance_id = self._GetInstanceId()
if instance_id != self.instance_config.GetOptionString(
section, 'instance_id'):
self.logger.info('Generating SSH host keys for instance %s.', instance_id)
file_regex = re.compile(r'ssh_host_(?P<type>[a-z0-9]*)_key\Z')
key_dir = '/etc/ssh'
key_files = [f for f in os.listdir(key_dir) if file_regex.match(f)]
key_types = host_key_types.split(',') if host_key_types else []
key_types_files = ['ssh_host_%s_key' % key_type for key_type in key_types]
for key_file in set(key_files) | set(key_types_files):
key_type = file_regex.match(key_file).group('type')
key_dest = os.path.join(key_dir, key_file)
self._GenerateSshKey(key_type, key_dest)
self._StartSshd()
self.instance_config.SetOption(section, 'instance_id', str(instance_id))
|
python
|
def _SetSshHostKeys(self, host_key_types=None):
"""Regenerates SSH host keys when the VM is restarted with a new IP address.
Booting a VM from an image with a known SSH key allows a number of attacks.
This function will regenerating the host key whenever the IP address
changes. This applies the first time the instance is booted, and each time
the disk is used to boot a new instance.
Args:
host_key_types: string, a comma separated list of host key types.
"""
section = 'Instance'
instance_id = self._GetInstanceId()
if instance_id != self.instance_config.GetOptionString(
section, 'instance_id'):
self.logger.info('Generating SSH host keys for instance %s.', instance_id)
file_regex = re.compile(r'ssh_host_(?P<type>[a-z0-9]*)_key\Z')
key_dir = '/etc/ssh'
key_files = [f for f in os.listdir(key_dir) if file_regex.match(f)]
key_types = host_key_types.split(',') if host_key_types else []
key_types_files = ['ssh_host_%s_key' % key_type for key_type in key_types]
for key_file in set(key_files) | set(key_types_files):
key_type = file_regex.match(key_file).group('type')
key_dest = os.path.join(key_dir, key_file)
self._GenerateSshKey(key_type, key_dest)
self._StartSshd()
self.instance_config.SetOption(section, 'instance_id', str(instance_id))
|
[
"def",
"_SetSshHostKeys",
"(",
"self",
",",
"host_key_types",
"=",
"None",
")",
":",
"section",
"=",
"'Instance'",
"instance_id",
"=",
"self",
".",
"_GetInstanceId",
"(",
")",
"if",
"instance_id",
"!=",
"self",
".",
"instance_config",
".",
"GetOptionString",
"(",
"section",
",",
"'instance_id'",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Generating SSH host keys for instance %s.'",
",",
"instance_id",
")",
"file_regex",
"=",
"re",
".",
"compile",
"(",
"r'ssh_host_(?P<type>[a-z0-9]*)_key\\Z'",
")",
"key_dir",
"=",
"'/etc/ssh'",
"key_files",
"=",
"[",
"f",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"key_dir",
")",
"if",
"file_regex",
".",
"match",
"(",
"f",
")",
"]",
"key_types",
"=",
"host_key_types",
".",
"split",
"(",
"','",
")",
"if",
"host_key_types",
"else",
"[",
"]",
"key_types_files",
"=",
"[",
"'ssh_host_%s_key'",
"%",
"key_type",
"for",
"key_type",
"in",
"key_types",
"]",
"for",
"key_file",
"in",
"set",
"(",
"key_files",
")",
"|",
"set",
"(",
"key_types_files",
")",
":",
"key_type",
"=",
"file_regex",
".",
"match",
"(",
"key_file",
")",
".",
"group",
"(",
"'type'",
")",
"key_dest",
"=",
"os",
".",
"path",
".",
"join",
"(",
"key_dir",
",",
"key_file",
")",
"self",
".",
"_GenerateSshKey",
"(",
"key_type",
",",
"key_dest",
")",
"self",
".",
"_StartSshd",
"(",
")",
"self",
".",
"instance_config",
".",
"SetOption",
"(",
"section",
",",
"'instance_id'",
",",
"str",
"(",
"instance_id",
")",
")"
] |
Regenerates SSH host keys when the VM is restarted with a new IP address.
Booting a VM from an image with a known SSH key allows a number of attacks.
This function will regenerating the host key whenever the IP address
changes. This applies the first time the instance is booted, and each time
the disk is used to boot a new instance.
Args:
host_key_types: string, a comma separated list of host key types.
|
[
"Regenerates",
"SSH",
"host",
"keys",
"when",
"the",
"VM",
"is",
"restarted",
"with",
"a",
"new",
"IP",
"address",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py#L159-L185
|
234,465
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py
|
InstanceSetup._SetupBotoConfig
|
def _SetupBotoConfig(self):
"""Set the boto config so GSUtil works with provisioned service accounts."""
project_id = self._GetNumericProjectId()
try:
boto_config.BotoConfig(project_id, debug=self.debug)
except (IOError, OSError) as e:
self.logger.warning(str(e))
|
python
|
def _SetupBotoConfig(self):
"""Set the boto config so GSUtil works with provisioned service accounts."""
project_id = self._GetNumericProjectId()
try:
boto_config.BotoConfig(project_id, debug=self.debug)
except (IOError, OSError) as e:
self.logger.warning(str(e))
|
[
"def",
"_SetupBotoConfig",
"(",
"self",
")",
":",
"project_id",
"=",
"self",
".",
"_GetNumericProjectId",
"(",
")",
"try",
":",
"boto_config",
".",
"BotoConfig",
"(",
"project_id",
",",
"debug",
"=",
"self",
".",
"debug",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"str",
"(",
"e",
")",
")"
] |
Set the boto config so GSUtil works with provisioned service accounts.
|
[
"Set",
"the",
"boto",
"config",
"so",
"GSUtil",
"works",
"with",
"provisioned",
"service",
"accounts",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/instance_setup/instance_setup.py#L199-L205
|
234,466
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py
|
ScriptRetriever._DownloadAuthUrl
|
def _DownloadAuthUrl(self, url, dest_dir):
"""Download a Google Storage URL using an authentication token.
If the token cannot be fetched, fallback to unauthenticated download.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script.
"""
dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False)
dest_file.close()
dest = dest_file.name
self.logger.info(
'Downloading url from %s to %s using authentication token.', url, dest)
if not self.token:
response = self.watcher.GetMetadata(
self.token_metadata_key, recursive=False, retry=False)
if not response:
self.logger.info(
'Authentication token not found. Attempting unauthenticated '
'download.')
return self._DownloadUrl(url, dest_dir)
self.token = '%s %s' % (
response.get('token_type', ''), response.get('access_token', ''))
try:
request = urlrequest.Request(url)
request.add_unredirected_header('Metadata-Flavor', 'Google')
request.add_unredirected_header('Authorization', self.token)
content = urlrequest.urlopen(request).read().decode('utf-8')
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
self.logger.warning('Could not download %s. %s.', url, str(e))
return None
with open(dest, 'wb') as f:
f.write(content)
return dest
|
python
|
def _DownloadAuthUrl(self, url, dest_dir):
"""Download a Google Storage URL using an authentication token.
If the token cannot be fetched, fallback to unauthenticated download.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script.
"""
dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False)
dest_file.close()
dest = dest_file.name
self.logger.info(
'Downloading url from %s to %s using authentication token.', url, dest)
if not self.token:
response = self.watcher.GetMetadata(
self.token_metadata_key, recursive=False, retry=False)
if not response:
self.logger.info(
'Authentication token not found. Attempting unauthenticated '
'download.')
return self._DownloadUrl(url, dest_dir)
self.token = '%s %s' % (
response.get('token_type', ''), response.get('access_token', ''))
try:
request = urlrequest.Request(url)
request.add_unredirected_header('Metadata-Flavor', 'Google')
request.add_unredirected_header('Authorization', self.token)
content = urlrequest.urlopen(request).read().decode('utf-8')
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
self.logger.warning('Could not download %s. %s.', url, str(e))
return None
with open(dest, 'wb') as f:
f.write(content)
return dest
|
[
"def",
"_DownloadAuthUrl",
"(",
"self",
",",
"url",
",",
"dest_dir",
")",
":",
"dest_file",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"dir",
"=",
"dest_dir",
",",
"delete",
"=",
"False",
")",
"dest_file",
".",
"close",
"(",
")",
"dest",
"=",
"dest_file",
".",
"name",
"self",
".",
"logger",
".",
"info",
"(",
"'Downloading url from %s to %s using authentication token.'",
",",
"url",
",",
"dest",
")",
"if",
"not",
"self",
".",
"token",
":",
"response",
"=",
"self",
".",
"watcher",
".",
"GetMetadata",
"(",
"self",
".",
"token_metadata_key",
",",
"recursive",
"=",
"False",
",",
"retry",
"=",
"False",
")",
"if",
"not",
"response",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Authentication token not found. Attempting unauthenticated '",
"'download.'",
")",
"return",
"self",
".",
"_DownloadUrl",
"(",
"url",
",",
"dest_dir",
")",
"self",
".",
"token",
"=",
"'%s %s'",
"%",
"(",
"response",
".",
"get",
"(",
"'token_type'",
",",
"''",
")",
",",
"response",
".",
"get",
"(",
"'access_token'",
",",
"''",
")",
")",
"try",
":",
"request",
"=",
"urlrequest",
".",
"Request",
"(",
"url",
")",
"request",
".",
"add_unredirected_header",
"(",
"'Metadata-Flavor'",
",",
"'Google'",
")",
"request",
".",
"add_unredirected_header",
"(",
"'Authorization'",
",",
"self",
".",
"token",
")",
"content",
"=",
"urlrequest",
".",
"urlopen",
"(",
"request",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
"(",
"httpclient",
".",
"HTTPException",
",",
"socket",
".",
"error",
",",
"urlerror",
".",
"URLError",
")",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Could not download %s. %s.'",
",",
"url",
",",
"str",
"(",
"e",
")",
")",
"return",
"None",
"with",
"open",
"(",
"dest",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"content",
")",
"return",
"dest"
] |
Download a Google Storage URL using an authentication token.
If the token cannot be fetched, fallback to unauthenticated download.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script.
|
[
"Download",
"a",
"Google",
"Storage",
"URL",
"using",
"an",
"authentication",
"token",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py#L48-L92
|
234,467
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py
|
ScriptRetriever._DownloadUrl
|
def _DownloadUrl(self, url, dest_dir):
"""Download a script from a given URL.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script.
"""
dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False)
dest_file.close()
dest = dest_file.name
self.logger.info('Downloading url from %s to %s.', url, dest)
try:
urlretrieve.urlretrieve(url, dest)
return dest
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
self.logger.warning('Could not download %s. %s.', url, str(e))
except Exception as e:
self.logger.warning('Exception downloading %s. %s.', url, str(e))
return None
|
python
|
def _DownloadUrl(self, url, dest_dir):
"""Download a script from a given URL.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script.
"""
dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False)
dest_file.close()
dest = dest_file.name
self.logger.info('Downloading url from %s to %s.', url, dest)
try:
urlretrieve.urlretrieve(url, dest)
return dest
except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
self.logger.warning('Could not download %s. %s.', url, str(e))
except Exception as e:
self.logger.warning('Exception downloading %s. %s.', url, str(e))
return None
|
[
"def",
"_DownloadUrl",
"(",
"self",
",",
"url",
",",
"dest_dir",
")",
":",
"dest_file",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"dir",
"=",
"dest_dir",
",",
"delete",
"=",
"False",
")",
"dest_file",
".",
"close",
"(",
")",
"dest",
"=",
"dest_file",
".",
"name",
"self",
".",
"logger",
".",
"info",
"(",
"'Downloading url from %s to %s.'",
",",
"url",
",",
"dest",
")",
"try",
":",
"urlretrieve",
".",
"urlretrieve",
"(",
"url",
",",
"dest",
")",
"return",
"dest",
"except",
"(",
"httpclient",
".",
"HTTPException",
",",
"socket",
".",
"error",
",",
"urlerror",
".",
"URLError",
")",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Could not download %s. %s.'",
",",
"url",
",",
"str",
"(",
"e",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Exception downloading %s. %s.'",
",",
"url",
",",
"str",
"(",
"e",
")",
")",
"return",
"None"
] |
Download a script from a given URL.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script.
|
[
"Download",
"a",
"script",
"from",
"a",
"given",
"URL",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py#L94-L116
|
234,468
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py
|
ScriptRetriever._DownloadScript
|
def _DownloadScript(self, url, dest_dir):
"""Download the contents of the URL to the destination.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script.
"""
# Check for the preferred Google Storage URL format:
# gs://<bucket>/<object>
if url.startswith(r'gs://'):
# Convert the string into a standard URL.
url = re.sub('^gs://', 'https://storage.googleapis.com/', url)
return self._DownloadAuthUrl(url, dest_dir)
header = r'http[s]?://'
domain = r'storage\.googleapis\.com'
# Many of the Google Storage URLs are supported below.
# It is prefered that customers specify their object using
# its gs://<bucket>/<object> url.
bucket = r'(?P<bucket>[a-z0-9][-_.a-z0-9]*[a-z0-9])'
# Accept any non-empty string that doesn't contain a wildcard character
obj = r'(?P<obj>[^\*\?]+)'
# Check for the Google Storage URLs:
# http://<bucket>.storage.googleapis.com/<object>
# https://<bucket>.storage.googleapis.com/<object>
gs_regex = re.compile(r'\A%s%s\.%s/%s\Z' % (header, bucket, domain, obj))
match = gs_regex.match(url)
if match:
return self._DownloadAuthUrl(url, dest_dir)
# Check for the other possible Google Storage URLs:
# http://storage.googleapis.com/<bucket>/<object>
# https://storage.googleapis.com/<bucket>/<object>
#
# The following are deprecated but checked:
# http://commondatastorage.googleapis.com/<bucket>/<object>
# https://commondatastorage.googleapis.com/<bucket>/<object>
gs_regex = re.compile(
r'\A%s(commondata)?%s/%s/%s\Z' % (header, domain, bucket, obj))
match = gs_regex.match(url)
if match:
return self._DownloadAuthUrl(url, dest_dir)
# Unauthenticated download of the object.
return self._DownloadUrl(url, dest_dir)
|
python
|
def _DownloadScript(self, url, dest_dir):
"""Download the contents of the URL to the destination.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script.
"""
# Check for the preferred Google Storage URL format:
# gs://<bucket>/<object>
if url.startswith(r'gs://'):
# Convert the string into a standard URL.
url = re.sub('^gs://', 'https://storage.googleapis.com/', url)
return self._DownloadAuthUrl(url, dest_dir)
header = r'http[s]?://'
domain = r'storage\.googleapis\.com'
# Many of the Google Storage URLs are supported below.
# It is prefered that customers specify their object using
# its gs://<bucket>/<object> url.
bucket = r'(?P<bucket>[a-z0-9][-_.a-z0-9]*[a-z0-9])'
# Accept any non-empty string that doesn't contain a wildcard character
obj = r'(?P<obj>[^\*\?]+)'
# Check for the Google Storage URLs:
# http://<bucket>.storage.googleapis.com/<object>
# https://<bucket>.storage.googleapis.com/<object>
gs_regex = re.compile(r'\A%s%s\.%s/%s\Z' % (header, bucket, domain, obj))
match = gs_regex.match(url)
if match:
return self._DownloadAuthUrl(url, dest_dir)
# Check for the other possible Google Storage URLs:
# http://storage.googleapis.com/<bucket>/<object>
# https://storage.googleapis.com/<bucket>/<object>
#
# The following are deprecated but checked:
# http://commondatastorage.googleapis.com/<bucket>/<object>
# https://commondatastorage.googleapis.com/<bucket>/<object>
gs_regex = re.compile(
r'\A%s(commondata)?%s/%s/%s\Z' % (header, domain, bucket, obj))
match = gs_regex.match(url)
if match:
return self._DownloadAuthUrl(url, dest_dir)
# Unauthenticated download of the object.
return self._DownloadUrl(url, dest_dir)
|
[
"def",
"_DownloadScript",
"(",
"self",
",",
"url",
",",
"dest_dir",
")",
":",
"# Check for the preferred Google Storage URL format:",
"# gs://<bucket>/<object>",
"if",
"url",
".",
"startswith",
"(",
"r'gs://'",
")",
":",
"# Convert the string into a standard URL.",
"url",
"=",
"re",
".",
"sub",
"(",
"'^gs://'",
",",
"'https://storage.googleapis.com/'",
",",
"url",
")",
"return",
"self",
".",
"_DownloadAuthUrl",
"(",
"url",
",",
"dest_dir",
")",
"header",
"=",
"r'http[s]?://'",
"domain",
"=",
"r'storage\\.googleapis\\.com'",
"# Many of the Google Storage URLs are supported below.",
"# It is prefered that customers specify their object using",
"# its gs://<bucket>/<object> url.",
"bucket",
"=",
"r'(?P<bucket>[a-z0-9][-_.a-z0-9]*[a-z0-9])'",
"# Accept any non-empty string that doesn't contain a wildcard character",
"obj",
"=",
"r'(?P<obj>[^\\*\\?]+)'",
"# Check for the Google Storage URLs:",
"# http://<bucket>.storage.googleapis.com/<object>",
"# https://<bucket>.storage.googleapis.com/<object>",
"gs_regex",
"=",
"re",
".",
"compile",
"(",
"r'\\A%s%s\\.%s/%s\\Z'",
"%",
"(",
"header",
",",
"bucket",
",",
"domain",
",",
"obj",
")",
")",
"match",
"=",
"gs_regex",
".",
"match",
"(",
"url",
")",
"if",
"match",
":",
"return",
"self",
".",
"_DownloadAuthUrl",
"(",
"url",
",",
"dest_dir",
")",
"# Check for the other possible Google Storage URLs:",
"# http://storage.googleapis.com/<bucket>/<object>",
"# https://storage.googleapis.com/<bucket>/<object>",
"#",
"# The following are deprecated but checked:",
"# http://commondatastorage.googleapis.com/<bucket>/<object>",
"# https://commondatastorage.googleapis.com/<bucket>/<object>",
"gs_regex",
"=",
"re",
".",
"compile",
"(",
"r'\\A%s(commondata)?%s/%s/%s\\Z'",
"%",
"(",
"header",
",",
"domain",
",",
"bucket",
",",
"obj",
")",
")",
"match",
"=",
"gs_regex",
".",
"match",
"(",
"url",
")",
"if",
"match",
":",
"return",
"self",
".",
"_DownloadAuthUrl",
"(",
"url",
",",
"dest_dir",
")",
"# Unauthenticated download of the object.",
"return",
"self",
".",
"_DownloadUrl",
"(",
"url",
",",
"dest_dir",
")"
] |
Download the contents of the URL to the destination.
Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
string, the path to the file storing the metadata script.
|
[
"Download",
"the",
"contents",
"of",
"the",
"URL",
"to",
"the",
"destination",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py#L118-L168
|
234,469
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py
|
ScriptRetriever._GetAttributeScripts
|
def _GetAttributeScripts(self, attribute_data, dest_dir):
"""Retrieve the scripts from attribute metadata.
Args:
attribute_data: dict, the contents of the attributes metadata.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping metadata keys to files storing scripts.
"""
script_dict = {}
attribute_data = attribute_data or {}
metadata_key = '%s-script' % self.script_type
metadata_value = attribute_data.get(metadata_key)
if metadata_value:
self.logger.info('Found %s in metadata.', metadata_key)
with tempfile.NamedTemporaryFile(
mode='w', dir=dest_dir, delete=False) as dest:
dest.write(metadata_value.lstrip())
script_dict[metadata_key] = dest.name
metadata_key = '%s-script-url' % self.script_type
metadata_value = attribute_data.get(metadata_key)
if metadata_value:
self.logger.info('Found %s in metadata.', metadata_key)
script_dict[metadata_key] = self._DownloadScript(
metadata_value, dest_dir)
return script_dict
|
python
|
def _GetAttributeScripts(self, attribute_data, dest_dir):
"""Retrieve the scripts from attribute metadata.
Args:
attribute_data: dict, the contents of the attributes metadata.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping metadata keys to files storing scripts.
"""
script_dict = {}
attribute_data = attribute_data or {}
metadata_key = '%s-script' % self.script_type
metadata_value = attribute_data.get(metadata_key)
if metadata_value:
self.logger.info('Found %s in metadata.', metadata_key)
with tempfile.NamedTemporaryFile(
mode='w', dir=dest_dir, delete=False) as dest:
dest.write(metadata_value.lstrip())
script_dict[metadata_key] = dest.name
metadata_key = '%s-script-url' % self.script_type
metadata_value = attribute_data.get(metadata_key)
if metadata_value:
self.logger.info('Found %s in metadata.', metadata_key)
script_dict[metadata_key] = self._DownloadScript(
metadata_value, dest_dir)
return script_dict
|
[
"def",
"_GetAttributeScripts",
"(",
"self",
",",
"attribute_data",
",",
"dest_dir",
")",
":",
"script_dict",
"=",
"{",
"}",
"attribute_data",
"=",
"attribute_data",
"or",
"{",
"}",
"metadata_key",
"=",
"'%s-script'",
"%",
"self",
".",
"script_type",
"metadata_value",
"=",
"attribute_data",
".",
"get",
"(",
"metadata_key",
")",
"if",
"metadata_value",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Found %s in metadata.'",
",",
"metadata_key",
")",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w'",
",",
"dir",
"=",
"dest_dir",
",",
"delete",
"=",
"False",
")",
"as",
"dest",
":",
"dest",
".",
"write",
"(",
"metadata_value",
".",
"lstrip",
"(",
")",
")",
"script_dict",
"[",
"metadata_key",
"]",
"=",
"dest",
".",
"name",
"metadata_key",
"=",
"'%s-script-url'",
"%",
"self",
".",
"script_type",
"metadata_value",
"=",
"attribute_data",
".",
"get",
"(",
"metadata_key",
")",
"if",
"metadata_value",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Found %s in metadata.'",
",",
"metadata_key",
")",
"script_dict",
"[",
"metadata_key",
"]",
"=",
"self",
".",
"_DownloadScript",
"(",
"metadata_value",
",",
"dest_dir",
")",
"return",
"script_dict"
] |
Retrieve the scripts from attribute metadata.
Args:
attribute_data: dict, the contents of the attributes metadata.
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping metadata keys to files storing scripts.
|
[
"Retrieve",
"the",
"scripts",
"from",
"attribute",
"metadata",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py#L170-L198
|
234,470
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py
|
ScriptRetriever.GetScripts
|
def GetScripts(self, dest_dir):
"""Retrieve the scripts to execute.
Args:
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping set metadata keys with associated scripts.
"""
metadata_dict = self.watcher.GetMetadata() or {}
try:
instance_data = metadata_dict['instance']['attributes']
except KeyError:
instance_data = None
self.logger.warning('Instance attributes were not found.')
try:
project_data = metadata_dict['project']['attributes']
except KeyError:
project_data = None
self.logger.warning('Project attributes were not found.')
return (self._GetAttributeScripts(instance_data, dest_dir)
or self._GetAttributeScripts(project_data, dest_dir))
|
python
|
def GetScripts(self, dest_dir):
"""Retrieve the scripts to execute.
Args:
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping set metadata keys with associated scripts.
"""
metadata_dict = self.watcher.GetMetadata() or {}
try:
instance_data = metadata_dict['instance']['attributes']
except KeyError:
instance_data = None
self.logger.warning('Instance attributes were not found.')
try:
project_data = metadata_dict['project']['attributes']
except KeyError:
project_data = None
self.logger.warning('Project attributes were not found.')
return (self._GetAttributeScripts(instance_data, dest_dir)
or self._GetAttributeScripts(project_data, dest_dir))
|
[
"def",
"GetScripts",
"(",
"self",
",",
"dest_dir",
")",
":",
"metadata_dict",
"=",
"self",
".",
"watcher",
".",
"GetMetadata",
"(",
")",
"or",
"{",
"}",
"try",
":",
"instance_data",
"=",
"metadata_dict",
"[",
"'instance'",
"]",
"[",
"'attributes'",
"]",
"except",
"KeyError",
":",
"instance_data",
"=",
"None",
"self",
".",
"logger",
".",
"warning",
"(",
"'Instance attributes were not found.'",
")",
"try",
":",
"project_data",
"=",
"metadata_dict",
"[",
"'project'",
"]",
"[",
"'attributes'",
"]",
"except",
"KeyError",
":",
"project_data",
"=",
"None",
"self",
".",
"logger",
".",
"warning",
"(",
"'Project attributes were not found.'",
")",
"return",
"(",
"self",
".",
"_GetAttributeScripts",
"(",
"instance_data",
",",
"dest_dir",
")",
"or",
"self",
".",
"_GetAttributeScripts",
"(",
"project_data",
",",
"dest_dir",
")",
")"
] |
Retrieve the scripts to execute.
Args:
dest_dir: string, the path to a directory for storing metadata scripts.
Returns:
dict, a dictionary mapping set metadata keys with associated scripts.
|
[
"Retrieve",
"the",
"scripts",
"to",
"execute",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_retriever.py#L200-L224
|
234,471
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_executor.py
|
ScriptExecutor._MakeExecutable
|
def _MakeExecutable(self, metadata_script):
"""Add executable permissions to a file.
Args:
metadata_script: string, the path to the executable file.
"""
mode = os.stat(metadata_script).st_mode
os.chmod(metadata_script, mode | stat.S_IEXEC)
|
python
|
def _MakeExecutable(self, metadata_script):
"""Add executable permissions to a file.
Args:
metadata_script: string, the path to the executable file.
"""
mode = os.stat(metadata_script).st_mode
os.chmod(metadata_script, mode | stat.S_IEXEC)
|
[
"def",
"_MakeExecutable",
"(",
"self",
",",
"metadata_script",
")",
":",
"mode",
"=",
"os",
".",
"stat",
"(",
"metadata_script",
")",
".",
"st_mode",
"os",
".",
"chmod",
"(",
"metadata_script",
",",
"mode",
"|",
"stat",
".",
"S_IEXEC",
")"
] |
Add executable permissions to a file.
Args:
metadata_script: string, the path to the executable file.
|
[
"Add",
"executable",
"permissions",
"to",
"a",
"file",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_executor.py#L38-L45
|
234,472
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_executor.py
|
ScriptExecutor.RunScripts
|
def RunScripts(self, script_dict):
"""Run the metadata scripts; execute a URL script first if one is provided.
Args:
script_dict: a dictionary mapping metadata keys to script files.
"""
metadata_types = ['%s-script-url', '%s-script']
metadata_keys = [key % self.script_type for key in metadata_types]
metadata_keys = [key for key in metadata_keys if script_dict.get(key)]
if not metadata_keys:
self.logger.info('No %s scripts found in metadata.', self.script_type)
for metadata_key in metadata_keys:
metadata_script = script_dict.get(metadata_key)
self._MakeExecutable(metadata_script)
self._RunScript(metadata_key, metadata_script)
|
python
|
def RunScripts(self, script_dict):
"""Run the metadata scripts; execute a URL script first if one is provided.
Args:
script_dict: a dictionary mapping metadata keys to script files.
"""
metadata_types = ['%s-script-url', '%s-script']
metadata_keys = [key % self.script_type for key in metadata_types]
metadata_keys = [key for key in metadata_keys if script_dict.get(key)]
if not metadata_keys:
self.logger.info('No %s scripts found in metadata.', self.script_type)
for metadata_key in metadata_keys:
metadata_script = script_dict.get(metadata_key)
self._MakeExecutable(metadata_script)
self._RunScript(metadata_key, metadata_script)
|
[
"def",
"RunScripts",
"(",
"self",
",",
"script_dict",
")",
":",
"metadata_types",
"=",
"[",
"'%s-script-url'",
",",
"'%s-script'",
"]",
"metadata_keys",
"=",
"[",
"key",
"%",
"self",
".",
"script_type",
"for",
"key",
"in",
"metadata_types",
"]",
"metadata_keys",
"=",
"[",
"key",
"for",
"key",
"in",
"metadata_keys",
"if",
"script_dict",
".",
"get",
"(",
"key",
")",
"]",
"if",
"not",
"metadata_keys",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'No %s scripts found in metadata.'",
",",
"self",
".",
"script_type",
")",
"for",
"metadata_key",
"in",
"metadata_keys",
":",
"metadata_script",
"=",
"script_dict",
".",
"get",
"(",
"metadata_key",
")",
"self",
".",
"_MakeExecutable",
"(",
"metadata_script",
")",
"self",
".",
"_RunScript",
"(",
"metadata_key",
",",
"metadata_script",
")"
] |
Run the metadata scripts; execute a URL script first if one is provided.
Args:
script_dict: a dictionary mapping metadata keys to script files.
|
[
"Run",
"the",
"metadata",
"scripts",
";",
"execute",
"a",
"URL",
"script",
"first",
"if",
"one",
"is",
"provided",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/metadata_scripts/script_executor.py#L67-L81
|
234,473
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/config_manager.py
|
ConfigManager._AddHeader
|
def _AddHeader(self, fp):
"""Create a file header in the config.
Args:
fp: int, a file pointer for writing the header.
"""
text = textwrap.wrap(
textwrap.dedent(self.config_header), break_on_hyphens=False)
fp.write('\n'.join(['# ' + line for line in text]))
fp.write('\n\n')
|
python
|
def _AddHeader(self, fp):
"""Create a file header in the config.
Args:
fp: int, a file pointer for writing the header.
"""
text = textwrap.wrap(
textwrap.dedent(self.config_header), break_on_hyphens=False)
fp.write('\n'.join(['# ' + line for line in text]))
fp.write('\n\n')
|
[
"def",
"_AddHeader",
"(",
"self",
",",
"fp",
")",
":",
"text",
"=",
"textwrap",
".",
"wrap",
"(",
"textwrap",
".",
"dedent",
"(",
"self",
".",
"config_header",
")",
",",
"break_on_hyphens",
"=",
"False",
")",
"fp",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"[",
"'# '",
"+",
"line",
"for",
"line",
"in",
"text",
"]",
")",
")",
"fp",
".",
"write",
"(",
"'\\n\\n'",
")"
] |
Create a file header in the config.
Args:
fp: int, a file pointer for writing the header.
|
[
"Create",
"a",
"file",
"header",
"in",
"the",
"config",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/config_manager.py#L43-L52
|
234,474
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/config_manager.py
|
ConfigManager.SetOption
|
def SetOption(self, section, option, value, overwrite=True):
"""Set the value of an option in the config file.
Args:
section: string, the section of the config file to check.
option: string, the option to set the value of.
value: string, the value to set the option.
overwrite: bool, True to overwrite an existing value in the config file.
"""
if not overwrite and self.config.has_option(section, option):
return
if not self.config.has_section(section):
self.config.add_section(section)
self.config.set(section, option, str(value))
|
python
|
def SetOption(self, section, option, value, overwrite=True):
"""Set the value of an option in the config file.
Args:
section: string, the section of the config file to check.
option: string, the option to set the value of.
value: string, the value to set the option.
overwrite: bool, True to overwrite an existing value in the config file.
"""
if not overwrite and self.config.has_option(section, option):
return
if not self.config.has_section(section):
self.config.add_section(section)
self.config.set(section, option, str(value))
|
[
"def",
"SetOption",
"(",
"self",
",",
"section",
",",
"option",
",",
"value",
",",
"overwrite",
"=",
"True",
")",
":",
"if",
"not",
"overwrite",
"and",
"self",
".",
"config",
".",
"has_option",
"(",
"section",
",",
"option",
")",
":",
"return",
"if",
"not",
"self",
".",
"config",
".",
"has_section",
"(",
"section",
")",
":",
"self",
".",
"config",
".",
"add_section",
"(",
"section",
")",
"self",
".",
"config",
".",
"set",
"(",
"section",
",",
"option",
",",
"str",
"(",
"value",
")",
")"
] |
Set the value of an option in the config file.
Args:
section: string, the section of the config file to check.
option: string, the option to set the value of.
value: string, the value to set the option.
overwrite: bool, True to overwrite an existing value in the config file.
|
[
"Set",
"the",
"value",
"of",
"an",
"option",
"in",
"the",
"config",
"file",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/config_manager.py#L82-L95
|
234,475
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/config_manager.py
|
ConfigManager.WriteConfig
|
def WriteConfig(self, config_file=None):
"""Write the config values to a given file.
Args:
config_file: string, the file location of the config file to write.
"""
config_file = config_file or self.config_file
config_name = os.path.splitext(os.path.basename(config_file))[0]
config_lock = (
'%s/lock/google_%s.lock' % (constants.LOCALSTATEDIR, config_name))
with file_utils.LockFile(config_lock):
with open(config_file, 'w') as config_fp:
if self.config_header:
self._AddHeader(config_fp)
self.config.write(config_fp)
|
python
|
def WriteConfig(self, config_file=None):
"""Write the config values to a given file.
Args:
config_file: string, the file location of the config file to write.
"""
config_file = config_file or self.config_file
config_name = os.path.splitext(os.path.basename(config_file))[0]
config_lock = (
'%s/lock/google_%s.lock' % (constants.LOCALSTATEDIR, config_name))
with file_utils.LockFile(config_lock):
with open(config_file, 'w') as config_fp:
if self.config_header:
self._AddHeader(config_fp)
self.config.write(config_fp)
|
[
"def",
"WriteConfig",
"(",
"self",
",",
"config_file",
"=",
"None",
")",
":",
"config_file",
"=",
"config_file",
"or",
"self",
".",
"config_file",
"config_name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"config_file",
")",
")",
"[",
"0",
"]",
"config_lock",
"=",
"(",
"'%s/lock/google_%s.lock'",
"%",
"(",
"constants",
".",
"LOCALSTATEDIR",
",",
"config_name",
")",
")",
"with",
"file_utils",
".",
"LockFile",
"(",
"config_lock",
")",
":",
"with",
"open",
"(",
"config_file",
",",
"'w'",
")",
"as",
"config_fp",
":",
"if",
"self",
".",
"config_header",
":",
"self",
".",
"_AddHeader",
"(",
"config_fp",
")",
"self",
".",
"config",
".",
"write",
"(",
"config_fp",
")"
] |
Write the config values to a given file.
Args:
config_file: string, the file location of the config file to write.
|
[
"Write",
"the",
"config",
"values",
"to",
"a",
"given",
"file",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/config_manager.py#L97-L111
|
234,476
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/logger.py
|
Logger
|
def Logger(name, debug=False, facility=None):
"""Get a logging object with handlers for sending logs to SysLog.
Args:
name: string, the name of the logger which will be added to log entries.
debug: bool, True if debug output should write to the console.
facility: int, an encoding of the SysLog handler's facility and priority.
Returns:
logging object, an object for logging entries.
"""
logger = logging.getLogger(name)
logger.handlers = []
logger.addHandler(logging.NullHandler())
logger.propagate = False
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(name + ': %(levelname)s %(message)s')
if debug:
# Create a handler for console logging.
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
if facility:
# Create a handler for sending logs to SysLog.
syslog_handler = logging.handlers.SysLogHandler(
address=constants.SYSLOG_SOCKET, facility=facility)
syslog_handler.setLevel(logging.INFO)
syslog_handler.setFormatter(formatter)
logger.addHandler(syslog_handler)
return logger
|
python
|
def Logger(name, debug=False, facility=None):
"""Get a logging object with handlers for sending logs to SysLog.
Args:
name: string, the name of the logger which will be added to log entries.
debug: bool, True if debug output should write to the console.
facility: int, an encoding of the SysLog handler's facility and priority.
Returns:
logging object, an object for logging entries.
"""
logger = logging.getLogger(name)
logger.handlers = []
logger.addHandler(logging.NullHandler())
logger.propagate = False
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(name + ': %(levelname)s %(message)s')
if debug:
# Create a handler for console logging.
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
if facility:
# Create a handler for sending logs to SysLog.
syslog_handler = logging.handlers.SysLogHandler(
address=constants.SYSLOG_SOCKET, facility=facility)
syslog_handler.setLevel(logging.INFO)
syslog_handler.setFormatter(formatter)
logger.addHandler(syslog_handler)
return logger
|
[
"def",
"Logger",
"(",
"name",
",",
"debug",
"=",
"False",
",",
"facility",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"logger",
".",
"handlers",
"=",
"[",
"]",
"logger",
".",
"addHandler",
"(",
"logging",
".",
"NullHandler",
"(",
")",
")",
"logger",
".",
"propagate",
"=",
"False",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"name",
"+",
"': %(levelname)s %(message)s'",
")",
"if",
"debug",
":",
"# Create a handler for console logging.",
"console_handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"console_handler",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"console_handler",
".",
"setFormatter",
"(",
"formatter",
")",
"logger",
".",
"addHandler",
"(",
"console_handler",
")",
"if",
"facility",
":",
"# Create a handler for sending logs to SysLog.",
"syslog_handler",
"=",
"logging",
".",
"handlers",
".",
"SysLogHandler",
"(",
"address",
"=",
"constants",
".",
"SYSLOG_SOCKET",
",",
"facility",
"=",
"facility",
")",
"syslog_handler",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"syslog_handler",
".",
"setFormatter",
"(",
"formatter",
")",
"logger",
".",
"addHandler",
"(",
"syslog_handler",
")",
"return",
"logger"
] |
Get a logging object with handlers for sending logs to SysLog.
Args:
name: string, the name of the logger which will be added to log entries.
debug: bool, True if debug output should write to the console.
facility: int, an encoding of the SysLog handler's facility and priority.
Returns:
logging object, an object for logging entries.
|
[
"Get",
"a",
"logging",
"object",
"with",
"handlers",
"for",
"sending",
"logs",
"to",
"SysLog",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/logger.py#L22-L55
|
234,477
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py
|
AccountsUtils._CreateSudoersGroup
|
def _CreateSudoersGroup(self):
"""Create a Linux group for Google added sudo user accounts."""
if not self._GetGroup(self.google_sudoers_group):
try:
command = self.groupadd_cmd.format(group=self.google_sudoers_group)
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not create the sudoers group. %s.', str(e))
if not os.path.exists(self.google_sudoers_file):
try:
with open(self.google_sudoers_file, 'w') as group:
message = '%{0} ALL=(ALL:ALL) NOPASSWD:ALL'.format(
self.google_sudoers_group)
group.write(message)
except IOError as e:
self.logger.error(
'Could not write sudoers file. %s. %s',
self.google_sudoers_file, str(e))
return
file_utils.SetPermissions(
self.google_sudoers_file, mode=0o440, uid=0, gid=0)
|
python
|
def _CreateSudoersGroup(self):
"""Create a Linux group for Google added sudo user accounts."""
if not self._GetGroup(self.google_sudoers_group):
try:
command = self.groupadd_cmd.format(group=self.google_sudoers_group)
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not create the sudoers group. %s.', str(e))
if not os.path.exists(self.google_sudoers_file):
try:
with open(self.google_sudoers_file, 'w') as group:
message = '%{0} ALL=(ALL:ALL) NOPASSWD:ALL'.format(
self.google_sudoers_group)
group.write(message)
except IOError as e:
self.logger.error(
'Could not write sudoers file. %s. %s',
self.google_sudoers_file, str(e))
return
file_utils.SetPermissions(
self.google_sudoers_file, mode=0o440, uid=0, gid=0)
|
[
"def",
"_CreateSudoersGroup",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_GetGroup",
"(",
"self",
".",
"google_sudoers_group",
")",
":",
"try",
":",
"command",
"=",
"self",
".",
"groupadd_cmd",
".",
"format",
"(",
"group",
"=",
"self",
".",
"google_sudoers_group",
")",
"subprocess",
".",
"check_call",
"(",
"command",
".",
"split",
"(",
"' '",
")",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Could not create the sudoers group. %s.'",
",",
"str",
"(",
"e",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"google_sudoers_file",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"google_sudoers_file",
",",
"'w'",
")",
"as",
"group",
":",
"message",
"=",
"'%{0} ALL=(ALL:ALL) NOPASSWD:ALL'",
".",
"format",
"(",
"self",
".",
"google_sudoers_group",
")",
"group",
".",
"write",
"(",
"message",
")",
"except",
"IOError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"error",
"(",
"'Could not write sudoers file. %s. %s'",
",",
"self",
".",
"google_sudoers_file",
",",
"str",
"(",
"e",
")",
")",
"return",
"file_utils",
".",
"SetPermissions",
"(",
"self",
".",
"google_sudoers_file",
",",
"mode",
"=",
"0o440",
",",
"uid",
"=",
"0",
",",
"gid",
"=",
"0",
")"
] |
Create a Linux group for Google added sudo user accounts.
|
[
"Create",
"a",
"Linux",
"group",
"for",
"Google",
"added",
"sudo",
"user",
"accounts",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L92-L114
|
234,478
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py
|
AccountsUtils._AddUser
|
def _AddUser(self, user):
"""Configure a Linux user account.
Args:
user: string, the name of the Linux user account to create.
Returns:
bool, True if user creation succeeded.
"""
self.logger.info('Creating a new user account for %s.', user)
command = self.useradd_cmd.format(user=user)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not create user %s. %s.', user, str(e))
return False
else:
self.logger.info('Created user account %s.', user)
return True
|
python
|
def _AddUser(self, user):
"""Configure a Linux user account.
Args:
user: string, the name of the Linux user account to create.
Returns:
bool, True if user creation succeeded.
"""
self.logger.info('Creating a new user account for %s.', user)
command = self.useradd_cmd.format(user=user)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not create user %s. %s.', user, str(e))
return False
else:
self.logger.info('Created user account %s.', user)
return True
|
[
"def",
"_AddUser",
"(",
"self",
",",
"user",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Creating a new user account for %s.'",
",",
"user",
")",
"command",
"=",
"self",
".",
"useradd_cmd",
".",
"format",
"(",
"user",
"=",
"user",
")",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"command",
".",
"split",
"(",
"' '",
")",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Could not create user %s. %s.'",
",",
"user",
",",
"str",
"(",
"e",
")",
")",
"return",
"False",
"else",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Created user account %s.'",
",",
"user",
")",
"return",
"True"
] |
Configure a Linux user account.
Args:
user: string, the name of the Linux user account to create.
Returns:
bool, True if user creation succeeded.
|
[
"Configure",
"a",
"Linux",
"user",
"account",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L130-L149
|
234,479
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py
|
AccountsUtils._UpdateUserGroups
|
def _UpdateUserGroups(self, user, groups):
"""Update group membership for a Linux user.
Args:
user: string, the name of the Linux user account.
groups: list, the group names to add the user as a member.
Returns:
bool, True if user update succeeded.
"""
groups = ','.join(groups)
self.logger.debug('Updating user %s with groups %s.', user, groups)
command = self.usermod_cmd.format(user=user, groups=groups)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not update user %s. %s.', user, str(e))
return False
else:
self.logger.debug('Updated user account %s.', user)
return True
|
python
|
def _UpdateUserGroups(self, user, groups):
"""Update group membership for a Linux user.
Args:
user: string, the name of the Linux user account.
groups: list, the group names to add the user as a member.
Returns:
bool, True if user update succeeded.
"""
groups = ','.join(groups)
self.logger.debug('Updating user %s with groups %s.', user, groups)
command = self.usermod_cmd.format(user=user, groups=groups)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not update user %s. %s.', user, str(e))
return False
else:
self.logger.debug('Updated user account %s.', user)
return True
|
[
"def",
"_UpdateUserGroups",
"(",
"self",
",",
"user",
",",
"groups",
")",
":",
"groups",
"=",
"','",
".",
"join",
"(",
"groups",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'Updating user %s with groups %s.'",
",",
"user",
",",
"groups",
")",
"command",
"=",
"self",
".",
"usermod_cmd",
".",
"format",
"(",
"user",
"=",
"user",
",",
"groups",
"=",
"groups",
")",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"command",
".",
"split",
"(",
"' '",
")",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Could not update user %s. %s.'",
",",
"user",
",",
"str",
"(",
"e",
")",
")",
"return",
"False",
"else",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Updated user account %s.'",
",",
"user",
")",
"return",
"True"
] |
Update group membership for a Linux user.
Args:
user: string, the name of the Linux user account.
groups: list, the group names to add the user as a member.
Returns:
bool, True if user update succeeded.
|
[
"Update",
"group",
"membership",
"for",
"a",
"Linux",
"user",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L151-L171
|
234,480
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py
|
AccountsUtils._UpdateAuthorizedKeys
|
def _UpdateAuthorizedKeys(self, user, ssh_keys):
"""Update the authorized keys file for a Linux user with a list of SSH keys.
Args:
user: string, the name of the Linux user account.
ssh_keys: list, the SSH key strings associated with the user.
Raises:
IOError, raised when there is an exception updating a file.
OSError, raised when setting permissions or writing to a read-only
file system.
"""
pw_entry = self._GetUser(user)
if not pw_entry:
return
uid = pw_entry.pw_uid
gid = pw_entry.pw_gid
home_dir = pw_entry.pw_dir
ssh_dir = os.path.join(home_dir, '.ssh')
# Not all sshd's support multiple authorized_keys files so we have to
# share one with the user. We add each of our entries as follows:
# # Added by Google
# authorized_key_entry
authorized_keys_file = os.path.join(ssh_dir, 'authorized_keys')
# Do not write to the authorized keys file if it is a symlink.
if os.path.islink(ssh_dir) or os.path.islink(authorized_keys_file):
self.logger.warning(
'Not updating authorized keys for user %s. File is a symlink.', user)
return
# Create home directory if it does not exist. This can happen if _GetUser
# (getpwnam) returns non-local user info (e.g., from LDAP).
if not os.path.exists(home_dir):
file_utils.SetPermissions(home_dir, mode=0o755, uid=uid, gid=gid,
mkdir=True)
# Create ssh directory if it does not exist.
file_utils.SetPermissions(ssh_dir, mode=0o700, uid=uid, gid=gid, mkdir=True)
# Create entry in the authorized keys file.
prefix = self.logger.name + '-'
with tempfile.NamedTemporaryFile(
mode='w', prefix=prefix, delete=True) as updated_keys:
updated_keys_file = updated_keys.name
if os.path.exists(authorized_keys_file):
lines = open(authorized_keys_file).readlines()
else:
lines = []
google_lines = set()
for i, line in enumerate(lines):
if line.startswith(self.google_comment):
google_lines.update([i, i+1])
# Write user's authorized key entries.
for i, line in enumerate(lines):
if i not in google_lines and line:
line += '\n' if not line.endswith('\n') else ''
updated_keys.write(line)
# Write the Google authorized key entries at the end of the file.
# Each entry is preceded by '# Added by Google'.
for ssh_key in ssh_keys:
ssh_key += '\n' if not ssh_key.endswith('\n') else ''
updated_keys.write('%s\n' % self.google_comment)
updated_keys.write(ssh_key)
# Write buffered data to the updated keys file without closing it and
# update the Linux user's authorized keys file.
updated_keys.flush()
shutil.copy(updated_keys_file, authorized_keys_file)
file_utils.SetPermissions(
authorized_keys_file, mode=0o600, uid=uid, gid=gid)
|
python
|
def _UpdateAuthorizedKeys(self, user, ssh_keys):
"""Update the authorized keys file for a Linux user with a list of SSH keys.
Args:
user: string, the name of the Linux user account.
ssh_keys: list, the SSH key strings associated with the user.
Raises:
IOError, raised when there is an exception updating a file.
OSError, raised when setting permissions or writing to a read-only
file system.
"""
pw_entry = self._GetUser(user)
if not pw_entry:
return
uid = pw_entry.pw_uid
gid = pw_entry.pw_gid
home_dir = pw_entry.pw_dir
ssh_dir = os.path.join(home_dir, '.ssh')
# Not all sshd's support multiple authorized_keys files so we have to
# share one with the user. We add each of our entries as follows:
# # Added by Google
# authorized_key_entry
authorized_keys_file = os.path.join(ssh_dir, 'authorized_keys')
# Do not write to the authorized keys file if it is a symlink.
if os.path.islink(ssh_dir) or os.path.islink(authorized_keys_file):
self.logger.warning(
'Not updating authorized keys for user %s. File is a symlink.', user)
return
# Create home directory if it does not exist. This can happen if _GetUser
# (getpwnam) returns non-local user info (e.g., from LDAP).
if not os.path.exists(home_dir):
file_utils.SetPermissions(home_dir, mode=0o755, uid=uid, gid=gid,
mkdir=True)
# Create ssh directory if it does not exist.
file_utils.SetPermissions(ssh_dir, mode=0o700, uid=uid, gid=gid, mkdir=True)
# Create entry in the authorized keys file.
prefix = self.logger.name + '-'
with tempfile.NamedTemporaryFile(
mode='w', prefix=prefix, delete=True) as updated_keys:
updated_keys_file = updated_keys.name
if os.path.exists(authorized_keys_file):
lines = open(authorized_keys_file).readlines()
else:
lines = []
google_lines = set()
for i, line in enumerate(lines):
if line.startswith(self.google_comment):
google_lines.update([i, i+1])
# Write user's authorized key entries.
for i, line in enumerate(lines):
if i not in google_lines and line:
line += '\n' if not line.endswith('\n') else ''
updated_keys.write(line)
# Write the Google authorized key entries at the end of the file.
# Each entry is preceded by '# Added by Google'.
for ssh_key in ssh_keys:
ssh_key += '\n' if not ssh_key.endswith('\n') else ''
updated_keys.write('%s\n' % self.google_comment)
updated_keys.write(ssh_key)
# Write buffered data to the updated keys file without closing it and
# update the Linux user's authorized keys file.
updated_keys.flush()
shutil.copy(updated_keys_file, authorized_keys_file)
file_utils.SetPermissions(
authorized_keys_file, mode=0o600, uid=uid, gid=gid)
|
[
"def",
"_UpdateAuthorizedKeys",
"(",
"self",
",",
"user",
",",
"ssh_keys",
")",
":",
"pw_entry",
"=",
"self",
".",
"_GetUser",
"(",
"user",
")",
"if",
"not",
"pw_entry",
":",
"return",
"uid",
"=",
"pw_entry",
".",
"pw_uid",
"gid",
"=",
"pw_entry",
".",
"pw_gid",
"home_dir",
"=",
"pw_entry",
".",
"pw_dir",
"ssh_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home_dir",
",",
"'.ssh'",
")",
"# Not all sshd's support multiple authorized_keys files so we have to",
"# share one with the user. We add each of our entries as follows:",
"# # Added by Google",
"# authorized_key_entry",
"authorized_keys_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ssh_dir",
",",
"'authorized_keys'",
")",
"# Do not write to the authorized keys file if it is a symlink.",
"if",
"os",
".",
"path",
".",
"islink",
"(",
"ssh_dir",
")",
"or",
"os",
".",
"path",
".",
"islink",
"(",
"authorized_keys_file",
")",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Not updating authorized keys for user %s. File is a symlink.'",
",",
"user",
")",
"return",
"# Create home directory if it does not exist. This can happen if _GetUser",
"# (getpwnam) returns non-local user info (e.g., from LDAP).",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"home_dir",
")",
":",
"file_utils",
".",
"SetPermissions",
"(",
"home_dir",
",",
"mode",
"=",
"0o755",
",",
"uid",
"=",
"uid",
",",
"gid",
"=",
"gid",
",",
"mkdir",
"=",
"True",
")",
"# Create ssh directory if it does not exist.",
"file_utils",
".",
"SetPermissions",
"(",
"ssh_dir",
",",
"mode",
"=",
"0o700",
",",
"uid",
"=",
"uid",
",",
"gid",
"=",
"gid",
",",
"mkdir",
"=",
"True",
")",
"# Create entry in the authorized keys file.",
"prefix",
"=",
"self",
".",
"logger",
".",
"name",
"+",
"'-'",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w'",
",",
"prefix",
"=",
"prefix",
",",
"delete",
"=",
"True",
")",
"as",
"updated_keys",
":",
"updated_keys_file",
"=",
"updated_keys",
".",
"name",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"authorized_keys_file",
")",
":",
"lines",
"=",
"open",
"(",
"authorized_keys_file",
")",
".",
"readlines",
"(",
")",
"else",
":",
"lines",
"=",
"[",
"]",
"google_lines",
"=",
"set",
"(",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"self",
".",
"google_comment",
")",
":",
"google_lines",
".",
"update",
"(",
"[",
"i",
",",
"i",
"+",
"1",
"]",
")",
"# Write user's authorized key entries.",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"if",
"i",
"not",
"in",
"google_lines",
"and",
"line",
":",
"line",
"+=",
"'\\n'",
"if",
"not",
"line",
".",
"endswith",
"(",
"'\\n'",
")",
"else",
"''",
"updated_keys",
".",
"write",
"(",
"line",
")",
"# Write the Google authorized key entries at the end of the file.",
"# Each entry is preceded by '# Added by Google'.",
"for",
"ssh_key",
"in",
"ssh_keys",
":",
"ssh_key",
"+=",
"'\\n'",
"if",
"not",
"ssh_key",
".",
"endswith",
"(",
"'\\n'",
")",
"else",
"''",
"updated_keys",
".",
"write",
"(",
"'%s\\n'",
"%",
"self",
".",
"google_comment",
")",
"updated_keys",
".",
"write",
"(",
"ssh_key",
")",
"# Write buffered data to the updated keys file without closing it and",
"# update the Linux user's authorized keys file.",
"updated_keys",
".",
"flush",
"(",
")",
"shutil",
".",
"copy",
"(",
"updated_keys_file",
",",
"authorized_keys_file",
")",
"file_utils",
".",
"SetPermissions",
"(",
"authorized_keys_file",
",",
"mode",
"=",
"0o600",
",",
"uid",
"=",
"uid",
",",
"gid",
"=",
"gid",
")"
] |
Update the authorized keys file for a Linux user with a list of SSH keys.
Args:
user: string, the name of the Linux user account.
ssh_keys: list, the SSH key strings associated with the user.
Raises:
IOError, raised when there is an exception updating a file.
OSError, raised when setting permissions or writing to a read-only
file system.
|
[
"Update",
"the",
"authorized",
"keys",
"file",
"for",
"a",
"Linux",
"user",
"with",
"a",
"list",
"of",
"SSH",
"keys",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L173-L249
|
234,481
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py
|
AccountsUtils._UpdateSudoer
|
def _UpdateSudoer(self, user, sudoer=False):
"""Update sudoer group membership for a Linux user account.
Args:
user: string, the name of the Linux user account.
sudoer: bool, True if the user should be a sudoer.
Returns:
bool, True if user update succeeded.
"""
if sudoer:
self.logger.info('Adding user %s to the Google sudoers group.', user)
command = self.gpasswd_add_cmd.format(
user=user, group=self.google_sudoers_group)
else:
self.logger.info('Removing user %s from the Google sudoers group.', user)
command = self.gpasswd_remove_cmd.format(
user=user, group=self.google_sudoers_group)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not update user %s. %s.', user, str(e))
return False
else:
self.logger.debug('Removed user %s from the Google sudoers group.', user)
return True
|
python
|
def _UpdateSudoer(self, user, sudoer=False):
"""Update sudoer group membership for a Linux user account.
Args:
user: string, the name of the Linux user account.
sudoer: bool, True if the user should be a sudoer.
Returns:
bool, True if user update succeeded.
"""
if sudoer:
self.logger.info('Adding user %s to the Google sudoers group.', user)
command = self.gpasswd_add_cmd.format(
user=user, group=self.google_sudoers_group)
else:
self.logger.info('Removing user %s from the Google sudoers group.', user)
command = self.gpasswd_remove_cmd.format(
user=user, group=self.google_sudoers_group)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not update user %s. %s.', user, str(e))
return False
else:
self.logger.debug('Removed user %s from the Google sudoers group.', user)
return True
|
[
"def",
"_UpdateSudoer",
"(",
"self",
",",
"user",
",",
"sudoer",
"=",
"False",
")",
":",
"if",
"sudoer",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Adding user %s to the Google sudoers group.'",
",",
"user",
")",
"command",
"=",
"self",
".",
"gpasswd_add_cmd",
".",
"format",
"(",
"user",
"=",
"user",
",",
"group",
"=",
"self",
".",
"google_sudoers_group",
")",
"else",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Removing user %s from the Google sudoers group.'",
",",
"user",
")",
"command",
"=",
"self",
".",
"gpasswd_remove_cmd",
".",
"format",
"(",
"user",
"=",
"user",
",",
"group",
"=",
"self",
".",
"google_sudoers_group",
")",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"command",
".",
"split",
"(",
"' '",
")",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Could not update user %s. %s.'",
",",
"user",
",",
"str",
"(",
"e",
")",
")",
"return",
"False",
"else",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Removed user %s from the Google sudoers group.'",
",",
"user",
")",
"return",
"True"
] |
Update sudoer group membership for a Linux user account.
Args:
user: string, the name of the Linux user account.
sudoer: bool, True if the user should be a sudoer.
Returns:
bool, True if user update succeeded.
|
[
"Update",
"sudoer",
"group",
"membership",
"for",
"a",
"Linux",
"user",
"account",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L251-L277
|
234,482
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py
|
AccountsUtils._RemoveAuthorizedKeys
|
def _RemoveAuthorizedKeys(self, user):
"""Remove a Linux user account's authorized keys file to prevent login.
Args:
user: string, the Linux user account to remove access.
"""
pw_entry = self._GetUser(user)
if not pw_entry:
return
home_dir = pw_entry.pw_dir
authorized_keys_file = os.path.join(home_dir, '.ssh', 'authorized_keys')
if os.path.exists(authorized_keys_file):
try:
os.remove(authorized_keys_file)
except OSError as e:
message = 'Could not remove authorized keys for user %s. %s.'
self.logger.warning(message, user, str(e))
|
python
|
def _RemoveAuthorizedKeys(self, user):
"""Remove a Linux user account's authorized keys file to prevent login.
Args:
user: string, the Linux user account to remove access.
"""
pw_entry = self._GetUser(user)
if not pw_entry:
return
home_dir = pw_entry.pw_dir
authorized_keys_file = os.path.join(home_dir, '.ssh', 'authorized_keys')
if os.path.exists(authorized_keys_file):
try:
os.remove(authorized_keys_file)
except OSError as e:
message = 'Could not remove authorized keys for user %s. %s.'
self.logger.warning(message, user, str(e))
|
[
"def",
"_RemoveAuthorizedKeys",
"(",
"self",
",",
"user",
")",
":",
"pw_entry",
"=",
"self",
".",
"_GetUser",
"(",
"user",
")",
"if",
"not",
"pw_entry",
":",
"return",
"home_dir",
"=",
"pw_entry",
".",
"pw_dir",
"authorized_keys_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home_dir",
",",
"'.ssh'",
",",
"'authorized_keys'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"authorized_keys_file",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"authorized_keys_file",
")",
"except",
"OSError",
"as",
"e",
":",
"message",
"=",
"'Could not remove authorized keys for user %s. %s.'",
"self",
".",
"logger",
".",
"warning",
"(",
"message",
",",
"user",
",",
"str",
"(",
"e",
")",
")"
] |
Remove a Linux user account's authorized keys file to prevent login.
Args:
user: string, the Linux user account to remove access.
|
[
"Remove",
"a",
"Linux",
"user",
"account",
"s",
"authorized",
"keys",
"file",
"to",
"prevent",
"login",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L279-L296
|
234,483
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py
|
AccountsUtils.GetConfiguredUsers
|
def GetConfiguredUsers(self):
"""Retrieve the list of configured Google user accounts.
Returns:
list, the username strings of users congfigured by Google.
"""
if os.path.exists(self.google_users_file):
users = open(self.google_users_file).readlines()
else:
users = []
return [user.strip() for user in users]
|
python
|
def GetConfiguredUsers(self):
"""Retrieve the list of configured Google user accounts.
Returns:
list, the username strings of users congfigured by Google.
"""
if os.path.exists(self.google_users_file):
users = open(self.google_users_file).readlines()
else:
users = []
return [user.strip() for user in users]
|
[
"def",
"GetConfiguredUsers",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"google_users_file",
")",
":",
"users",
"=",
"open",
"(",
"self",
".",
"google_users_file",
")",
".",
"readlines",
"(",
")",
"else",
":",
"users",
"=",
"[",
"]",
"return",
"[",
"user",
".",
"strip",
"(",
")",
"for",
"user",
"in",
"users",
"]"
] |
Retrieve the list of configured Google user accounts.
Returns:
list, the username strings of users congfigured by Google.
|
[
"Retrieve",
"the",
"list",
"of",
"configured",
"Google",
"user",
"accounts",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L298-L308
|
234,484
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py
|
AccountsUtils.SetConfiguredUsers
|
def SetConfiguredUsers(self, users):
"""Set the list of configured Google user accounts.
Args:
users: list, the username strings of the Linux accounts.
"""
prefix = self.logger.name + '-'
with tempfile.NamedTemporaryFile(
mode='w', prefix=prefix, delete=True) as updated_users:
updated_users_file = updated_users.name
for user in users:
updated_users.write(user + '\n')
updated_users.flush()
if not os.path.exists(self.google_users_dir):
os.makedirs(self.google_users_dir)
shutil.copy(updated_users_file, self.google_users_file)
file_utils.SetPermissions(self.google_users_file, mode=0o600, uid=0, gid=0)
|
python
|
def SetConfiguredUsers(self, users):
"""Set the list of configured Google user accounts.
Args:
users: list, the username strings of the Linux accounts.
"""
prefix = self.logger.name + '-'
with tempfile.NamedTemporaryFile(
mode='w', prefix=prefix, delete=True) as updated_users:
updated_users_file = updated_users.name
for user in users:
updated_users.write(user + '\n')
updated_users.flush()
if not os.path.exists(self.google_users_dir):
os.makedirs(self.google_users_dir)
shutil.copy(updated_users_file, self.google_users_file)
file_utils.SetPermissions(self.google_users_file, mode=0o600, uid=0, gid=0)
|
[
"def",
"SetConfiguredUsers",
"(",
"self",
",",
"users",
")",
":",
"prefix",
"=",
"self",
".",
"logger",
".",
"name",
"+",
"'-'",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"'w'",
",",
"prefix",
"=",
"prefix",
",",
"delete",
"=",
"True",
")",
"as",
"updated_users",
":",
"updated_users_file",
"=",
"updated_users",
".",
"name",
"for",
"user",
"in",
"users",
":",
"updated_users",
".",
"write",
"(",
"user",
"+",
"'\\n'",
")",
"updated_users",
".",
"flush",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"google_users_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"google_users_dir",
")",
"shutil",
".",
"copy",
"(",
"updated_users_file",
",",
"self",
".",
"google_users_file",
")",
"file_utils",
".",
"SetPermissions",
"(",
"self",
".",
"google_users_file",
",",
"mode",
"=",
"0o600",
",",
"uid",
"=",
"0",
",",
"gid",
"=",
"0",
")"
] |
Set the list of configured Google user accounts.
Args:
users: list, the username strings of the Linux accounts.
|
[
"Set",
"the",
"list",
"of",
"configured",
"Google",
"user",
"accounts",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L310-L327
|
234,485
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py
|
AccountsUtils.UpdateUser
|
def UpdateUser(self, user, ssh_keys):
"""Update a Linux user with authorized SSH keys.
Args:
user: string, the name of the Linux user account.
ssh_keys: list, the SSH key strings associated with the user.
Returns:
bool, True if the user account updated successfully.
"""
if not bool(USER_REGEX.match(user)):
self.logger.warning('Invalid user account name %s.', user)
return False
if not self._GetUser(user):
# User does not exist. Attempt to create the user and add them to the
# appropriate user groups.
if not (self._AddUser(user)
and self._UpdateUserGroups(user, self.groups)):
return False
# Add the user to the google sudoers group.
if not self._UpdateSudoer(user, sudoer=True):
return False
# Don't try to manage account SSH keys with a shell set to disable
# logins. This helps avoid problems caused by operator and root sharing
# a home directory in CentOS and RHEL.
pw_entry = self._GetUser(user)
if pw_entry and os.path.basename(pw_entry.pw_shell) == 'nologin':
message = 'Not updating user %s. User set `nologin` as login shell.'
self.logger.debug(message, user)
return True
try:
self._UpdateAuthorizedKeys(user, ssh_keys)
except (IOError, OSError) as e:
message = 'Could not update the authorized keys file for user %s. %s.'
self.logger.warning(message, user, str(e))
return False
else:
return True
|
python
|
def UpdateUser(self, user, ssh_keys):
"""Update a Linux user with authorized SSH keys.
Args:
user: string, the name of the Linux user account.
ssh_keys: list, the SSH key strings associated with the user.
Returns:
bool, True if the user account updated successfully.
"""
if not bool(USER_REGEX.match(user)):
self.logger.warning('Invalid user account name %s.', user)
return False
if not self._GetUser(user):
# User does not exist. Attempt to create the user and add them to the
# appropriate user groups.
if not (self._AddUser(user)
and self._UpdateUserGroups(user, self.groups)):
return False
# Add the user to the google sudoers group.
if not self._UpdateSudoer(user, sudoer=True):
return False
# Don't try to manage account SSH keys with a shell set to disable
# logins. This helps avoid problems caused by operator and root sharing
# a home directory in CentOS and RHEL.
pw_entry = self._GetUser(user)
if pw_entry and os.path.basename(pw_entry.pw_shell) == 'nologin':
message = 'Not updating user %s. User set `nologin` as login shell.'
self.logger.debug(message, user)
return True
try:
self._UpdateAuthorizedKeys(user, ssh_keys)
except (IOError, OSError) as e:
message = 'Could not update the authorized keys file for user %s. %s.'
self.logger.warning(message, user, str(e))
return False
else:
return True
|
[
"def",
"UpdateUser",
"(",
"self",
",",
"user",
",",
"ssh_keys",
")",
":",
"if",
"not",
"bool",
"(",
"USER_REGEX",
".",
"match",
"(",
"user",
")",
")",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Invalid user account name %s.'",
",",
"user",
")",
"return",
"False",
"if",
"not",
"self",
".",
"_GetUser",
"(",
"user",
")",
":",
"# User does not exist. Attempt to create the user and add them to the",
"# appropriate user groups.",
"if",
"not",
"(",
"self",
".",
"_AddUser",
"(",
"user",
")",
"and",
"self",
".",
"_UpdateUserGroups",
"(",
"user",
",",
"self",
".",
"groups",
")",
")",
":",
"return",
"False",
"# Add the user to the google sudoers group.",
"if",
"not",
"self",
".",
"_UpdateSudoer",
"(",
"user",
",",
"sudoer",
"=",
"True",
")",
":",
"return",
"False",
"# Don't try to manage account SSH keys with a shell set to disable",
"# logins. This helps avoid problems caused by operator and root sharing",
"# a home directory in CentOS and RHEL.",
"pw_entry",
"=",
"self",
".",
"_GetUser",
"(",
"user",
")",
"if",
"pw_entry",
"and",
"os",
".",
"path",
".",
"basename",
"(",
"pw_entry",
".",
"pw_shell",
")",
"==",
"'nologin'",
":",
"message",
"=",
"'Not updating user %s. User set `nologin` as login shell.'",
"self",
".",
"logger",
".",
"debug",
"(",
"message",
",",
"user",
")",
"return",
"True",
"try",
":",
"self",
".",
"_UpdateAuthorizedKeys",
"(",
"user",
",",
"ssh_keys",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
"as",
"e",
":",
"message",
"=",
"'Could not update the authorized keys file for user %s. %s.'",
"self",
".",
"logger",
".",
"warning",
"(",
"message",
",",
"user",
",",
"str",
"(",
"e",
")",
")",
"return",
"False",
"else",
":",
"return",
"True"
] |
Update a Linux user with authorized SSH keys.
Args:
user: string, the name of the Linux user account.
ssh_keys: list, the SSH key strings associated with the user.
Returns:
bool, True if the user account updated successfully.
|
[
"Update",
"a",
"Linux",
"user",
"with",
"authorized",
"SSH",
"keys",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L329-L368
|
234,486
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py
|
AccountsUtils.RemoveUser
|
def RemoveUser(self, user):
"""Remove a Linux user account.
Args:
user: string, the Linux user account to remove.
"""
self.logger.info('Removing user %s.', user)
if self.remove:
command = self.userdel_cmd.format(user=user)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not remove user %s. %s.', user, str(e))
else:
self.logger.info('Removed user account %s.', user)
self._RemoveAuthorizedKeys(user)
self._UpdateSudoer(user, sudoer=False)
|
python
|
def RemoveUser(self, user):
"""Remove a Linux user account.
Args:
user: string, the Linux user account to remove.
"""
self.logger.info('Removing user %s.', user)
if self.remove:
command = self.userdel_cmd.format(user=user)
try:
subprocess.check_call(command.split(' '))
except subprocess.CalledProcessError as e:
self.logger.warning('Could not remove user %s. %s.', user, str(e))
else:
self.logger.info('Removed user account %s.', user)
self._RemoveAuthorizedKeys(user)
self._UpdateSudoer(user, sudoer=False)
|
[
"def",
"RemoveUser",
"(",
"self",
",",
"user",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Removing user %s.'",
",",
"user",
")",
"if",
"self",
".",
"remove",
":",
"command",
"=",
"self",
".",
"userdel_cmd",
".",
"format",
"(",
"user",
"=",
"user",
")",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"command",
".",
"split",
"(",
"' '",
")",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Could not remove user %s. %s.'",
",",
"user",
",",
"str",
"(",
"e",
")",
")",
"else",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Removed user account %s.'",
",",
"user",
")",
"self",
".",
"_RemoveAuthorizedKeys",
"(",
"user",
")",
"self",
".",
"_UpdateSudoer",
"(",
"user",
",",
"sudoer",
"=",
"False",
")"
] |
Remove a Linux user account.
Args:
user: string, the Linux user account to remove.
|
[
"Remove",
"a",
"Linux",
"user",
"account",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/accounts_utils.py#L370-L386
|
234,487
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py
|
OsLoginUtils._RunOsLoginControl
|
def _RunOsLoginControl(self, params):
"""Run the OS Login control script.
Args:
params: list, the params to pass to the script
Returns:
int, the return code from the call, or None if the script is not found.
"""
try:
return subprocess.call([constants.OSLOGIN_CONTROL_SCRIPT] + params)
except OSError as e:
if e.errno == errno.ENOENT:
return None
else:
raise
|
python
|
def _RunOsLoginControl(self, params):
"""Run the OS Login control script.
Args:
params: list, the params to pass to the script
Returns:
int, the return code from the call, or None if the script is not found.
"""
try:
return subprocess.call([constants.OSLOGIN_CONTROL_SCRIPT] + params)
except OSError as e:
if e.errno == errno.ENOENT:
return None
else:
raise
|
[
"def",
"_RunOsLoginControl",
"(",
"self",
",",
"params",
")",
":",
"try",
":",
"return",
"subprocess",
".",
"call",
"(",
"[",
"constants",
".",
"OSLOGIN_CONTROL_SCRIPT",
"]",
"+",
"params",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"return",
"None",
"else",
":",
"raise"
] |
Run the OS Login control script.
Args:
params: list, the params to pass to the script
Returns:
int, the return code from the call, or None if the script is not found.
|
[
"Run",
"the",
"OS",
"Login",
"control",
"script",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py#L41-L56
|
234,488
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py
|
OsLoginUtils._GetStatus
|
def _GetStatus(self, two_factor=False):
"""Check whether OS Login is installed.
Args:
two_factor: bool, True if two factor should be enabled.
Returns:
bool, True if OS Login is installed.
"""
params = ['status']
if two_factor:
params += ['--twofactor']
retcode = self._RunOsLoginControl(params)
if retcode is None:
if self.oslogin_installed:
self.logger.warning('OS Login not installed.')
self.oslogin_installed = False
return None
# Prevent log spam when OS Login is not installed.
self.oslogin_installed = True
if not os.path.exists(constants.OSLOGIN_NSS_CACHE):
return False
return not retcode
|
python
|
def _GetStatus(self, two_factor=False):
"""Check whether OS Login is installed.
Args:
two_factor: bool, True if two factor should be enabled.
Returns:
bool, True if OS Login is installed.
"""
params = ['status']
if two_factor:
params += ['--twofactor']
retcode = self._RunOsLoginControl(params)
if retcode is None:
if self.oslogin_installed:
self.logger.warning('OS Login not installed.')
self.oslogin_installed = False
return None
# Prevent log spam when OS Login is not installed.
self.oslogin_installed = True
if not os.path.exists(constants.OSLOGIN_NSS_CACHE):
return False
return not retcode
|
[
"def",
"_GetStatus",
"(",
"self",
",",
"two_factor",
"=",
"False",
")",
":",
"params",
"=",
"[",
"'status'",
"]",
"if",
"two_factor",
":",
"params",
"+=",
"[",
"'--twofactor'",
"]",
"retcode",
"=",
"self",
".",
"_RunOsLoginControl",
"(",
"params",
")",
"if",
"retcode",
"is",
"None",
":",
"if",
"self",
".",
"oslogin_installed",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'OS Login not installed.'",
")",
"self",
".",
"oslogin_installed",
"=",
"False",
"return",
"None",
"# Prevent log spam when OS Login is not installed.",
"self",
".",
"oslogin_installed",
"=",
"True",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"constants",
".",
"OSLOGIN_NSS_CACHE",
")",
":",
"return",
"False",
"return",
"not",
"retcode"
] |
Check whether OS Login is installed.
Args:
two_factor: bool, True if two factor should be enabled.
Returns:
bool, True if OS Login is installed.
|
[
"Check",
"whether",
"OS",
"Login",
"is",
"installed",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py#L58-L81
|
234,489
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py
|
OsLoginUtils._RunOsLoginNssCache
|
def _RunOsLoginNssCache(self):
"""Run the OS Login NSS cache binary.
Returns:
int, the return code from the call, or None if the script is not found.
"""
try:
return subprocess.call([constants.OSLOGIN_NSS_CACHE_SCRIPT])
except OSError as e:
if e.errno == errno.ENOENT:
return None
else:
raise
|
python
|
def _RunOsLoginNssCache(self):
"""Run the OS Login NSS cache binary.
Returns:
int, the return code from the call, or None if the script is not found.
"""
try:
return subprocess.call([constants.OSLOGIN_NSS_CACHE_SCRIPT])
except OSError as e:
if e.errno == errno.ENOENT:
return None
else:
raise
|
[
"def",
"_RunOsLoginNssCache",
"(",
"self",
")",
":",
"try",
":",
"return",
"subprocess",
".",
"call",
"(",
"[",
"constants",
".",
"OSLOGIN_NSS_CACHE_SCRIPT",
"]",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"return",
"None",
"else",
":",
"raise"
] |
Run the OS Login NSS cache binary.
Returns:
int, the return code from the call, or None if the script is not found.
|
[
"Run",
"the",
"OS",
"Login",
"NSS",
"cache",
"binary",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py#L83-L95
|
234,490
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py
|
OsLoginUtils._RemoveOsLoginNssCache
|
def _RemoveOsLoginNssCache(self):
"""Remove the OS Login NSS cache file."""
if os.path.exists(constants.OSLOGIN_NSS_CACHE):
try:
os.remove(constants.OSLOGIN_NSS_CACHE)
except OSError as e:
if e.errno != errno.ENOENT:
raise
|
python
|
def _RemoveOsLoginNssCache(self):
"""Remove the OS Login NSS cache file."""
if os.path.exists(constants.OSLOGIN_NSS_CACHE):
try:
os.remove(constants.OSLOGIN_NSS_CACHE)
except OSError as e:
if e.errno != errno.ENOENT:
raise
|
[
"def",
"_RemoveOsLoginNssCache",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"constants",
".",
"OSLOGIN_NSS_CACHE",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"constants",
".",
"OSLOGIN_NSS_CACHE",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise"
] |
Remove the OS Login NSS cache file.
|
[
"Remove",
"the",
"OS",
"Login",
"NSS",
"cache",
"file",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py#L97-L104
|
234,491
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py
|
OsLoginUtils.UpdateOsLogin
|
def UpdateOsLogin(self, oslogin_desired, two_factor_desired=False):
"""Update whether OS Login is enabled and update NSS cache if necessary.
Args:
oslogin_desired: bool, enable OS Login if True, disable if False.
two_factor_desired: bool, enable two factor if True, disable if False.
Returns:
int, the return code from updating OS Login, or None if not present.
"""
oslogin_configured = self._GetStatus(two_factor=False)
if oslogin_configured is None:
return None
two_factor_configured = self._GetStatus(two_factor=True)
# Two factor can only be enabled when OS Login is enabled.
two_factor_desired = two_factor_desired and oslogin_desired
if oslogin_desired:
params = ['activate']
if two_factor_desired:
params += ['--twofactor']
# OS Login is desired and not enabled.
if not oslogin_configured:
self.logger.info('Activating OS Login.')
return self._RunOsLoginControl(params) or self._RunOsLoginNssCache()
# Enable two factor authentication.
if two_factor_desired and not two_factor_configured:
self.logger.info('Activating OS Login two factor authentication.')
return self._RunOsLoginControl(params) or self._RunOsLoginNssCache()
# Deactivate two factor authentication.
if two_factor_configured and not two_factor_desired:
self.logger.info('Reactivating OS Login with two factor disabled.')
return (self._RunOsLoginControl(['deactivate'])
or self._RunOsLoginControl(params))
# OS Login features are already enabled. Update the cache if appropriate.
current_time = time.time()
if current_time - self.update_time > NSS_CACHE_DURATION_SEC:
self.update_time = current_time
return self._RunOsLoginNssCache()
elif oslogin_configured:
self.logger.info('Deactivating OS Login.')
return (self._RunOsLoginControl(['deactivate'])
or self._RemoveOsLoginNssCache())
# No action was needed.
return 0
|
python
|
def UpdateOsLogin(self, oslogin_desired, two_factor_desired=False):
"""Update whether OS Login is enabled and update NSS cache if necessary.
Args:
oslogin_desired: bool, enable OS Login if True, disable if False.
two_factor_desired: bool, enable two factor if True, disable if False.
Returns:
int, the return code from updating OS Login, or None if not present.
"""
oslogin_configured = self._GetStatus(two_factor=False)
if oslogin_configured is None:
return None
two_factor_configured = self._GetStatus(two_factor=True)
# Two factor can only be enabled when OS Login is enabled.
two_factor_desired = two_factor_desired and oslogin_desired
if oslogin_desired:
params = ['activate']
if two_factor_desired:
params += ['--twofactor']
# OS Login is desired and not enabled.
if not oslogin_configured:
self.logger.info('Activating OS Login.')
return self._RunOsLoginControl(params) or self._RunOsLoginNssCache()
# Enable two factor authentication.
if two_factor_desired and not two_factor_configured:
self.logger.info('Activating OS Login two factor authentication.')
return self._RunOsLoginControl(params) or self._RunOsLoginNssCache()
# Deactivate two factor authentication.
if two_factor_configured and not two_factor_desired:
self.logger.info('Reactivating OS Login with two factor disabled.')
return (self._RunOsLoginControl(['deactivate'])
or self._RunOsLoginControl(params))
# OS Login features are already enabled. Update the cache if appropriate.
current_time = time.time()
if current_time - self.update_time > NSS_CACHE_DURATION_SEC:
self.update_time = current_time
return self._RunOsLoginNssCache()
elif oslogin_configured:
self.logger.info('Deactivating OS Login.')
return (self._RunOsLoginControl(['deactivate'])
or self._RemoveOsLoginNssCache())
# No action was needed.
return 0
|
[
"def",
"UpdateOsLogin",
"(",
"self",
",",
"oslogin_desired",
",",
"two_factor_desired",
"=",
"False",
")",
":",
"oslogin_configured",
"=",
"self",
".",
"_GetStatus",
"(",
"two_factor",
"=",
"False",
")",
"if",
"oslogin_configured",
"is",
"None",
":",
"return",
"None",
"two_factor_configured",
"=",
"self",
".",
"_GetStatus",
"(",
"two_factor",
"=",
"True",
")",
"# Two factor can only be enabled when OS Login is enabled.",
"two_factor_desired",
"=",
"two_factor_desired",
"and",
"oslogin_desired",
"if",
"oslogin_desired",
":",
"params",
"=",
"[",
"'activate'",
"]",
"if",
"two_factor_desired",
":",
"params",
"+=",
"[",
"'--twofactor'",
"]",
"# OS Login is desired and not enabled.",
"if",
"not",
"oslogin_configured",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Activating OS Login.'",
")",
"return",
"self",
".",
"_RunOsLoginControl",
"(",
"params",
")",
"or",
"self",
".",
"_RunOsLoginNssCache",
"(",
")",
"# Enable two factor authentication.",
"if",
"two_factor_desired",
"and",
"not",
"two_factor_configured",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Activating OS Login two factor authentication.'",
")",
"return",
"self",
".",
"_RunOsLoginControl",
"(",
"params",
")",
"or",
"self",
".",
"_RunOsLoginNssCache",
"(",
")",
"# Deactivate two factor authentication.",
"if",
"two_factor_configured",
"and",
"not",
"two_factor_desired",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Reactivating OS Login with two factor disabled.'",
")",
"return",
"(",
"self",
".",
"_RunOsLoginControl",
"(",
"[",
"'deactivate'",
"]",
")",
"or",
"self",
".",
"_RunOsLoginControl",
"(",
"params",
")",
")",
"# OS Login features are already enabled. Update the cache if appropriate.",
"current_time",
"=",
"time",
".",
"time",
"(",
")",
"if",
"current_time",
"-",
"self",
".",
"update_time",
">",
"NSS_CACHE_DURATION_SEC",
":",
"self",
".",
"update_time",
"=",
"current_time",
"return",
"self",
".",
"_RunOsLoginNssCache",
"(",
")",
"elif",
"oslogin_configured",
":",
"self",
".",
"logger",
".",
"info",
"(",
"'Deactivating OS Login.'",
")",
"return",
"(",
"self",
".",
"_RunOsLoginControl",
"(",
"[",
"'deactivate'",
"]",
")",
"or",
"self",
".",
"_RemoveOsLoginNssCache",
"(",
")",
")",
"# No action was needed.",
"return",
"0"
] |
Update whether OS Login is enabled and update NSS cache if necessary.
Args:
oslogin_desired: bool, enable OS Login if True, disable if False.
two_factor_desired: bool, enable two factor if True, disable if False.
Returns:
int, the return code from updating OS Login, or None if not present.
|
[
"Update",
"whether",
"OS",
"Login",
"is",
"enabled",
"and",
"update",
"NSS",
"cache",
"if",
"necessary",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/accounts/oslogin_utils.py#L106-L152
|
234,492
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/distro_lib/helpers.py
|
CallDhclient
|
def CallDhclient(
interfaces, logger, dhclient_script=None):
"""Configure the network interfaces using dhclient.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
dhclient_script: string, the path to a dhclient script used by dhclient.
"""
logger.info('Enabling the Ethernet interfaces %s.', interfaces)
dhclient_command = ['dhclient']
if dhclient_script and os.path.exists(dhclient_script):
dhclient_command += ['-sf', dhclient_script]
try:
subprocess.check_call(dhclient_command + ['-x'] + interfaces)
subprocess.check_call(dhclient_command + interfaces)
except subprocess.CalledProcessError:
logger.warning('Could not enable interfaces %s.', interfaces)
|
python
|
def CallDhclient(
interfaces, logger, dhclient_script=None):
"""Configure the network interfaces using dhclient.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
dhclient_script: string, the path to a dhclient script used by dhclient.
"""
logger.info('Enabling the Ethernet interfaces %s.', interfaces)
dhclient_command = ['dhclient']
if dhclient_script and os.path.exists(dhclient_script):
dhclient_command += ['-sf', dhclient_script]
try:
subprocess.check_call(dhclient_command + ['-x'] + interfaces)
subprocess.check_call(dhclient_command + interfaces)
except subprocess.CalledProcessError:
logger.warning('Could not enable interfaces %s.', interfaces)
|
[
"def",
"CallDhclient",
"(",
"interfaces",
",",
"logger",
",",
"dhclient_script",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"'Enabling the Ethernet interfaces %s.'",
",",
"interfaces",
")",
"dhclient_command",
"=",
"[",
"'dhclient'",
"]",
"if",
"dhclient_script",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"dhclient_script",
")",
":",
"dhclient_command",
"+=",
"[",
"'-sf'",
",",
"dhclient_script",
"]",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"dhclient_command",
"+",
"[",
"'-x'",
"]",
"+",
"interfaces",
")",
"subprocess",
".",
"check_call",
"(",
"dhclient_command",
"+",
"interfaces",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"logger",
".",
"warning",
"(",
"'Could not enable interfaces %s.'",
",",
"interfaces",
")"
] |
Configure the network interfaces using dhclient.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
dhclient_script: string, the path to a dhclient script used by dhclient.
|
[
"Configure",
"the",
"network",
"interfaces",
"using",
"dhclient",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/helpers.py#L22-L42
|
234,493
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/distro_lib/helpers.py
|
CallHwclock
|
def CallHwclock(logger):
"""Sync clock using hwclock.
Args:
logger: logger object, used to write to SysLog and serial port.
"""
command = ['/sbin/hwclock', '--hctosys']
try:
subprocess.check_call(command)
except subprocess.CalledProcessError:
logger.warning('Failed to sync system time with hardware clock.')
else:
logger.info('Synced system time with hardware clock.')
|
python
|
def CallHwclock(logger):
"""Sync clock using hwclock.
Args:
logger: logger object, used to write to SysLog and serial port.
"""
command = ['/sbin/hwclock', '--hctosys']
try:
subprocess.check_call(command)
except subprocess.CalledProcessError:
logger.warning('Failed to sync system time with hardware clock.')
else:
logger.info('Synced system time with hardware clock.')
|
[
"def",
"CallHwclock",
"(",
"logger",
")",
":",
"command",
"=",
"[",
"'/sbin/hwclock'",
",",
"'--hctosys'",
"]",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"command",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"logger",
".",
"warning",
"(",
"'Failed to sync system time with hardware clock.'",
")",
"else",
":",
"logger",
".",
"info",
"(",
"'Synced system time with hardware clock.'",
")"
] |
Sync clock using hwclock.
Args:
logger: logger object, used to write to SysLog and serial port.
|
[
"Sync",
"clock",
"using",
"hwclock",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/helpers.py#L45-L57
|
234,494
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/distro_lib/helpers.py
|
CallNtpdate
|
def CallNtpdate(logger):
"""Sync clock using ntpdate.
Args:
logger: logger object, used to write to SysLog and serial port.
"""
ntpd_inactive = subprocess.call(['service', 'ntpd', 'status'])
try:
if not ntpd_inactive:
subprocess.check_call(['service', 'ntpd', 'stop'])
subprocess.check_call(
'ntpdate `awk \'$1=="server" {print $2}\' /etc/ntp.conf`', shell=True)
if not ntpd_inactive:
subprocess.check_call(['service', 'ntpd', 'start'])
except subprocess.CalledProcessError:
logger.warning('Failed to sync system time with ntp server.')
else:
logger.info('Synced system time with ntp server.')
|
python
|
def CallNtpdate(logger):
"""Sync clock using ntpdate.
Args:
logger: logger object, used to write to SysLog and serial port.
"""
ntpd_inactive = subprocess.call(['service', 'ntpd', 'status'])
try:
if not ntpd_inactive:
subprocess.check_call(['service', 'ntpd', 'stop'])
subprocess.check_call(
'ntpdate `awk \'$1=="server" {print $2}\' /etc/ntp.conf`', shell=True)
if not ntpd_inactive:
subprocess.check_call(['service', 'ntpd', 'start'])
except subprocess.CalledProcessError:
logger.warning('Failed to sync system time with ntp server.')
else:
logger.info('Synced system time with ntp server.')
|
[
"def",
"CallNtpdate",
"(",
"logger",
")",
":",
"ntpd_inactive",
"=",
"subprocess",
".",
"call",
"(",
"[",
"'service'",
",",
"'ntpd'",
",",
"'status'",
"]",
")",
"try",
":",
"if",
"not",
"ntpd_inactive",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"'service'",
",",
"'ntpd'",
",",
"'stop'",
"]",
")",
"subprocess",
".",
"check_call",
"(",
"'ntpdate `awk \\'$1==\"server\" {print $2}\\' /etc/ntp.conf`'",
",",
"shell",
"=",
"True",
")",
"if",
"not",
"ntpd_inactive",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"'service'",
",",
"'ntpd'",
",",
"'start'",
"]",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"logger",
".",
"warning",
"(",
"'Failed to sync system time with ntp server.'",
")",
"else",
":",
"logger",
".",
"info",
"(",
"'Synced system time with ntp server.'",
")"
] |
Sync clock using ntpdate.
Args:
logger: logger object, used to write to SysLog and serial port.
|
[
"Sync",
"clock",
"using",
"ntpdate",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/helpers.py#L60-L77
|
234,495
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/boto/boto_config.py
|
BotoConfig._GetNumericProjectId
|
def _GetNumericProjectId(self):
"""Get the numeric project ID for this VM.
Returns:
string, the numeric project ID if one is found.
"""
project_id = 'project/numeric-project-id'
return self.watcher.GetMetadata(metadata_key=project_id, recursive=False)
|
python
|
def _GetNumericProjectId(self):
"""Get the numeric project ID for this VM.
Returns:
string, the numeric project ID if one is found.
"""
project_id = 'project/numeric-project-id'
return self.watcher.GetMetadata(metadata_key=project_id, recursive=False)
|
[
"def",
"_GetNumericProjectId",
"(",
"self",
")",
":",
"project_id",
"=",
"'project/numeric-project-id'",
"return",
"self",
".",
"watcher",
".",
"GetMetadata",
"(",
"metadata_key",
"=",
"project_id",
",",
"recursive",
"=",
"False",
")"
] |
Get the numeric project ID for this VM.
Returns:
string, the numeric project ID if one is found.
|
[
"Get",
"the",
"numeric",
"project",
"ID",
"for",
"this",
"VM",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/boto/boto_config.py#L57-L64
|
234,496
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/boto/boto_config.py
|
BotoConfig._CreateConfig
|
def _CreateConfig(self, project_id):
"""Create the boto config to support standalone GSUtil.
Args:
project_id: string, the project ID to use in the config file.
"""
project_id = project_id or self._GetNumericProjectId()
# Our project doesn't support service accounts.
if not project_id:
return
self.boto_config_header %= (
self.boto_config_script, self.boto_config_template)
config = config_manager.ConfigManager(
config_file=self.boto_config_template,
config_header=self.boto_config_header)
boto_dir = os.path.dirname(self.boto_config_script)
config.SetOption('GSUtil', 'default_project_id', project_id)
config.SetOption('GSUtil', 'default_api_version', '2')
config.SetOption('GoogleCompute', 'service_account', 'default')
config.SetOption('Plugin', 'plugin_directory', boto_dir)
config.WriteConfig(config_file=self.boto_config)
|
python
|
def _CreateConfig(self, project_id):
"""Create the boto config to support standalone GSUtil.
Args:
project_id: string, the project ID to use in the config file.
"""
project_id = project_id or self._GetNumericProjectId()
# Our project doesn't support service accounts.
if not project_id:
return
self.boto_config_header %= (
self.boto_config_script, self.boto_config_template)
config = config_manager.ConfigManager(
config_file=self.boto_config_template,
config_header=self.boto_config_header)
boto_dir = os.path.dirname(self.boto_config_script)
config.SetOption('GSUtil', 'default_project_id', project_id)
config.SetOption('GSUtil', 'default_api_version', '2')
config.SetOption('GoogleCompute', 'service_account', 'default')
config.SetOption('Plugin', 'plugin_directory', boto_dir)
config.WriteConfig(config_file=self.boto_config)
|
[
"def",
"_CreateConfig",
"(",
"self",
",",
"project_id",
")",
":",
"project_id",
"=",
"project_id",
"or",
"self",
".",
"_GetNumericProjectId",
"(",
")",
"# Our project doesn't support service accounts.",
"if",
"not",
"project_id",
":",
"return",
"self",
".",
"boto_config_header",
"%=",
"(",
"self",
".",
"boto_config_script",
",",
"self",
".",
"boto_config_template",
")",
"config",
"=",
"config_manager",
".",
"ConfigManager",
"(",
"config_file",
"=",
"self",
".",
"boto_config_template",
",",
"config_header",
"=",
"self",
".",
"boto_config_header",
")",
"boto_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"boto_config_script",
")",
"config",
".",
"SetOption",
"(",
"'GSUtil'",
",",
"'default_project_id'",
",",
"project_id",
")",
"config",
".",
"SetOption",
"(",
"'GSUtil'",
",",
"'default_api_version'",
",",
"'2'",
")",
"config",
".",
"SetOption",
"(",
"'GoogleCompute'",
",",
"'service_account'",
",",
"'default'",
")",
"config",
".",
"SetOption",
"(",
"'Plugin'",
",",
"'plugin_directory'",
",",
"boto_dir",
")",
"config",
".",
"WriteConfig",
"(",
"config_file",
"=",
"self",
".",
"boto_config",
")"
] |
Create the boto config to support standalone GSUtil.
Args:
project_id: string, the project ID to use in the config file.
|
[
"Create",
"the",
"boto",
"config",
"to",
"support",
"standalone",
"GSUtil",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/boto/boto_config.py#L66-L89
|
234,497
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/distro_lib/ip_forwarding_utils.py
|
IpForwardingUtilsIproute._CreateRouteOptions
|
def _CreateRouteOptions(self, **kwargs):
"""Create a dictionary of parameters to append to the ip route command.
Args:
**kwargs: dict, the string parameters to update in the ip route command.
Returns:
dict, the string parameters to append to the ip route command.
"""
options = {
'proto': self.proto_id,
'scope': 'host',
}
options.update(kwargs)
return options
|
python
|
def _CreateRouteOptions(self, **kwargs):
"""Create a dictionary of parameters to append to the ip route command.
Args:
**kwargs: dict, the string parameters to update in the ip route command.
Returns:
dict, the string parameters to append to the ip route command.
"""
options = {
'proto': self.proto_id,
'scope': 'host',
}
options.update(kwargs)
return options
|
[
"def",
"_CreateRouteOptions",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"options",
"=",
"{",
"'proto'",
":",
"self",
".",
"proto_id",
",",
"'scope'",
":",
"'host'",
",",
"}",
"options",
".",
"update",
"(",
"kwargs",
")",
"return",
"options"
] |
Create a dictionary of parameters to append to the ip route command.
Args:
**kwargs: dict, the string parameters to update in the ip route command.
Returns:
dict, the string parameters to append to the ip route command.
|
[
"Create",
"a",
"dictionary",
"of",
"parameters",
"to",
"append",
"to",
"the",
"ip",
"route",
"command",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/ip_forwarding_utils.py#L97-L111
|
234,498
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/distro_lib/ip_forwarding_utils.py
|
IpForwardingUtilsIproute._RunIpRoute
|
def _RunIpRoute(self, args=None, options=None):
"""Run a command with ip route and return the response.
Args:
args: list, the string ip route command args to execute.
options: dict, the string parameters to append to the ip route command.
Returns:
string, the standard output from the ip route command execution.
"""
args = args or []
options = options or {}
command = ['ip', 'route']
command.extend(args)
for item in options.items():
command.extend(item)
try:
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
except OSError as e:
self.logger.warning('Exception running %s. %s.', command, str(e))
else:
if process.returncode:
message = 'Non-zero exit status running %s. %s.'
self.logger.warning(message, command, stderr.strip())
else:
return stdout.decode('utf-8', 'replace')
return ''
|
python
|
def _RunIpRoute(self, args=None, options=None):
"""Run a command with ip route and return the response.
Args:
args: list, the string ip route command args to execute.
options: dict, the string parameters to append to the ip route command.
Returns:
string, the standard output from the ip route command execution.
"""
args = args or []
options = options or {}
command = ['ip', 'route']
command.extend(args)
for item in options.items():
command.extend(item)
try:
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
except OSError as e:
self.logger.warning('Exception running %s. %s.', command, str(e))
else:
if process.returncode:
message = 'Non-zero exit status running %s. %s.'
self.logger.warning(message, command, stderr.strip())
else:
return stdout.decode('utf-8', 'replace')
return ''
|
[
"def",
"_RunIpRoute",
"(",
"self",
",",
"args",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"args",
"=",
"args",
"or",
"[",
"]",
"options",
"=",
"options",
"or",
"{",
"}",
"command",
"=",
"[",
"'ip'",
",",
"'route'",
"]",
"command",
".",
"extend",
"(",
"args",
")",
"for",
"item",
"in",
"options",
".",
"items",
"(",
")",
":",
"command",
".",
"extend",
"(",
"item",
")",
"try",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"stdout",
",",
"stderr",
"=",
"process",
".",
"communicate",
"(",
")",
"except",
"OSError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Exception running %s. %s.'",
",",
"command",
",",
"str",
"(",
"e",
")",
")",
"else",
":",
"if",
"process",
".",
"returncode",
":",
"message",
"=",
"'Non-zero exit status running %s. %s.'",
"self",
".",
"logger",
".",
"warning",
"(",
"message",
",",
"command",
",",
"stderr",
".",
"strip",
"(",
")",
")",
"else",
":",
"return",
"stdout",
".",
"decode",
"(",
"'utf-8'",
",",
"'replace'",
")",
"return",
"''"
] |
Run a command with ip route and return the response.
Args:
args: list, the string ip route command args to execute.
options: dict, the string parameters to append to the ip route command.
Returns:
string, the standard output from the ip route command execution.
|
[
"Run",
"a",
"command",
"with",
"ip",
"route",
"and",
"return",
"the",
"response",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/ip_forwarding_utils.py#L113-L141
|
234,499
|
GoogleCloudPlatform/compute-image-packages
|
packages/python-google-compute-engine/google_compute_engine/distro_lib/ip_forwarding_utils.py
|
IpForwardingUtilsIfconfig.RemoveForwardedIp
|
def RemoveForwardedIp(self, address, interface):
"""Delete an IP address on the network interface.
Args:
address: string, the IP address to configure.
interface: string, the output device to use.
"""
ip = netaddr.IPNetwork(address)
self._RunIfconfig(args=[interface, '-alias', str(ip.ip)])
|
python
|
def RemoveForwardedIp(self, address, interface):
"""Delete an IP address on the network interface.
Args:
address: string, the IP address to configure.
interface: string, the output device to use.
"""
ip = netaddr.IPNetwork(address)
self._RunIfconfig(args=[interface, '-alias', str(ip.ip)])
|
[
"def",
"RemoveForwardedIp",
"(",
"self",
",",
"address",
",",
"interface",
")",
":",
"ip",
"=",
"netaddr",
".",
"IPNetwork",
"(",
"address",
")",
"self",
".",
"_RunIfconfig",
"(",
"args",
"=",
"[",
"interface",
",",
"'-alias'",
",",
"str",
"(",
"ip",
".",
"ip",
")",
"]",
")"
] |
Delete an IP address on the network interface.
Args:
address: string, the IP address to configure.
interface: string, the output device to use.
|
[
"Delete",
"an",
"IP",
"address",
"on",
"the",
"network",
"interface",
"."
] |
53ea8cd069fb4d9a1984d1c167e54c133033f8da
|
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/distro_lib/ip_forwarding_utils.py#L294-L302
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.