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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
quantopian/trading_calendars | trading_calendars/trading_calendar.py | TradingCalendar.minutes_for_sessions_in_range | def minutes_for_sessions_in_range(self,
start_session_label,
end_session_label):
"""
Returns all the minutes for all the sessions from the given start
session label to the given end session label, inclusive.
Parameters
----------
start_session_label: pd.Timestamp
The label of the first session in the range.
end_session_label: pd.Timestamp
The label of the last session in the range.
Returns
-------
pd.DatetimeIndex
The minutes in the desired range.
"""
first_minute, _ = self.open_and_close_for_session(start_session_label)
_, last_minute = self.open_and_close_for_session(end_session_label)
return self.minutes_in_range(first_minute, last_minute) | python | def minutes_for_sessions_in_range(self,
start_session_label,
end_session_label):
"""
Returns all the minutes for all the sessions from the given start
session label to the given end session label, inclusive.
Parameters
----------
start_session_label: pd.Timestamp
The label of the first session in the range.
end_session_label: pd.Timestamp
The label of the last session in the range.
Returns
-------
pd.DatetimeIndex
The minutes in the desired range.
"""
first_minute, _ = self.open_and_close_for_session(start_session_label)
_, last_minute = self.open_and_close_for_session(end_session_label)
return self.minutes_in_range(first_minute, last_minute) | [
"def",
"minutes_for_sessions_in_range",
"(",
"self",
",",
"start_session_label",
",",
"end_session_label",
")",
":",
"first_minute",
",",
"_",
"=",
"self",
".",
"open_and_close_for_session",
"(",
"start_session_label",
")",
"_",
",",
"last_minute",
"=",
"self",
".",... | Returns all the minutes for all the sessions from the given start
session label to the given end session label, inclusive.
Parameters
----------
start_session_label: pd.Timestamp
The label of the first session in the range.
end_session_label: pd.Timestamp
The label of the last session in the range.
Returns
-------
pd.DatetimeIndex
The minutes in the desired range. | [
"Returns",
"all",
"the",
"minutes",
"for",
"all",
"the",
"sessions",
"from",
"the",
"given",
"start",
"session",
"label",
"to",
"the",
"given",
"end",
"session",
"label",
"inclusive",
"."
] | 951711c82c8a2875c09e96e2979faaf8734fb4df | https://github.com/quantopian/trading_calendars/blob/951711c82c8a2875c09e96e2979faaf8734fb4df/trading_calendars/trading_calendar.py#L713-L737 | train | 229,500 |
quantopian/trading_calendars | trading_calendars/trading_calendar.py | TradingCalendar.open_and_close_for_session | def open_and_close_for_session(self, session_label):
"""
Returns a tuple of timestamps of the open and close of the session
represented by the given label.
Parameters
----------
session_label: pd.Timestamp
The session whose open and close are desired.
Returns
-------
(Timestamp, Timestamp)
The open and close for the given session.
"""
sched = self.schedule
# `market_open` and `market_close` should be timezone aware, but pandas
# 0.16.1 does not appear to support this:
# http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#datetime-with-tz # noqa
return (
sched.at[session_label, 'market_open'].tz_localize(UTC),
sched.at[session_label, 'market_close'].tz_localize(UTC),
) | python | def open_and_close_for_session(self, session_label):
"""
Returns a tuple of timestamps of the open and close of the session
represented by the given label.
Parameters
----------
session_label: pd.Timestamp
The session whose open and close are desired.
Returns
-------
(Timestamp, Timestamp)
The open and close for the given session.
"""
sched = self.schedule
# `market_open` and `market_close` should be timezone aware, but pandas
# 0.16.1 does not appear to support this:
# http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#datetime-with-tz # noqa
return (
sched.at[session_label, 'market_open'].tz_localize(UTC),
sched.at[session_label, 'market_close'].tz_localize(UTC),
) | [
"def",
"open_and_close_for_session",
"(",
"self",
",",
"session_label",
")",
":",
"sched",
"=",
"self",
".",
"schedule",
"# `market_open` and `market_close` should be timezone aware, but pandas",
"# 0.16.1 does not appear to support this:",
"# http://pandas.pydata.org/pandas-docs/stabl... | Returns a tuple of timestamps of the open and close of the session
represented by the given label.
Parameters
----------
session_label: pd.Timestamp
The session whose open and close are desired.
Returns
-------
(Timestamp, Timestamp)
The open and close for the given session. | [
"Returns",
"a",
"tuple",
"of",
"timestamps",
"of",
"the",
"open",
"and",
"close",
"of",
"the",
"session",
"represented",
"by",
"the",
"given",
"label",
"."
] | 951711c82c8a2875c09e96e2979faaf8734fb4df | https://github.com/quantopian/trading_calendars/blob/951711c82c8a2875c09e96e2979faaf8734fb4df/trading_calendars/trading_calendar.py#L739-L762 | train | 229,501 |
quantopian/trading_calendars | trading_calendars/trading_calendar.py | TradingCalendar.all_minutes | def all_minutes(self):
"""
Returns a DatetimeIndex representing all the minutes in this calendar.
"""
opens_in_ns = self._opens.values.astype(
'datetime64[ns]',
).view('int64')
closes_in_ns = self._closes.values.astype(
'datetime64[ns]',
).view('int64')
return DatetimeIndex(
compute_all_minutes(opens_in_ns, closes_in_ns),
tz=UTC,
) | python | def all_minutes(self):
"""
Returns a DatetimeIndex representing all the minutes in this calendar.
"""
opens_in_ns = self._opens.values.astype(
'datetime64[ns]',
).view('int64')
closes_in_ns = self._closes.values.astype(
'datetime64[ns]',
).view('int64')
return DatetimeIndex(
compute_all_minutes(opens_in_ns, closes_in_ns),
tz=UTC,
) | [
"def",
"all_minutes",
"(",
"self",
")",
":",
"opens_in_ns",
"=",
"self",
".",
"_opens",
".",
"values",
".",
"astype",
"(",
"'datetime64[ns]'",
",",
")",
".",
"view",
"(",
"'int64'",
")",
"closes_in_ns",
"=",
"self",
".",
"_closes",
".",
"values",
".",
... | Returns a DatetimeIndex representing all the minutes in this calendar. | [
"Returns",
"a",
"DatetimeIndex",
"representing",
"all",
"the",
"minutes",
"in",
"this",
"calendar",
"."
] | 951711c82c8a2875c09e96e2979faaf8734fb4df | https://github.com/quantopian/trading_calendars/blob/951711c82c8a2875c09e96e2979faaf8734fb4df/trading_calendars/trading_calendar.py#L807-L822 | train | 229,502 |
quantopian/trading_calendars | trading_calendars/trading_calendar.py | TradingCalendar.minute_to_session_label | def minute_to_session_label(self, dt, direction="next"):
"""
Given a minute, get the label of its containing session.
Parameters
----------
dt : pd.Timestamp or nanosecond offset
The dt for which to get the containing session.
direction: str
"next" (default) means that if the given dt is not part of a
session, return the label of the next session.
"previous" means that if the given dt is not part of a session,
return the label of the previous session.
"none" means that a KeyError will be raised if the given
dt is not part of a session.
Returns
-------
pd.Timestamp (midnight UTC)
The label of the containing session.
"""
if direction == "next":
try:
return self._minute_to_session_label_cache[dt]
except KeyError:
pass
idx = searchsorted(self.market_closes_nanos, dt)
current_or_next_session = self.schedule.index[idx]
self._minute_to_session_label_cache[dt] = current_or_next_session
if direction == "next":
return current_or_next_session
elif direction == "previous":
if not is_open(self.market_opens_nanos, self.market_closes_nanos,
dt):
# if the exchange is closed, use the previous session
return self.schedule.index[idx - 1]
elif direction == "none":
if not is_open(self.market_opens_nanos, self.market_closes_nanos,
dt):
# if the exchange is closed, blow up
raise ValueError("The given dt is not an exchange minute!")
else:
# invalid direction
raise ValueError("Invalid direction parameter: "
"{0}".format(direction))
return current_or_next_session | python | def minute_to_session_label(self, dt, direction="next"):
"""
Given a minute, get the label of its containing session.
Parameters
----------
dt : pd.Timestamp or nanosecond offset
The dt for which to get the containing session.
direction: str
"next" (default) means that if the given dt is not part of a
session, return the label of the next session.
"previous" means that if the given dt is not part of a session,
return the label of the previous session.
"none" means that a KeyError will be raised if the given
dt is not part of a session.
Returns
-------
pd.Timestamp (midnight UTC)
The label of the containing session.
"""
if direction == "next":
try:
return self._minute_to_session_label_cache[dt]
except KeyError:
pass
idx = searchsorted(self.market_closes_nanos, dt)
current_or_next_session = self.schedule.index[idx]
self._minute_to_session_label_cache[dt] = current_or_next_session
if direction == "next":
return current_or_next_session
elif direction == "previous":
if not is_open(self.market_opens_nanos, self.market_closes_nanos,
dt):
# if the exchange is closed, use the previous session
return self.schedule.index[idx - 1]
elif direction == "none":
if not is_open(self.market_opens_nanos, self.market_closes_nanos,
dt):
# if the exchange is closed, blow up
raise ValueError("The given dt is not an exchange minute!")
else:
# invalid direction
raise ValueError("Invalid direction parameter: "
"{0}".format(direction))
return current_or_next_session | [
"def",
"minute_to_session_label",
"(",
"self",
",",
"dt",
",",
"direction",
"=",
"\"next\"",
")",
":",
"if",
"direction",
"==",
"\"next\"",
":",
"try",
":",
"return",
"self",
".",
"_minute_to_session_label_cache",
"[",
"dt",
"]",
"except",
"KeyError",
":",
"... | Given a minute, get the label of its containing session.
Parameters
----------
dt : pd.Timestamp or nanosecond offset
The dt for which to get the containing session.
direction: str
"next" (default) means that if the given dt is not part of a
session, return the label of the next session.
"previous" means that if the given dt is not part of a session,
return the label of the previous session.
"none" means that a KeyError will be raised if the given
dt is not part of a session.
Returns
-------
pd.Timestamp (midnight UTC)
The label of the containing session. | [
"Given",
"a",
"minute",
"get",
"the",
"label",
"of",
"its",
"containing",
"session",
"."
] | 951711c82c8a2875c09e96e2979faaf8734fb4df | https://github.com/quantopian/trading_calendars/blob/951711c82c8a2875c09e96e2979faaf8734fb4df/trading_calendars/trading_calendar.py#L825-L876 | train | 229,503 |
quantopian/trading_calendars | trading_calendars/trading_calendar.py | TradingCalendar.minute_index_to_session_labels | def minute_index_to_session_labels(self, index):
"""
Given a sorted DatetimeIndex of market minutes, return a
DatetimeIndex of the corresponding session labels.
Parameters
----------
index: pd.DatetimeIndex or pd.Series
The ordered list of market minutes we want session labels for.
Returns
-------
pd.DatetimeIndex (UTC)
The list of session labels corresponding to the given minutes.
"""
if not index.is_monotonic_increasing:
raise ValueError(
"Non-ordered index passed to minute_index_to_session_labels."
)
# Find the indices of the previous open and the next close for each
# minute.
prev_opens = (
self._opens.values.searchsorted(index.values, side='right') - 1
)
next_closes = (
self._closes.values.searchsorted(index.values, side='left')
)
# If they don't match, the minute is outside the trading day. Barf.
mismatches = (prev_opens != next_closes)
if mismatches.any():
# Show the first bad minute in the error message.
bad_ix = np.flatnonzero(mismatches)[0]
example = index[bad_ix]
prev_day = prev_opens[bad_ix]
prev_open, prev_close = self.schedule.iloc[prev_day]
next_open, next_close = self.schedule.iloc[prev_day + 1]
raise ValueError(
"{num} non-market minutes in minute_index_to_session_labels:\n"
"First Bad Minute: {first_bad}\n"
"Previous Session: {prev_open} -> {prev_close}\n"
"Next Session: {next_open} -> {next_close}"
.format(
num=mismatches.sum(),
first_bad=example,
prev_open=prev_open, prev_close=prev_close,
next_open=next_open, next_close=next_close)
)
return self.schedule.index[prev_opens] | python | def minute_index_to_session_labels(self, index):
"""
Given a sorted DatetimeIndex of market minutes, return a
DatetimeIndex of the corresponding session labels.
Parameters
----------
index: pd.DatetimeIndex or pd.Series
The ordered list of market minutes we want session labels for.
Returns
-------
pd.DatetimeIndex (UTC)
The list of session labels corresponding to the given minutes.
"""
if not index.is_monotonic_increasing:
raise ValueError(
"Non-ordered index passed to minute_index_to_session_labels."
)
# Find the indices of the previous open and the next close for each
# minute.
prev_opens = (
self._opens.values.searchsorted(index.values, side='right') - 1
)
next_closes = (
self._closes.values.searchsorted(index.values, side='left')
)
# If they don't match, the minute is outside the trading day. Barf.
mismatches = (prev_opens != next_closes)
if mismatches.any():
# Show the first bad minute in the error message.
bad_ix = np.flatnonzero(mismatches)[0]
example = index[bad_ix]
prev_day = prev_opens[bad_ix]
prev_open, prev_close = self.schedule.iloc[prev_day]
next_open, next_close = self.schedule.iloc[prev_day + 1]
raise ValueError(
"{num} non-market minutes in minute_index_to_session_labels:\n"
"First Bad Minute: {first_bad}\n"
"Previous Session: {prev_open} -> {prev_close}\n"
"Next Session: {next_open} -> {next_close}"
.format(
num=mismatches.sum(),
first_bad=example,
prev_open=prev_open, prev_close=prev_close,
next_open=next_open, next_close=next_close)
)
return self.schedule.index[prev_opens] | [
"def",
"minute_index_to_session_labels",
"(",
"self",
",",
"index",
")",
":",
"if",
"not",
"index",
".",
"is_monotonic_increasing",
":",
"raise",
"ValueError",
"(",
"\"Non-ordered index passed to minute_index_to_session_labels.\"",
")",
"# Find the indices of the previous open ... | Given a sorted DatetimeIndex of market minutes, return a
DatetimeIndex of the corresponding session labels.
Parameters
----------
index: pd.DatetimeIndex or pd.Series
The ordered list of market minutes we want session labels for.
Returns
-------
pd.DatetimeIndex (UTC)
The list of session labels corresponding to the given minutes. | [
"Given",
"a",
"sorted",
"DatetimeIndex",
"of",
"market",
"minutes",
"return",
"a",
"DatetimeIndex",
"of",
"the",
"corresponding",
"session",
"labels",
"."
] | 951711c82c8a2875c09e96e2979faaf8734fb4df | https://github.com/quantopian/trading_calendars/blob/951711c82c8a2875c09e96e2979faaf8734fb4df/trading_calendars/trading_calendar.py#L878-L930 | train | 229,504 |
quantopian/trading_calendars | trading_calendars/trading_calendar.py | TradingCalendar._special_dates | def _special_dates(self, calendars, ad_hoc_dates, start_date, end_date):
"""
Compute a Series of times associated with special dates.
Parameters
----------
holiday_calendars : list[(datetime.time, HolidayCalendar)]
Pairs of time and calendar describing when that time occurs. These
are used to describe regularly-scheduled late opens or early
closes.
ad_hoc_dates : list[(datetime.time, list[pd.Timestamp])]
Pairs of time and list of dates associated with the given times.
These are used to describe late opens or early closes that occurred
for unscheduled or otherwise irregular reasons.
start_date : pd.Timestamp
Start of the range for which we should calculate special dates.
end_date : pd.Timestamp
End of the range for which we should calculate special dates.
Returns
-------
special_dates : pd.Series
Series mapping trading sessions with special opens/closes to the
special open/close for that session.
"""
# List of Series for regularly-scheduled times.
regular = [
scheduled_special_times(
calendar,
start_date,
end_date,
time_,
self.tz,
)
for time_, calendar in calendars
]
# List of Series for ad-hoc times.
ad_hoc = [
pd.Series(
index=pd.to_datetime(datetimes, utc=True),
data=days_at_time(datetimes, time_, self.tz),
)
for time_, datetimes in ad_hoc_dates
]
merged = regular + ad_hoc
if not merged:
# Concat barfs if the input has length 0.
return pd.Series([])
result = pd.concat(merged).sort_index()
return result.loc[(result >= start_date) & (result <= end_date)] | python | def _special_dates(self, calendars, ad_hoc_dates, start_date, end_date):
"""
Compute a Series of times associated with special dates.
Parameters
----------
holiday_calendars : list[(datetime.time, HolidayCalendar)]
Pairs of time and calendar describing when that time occurs. These
are used to describe regularly-scheduled late opens or early
closes.
ad_hoc_dates : list[(datetime.time, list[pd.Timestamp])]
Pairs of time and list of dates associated with the given times.
These are used to describe late opens or early closes that occurred
for unscheduled or otherwise irregular reasons.
start_date : pd.Timestamp
Start of the range for which we should calculate special dates.
end_date : pd.Timestamp
End of the range for which we should calculate special dates.
Returns
-------
special_dates : pd.Series
Series mapping trading sessions with special opens/closes to the
special open/close for that session.
"""
# List of Series for regularly-scheduled times.
regular = [
scheduled_special_times(
calendar,
start_date,
end_date,
time_,
self.tz,
)
for time_, calendar in calendars
]
# List of Series for ad-hoc times.
ad_hoc = [
pd.Series(
index=pd.to_datetime(datetimes, utc=True),
data=days_at_time(datetimes, time_, self.tz),
)
for time_, datetimes in ad_hoc_dates
]
merged = regular + ad_hoc
if not merged:
# Concat barfs if the input has length 0.
return pd.Series([])
result = pd.concat(merged).sort_index()
return result.loc[(result >= start_date) & (result <= end_date)] | [
"def",
"_special_dates",
"(",
"self",
",",
"calendars",
",",
"ad_hoc_dates",
",",
"start_date",
",",
"end_date",
")",
":",
"# List of Series for regularly-scheduled times.",
"regular",
"=",
"[",
"scheduled_special_times",
"(",
"calendar",
",",
"start_date",
",",
"end_... | Compute a Series of times associated with special dates.
Parameters
----------
holiday_calendars : list[(datetime.time, HolidayCalendar)]
Pairs of time and calendar describing when that time occurs. These
are used to describe regularly-scheduled late opens or early
closes.
ad_hoc_dates : list[(datetime.time, list[pd.Timestamp])]
Pairs of time and list of dates associated with the given times.
These are used to describe late opens or early closes that occurred
for unscheduled or otherwise irregular reasons.
start_date : pd.Timestamp
Start of the range for which we should calculate special dates.
end_date : pd.Timestamp
End of the range for which we should calculate special dates.
Returns
-------
special_dates : pd.Series
Series mapping trading sessions with special opens/closes to the
special open/close for that session. | [
"Compute",
"a",
"Series",
"of",
"times",
"associated",
"with",
"special",
"dates",
"."
] | 951711c82c8a2875c09e96e2979faaf8734fb4df | https://github.com/quantopian/trading_calendars/blob/951711c82c8a2875c09e96e2979faaf8734fb4df/trading_calendars/trading_calendar.py#L932-L984 | train | 229,505 |
datahq/dataflows | setup.py | read | def read(*paths):
"""Read a text file."""
basedir = os.path.dirname(__file__)
fullpath = os.path.join(basedir, *paths)
contents = io.open(fullpath, encoding='utf-8').read().strip()
return contents | python | def read(*paths):
"""Read a text file."""
basedir = os.path.dirname(__file__)
fullpath = os.path.join(basedir, *paths)
contents = io.open(fullpath, encoding='utf-8').read().strip()
return contents | [
"def",
"read",
"(",
"*",
"paths",
")",
":",
"basedir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
"fullpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"*",
"paths",
")",
"contents",
"=",
"io",
".",
"open",
"(",... | Read a text file. | [
"Read",
"a",
"text",
"file",
"."
] | 2c5e5e01e09c8b44e0ff36d85b3f2f4dcf4e8465 | https://github.com/datahq/dataflows/blob/2c5e5e01e09c8b44e0ff36d85b3f2f4dcf4e8465/setup.py#L12-L17 | train | 229,506 |
ipfs/py-ipfs-api | ipfsapi/encoding.py | Encoding.parse | def parse(self, raw):
"""Returns a Python object decoded from the bytes of this encoding.
Raises
------
~ipfsapi.exceptions.DecodingError
Parameters
----------
raw : bytes
Data to be parsed
Returns
-------
object
"""
results = list(self.parse_partial(raw))
results.extend(self.parse_finalize())
return results[0] if len(results) == 1 else results | python | def parse(self, raw):
"""Returns a Python object decoded from the bytes of this encoding.
Raises
------
~ipfsapi.exceptions.DecodingError
Parameters
----------
raw : bytes
Data to be parsed
Returns
-------
object
"""
results = list(self.parse_partial(raw))
results.extend(self.parse_finalize())
return results[0] if len(results) == 1 else results | [
"def",
"parse",
"(",
"self",
",",
"raw",
")",
":",
"results",
"=",
"list",
"(",
"self",
".",
"parse_partial",
"(",
"raw",
")",
")",
"results",
".",
"extend",
"(",
"self",
".",
"parse_finalize",
"(",
")",
")",
"return",
"results",
"[",
"0",
"]",
"if... | Returns a Python object decoded from the bytes of this encoding.
Raises
------
~ipfsapi.exceptions.DecodingError
Parameters
----------
raw : bytes
Data to be parsed
Returns
-------
object | [
"Returns",
"a",
"Python",
"object",
"decoded",
"from",
"the",
"bytes",
"of",
"this",
"encoding",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/encoding.py#L60-L78 | train | 229,507 |
ipfs/py-ipfs-api | ipfsapi/encoding.py | Json.parse_partial | def parse_partial(self, data):
"""Incrementally decodes JSON data sets into Python objects.
Raises
------
~ipfsapi.exceptions.DecodingError
Returns
-------
generator
"""
try:
# Python 3 requires all JSON data to be a text string
lines = self._decoder1.decode(data, False).split("\n")
# Add first input line to last buffer line, if applicable, to
# handle cases where the JSON string has been chopped in half
# at the network level due to streaming
if len(self._buffer) > 0 and self._buffer[-1] is not None:
self._buffer[-1] += lines[0]
self._buffer.extend(lines[1:])
else:
self._buffer.extend(lines)
except UnicodeDecodeError as error:
raise exceptions.DecodingError('json', error)
# Process data buffer
index = 0
try:
# Process each line as separate buffer
#PERF: This way the `.lstrip()` call becomes almost always a NOP
# even if it does return a different string it will only
# have to allocate a new buffer for the currently processed
# line.
while index < len(self._buffer):
while self._buffer[index]:
# Make sure buffer does not start with whitespace
#PERF: `.lstrip()` does not reallocate if the string does
# not actually start with whitespace.
self._buffer[index] = self._buffer[index].lstrip()
# Handle case where the remainder of the line contained
# only whitespace
if not self._buffer[index]:
self._buffer[index] = None
continue
# Try decoding the partial data buffer and return results
# from this
data = self._buffer[index]
for index2 in range(index, len(self._buffer)):
# If decoding doesn't succeed with the currently
# selected buffer (very unlikely with our current
# class of input data) then retry with appending
# any other pending pieces of input data
# This will happen with JSON data that contains
# arbitrary new-lines: "{1:\n2,\n3:4}"
if index2 > index:
data += "\n" + self._buffer[index2]
try:
(obj, offset) = self._decoder2.raw_decode(data)
except ValueError:
# Treat error as fatal if we have already added
# the final buffer to the input
if (index2 + 1) == len(self._buffer):
raise
else:
index = index2
break
# Decoding succeeded – yield result and shorten buffer
yield obj
if offset < len(self._buffer[index]):
self._buffer[index] = self._buffer[index][offset:]
else:
self._buffer[index] = None
index += 1
except ValueError as error:
# It is unfortunately not possible to reliably detect whether
# parsing ended because of an error *within* the JSON string, or
# an unexpected *end* of the JSON string.
# We therefor have to assume that any error that occurs here
# *might* be related to the JSON parser hitting EOF and therefor
# have to postpone error reporting until `parse_finalize` is
# called.
self._lasterror = error
finally:
# Remove all processed buffers
del self._buffer[0:index] | python | def parse_partial(self, data):
"""Incrementally decodes JSON data sets into Python objects.
Raises
------
~ipfsapi.exceptions.DecodingError
Returns
-------
generator
"""
try:
# Python 3 requires all JSON data to be a text string
lines = self._decoder1.decode(data, False).split("\n")
# Add first input line to last buffer line, if applicable, to
# handle cases where the JSON string has been chopped in half
# at the network level due to streaming
if len(self._buffer) > 0 and self._buffer[-1] is not None:
self._buffer[-1] += lines[0]
self._buffer.extend(lines[1:])
else:
self._buffer.extend(lines)
except UnicodeDecodeError as error:
raise exceptions.DecodingError('json', error)
# Process data buffer
index = 0
try:
# Process each line as separate buffer
#PERF: This way the `.lstrip()` call becomes almost always a NOP
# even if it does return a different string it will only
# have to allocate a new buffer for the currently processed
# line.
while index < len(self._buffer):
while self._buffer[index]:
# Make sure buffer does not start with whitespace
#PERF: `.lstrip()` does not reallocate if the string does
# not actually start with whitespace.
self._buffer[index] = self._buffer[index].lstrip()
# Handle case where the remainder of the line contained
# only whitespace
if not self._buffer[index]:
self._buffer[index] = None
continue
# Try decoding the partial data buffer and return results
# from this
data = self._buffer[index]
for index2 in range(index, len(self._buffer)):
# If decoding doesn't succeed with the currently
# selected buffer (very unlikely with our current
# class of input data) then retry with appending
# any other pending pieces of input data
# This will happen with JSON data that contains
# arbitrary new-lines: "{1:\n2,\n3:4}"
if index2 > index:
data += "\n" + self._buffer[index2]
try:
(obj, offset) = self._decoder2.raw_decode(data)
except ValueError:
# Treat error as fatal if we have already added
# the final buffer to the input
if (index2 + 1) == len(self._buffer):
raise
else:
index = index2
break
# Decoding succeeded – yield result and shorten buffer
yield obj
if offset < len(self._buffer[index]):
self._buffer[index] = self._buffer[index][offset:]
else:
self._buffer[index] = None
index += 1
except ValueError as error:
# It is unfortunately not possible to reliably detect whether
# parsing ended because of an error *within* the JSON string, or
# an unexpected *end* of the JSON string.
# We therefor have to assume that any error that occurs here
# *might* be related to the JSON parser hitting EOF and therefor
# have to postpone error reporting until `parse_finalize` is
# called.
self._lasterror = error
finally:
# Remove all processed buffers
del self._buffer[0:index] | [
"def",
"parse_partial",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"# Python 3 requires all JSON data to be a text string",
"lines",
"=",
"self",
".",
"_decoder1",
".",
"decode",
"(",
"data",
",",
"False",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"# Add fi... | Incrementally decodes JSON data sets into Python objects.
Raises
------
~ipfsapi.exceptions.DecodingError
Returns
-------
generator | [
"Incrementally",
"decodes",
"JSON",
"data",
"sets",
"into",
"Python",
"objects",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/encoding.py#L141-L230 | train | 229,508 |
ipfs/py-ipfs-api | ipfsapi/encoding.py | Json.parse_finalize | def parse_finalize(self):
"""Raises errors for incomplete buffered data that could not be parsed
because the end of the input data has been reached.
Raises
------
~ipfsapi.exceptions.DecodingError
Returns
-------
tuple : Always empty
"""
try:
try:
# Raise exception for remaining bytes in bytes decoder
self._decoder1.decode(b'', True)
except UnicodeDecodeError as error:
raise exceptions.DecodingError('json', error)
# Late raise errors that looked like they could have been fixed if
# the caller had provided more data
if self._buffer:
raise exceptions.DecodingError('json', self._lasterror)
finally:
# Reset state
self._buffer = []
self._lasterror = None
self._decoder1.reset()
return () | python | def parse_finalize(self):
"""Raises errors for incomplete buffered data that could not be parsed
because the end of the input data has been reached.
Raises
------
~ipfsapi.exceptions.DecodingError
Returns
-------
tuple : Always empty
"""
try:
try:
# Raise exception for remaining bytes in bytes decoder
self._decoder1.decode(b'', True)
except UnicodeDecodeError as error:
raise exceptions.DecodingError('json', error)
# Late raise errors that looked like they could have been fixed if
# the caller had provided more data
if self._buffer:
raise exceptions.DecodingError('json', self._lasterror)
finally:
# Reset state
self._buffer = []
self._lasterror = None
self._decoder1.reset()
return () | [
"def",
"parse_finalize",
"(",
"self",
")",
":",
"try",
":",
"try",
":",
"# Raise exception for remaining bytes in bytes decoder",
"self",
".",
"_decoder1",
".",
"decode",
"(",
"b''",
",",
"True",
")",
"except",
"UnicodeDecodeError",
"as",
"error",
":",
"raise",
... | Raises errors for incomplete buffered data that could not be parsed
because the end of the input data has been reached.
Raises
------
~ipfsapi.exceptions.DecodingError
Returns
-------
tuple : Always empty | [
"Raises",
"errors",
"for",
"incomplete",
"buffered",
"data",
"that",
"could",
"not",
"be",
"parsed",
"because",
"the",
"end",
"of",
"the",
"input",
"data",
"has",
"been",
"reached",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/encoding.py#L232-L261 | train | 229,509 |
ipfs/py-ipfs-api | ipfsapi/encoding.py | Json.encode | def encode(self, obj):
"""Returns ``obj`` serialized as JSON formatted bytes.
Raises
------
~ipfsapi.exceptions.EncodingError
Parameters
----------
obj : str | list | dict | int
JSON serializable Python object
Returns
-------
bytes
"""
try:
result = json.dumps(obj, sort_keys=True, indent=None,
separators=(',', ':'), ensure_ascii=False)
if isinstance(result, six.text_type):
return result.encode("utf-8")
else:
return result
except (UnicodeEncodeError, TypeError) as error:
raise exceptions.EncodingError('json', error) | python | def encode(self, obj):
"""Returns ``obj`` serialized as JSON formatted bytes.
Raises
------
~ipfsapi.exceptions.EncodingError
Parameters
----------
obj : str | list | dict | int
JSON serializable Python object
Returns
-------
bytes
"""
try:
result = json.dumps(obj, sort_keys=True, indent=None,
separators=(',', ':'), ensure_ascii=False)
if isinstance(result, six.text_type):
return result.encode("utf-8")
else:
return result
except (UnicodeEncodeError, TypeError) as error:
raise exceptions.EncodingError('json', error) | [
"def",
"encode",
"(",
"self",
",",
"obj",
")",
":",
"try",
":",
"result",
"=",
"json",
".",
"dumps",
"(",
"obj",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"None",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
",",
"ensure_ascii",
... | Returns ``obj`` serialized as JSON formatted bytes.
Raises
------
~ipfsapi.exceptions.EncodingError
Parameters
----------
obj : str | list | dict | int
JSON serializable Python object
Returns
-------
bytes | [
"Returns",
"obj",
"serialized",
"as",
"JSON",
"formatted",
"bytes",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/encoding.py#L263-L287 | train | 229,510 |
ipfs/py-ipfs-api | ipfsapi/encoding.py | Pickle.parse_finalize | def parse_finalize(self):
"""Parses the buffered data and yields the result.
Raises
------
~ipfsapi.exceptions.DecodingError
Returns
-------
generator
"""
try:
self._buffer.seek(0, 0)
yield pickle.load(self._buffer)
except pickle.UnpicklingError as error:
raise exceptions.DecodingError('pickle', error) | python | def parse_finalize(self):
"""Parses the buffered data and yields the result.
Raises
------
~ipfsapi.exceptions.DecodingError
Returns
-------
generator
"""
try:
self._buffer.seek(0, 0)
yield pickle.load(self._buffer)
except pickle.UnpicklingError as error:
raise exceptions.DecodingError('pickle', error) | [
"def",
"parse_finalize",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_buffer",
".",
"seek",
"(",
"0",
",",
"0",
")",
"yield",
"pickle",
".",
"load",
"(",
"self",
".",
"_buffer",
")",
"except",
"pickle",
".",
"UnpicklingError",
"as",
"error",
":"... | Parses the buffered data and yields the result.
Raises
------
~ipfsapi.exceptions.DecodingError
Returns
-------
generator | [
"Parses",
"the",
"buffered",
"data",
"and",
"yields",
"the",
"result",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/encoding.py#L319-L334 | train | 229,511 |
ipfs/py-ipfs-api | ipfsapi/encoding.py | Pickle.encode | def encode(self, obj):
"""Returns ``obj`` serialized as a pickle binary string.
Raises
------
~ipfsapi.exceptions.EncodingError
Parameters
----------
obj : object
Serializable Python object
Returns
-------
bytes
"""
try:
return pickle.dumps(obj)
except pickle.PicklingError as error:
raise exceptions.EncodingError('pickle', error) | python | def encode(self, obj):
"""Returns ``obj`` serialized as a pickle binary string.
Raises
------
~ipfsapi.exceptions.EncodingError
Parameters
----------
obj : object
Serializable Python object
Returns
-------
bytes
"""
try:
return pickle.dumps(obj)
except pickle.PicklingError as error:
raise exceptions.EncodingError('pickle', error) | [
"def",
"encode",
"(",
"self",
",",
"obj",
")",
":",
"try",
":",
"return",
"pickle",
".",
"dumps",
"(",
"obj",
")",
"except",
"pickle",
".",
"PicklingError",
"as",
"error",
":",
"raise",
"exceptions",
".",
"EncodingError",
"(",
"'pickle'",
",",
"error",
... | Returns ``obj`` serialized as a pickle binary string.
Raises
------
~ipfsapi.exceptions.EncodingError
Parameters
----------
obj : object
Serializable Python object
Returns
-------
bytes | [
"Returns",
"obj",
"serialized",
"as",
"a",
"pickle",
"binary",
"string",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/encoding.py#L360-L379 | train | 229,512 |
ipfs/py-ipfs-api | ipfsapi/multipart.py | glob_compile | def glob_compile(pat):
"""Translate a shell glob PATTERN to a regular expression.
This is almost entirely based on `fnmatch.translate` source-code from the
python 3.5 standard-library.
"""
i, n = 0, len(pat)
res = ''
while i < n:
c = pat[i]
i = i + 1
if c == '/' and len(pat) > (i + 2) and pat[i:(i + 3)] == '**/':
# Special-case for "any number of sub-directories" operator since
# may also expand to no entries:
# Otherwise `a/**/b` would expand to `a[/].*[/]b` which wouldn't
# match the immediate sub-directories of `a`, like `a/b`.
i = i + 3
res = res + '[/]([^/]*[/])*'
elif c == '*':
if len(pat) > i and pat[i] == '*':
i = i + 1
res = res + '.*'
else:
res = res + '[^/]*'
elif c == '?':
res = res + '[^/]'
elif c == '[':
j = i
if j < n and pat[j] == '!':
j = j + 1
if j < n and pat[j] == ']':
j = j + 1
while j < n and pat[j] != ']':
j = j + 1
if j >= n:
res = res + '\\['
else:
stuff = pat[i:j].replace('\\', '\\\\')
i = j + 1
if stuff[0] == '!':
stuff = '^' + stuff[1:]
elif stuff[0] == '^':
stuff = '\\' + stuff
res = '%s[%s]' % (res, stuff)
else:
res = res + re.escape(c)
return re.compile('^' + res + '\Z(?ms)' + '$') | python | def glob_compile(pat):
"""Translate a shell glob PATTERN to a regular expression.
This is almost entirely based on `fnmatch.translate` source-code from the
python 3.5 standard-library.
"""
i, n = 0, len(pat)
res = ''
while i < n:
c = pat[i]
i = i + 1
if c == '/' and len(pat) > (i + 2) and pat[i:(i + 3)] == '**/':
# Special-case for "any number of sub-directories" operator since
# may also expand to no entries:
# Otherwise `a/**/b` would expand to `a[/].*[/]b` which wouldn't
# match the immediate sub-directories of `a`, like `a/b`.
i = i + 3
res = res + '[/]([^/]*[/])*'
elif c == '*':
if len(pat) > i and pat[i] == '*':
i = i + 1
res = res + '.*'
else:
res = res + '[^/]*'
elif c == '?':
res = res + '[^/]'
elif c == '[':
j = i
if j < n and pat[j] == '!':
j = j + 1
if j < n and pat[j] == ']':
j = j + 1
while j < n and pat[j] != ']':
j = j + 1
if j >= n:
res = res + '\\['
else:
stuff = pat[i:j].replace('\\', '\\\\')
i = j + 1
if stuff[0] == '!':
stuff = '^' + stuff[1:]
elif stuff[0] == '^':
stuff = '\\' + stuff
res = '%s[%s]' % (res, stuff)
else:
res = res + re.escape(c)
return re.compile('^' + res + '\Z(?ms)' + '$') | [
"def",
"glob_compile",
"(",
"pat",
")",
":",
"i",
",",
"n",
"=",
"0",
",",
"len",
"(",
"pat",
")",
"res",
"=",
"''",
"while",
"i",
"<",
"n",
":",
"c",
"=",
"pat",
"[",
"i",
"]",
"i",
"=",
"i",
"+",
"1",
"if",
"c",
"==",
"'/'",
"and",
"l... | Translate a shell glob PATTERN to a regular expression.
This is almost entirely based on `fnmatch.translate` source-code from the
python 3.5 standard-library. | [
"Translate",
"a",
"shell",
"glob",
"PATTERN",
"to",
"a",
"regular",
"expression",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/multipart.py#L319-L366 | train | 229,513 |
ipfs/py-ipfs-api | ipfsapi/multipart.py | stream_files | def stream_files(files, chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming files.
Returns a buffered generator which encodes a file or list of files as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
files : str
The file(s) to stream
chunk_size : int
Maximum size of each stream chunk
"""
stream = FileStream(files, chunk_size=chunk_size)
return stream.body(), stream.headers | python | def stream_files(files, chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming files.
Returns a buffered generator which encodes a file or list of files as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
files : str
The file(s) to stream
chunk_size : int
Maximum size of each stream chunk
"""
stream = FileStream(files, chunk_size=chunk_size)
return stream.body(), stream.headers | [
"def",
"stream_files",
"(",
"files",
",",
"chunk_size",
"=",
"default_chunk_size",
")",
":",
"stream",
"=",
"FileStream",
"(",
"files",
",",
"chunk_size",
"=",
"chunk_size",
")",
"return",
"stream",
".",
"body",
"(",
")",
",",
"stream",
".",
"headers"
] | Gets a buffered generator for streaming files.
Returns a buffered generator which encodes a file or list of files as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
files : str
The file(s) to stream
chunk_size : int
Maximum size of each stream chunk | [
"Gets",
"a",
"buffered",
"generator",
"for",
"streaming",
"files",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/multipart.py#L560-L575 | train | 229,514 |
ipfs/py-ipfs-api | ipfsapi/multipart.py | stream_directory | def stream_directory(directory,
recursive=False,
patterns='**',
chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming directories.
Returns a buffered generator which encodes a directory as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
directory : str
The filepath of the directory to stream
recursive : bool
Stream all content within the directory recursively?
patterns : str | list
Single *glob* pattern or list of *glob* patterns and compiled
regular expressions to match the names of the filepaths to keep
chunk_size : int
Maximum size of each stream chunk
"""
stream = DirectoryStream(directory,
recursive=recursive,
patterns=patterns,
chunk_size=chunk_size)
return stream.body(), stream.headers | python | def stream_directory(directory,
recursive=False,
patterns='**',
chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming directories.
Returns a buffered generator which encodes a directory as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
directory : str
The filepath of the directory to stream
recursive : bool
Stream all content within the directory recursively?
patterns : str | list
Single *glob* pattern or list of *glob* patterns and compiled
regular expressions to match the names of the filepaths to keep
chunk_size : int
Maximum size of each stream chunk
"""
stream = DirectoryStream(directory,
recursive=recursive,
patterns=patterns,
chunk_size=chunk_size)
return stream.body(), stream.headers | [
"def",
"stream_directory",
"(",
"directory",
",",
"recursive",
"=",
"False",
",",
"patterns",
"=",
"'**'",
",",
"chunk_size",
"=",
"default_chunk_size",
")",
":",
"stream",
"=",
"DirectoryStream",
"(",
"directory",
",",
"recursive",
"=",
"recursive",
",",
"pat... | Gets a buffered generator for streaming directories.
Returns a buffered generator which encodes a directory as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
directory : str
The filepath of the directory to stream
recursive : bool
Stream all content within the directory recursively?
patterns : str | list
Single *glob* pattern or list of *glob* patterns and compiled
regular expressions to match the names of the filepaths to keep
chunk_size : int
Maximum size of each stream chunk | [
"Gets",
"a",
"buffered",
"generator",
"for",
"streaming",
"directories",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/multipart.py#L578-L604 | train | 229,515 |
ipfs/py-ipfs-api | ipfsapi/multipart.py | stream_filesystem_node | def stream_filesystem_node(path,
recursive=False,
patterns='**',
chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming either files or directories.
Returns a buffered generator which encodes the file or directory at the
given path as :mimetype:`multipart/form-data` with the corresponding
headers.
Parameters
----------
path : str
The filepath of the directory or file to stream
recursive : bool
Stream all content within the directory recursively?
patterns : str | list
Single *glob* pattern or list of *glob* patterns and compiled
regular expressions to match the names of the filepaths to keep
chunk_size : int
Maximum size of each stream chunk
"""
is_dir = isinstance(path, six.string_types) and os.path.isdir(path)
if recursive or is_dir:
return stream_directory(path, recursive, patterns, chunk_size)
else:
return stream_files(path, chunk_size) | python | def stream_filesystem_node(path,
recursive=False,
patterns='**',
chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming either files or directories.
Returns a buffered generator which encodes the file or directory at the
given path as :mimetype:`multipart/form-data` with the corresponding
headers.
Parameters
----------
path : str
The filepath of the directory or file to stream
recursive : bool
Stream all content within the directory recursively?
patterns : str | list
Single *glob* pattern or list of *glob* patterns and compiled
regular expressions to match the names of the filepaths to keep
chunk_size : int
Maximum size of each stream chunk
"""
is_dir = isinstance(path, six.string_types) and os.path.isdir(path)
if recursive or is_dir:
return stream_directory(path, recursive, patterns, chunk_size)
else:
return stream_files(path, chunk_size) | [
"def",
"stream_filesystem_node",
"(",
"path",
",",
"recursive",
"=",
"False",
",",
"patterns",
"=",
"'**'",
",",
"chunk_size",
"=",
"default_chunk_size",
")",
":",
"is_dir",
"=",
"isinstance",
"(",
"path",
",",
"six",
".",
"string_types",
")",
"and",
"os",
... | Gets a buffered generator for streaming either files or directories.
Returns a buffered generator which encodes the file or directory at the
given path as :mimetype:`multipart/form-data` with the corresponding
headers.
Parameters
----------
path : str
The filepath of the directory or file to stream
recursive : bool
Stream all content within the directory recursively?
patterns : str | list
Single *glob* pattern or list of *glob* patterns and compiled
regular expressions to match the names of the filepaths to keep
chunk_size : int
Maximum size of each stream chunk | [
"Gets",
"a",
"buffered",
"generator",
"for",
"streaming",
"either",
"files",
"or",
"directories",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/multipart.py#L607-L633 | train | 229,516 |
ipfs/py-ipfs-api | ipfsapi/multipart.py | stream_bytes | def stream_bytes(data, chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming binary data.
Returns a buffered generator which encodes binary data as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
data : bytes
The data bytes to stream
chunk_size : int
The maximum size of each stream chunk
Returns
-------
(generator, dict)
"""
stream = BytesStream(data, chunk_size=chunk_size)
return stream.body(), stream.headers | python | def stream_bytes(data, chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming binary data.
Returns a buffered generator which encodes binary data as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
data : bytes
The data bytes to stream
chunk_size : int
The maximum size of each stream chunk
Returns
-------
(generator, dict)
"""
stream = BytesStream(data, chunk_size=chunk_size)
return stream.body(), stream.headers | [
"def",
"stream_bytes",
"(",
"data",
",",
"chunk_size",
"=",
"default_chunk_size",
")",
":",
"stream",
"=",
"BytesStream",
"(",
"data",
",",
"chunk_size",
"=",
"chunk_size",
")",
"return",
"stream",
".",
"body",
"(",
")",
",",
"stream",
".",
"headers"
] | Gets a buffered generator for streaming binary data.
Returns a buffered generator which encodes binary data as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
data : bytes
The data bytes to stream
chunk_size : int
The maximum size of each stream chunk
Returns
-------
(generator, dict) | [
"Gets",
"a",
"buffered",
"generator",
"for",
"streaming",
"binary",
"data",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/multipart.py#L636-L655 | train | 229,517 |
ipfs/py-ipfs-api | ipfsapi/multipart.py | stream_text | def stream_text(text, chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming text.
Returns a buffered generator which encodes a string as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
text : str
The data bytes to stream
chunk_size : int
The maximum size of each stream chunk
Returns
-------
(generator, dict)
"""
if isgenerator(text):
def binary_stream():
for item in text:
if six.PY2 and isinstance(text, six.binary_type):
#PY2: Allow binary strings under Python 2 since
# Python 2 code is not expected to always get the
# distinction between text and binary strings right.
yield text
else:
yield text.encode("utf-8")
data = binary_stream()
elif six.PY2 and isinstance(text, six.binary_type):
#PY2: See above.
data = text
else:
data = text.encode("utf-8")
return stream_bytes(data, chunk_size) | python | def stream_text(text, chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming text.
Returns a buffered generator which encodes a string as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
text : str
The data bytes to stream
chunk_size : int
The maximum size of each stream chunk
Returns
-------
(generator, dict)
"""
if isgenerator(text):
def binary_stream():
for item in text:
if six.PY2 and isinstance(text, six.binary_type):
#PY2: Allow binary strings under Python 2 since
# Python 2 code is not expected to always get the
# distinction between text and binary strings right.
yield text
else:
yield text.encode("utf-8")
data = binary_stream()
elif six.PY2 and isinstance(text, six.binary_type):
#PY2: See above.
data = text
else:
data = text.encode("utf-8")
return stream_bytes(data, chunk_size) | [
"def",
"stream_text",
"(",
"text",
",",
"chunk_size",
"=",
"default_chunk_size",
")",
":",
"if",
"isgenerator",
"(",
"text",
")",
":",
"def",
"binary_stream",
"(",
")",
":",
"for",
"item",
"in",
"text",
":",
"if",
"six",
".",
"PY2",
"and",
"isinstance",
... | Gets a buffered generator for streaming text.
Returns a buffered generator which encodes a string as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
text : str
The data bytes to stream
chunk_size : int
The maximum size of each stream chunk
Returns
-------
(generator, dict) | [
"Gets",
"a",
"buffered",
"generator",
"for",
"streaming",
"text",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/multipart.py#L658-L692 | train | 229,518 |
ipfs/py-ipfs-api | ipfsapi/multipart.py | BodyGenerator._write_headers | def _write_headers(self, headers):
"""Yields the HTTP header text for some content.
Parameters
----------
headers : dict
The headers to yield
"""
if headers:
for name in sorted(headers.keys()):
yield name.encode("ascii")
yield b': '
yield headers[name].encode("ascii")
yield CRLF
yield CRLF | python | def _write_headers(self, headers):
"""Yields the HTTP header text for some content.
Parameters
----------
headers : dict
The headers to yield
"""
if headers:
for name in sorted(headers.keys()):
yield name.encode("ascii")
yield b': '
yield headers[name].encode("ascii")
yield CRLF
yield CRLF | [
"def",
"_write_headers",
"(",
"self",
",",
"headers",
")",
":",
"if",
"headers",
":",
"for",
"name",
"in",
"sorted",
"(",
"headers",
".",
"keys",
"(",
")",
")",
":",
"yield",
"name",
".",
"encode",
"(",
"\"ascii\"",
")",
"yield",
"b': '",
"yield",
"h... | Yields the HTTP header text for some content.
Parameters
----------
headers : dict
The headers to yield | [
"Yields",
"the",
"HTTP",
"header",
"text",
"for",
"some",
"content",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/multipart.py#L141-L155 | train | 229,519 |
ipfs/py-ipfs-api | ipfsapi/multipart.py | BodyGenerator.file_open | def file_open(self, fn):
"""Yields the opening text of a file section in multipart HTTP.
Parameters
----------
fn : str
Filename for the file being opened and added to the HTTP body
"""
yield b'--'
yield self.boundary.encode()
yield CRLF
headers = content_disposition(fn)
headers.update(content_type(fn))
for c in self._write_headers(headers):
yield c | python | def file_open(self, fn):
"""Yields the opening text of a file section in multipart HTTP.
Parameters
----------
fn : str
Filename for the file being opened and added to the HTTP body
"""
yield b'--'
yield self.boundary.encode()
yield CRLF
headers = content_disposition(fn)
headers.update(content_type(fn))
for c in self._write_headers(headers):
yield c | [
"def",
"file_open",
"(",
"self",
",",
"fn",
")",
":",
"yield",
"b'--'",
"yield",
"self",
".",
"boundary",
".",
"encode",
"(",
")",
"yield",
"CRLF",
"headers",
"=",
"content_disposition",
"(",
"fn",
")",
"headers",
".",
"update",
"(",
"content_type",
"(",... | Yields the opening text of a file section in multipart HTTP.
Parameters
----------
fn : str
Filename for the file being opened and added to the HTTP body | [
"Yields",
"the",
"opening",
"text",
"of",
"a",
"file",
"section",
"in",
"multipart",
"HTTP",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/multipart.py#L169-L183 | train | 229,520 |
ipfs/py-ipfs-api | ipfsapi/multipart.py | BufferedGenerator.file_chunks | def file_chunks(self, fp):
"""Yields chunks of a file.
Parameters
----------
fp : io.RawIOBase
The file to break into chunks
(must be an open file or have the ``readinto`` method)
"""
fsize = utils.file_size(fp)
offset = 0
if hasattr(fp, 'readinto'):
while offset < fsize:
nb = fp.readinto(self._internal)
yield self.buf[:nb]
offset += nb
else:
while offset < fsize:
nb = min(self.chunk_size, fsize - offset)
yield fp.read(nb)
offset += nb | python | def file_chunks(self, fp):
"""Yields chunks of a file.
Parameters
----------
fp : io.RawIOBase
The file to break into chunks
(must be an open file or have the ``readinto`` method)
"""
fsize = utils.file_size(fp)
offset = 0
if hasattr(fp, 'readinto'):
while offset < fsize:
nb = fp.readinto(self._internal)
yield self.buf[:nb]
offset += nb
else:
while offset < fsize:
nb = min(self.chunk_size, fsize - offset)
yield fp.read(nb)
offset += nb | [
"def",
"file_chunks",
"(",
"self",
",",
"fp",
")",
":",
"fsize",
"=",
"utils",
".",
"file_size",
"(",
"fp",
")",
"offset",
"=",
"0",
"if",
"hasattr",
"(",
"fp",
",",
"'readinto'",
")",
":",
"while",
"offset",
"<",
"fsize",
":",
"nb",
"=",
"fp",
"... | Yields chunks of a file.
Parameters
----------
fp : io.RawIOBase
The file to break into chunks
(must be an open file or have the ``readinto`` method) | [
"Yields",
"chunks",
"of",
"a",
"file",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/multipart.py#L222-L242 | train | 229,521 |
ipfs/py-ipfs-api | ipfsapi/multipart.py | BufferedGenerator.gen_chunks | def gen_chunks(self, gen):
"""Generates byte chunks of a given size.
Takes a bytes generator and yields chunks of a maximum of
``chunk_size`` bytes.
Parameters
----------
gen : generator
The bytes generator that produces the bytes
"""
for data in gen:
size = len(data)
if size < self.chunk_size:
yield data
else:
mv = buffer(data)
offset = 0
while offset < size:
nb = min(self.chunk_size, size - offset)
yield mv[offset:offset + nb]
offset += nb | python | def gen_chunks(self, gen):
"""Generates byte chunks of a given size.
Takes a bytes generator and yields chunks of a maximum of
``chunk_size`` bytes.
Parameters
----------
gen : generator
The bytes generator that produces the bytes
"""
for data in gen:
size = len(data)
if size < self.chunk_size:
yield data
else:
mv = buffer(data)
offset = 0
while offset < size:
nb = min(self.chunk_size, size - offset)
yield mv[offset:offset + nb]
offset += nb | [
"def",
"gen_chunks",
"(",
"self",
",",
"gen",
")",
":",
"for",
"data",
"in",
"gen",
":",
"size",
"=",
"len",
"(",
"data",
")",
"if",
"size",
"<",
"self",
".",
"chunk_size",
":",
"yield",
"data",
"else",
":",
"mv",
"=",
"buffer",
"(",
"data",
")",... | Generates byte chunks of a given size.
Takes a bytes generator and yields chunks of a maximum of
``chunk_size`` bytes.
Parameters
----------
gen : generator
The bytes generator that produces the bytes | [
"Generates",
"byte",
"chunks",
"of",
"a",
"given",
"size",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/multipart.py#L244-L265 | train | 229,522 |
ipfs/py-ipfs-api | ipfsapi/multipart.py | FileStream.body | def body(self):
"""Yields the body of the buffered file."""
for fp, need_close in self.files:
try:
name = os.path.basename(fp.name)
except AttributeError:
name = ''
for chunk in self.gen_chunks(self.envelope.file_open(name)):
yield chunk
for chunk in self.file_chunks(fp):
yield chunk
for chunk in self.gen_chunks(self.envelope.file_close()):
yield chunk
if need_close:
fp.close()
for chunk in self.close():
yield chunk | python | def body(self):
"""Yields the body of the buffered file."""
for fp, need_close in self.files:
try:
name = os.path.basename(fp.name)
except AttributeError:
name = ''
for chunk in self.gen_chunks(self.envelope.file_open(name)):
yield chunk
for chunk in self.file_chunks(fp):
yield chunk
for chunk in self.gen_chunks(self.envelope.file_close()):
yield chunk
if need_close:
fp.close()
for chunk in self.close():
yield chunk | [
"def",
"body",
"(",
"self",
")",
":",
"for",
"fp",
",",
"need_close",
"in",
"self",
".",
"files",
":",
"try",
":",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"fp",
".",
"name",
")",
"except",
"AttributeError",
":",
"name",
"=",
"''",
"... | Yields the body of the buffered file. | [
"Yields",
"the",
"body",
"of",
"the",
"buffered",
"file",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/multipart.py#L300-L316 | train | 229,523 |
ipfs/py-ipfs-api | ipfsapi/multipart.py | DirectoryStream._prepare | def _prepare(self):
"""Pre-formats the multipart HTTP request to transmit the directory."""
names = []
added_directories = set()
def add_directory(short_path):
# Do not continue if this directory has already been added
if short_path in added_directories:
return
# Scan for first super-directory that has already been added
dir_base = short_path
dir_parts = []
while dir_base:
dir_base, dir_name = os.path.split(dir_base)
dir_parts.append(dir_name)
if dir_base in added_directories:
break
# Add missing intermediate directory nodes in the right order
while dir_parts:
dir_base = os.path.join(dir_base, dir_parts.pop())
# Create an empty, fake file to represent the directory
mock_file = io.StringIO()
mock_file.write(u'')
# Add this directory to those that will be sent
names.append(('files',
(dir_base.replace(os.sep, '/'), mock_file, 'application/x-directory')))
# Remember that this directory has already been sent
added_directories.add(dir_base)
def add_file(short_path, full_path):
try:
# Always add files in wildcard directories
names.append(('files', (short_name.replace(os.sep, '/'),
open(full_path, 'rb'),
'application/octet-stream')))
except OSError:
# File might have disappeared between `os.walk()` and `open()`
pass
def match_short_path(short_path):
# Remove initial path component so that all files are based in
# the target directory itself (not one level above)
if os.sep in short_path:
path = short_path.split(os.sep, 1)[1]
else:
return False
# Convert all path seperators to POSIX style
path = path.replace(os.sep, '/')
# Do the matching and the simplified path
for pattern in self.patterns:
if pattern.match(path):
return True
return False
# Identify the unecessary portion of the relative path
truncate = os.path.dirname(self.directory)
# Traverse the filesystem downward from the target directory's uri
# Errors: `os.walk()` will simply return an empty generator if the
# target directory does not exist.
wildcard_directories = set()
for curr_dir, _, files in os.walk(self.directory):
# find the path relative to the directory being added
if len(truncate) > 0:
_, _, short_path = curr_dir.partition(truncate)
else:
short_path = curr_dir
# remove leading / or \ if it is present
if short_path.startswith(os.sep):
short_path = short_path[1:]
wildcard_directory = False
if os.path.split(short_path)[0] in wildcard_directories:
# Parent directory has matched a pattern, all sub-nodes should
# be added too
wildcard_directories.add(short_path)
wildcard_directory = True
else:
# Check if directory path matches one of the patterns
if match_short_path(short_path):
# Directory matched pattern and it should therefor
# be added along with all of its contents
wildcard_directories.add(short_path)
wildcard_directory = True
# Always add directories within wildcard directories - even if they
# are empty
if wildcard_directory:
add_directory(short_path)
# Iterate across the files in the current directory
for filename in files:
# Find the filename relative to the directory being added
short_name = os.path.join(short_path, filename)
filepath = os.path.join(curr_dir, filename)
if wildcard_directory:
# Always add files in wildcard directories
add_file(short_name, filepath)
else:
# Add file (and all missing intermediary directories)
# if it matches one of the patterns
if match_short_path(short_name):
add_directory(short_path)
add_file(short_name, filepath)
# Send the request and present the response body to the user
req = requests.Request("POST", 'http://localhost', files=names)
prep = req.prepare()
return prep | python | def _prepare(self):
"""Pre-formats the multipart HTTP request to transmit the directory."""
names = []
added_directories = set()
def add_directory(short_path):
# Do not continue if this directory has already been added
if short_path in added_directories:
return
# Scan for first super-directory that has already been added
dir_base = short_path
dir_parts = []
while dir_base:
dir_base, dir_name = os.path.split(dir_base)
dir_parts.append(dir_name)
if dir_base in added_directories:
break
# Add missing intermediate directory nodes in the right order
while dir_parts:
dir_base = os.path.join(dir_base, dir_parts.pop())
# Create an empty, fake file to represent the directory
mock_file = io.StringIO()
mock_file.write(u'')
# Add this directory to those that will be sent
names.append(('files',
(dir_base.replace(os.sep, '/'), mock_file, 'application/x-directory')))
# Remember that this directory has already been sent
added_directories.add(dir_base)
def add_file(short_path, full_path):
try:
# Always add files in wildcard directories
names.append(('files', (short_name.replace(os.sep, '/'),
open(full_path, 'rb'),
'application/octet-stream')))
except OSError:
# File might have disappeared between `os.walk()` and `open()`
pass
def match_short_path(short_path):
# Remove initial path component so that all files are based in
# the target directory itself (not one level above)
if os.sep in short_path:
path = short_path.split(os.sep, 1)[1]
else:
return False
# Convert all path seperators to POSIX style
path = path.replace(os.sep, '/')
# Do the matching and the simplified path
for pattern in self.patterns:
if pattern.match(path):
return True
return False
# Identify the unecessary portion of the relative path
truncate = os.path.dirname(self.directory)
# Traverse the filesystem downward from the target directory's uri
# Errors: `os.walk()` will simply return an empty generator if the
# target directory does not exist.
wildcard_directories = set()
for curr_dir, _, files in os.walk(self.directory):
# find the path relative to the directory being added
if len(truncate) > 0:
_, _, short_path = curr_dir.partition(truncate)
else:
short_path = curr_dir
# remove leading / or \ if it is present
if short_path.startswith(os.sep):
short_path = short_path[1:]
wildcard_directory = False
if os.path.split(short_path)[0] in wildcard_directories:
# Parent directory has matched a pattern, all sub-nodes should
# be added too
wildcard_directories.add(short_path)
wildcard_directory = True
else:
# Check if directory path matches one of the patterns
if match_short_path(short_path):
# Directory matched pattern and it should therefor
# be added along with all of its contents
wildcard_directories.add(short_path)
wildcard_directory = True
# Always add directories within wildcard directories - even if they
# are empty
if wildcard_directory:
add_directory(short_path)
# Iterate across the files in the current directory
for filename in files:
# Find the filename relative to the directory being added
short_name = os.path.join(short_path, filename)
filepath = os.path.join(curr_dir, filename)
if wildcard_directory:
# Always add files in wildcard directories
add_file(short_name, filepath)
else:
# Add file (and all missing intermediary directories)
# if it matches one of the patterns
if match_short_path(short_name):
add_directory(short_path)
add_file(short_name, filepath)
# Send the request and present the response body to the user
req = requests.Request("POST", 'http://localhost', files=names)
prep = req.prepare()
return prep | [
"def",
"_prepare",
"(",
"self",
")",
":",
"names",
"=",
"[",
"]",
"added_directories",
"=",
"set",
"(",
")",
"def",
"add_directory",
"(",
"short_path",
")",
":",
"# Do not continue if this directory has already been added",
"if",
"short_path",
"in",
"added_directori... | Pre-formats the multipart HTTP request to transmit the directory. | [
"Pre",
"-",
"formats",
"the",
"multipart",
"HTTP",
"request",
"to",
"transmit",
"the",
"directory",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/multipart.py#L415-L528 | train | 229,524 |
ipfs/py-ipfs-api | ipfsapi/multipart.py | BytesStream.body | def body(self):
"""Yields the encoded body."""
for chunk in self.gen_chunks(self.envelope.file_open(self.name)):
yield chunk
for chunk in self.gen_chunks(self.data):
yield chunk
for chunk in self.gen_chunks(self.envelope.file_close()):
yield chunk
for chunk in self.close():
yield chunk | python | def body(self):
"""Yields the encoded body."""
for chunk in self.gen_chunks(self.envelope.file_open(self.name)):
yield chunk
for chunk in self.gen_chunks(self.data):
yield chunk
for chunk in self.gen_chunks(self.envelope.file_close()):
yield chunk
for chunk in self.close():
yield chunk | [
"def",
"body",
"(",
"self",
")",
":",
"for",
"chunk",
"in",
"self",
".",
"gen_chunks",
"(",
"self",
".",
"envelope",
".",
"file_open",
"(",
"self",
".",
"name",
")",
")",
":",
"yield",
"chunk",
"for",
"chunk",
"in",
"self",
".",
"gen_chunks",
"(",
... | Yields the encoded body. | [
"Yields",
"the",
"encoded",
"body",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/multipart.py#L548-L557 | train | 229,525 |
ipfs/py-ipfs-api | ipfsapi/http.py | pass_defaults | def pass_defaults(func):
"""Decorator that returns a function named wrapper.
When invoked, wrapper invokes func with default kwargs appended.
Parameters
----------
func : callable
The function to append the default kwargs to
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
merged = {}
merged.update(self.defaults)
merged.update(kwargs)
return func(self, *args, **merged)
return wrapper | python | def pass_defaults(func):
"""Decorator that returns a function named wrapper.
When invoked, wrapper invokes func with default kwargs appended.
Parameters
----------
func : callable
The function to append the default kwargs to
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
merged = {}
merged.update(self.defaults)
merged.update(kwargs)
return func(self, *args, **merged)
return wrapper | [
"def",
"pass_defaults",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"merged",
"=",
"{",
"}",
"merged",
".",
"update",
"(",
"self",
".... | Decorator that returns a function named wrapper.
When invoked, wrapper invokes func with default kwargs appended.
Parameters
----------
func : callable
The function to append the default kwargs to | [
"Decorator",
"that",
"returns",
"a",
"function",
"named",
"wrapper",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/http.py#L23-L39 | train | 229,526 |
ipfs/py-ipfs-api | ipfsapi/http.py | HTTPClient.request | def request(self, path,
args=[], files=[], opts={}, stream=False,
decoder=None, headers={}, data=None):
"""Makes an HTTP request to the IPFS daemon.
This function returns the contents of the HTTP response from the IPFS
daemon.
Raises
------
~ipfsapi.exceptions.ErrorResponse
~ipfsapi.exceptions.ConnectionError
~ipfsapi.exceptions.ProtocolError
~ipfsapi.exceptions.StatusError
~ipfsapi.exceptions.TimeoutError
Parameters
----------
path : str
The REST command path to send
args : list
Positional parameters to be sent along with the HTTP request
files : :class:`io.RawIOBase` | :obj:`str` | :obj:`list`
The file object(s) or path(s) to stream to the daemon
opts : dict
Query string paramters to be sent along with the HTTP request
decoder : str
The encoder to use to parse the HTTP response
kwargs : dict
Additional arguments to pass to :mod:`requests`
"""
url = self.base + path
params = []
params.append(('stream-channels', 'true'))
for opt in opts.items():
params.append(opt)
for arg in args:
params.append(('arg', arg))
method = 'post' if (files or data) else 'get'
parser = encoding.get_encoding(decoder if decoder else "none")
return self._request(method, url, params, parser, stream,
files, headers, data) | python | def request(self, path,
args=[], files=[], opts={}, stream=False,
decoder=None, headers={}, data=None):
"""Makes an HTTP request to the IPFS daemon.
This function returns the contents of the HTTP response from the IPFS
daemon.
Raises
------
~ipfsapi.exceptions.ErrorResponse
~ipfsapi.exceptions.ConnectionError
~ipfsapi.exceptions.ProtocolError
~ipfsapi.exceptions.StatusError
~ipfsapi.exceptions.TimeoutError
Parameters
----------
path : str
The REST command path to send
args : list
Positional parameters to be sent along with the HTTP request
files : :class:`io.RawIOBase` | :obj:`str` | :obj:`list`
The file object(s) or path(s) to stream to the daemon
opts : dict
Query string paramters to be sent along with the HTTP request
decoder : str
The encoder to use to parse the HTTP response
kwargs : dict
Additional arguments to pass to :mod:`requests`
"""
url = self.base + path
params = []
params.append(('stream-channels', 'true'))
for opt in opts.items():
params.append(opt)
for arg in args:
params.append(('arg', arg))
method = 'post' if (files or data) else 'get'
parser = encoding.get_encoding(decoder if decoder else "none")
return self._request(method, url, params, parser, stream,
files, headers, data) | [
"def",
"request",
"(",
"self",
",",
"path",
",",
"args",
"=",
"[",
"]",
",",
"files",
"=",
"[",
"]",
",",
"opts",
"=",
"{",
"}",
",",
"stream",
"=",
"False",
",",
"decoder",
"=",
"None",
",",
"headers",
"=",
"{",
"}",
",",
"data",
"=",
"None"... | Makes an HTTP request to the IPFS daemon.
This function returns the contents of the HTTP response from the IPFS
daemon.
Raises
------
~ipfsapi.exceptions.ErrorResponse
~ipfsapi.exceptions.ConnectionError
~ipfsapi.exceptions.ProtocolError
~ipfsapi.exceptions.StatusError
~ipfsapi.exceptions.TimeoutError
Parameters
----------
path : str
The REST command path to send
args : list
Positional parameters to be sent along with the HTTP request
files : :class:`io.RawIOBase` | :obj:`str` | :obj:`list`
The file object(s) or path(s) to stream to the daemon
opts : dict
Query string paramters to be sent along with the HTTP request
decoder : str
The encoder to use to parse the HTTP response
kwargs : dict
Additional arguments to pass to :mod:`requests` | [
"Makes",
"an",
"HTTP",
"request",
"to",
"the",
"IPFS",
"daemon",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/http.py#L202-L247 | train | 229,527 |
ipfs/py-ipfs-api | ipfsapi/http.py | HTTPClient.download | def download(self, path, args=[], filepath=None, opts={},
compress=True, **kwargs):
"""Makes a request to the IPFS daemon to download a file.
Downloads a file or files from IPFS into the current working
directory, or the directory given by ``filepath``.
Raises
------
~ipfsapi.exceptions.ErrorResponse
~ipfsapi.exceptions.ConnectionError
~ipfsapi.exceptions.ProtocolError
~ipfsapi.exceptions.StatusError
~ipfsapi.exceptions.TimeoutError
Parameters
----------
path : str
The REST command path to send
filepath : str
The local path where IPFS will store downloaded files
Defaults to the current working directory.
args : list
Positional parameters to be sent along with the HTTP request
opts : dict
Query string paramters to be sent along with the HTTP request
compress : bool
Whether the downloaded file should be GZip compressed by the
daemon before being sent to the client
kwargs : dict
Additional arguments to pass to :mod:`requests`
"""
url = self.base + path
wd = filepath or '.'
params = []
params.append(('stream-channels', 'true'))
params.append(('archive', 'true'))
if compress:
params.append(('compress', 'true'))
for opt in opts.items():
params.append(opt)
for arg in args:
params.append(('arg', arg))
method = 'get'
res = self._do_request(method, url, params=params, stream=True,
**kwargs)
self._do_raise_for_status(res)
# try to stream download as a tar file stream
mode = 'r|gz' if compress else 'r|'
with tarfile.open(fileobj=res.raw, mode=mode) as tf:
tf.extractall(path=wd) | python | def download(self, path, args=[], filepath=None, opts={},
compress=True, **kwargs):
"""Makes a request to the IPFS daemon to download a file.
Downloads a file or files from IPFS into the current working
directory, or the directory given by ``filepath``.
Raises
------
~ipfsapi.exceptions.ErrorResponse
~ipfsapi.exceptions.ConnectionError
~ipfsapi.exceptions.ProtocolError
~ipfsapi.exceptions.StatusError
~ipfsapi.exceptions.TimeoutError
Parameters
----------
path : str
The REST command path to send
filepath : str
The local path where IPFS will store downloaded files
Defaults to the current working directory.
args : list
Positional parameters to be sent along with the HTTP request
opts : dict
Query string paramters to be sent along with the HTTP request
compress : bool
Whether the downloaded file should be GZip compressed by the
daemon before being sent to the client
kwargs : dict
Additional arguments to pass to :mod:`requests`
"""
url = self.base + path
wd = filepath or '.'
params = []
params.append(('stream-channels', 'true'))
params.append(('archive', 'true'))
if compress:
params.append(('compress', 'true'))
for opt in opts.items():
params.append(opt)
for arg in args:
params.append(('arg', arg))
method = 'get'
res = self._do_request(method, url, params=params, stream=True,
**kwargs)
self._do_raise_for_status(res)
# try to stream download as a tar file stream
mode = 'r|gz' if compress else 'r|'
with tarfile.open(fileobj=res.raw, mode=mode) as tf:
tf.extractall(path=wd) | [
"def",
"download",
"(",
"self",
",",
"path",
",",
"args",
"=",
"[",
"]",
",",
"filepath",
"=",
"None",
",",
"opts",
"=",
"{",
"}",
",",
"compress",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"base",
"+",
"path",
... | Makes a request to the IPFS daemon to download a file.
Downloads a file or files from IPFS into the current working
directory, or the directory given by ``filepath``.
Raises
------
~ipfsapi.exceptions.ErrorResponse
~ipfsapi.exceptions.ConnectionError
~ipfsapi.exceptions.ProtocolError
~ipfsapi.exceptions.StatusError
~ipfsapi.exceptions.TimeoutError
Parameters
----------
path : str
The REST command path to send
filepath : str
The local path where IPFS will store downloaded files
Defaults to the current working directory.
args : list
Positional parameters to be sent along with the HTTP request
opts : dict
Query string paramters to be sent along with the HTTP request
compress : bool
Whether the downloaded file should be GZip compressed by the
daemon before being sent to the client
kwargs : dict
Additional arguments to pass to :mod:`requests` | [
"Makes",
"a",
"request",
"to",
"the",
"IPFS",
"daemon",
"to",
"download",
"a",
"file",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/http.py#L250-L308 | train | 229,528 |
ipfs/py-ipfs-api | ipfsapi/http.py | HTTPClient.session | def session(self):
"""A context manager for this client's session.
This function closes the current session when this client goes out of
scope.
"""
self._session = requests.session()
yield
self._session.close()
self._session = None | python | def session(self):
"""A context manager for this client's session.
This function closes the current session when this client goes out of
scope.
"""
self._session = requests.session()
yield
self._session.close()
self._session = None | [
"def",
"session",
"(",
"self",
")",
":",
"self",
".",
"_session",
"=",
"requests",
".",
"session",
"(",
")",
"yield",
"self",
".",
"_session",
".",
"close",
"(",
")",
"self",
".",
"_session",
"=",
"None"
] | A context manager for this client's session.
This function closes the current session when this client goes out of
scope. | [
"A",
"context",
"manager",
"for",
"this",
"client",
"s",
"session",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/http.py#L311-L320 | train | 229,529 |
ipfs/py-ipfs-api | ipfsapi/client.py | assert_version | def assert_version(version, minimum=VERSION_MINIMUM, maximum=VERSION_MAXIMUM):
"""Make sure that the given daemon version is supported by this client
version.
Raises
------
~ipfsapi.exceptions.VersionMismatch
Parameters
----------
version : str
The version of an IPFS daemon.
minimum : str
The minimal IPFS version to allow.
maximum : str
The maximum IPFS version to allow.
"""
# Convert version strings to integer tuples
version = list(map(int, version.split('-', 1)[0].split('.')))
minimum = list(map(int, minimum.split('-', 1)[0].split('.')))
maximum = list(map(int, maximum.split('-', 1)[0].split('.')))
if minimum > version or version >= maximum:
raise exceptions.VersionMismatch(version, minimum, maximum) | python | def assert_version(version, minimum=VERSION_MINIMUM, maximum=VERSION_MAXIMUM):
"""Make sure that the given daemon version is supported by this client
version.
Raises
------
~ipfsapi.exceptions.VersionMismatch
Parameters
----------
version : str
The version of an IPFS daemon.
minimum : str
The minimal IPFS version to allow.
maximum : str
The maximum IPFS version to allow.
"""
# Convert version strings to integer tuples
version = list(map(int, version.split('-', 1)[0].split('.')))
minimum = list(map(int, minimum.split('-', 1)[0].split('.')))
maximum = list(map(int, maximum.split('-', 1)[0].split('.')))
if minimum > version or version >= maximum:
raise exceptions.VersionMismatch(version, minimum, maximum) | [
"def",
"assert_version",
"(",
"version",
",",
"minimum",
"=",
"VERSION_MINIMUM",
",",
"maximum",
"=",
"VERSION_MAXIMUM",
")",
":",
"# Convert version strings to integer tuples",
"version",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"version",
".",
"split",
"(",
"... | Make sure that the given daemon version is supported by this client
version.
Raises
------
~ipfsapi.exceptions.VersionMismatch
Parameters
----------
version : str
The version of an IPFS daemon.
minimum : str
The minimal IPFS version to allow.
maximum : str
The maximum IPFS version to allow. | [
"Make",
"sure",
"that",
"the",
"given",
"daemon",
"version",
"is",
"supported",
"by",
"this",
"client",
"version",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L23-L46 | train | 229,530 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.add | def add(self, files, recursive=False, pattern='**', *args, **kwargs):
"""Add a file, or directory of files to IPFS.
.. code-block:: python
>>> with io.open('nurseryrhyme.txt', 'w', encoding='utf-8') as f:
... numbytes = f.write('Mary had a little lamb')
>>> c.add('nurseryrhyme.txt')
{'Hash': 'QmZfF6C9j4VtoCsTp4KSrhYH47QMd3DNXVZBKaxJdhaPab',
'Name': 'nurseryrhyme.txt'}
Parameters
----------
files : str
A filepath to either a file or directory
recursive : bool
Controls if files in subdirectories are added or not
pattern : str | list
Single `*glob* <https://docs.python.org/3/library/glob.html>`_
pattern or list of *glob* patterns and compiled regular expressions
to match the names of the filepaths to keep
trickle : bool
Use trickle-dag format (optimized for streaming) when generating
the dag; see `the FAQ <https://github.com/ipfs/faq/issues/218>` for
more information (Default: ``False``)
only_hash : bool
Only chunk and hash, but do not write to disk (Default: ``False``)
wrap_with_directory : bool
Wrap files with a directory object to preserve their filename
(Default: ``False``)
chunker : str
The chunking algorithm to use
pin : bool
Pin this object when adding (Default: ``True``)
Returns
-------
dict: File name and hash of the added file node
"""
#PY2: No support for kw-only parameters after glob parameters
opts = {
"trickle": kwargs.pop("trickle", False),
"only-hash": kwargs.pop("only_hash", False),
"wrap-with-directory": kwargs.pop("wrap_with_directory", False),
"pin": kwargs.pop("pin", True)
}
if "chunker" in kwargs:
opts["chunker"] = kwargs.pop("chunker")
kwargs.setdefault("opts", opts)
body, headers = multipart.stream_filesystem_node(
files, recursive, pattern, self.chunk_size
)
return self._client.request('/add', decoder='json',
data=body, headers=headers, **kwargs) | python | def add(self, files, recursive=False, pattern='**', *args, **kwargs):
"""Add a file, or directory of files to IPFS.
.. code-block:: python
>>> with io.open('nurseryrhyme.txt', 'w', encoding='utf-8') as f:
... numbytes = f.write('Mary had a little lamb')
>>> c.add('nurseryrhyme.txt')
{'Hash': 'QmZfF6C9j4VtoCsTp4KSrhYH47QMd3DNXVZBKaxJdhaPab',
'Name': 'nurseryrhyme.txt'}
Parameters
----------
files : str
A filepath to either a file or directory
recursive : bool
Controls if files in subdirectories are added or not
pattern : str | list
Single `*glob* <https://docs.python.org/3/library/glob.html>`_
pattern or list of *glob* patterns and compiled regular expressions
to match the names of the filepaths to keep
trickle : bool
Use trickle-dag format (optimized for streaming) when generating
the dag; see `the FAQ <https://github.com/ipfs/faq/issues/218>` for
more information (Default: ``False``)
only_hash : bool
Only chunk and hash, but do not write to disk (Default: ``False``)
wrap_with_directory : bool
Wrap files with a directory object to preserve their filename
(Default: ``False``)
chunker : str
The chunking algorithm to use
pin : bool
Pin this object when adding (Default: ``True``)
Returns
-------
dict: File name and hash of the added file node
"""
#PY2: No support for kw-only parameters after glob parameters
opts = {
"trickle": kwargs.pop("trickle", False),
"only-hash": kwargs.pop("only_hash", False),
"wrap-with-directory": kwargs.pop("wrap_with_directory", False),
"pin": kwargs.pop("pin", True)
}
if "chunker" in kwargs:
opts["chunker"] = kwargs.pop("chunker")
kwargs.setdefault("opts", opts)
body, headers = multipart.stream_filesystem_node(
files, recursive, pattern, self.chunk_size
)
return self._client.request('/add', decoder='json',
data=body, headers=headers, **kwargs) | [
"def",
"add",
"(",
"self",
",",
"files",
",",
"recursive",
"=",
"False",
",",
"pattern",
"=",
"'**'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#PY2: No support for kw-only parameters after glob parameters",
"opts",
"=",
"{",
"\"trickle\"",
":",
... | Add a file, or directory of files to IPFS.
.. code-block:: python
>>> with io.open('nurseryrhyme.txt', 'w', encoding='utf-8') as f:
... numbytes = f.write('Mary had a little lamb')
>>> c.add('nurseryrhyme.txt')
{'Hash': 'QmZfF6C9j4VtoCsTp4KSrhYH47QMd3DNXVZBKaxJdhaPab',
'Name': 'nurseryrhyme.txt'}
Parameters
----------
files : str
A filepath to either a file or directory
recursive : bool
Controls if files in subdirectories are added or not
pattern : str | list
Single `*glob* <https://docs.python.org/3/library/glob.html>`_
pattern or list of *glob* patterns and compiled regular expressions
to match the names of the filepaths to keep
trickle : bool
Use trickle-dag format (optimized for streaming) when generating
the dag; see `the FAQ <https://github.com/ipfs/faq/issues/218>` for
more information (Default: ``False``)
only_hash : bool
Only chunk and hash, but do not write to disk (Default: ``False``)
wrap_with_directory : bool
Wrap files with a directory object to preserve their filename
(Default: ``False``)
chunker : str
The chunking algorithm to use
pin : bool
Pin this object when adding (Default: ``True``)
Returns
-------
dict: File name and hash of the added file node | [
"Add",
"a",
"file",
"or",
"directory",
"of",
"files",
"to",
"IPFS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L135-L189 | train | 229,531 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.get | def get(self, multihash, **kwargs):
"""Downloads a file, or directory of files from IPFS.
Files are placed in the current working directory.
Parameters
----------
multihash : str
The path to the IPFS object(s) to be outputted
"""
args = (multihash,)
return self._client.download('/get', args, **kwargs) | python | def get(self, multihash, **kwargs):
"""Downloads a file, or directory of files from IPFS.
Files are placed in the current working directory.
Parameters
----------
multihash : str
The path to the IPFS object(s) to be outputted
"""
args = (multihash,)
return self._client.download('/get', args, **kwargs) | [
"def",
"get",
"(",
"self",
",",
"multihash",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"multihash",
",",
")",
"return",
"self",
".",
"_client",
".",
"download",
"(",
"'/get'",
",",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Downloads a file, or directory of files from IPFS.
Files are placed in the current working directory.
Parameters
----------
multihash : str
The path to the IPFS object(s) to be outputted | [
"Downloads",
"a",
"file",
"or",
"directory",
"of",
"files",
"from",
"IPFS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L191-L202 | train | 229,532 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.cat | def cat(self, multihash, offset=0, length=-1, **kwargs):
r"""Retrieves the contents of a file identified by hash.
.. code-block:: python
>>> c.cat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
Traceback (most recent call last):
...
ipfsapi.exceptions.Error: this dag node is a directory
>>> c.cat('QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX')
b'<!DOCTYPE html>\n<html>\n\n<head>\n<title>ipfs example viewer</…'
Parameters
----------
multihash : str
The path to the IPFS object(s) to be retrieved
offset : int
Byte offset to begin reading from
length : int
Maximum number of bytes to read(-1 for all)
Returns
-------
str : File contents
"""
opts = {}
if offset != 0:
opts['offset'] = offset
if length != -1:
opts['length'] = length
args = (multihash,)
return self._client.request('/cat', args, opts=opts, **kwargs) | python | def cat(self, multihash, offset=0, length=-1, **kwargs):
r"""Retrieves the contents of a file identified by hash.
.. code-block:: python
>>> c.cat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
Traceback (most recent call last):
...
ipfsapi.exceptions.Error: this dag node is a directory
>>> c.cat('QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX')
b'<!DOCTYPE html>\n<html>\n\n<head>\n<title>ipfs example viewer</…'
Parameters
----------
multihash : str
The path to the IPFS object(s) to be retrieved
offset : int
Byte offset to begin reading from
length : int
Maximum number of bytes to read(-1 for all)
Returns
-------
str : File contents
"""
opts = {}
if offset != 0:
opts['offset'] = offset
if length != -1:
opts['length'] = length
args = (multihash,)
return self._client.request('/cat', args, opts=opts, **kwargs) | [
"def",
"cat",
"(",
"self",
",",
"multihash",
",",
"offset",
"=",
"0",
",",
"length",
"=",
"-",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"opts",
"=",
"{",
"}",
"if",
"offset",
"!=",
"0",
":",
"opts",
"[",
"'offset'",
"]",
"=",
"offset",
"if",
"... | r"""Retrieves the contents of a file identified by hash.
.. code-block:: python
>>> c.cat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
Traceback (most recent call last):
...
ipfsapi.exceptions.Error: this dag node is a directory
>>> c.cat('QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX')
b'<!DOCTYPE html>\n<html>\n\n<head>\n<title>ipfs example viewer</…'
Parameters
----------
multihash : str
The path to the IPFS object(s) to be retrieved
offset : int
Byte offset to begin reading from
length : int
Maximum number of bytes to read(-1 for all)
Returns
-------
str : File contents | [
"r",
"Retrieves",
"the",
"contents",
"of",
"a",
"file",
"identified",
"by",
"hash",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L204-L235 | train | 229,533 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.ls | def ls(self, multihash, **kwargs):
"""Returns a list of objects linked to by the given hash.
.. code-block:: python
>>> c.ls('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Objects': [
{'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 174, 'Type': 2},
…
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version', 'Size': 55, 'Type': 2}
]}
]}
Parameters
----------
multihash : str
The path to the IPFS object(s) to list links from
Returns
-------
dict : Directory information and contents
"""
args = (multihash,)
return self._client.request('/ls', args, decoder='json', **kwargs) | python | def ls(self, multihash, **kwargs):
"""Returns a list of objects linked to by the given hash.
.. code-block:: python
>>> c.ls('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Objects': [
{'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 174, 'Type': 2},
…
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version', 'Size': 55, 'Type': 2}
]}
]}
Parameters
----------
multihash : str
The path to the IPFS object(s) to list links from
Returns
-------
dict : Directory information and contents
"""
args = (multihash,)
return self._client.request('/ls', args, decoder='json', **kwargs) | [
"def",
"ls",
"(",
"self",
",",
"multihash",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"multihash",
",",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/ls'",
",",
"args",
",",
"decoder",
"=",
"'json'",
",",
"*",
"*",
"kw... | Returns a list of objects linked to by the given hash.
.. code-block:: python
>>> c.ls('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Objects': [
{'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 174, 'Type': 2},
…
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version', 'Size': 55, 'Type': 2}
]}
]}
Parameters
----------
multihash : str
The path to the IPFS object(s) to list links from
Returns
-------
dict : Directory information and contents | [
"Returns",
"a",
"list",
"of",
"objects",
"linked",
"to",
"by",
"the",
"given",
"hash",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L237-L264 | train | 229,534 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.refs | def refs(self, multihash, **kwargs):
"""Returns a list of hashes of objects referenced by the given hash.
.. code-block:: python
>>> c.refs('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
[{'Ref': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7 … cNMV', 'Err': ''},
…
{'Ref': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTi … eXJY', 'Err': ''}]
Parameters
----------
multihash : str
Path to the object(s) to list refs from
Returns
-------
list
"""
args = (multihash,)
return self._client.request('/refs', args, decoder='json', **kwargs) | python | def refs(self, multihash, **kwargs):
"""Returns a list of hashes of objects referenced by the given hash.
.. code-block:: python
>>> c.refs('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
[{'Ref': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7 … cNMV', 'Err': ''},
…
{'Ref': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTi … eXJY', 'Err': ''}]
Parameters
----------
multihash : str
Path to the object(s) to list refs from
Returns
-------
list
"""
args = (multihash,)
return self._client.request('/refs', args, decoder='json', **kwargs) | [
"def",
"refs",
"(",
"self",
",",
"multihash",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"multihash",
",",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/refs'",
",",
"args",
",",
"decoder",
"=",
"'json'",
",",
"*",
"*",
... | Returns a list of hashes of objects referenced by the given hash.
.. code-block:: python
>>> c.refs('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
[{'Ref': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7 … cNMV', 'Err': ''},
…
{'Ref': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTi … eXJY', 'Err': ''}]
Parameters
----------
multihash : str
Path to the object(s) to list refs from
Returns
-------
list | [
"Returns",
"a",
"list",
"of",
"hashes",
"of",
"objects",
"referenced",
"by",
"the",
"given",
"hash",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L266-L286 | train | 229,535 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.block_stat | def block_stat(self, multihash, **kwargs):
"""Returns a dict with the size of the block with the given hash.
.. code-block:: python
>>> c.block_stat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Key': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Size': 258}
Parameters
----------
multihash : str
The base58 multihash of an existing block to stat
Returns
-------
dict : Information about the requested block
"""
args = (multihash,)
return self._client.request('/block/stat', args,
decoder='json', **kwargs) | python | def block_stat(self, multihash, **kwargs):
"""Returns a dict with the size of the block with the given hash.
.. code-block:: python
>>> c.block_stat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Key': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Size': 258}
Parameters
----------
multihash : str
The base58 multihash of an existing block to stat
Returns
-------
dict : Information about the requested block
"""
args = (multihash,)
return self._client.request('/block/stat', args,
decoder='json', **kwargs) | [
"def",
"block_stat",
"(",
"self",
",",
"multihash",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"multihash",
",",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/block/stat'",
",",
"args",
",",
"decoder",
"=",
"'json'",
",",
"... | Returns a dict with the size of the block with the given hash.
.. code-block:: python
>>> c.block_stat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Key': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Size': 258}
Parameters
----------
multihash : str
The base58 multihash of an existing block to stat
Returns
-------
dict : Information about the requested block | [
"Returns",
"a",
"dict",
"with",
"the",
"size",
"of",
"the",
"block",
"with",
"the",
"given",
"hash",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L304-L324 | train | 229,536 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.block_get | def block_get(self, multihash, **kwargs):
r"""Returns the raw contents of a block.
.. code-block:: python
>>> c.block_get('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
b'\x121\n"\x12 \xdaW>\x14\xe5\xc1\xf6\xe4\x92\xd1 … \n\x02\x08\x01'
Parameters
----------
multihash : str
The base58 multihash of an existing block to get
Returns
-------
str : Value of the requested block
"""
args = (multihash,)
return self._client.request('/block/get', args, **kwargs) | python | def block_get(self, multihash, **kwargs):
r"""Returns the raw contents of a block.
.. code-block:: python
>>> c.block_get('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
b'\x121\n"\x12 \xdaW>\x14\xe5\xc1\xf6\xe4\x92\xd1 … \n\x02\x08\x01'
Parameters
----------
multihash : str
The base58 multihash of an existing block to get
Returns
-------
str : Value of the requested block
"""
args = (multihash,)
return self._client.request('/block/get', args, **kwargs) | [
"def",
"block_get",
"(",
"self",
",",
"multihash",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"multihash",
",",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/block/get'",
",",
"args",
",",
"*",
"*",
"kwargs",
")"
] | r"""Returns the raw contents of a block.
.. code-block:: python
>>> c.block_get('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
b'\x121\n"\x12 \xdaW>\x14\xe5\xc1\xf6\xe4\x92\xd1 … \n\x02\x08\x01'
Parameters
----------
multihash : str
The base58 multihash of an existing block to get
Returns
-------
str : Value of the requested block | [
"r",
"Returns",
"the",
"raw",
"contents",
"of",
"a",
"block",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L326-L344 | train | 229,537 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.bitswap_wantlist | def bitswap_wantlist(self, peer=None, **kwargs):
"""Returns blocks currently on the bitswap wantlist.
.. code-block:: python
>>> c.bitswap_wantlist()
{'Keys': [
'QmeV6C6XVt1wf7V7as7Yak3mxPma8jzpqyhtRtCvpKcfBb',
'QmdCWFLDXqgdWQY9kVubbEHBbkieKd3uo7MtCm7nTZZE9K',
'QmVQ1XvYGF19X4eJqz1s7FJYJqAxFC4oqh3vWJJEXn66cp'
]}
Parameters
----------
peer : str
Peer to show wantlist for.
Returns
-------
dict : List of wanted blocks
"""
args = (peer,)
return self._client.request('/bitswap/wantlist', args,
decoder='json', **kwargs) | python | def bitswap_wantlist(self, peer=None, **kwargs):
"""Returns blocks currently on the bitswap wantlist.
.. code-block:: python
>>> c.bitswap_wantlist()
{'Keys': [
'QmeV6C6XVt1wf7V7as7Yak3mxPma8jzpqyhtRtCvpKcfBb',
'QmdCWFLDXqgdWQY9kVubbEHBbkieKd3uo7MtCm7nTZZE9K',
'QmVQ1XvYGF19X4eJqz1s7FJYJqAxFC4oqh3vWJJEXn66cp'
]}
Parameters
----------
peer : str
Peer to show wantlist for.
Returns
-------
dict : List of wanted blocks
"""
args = (peer,)
return self._client.request('/bitswap/wantlist', args,
decoder='json', **kwargs) | [
"def",
"bitswap_wantlist",
"(",
"self",
",",
"peer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"peer",
",",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/bitswap/wantlist'",
",",
"args",
",",
"decoder",
"=",
"... | Returns blocks currently on the bitswap wantlist.
.. code-block:: python
>>> c.bitswap_wantlist()
{'Keys': [
'QmeV6C6XVt1wf7V7as7Yak3mxPma8jzpqyhtRtCvpKcfBb',
'QmdCWFLDXqgdWQY9kVubbEHBbkieKd3uo7MtCm7nTZZE9K',
'QmVQ1XvYGF19X4eJqz1s7FJYJqAxFC4oqh3vWJJEXn66cp'
]}
Parameters
----------
peer : str
Peer to show wantlist for.
Returns
-------
dict : List of wanted blocks | [
"Returns",
"blocks",
"currently",
"on",
"the",
"bitswap",
"wantlist",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L370-L393 | train | 229,538 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.bitswap_unwant | def bitswap_unwant(self, key, **kwargs):
"""
Remove a given block from wantlist.
Parameters
----------
key : str
Key to remove from wantlist.
"""
args = (key,)
return self._client.request('/bitswap/unwant', args, **kwargs) | python | def bitswap_unwant(self, key, **kwargs):
"""
Remove a given block from wantlist.
Parameters
----------
key : str
Key to remove from wantlist.
"""
args = (key,)
return self._client.request('/bitswap/unwant', args, **kwargs) | [
"def",
"bitswap_unwant",
"(",
"self",
",",
"key",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"key",
",",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/bitswap/unwant'",
",",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Remove a given block from wantlist.
Parameters
----------
key : str
Key to remove from wantlist. | [
"Remove",
"a",
"given",
"block",
"from",
"wantlist",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L424-L434 | train | 229,539 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.object_data | def object_data(self, multihash, **kwargs):
r"""Returns the raw bytes in an IPFS object.
.. code-block:: python
>>> c.object_data('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
b'\x08\x01'
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
str : Raw object data
"""
args = (multihash,)
return self._client.request('/object/data', args, **kwargs) | python | def object_data(self, multihash, **kwargs):
r"""Returns the raw bytes in an IPFS object.
.. code-block:: python
>>> c.object_data('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
b'\x08\x01'
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
str : Raw object data
"""
args = (multihash,)
return self._client.request('/object/data', args, **kwargs) | [
"def",
"object_data",
"(",
"self",
",",
"multihash",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"multihash",
",",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/object/data'",
",",
"args",
",",
"*",
"*",
"kwargs",
")"
] | r"""Returns the raw bytes in an IPFS object.
.. code-block:: python
>>> c.object_data('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
b'\x08\x01'
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
str : Raw object data | [
"r",
"Returns",
"the",
"raw",
"bytes",
"in",
"an",
"IPFS",
"object",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L436-L454 | train | 229,540 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.object_new | def object_new(self, template=None, **kwargs):
"""Creates a new object from an IPFS template.
By default this creates and returns a new empty merkledag node, but you
may pass an optional template argument to create a preformatted node.
.. code-block:: python
>>> c.object_new()
{'Hash': 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n'}
Parameters
----------
template : str
Blueprints from which to construct the new object. Possible values:
* ``"unixfs-dir"``
* ``None``
Returns
-------
dict : Object hash
"""
args = (template,) if template is not None else ()
return self._client.request('/object/new', args,
decoder='json', **kwargs) | python | def object_new(self, template=None, **kwargs):
"""Creates a new object from an IPFS template.
By default this creates and returns a new empty merkledag node, but you
may pass an optional template argument to create a preformatted node.
.. code-block:: python
>>> c.object_new()
{'Hash': 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n'}
Parameters
----------
template : str
Blueprints from which to construct the new object. Possible values:
* ``"unixfs-dir"``
* ``None``
Returns
-------
dict : Object hash
"""
args = (template,) if template is not None else ()
return self._client.request('/object/new', args,
decoder='json', **kwargs) | [
"def",
"object_new",
"(",
"self",
",",
"template",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"template",
",",
")",
"if",
"template",
"is",
"not",
"None",
"else",
"(",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(... | Creates a new object from an IPFS template.
By default this creates and returns a new empty merkledag node, but you
may pass an optional template argument to create a preformatted node.
.. code-block:: python
>>> c.object_new()
{'Hash': 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n'}
Parameters
----------
template : str
Blueprints from which to construct the new object. Possible values:
* ``"unixfs-dir"``
* ``None``
Returns
-------
dict : Object hash | [
"Creates",
"a",
"new",
"object",
"from",
"an",
"IPFS",
"template",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L456-L481 | train | 229,541 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.object_links | def object_links(self, multihash, **kwargs):
"""Returns the links pointed to by the specified object.
.. code-block:: python
>>> c.object_links('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDx … ca7D')
{'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 174},
{'Hash': 'QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX',
'Name': 'example', 'Size': 1474},
{'Hash': 'QmZAL3oHMQYqsV61tGvoAVtQLs1WzRe1zkkamv9qxqnDuK',
'Name': 'home', 'Size': 3947},
{'Hash': 'QmZNPyKVriMsZwJSNXeQtVQSNU4v4KEKGUQaMT61LPahso',
'Name': 'lib', 'Size': 268261},
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version', 'Size': 55}]}
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
dict : Object hash and merkedag links
"""
args = (multihash,)
return self._client.request('/object/links', args,
decoder='json', **kwargs) | python | def object_links(self, multihash, **kwargs):
"""Returns the links pointed to by the specified object.
.. code-block:: python
>>> c.object_links('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDx … ca7D')
{'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 174},
{'Hash': 'QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX',
'Name': 'example', 'Size': 1474},
{'Hash': 'QmZAL3oHMQYqsV61tGvoAVtQLs1WzRe1zkkamv9qxqnDuK',
'Name': 'home', 'Size': 3947},
{'Hash': 'QmZNPyKVriMsZwJSNXeQtVQSNU4v4KEKGUQaMT61LPahso',
'Name': 'lib', 'Size': 268261},
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version', 'Size': 55}]}
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
dict : Object hash and merkedag links
"""
args = (multihash,)
return self._client.request('/object/links', args,
decoder='json', **kwargs) | [
"def",
"object_links",
"(",
"self",
",",
"multihash",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"multihash",
",",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/object/links'",
",",
"args",
",",
"decoder",
"=",
"'json'",
",",... | Returns the links pointed to by the specified object.
.. code-block:: python
>>> c.object_links('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDx … ca7D')
{'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 174},
{'Hash': 'QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX',
'Name': 'example', 'Size': 1474},
{'Hash': 'QmZAL3oHMQYqsV61tGvoAVtQLs1WzRe1zkkamv9qxqnDuK',
'Name': 'home', 'Size': 3947},
{'Hash': 'QmZNPyKVriMsZwJSNXeQtVQSNU4v4KEKGUQaMT61LPahso',
'Name': 'lib', 'Size': 268261},
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version', 'Size': 55}]}
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
dict : Object hash and merkedag links | [
"Returns",
"the",
"links",
"pointed",
"to",
"by",
"the",
"specified",
"object",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L483-L513 | train | 229,542 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.object_get | def object_get(self, multihash, **kwargs):
"""Get and serialize the DAG node named by multihash.
.. code-block:: python
>>> c.object_get('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Data': '\x08\x01',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 174},
{'Hash': 'QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX',
'Name': 'example', 'Size': 1474},
{'Hash': 'QmZAL3oHMQYqsV61tGvoAVtQLs1WzRe1zkkamv9qxqnDuK',
'Name': 'home', 'Size': 3947},
{'Hash': 'QmZNPyKVriMsZwJSNXeQtVQSNU4v4KEKGUQaMT61LPahso',
'Name': 'lib', 'Size': 268261},
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version', 'Size': 55}]}
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
dict : Object data and links
"""
args = (multihash,)
return self._client.request('/object/get', args,
decoder='json', **kwargs) | python | def object_get(self, multihash, **kwargs):
"""Get and serialize the DAG node named by multihash.
.. code-block:: python
>>> c.object_get('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Data': '\x08\x01',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 174},
{'Hash': 'QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX',
'Name': 'example', 'Size': 1474},
{'Hash': 'QmZAL3oHMQYqsV61tGvoAVtQLs1WzRe1zkkamv9qxqnDuK',
'Name': 'home', 'Size': 3947},
{'Hash': 'QmZNPyKVriMsZwJSNXeQtVQSNU4v4KEKGUQaMT61LPahso',
'Name': 'lib', 'Size': 268261},
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version', 'Size': 55}]}
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
dict : Object data and links
"""
args = (multihash,)
return self._client.request('/object/get', args,
decoder='json', **kwargs) | [
"def",
"object_get",
"(",
"self",
",",
"multihash",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"multihash",
",",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/object/get'",
",",
"args",
",",
"decoder",
"=",
"'json'",
",",
"... | Get and serialize the DAG node named by multihash.
.. code-block:: python
>>> c.object_get('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Data': '\x08\x01',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 174},
{'Hash': 'QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX',
'Name': 'example', 'Size': 1474},
{'Hash': 'QmZAL3oHMQYqsV61tGvoAVtQLs1WzRe1zkkamv9qxqnDuK',
'Name': 'home', 'Size': 3947},
{'Hash': 'QmZNPyKVriMsZwJSNXeQtVQSNU4v4KEKGUQaMT61LPahso',
'Name': 'lib', 'Size': 268261},
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version', 'Size': 55}]}
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
dict : Object data and links | [
"Get",
"and",
"serialize",
"the",
"DAG",
"node",
"named",
"by",
"multihash",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L515-L545 | train | 229,543 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.object_put | def object_put(self, file, **kwargs):
"""Stores input as a DAG object and returns its key.
.. code-block:: python
>>> c.object_put(io.BytesIO(b'''
... {
... "Data": "another",
... "Links": [ {
... "Name": "some link",
... "Hash": "QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCV … R39V",
... "Size": 8
... } ]
... }'''))
{'Hash': 'QmZZmY4KCu9r3e7M2Pcn46Fc5qbn6NpzaAGaYb22kbfTqm',
'Links': [
{'Hash': 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39V',
'Size': 8, 'Name': 'some link'}
]
}
Parameters
----------
file : io.RawIOBase
(JSON) object from which the DAG object will be created
Returns
-------
dict : Hash and links of the created DAG object
See :meth:`~ipfsapi.Object.object_links`
"""
body, headers = multipart.stream_files(file, self.chunk_size)
return self._client.request('/object/put', decoder='json',
data=body, headers=headers, **kwargs) | python | def object_put(self, file, **kwargs):
"""Stores input as a DAG object and returns its key.
.. code-block:: python
>>> c.object_put(io.BytesIO(b'''
... {
... "Data": "another",
... "Links": [ {
... "Name": "some link",
... "Hash": "QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCV … R39V",
... "Size": 8
... } ]
... }'''))
{'Hash': 'QmZZmY4KCu9r3e7M2Pcn46Fc5qbn6NpzaAGaYb22kbfTqm',
'Links': [
{'Hash': 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39V',
'Size': 8, 'Name': 'some link'}
]
}
Parameters
----------
file : io.RawIOBase
(JSON) object from which the DAG object will be created
Returns
-------
dict : Hash and links of the created DAG object
See :meth:`~ipfsapi.Object.object_links`
"""
body, headers = multipart.stream_files(file, self.chunk_size)
return self._client.request('/object/put', decoder='json',
data=body, headers=headers, **kwargs) | [
"def",
"object_put",
"(",
"self",
",",
"file",
",",
"*",
"*",
"kwargs",
")",
":",
"body",
",",
"headers",
"=",
"multipart",
".",
"stream_files",
"(",
"file",
",",
"self",
".",
"chunk_size",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
... | Stores input as a DAG object and returns its key.
.. code-block:: python
>>> c.object_put(io.BytesIO(b'''
... {
... "Data": "another",
... "Links": [ {
... "Name": "some link",
... "Hash": "QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCV … R39V",
... "Size": 8
... } ]
... }'''))
{'Hash': 'QmZZmY4KCu9r3e7M2Pcn46Fc5qbn6NpzaAGaYb22kbfTqm',
'Links': [
{'Hash': 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39V',
'Size': 8, 'Name': 'some link'}
]
}
Parameters
----------
file : io.RawIOBase
(JSON) object from which the DAG object will be created
Returns
-------
dict : Hash and links of the created DAG object
See :meth:`~ipfsapi.Object.object_links` | [
"Stores",
"input",
"as",
"a",
"DAG",
"object",
"and",
"returns",
"its",
"key",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L547-L581 | train | 229,544 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.object_stat | def object_stat(self, multihash, **kwargs):
"""Get stats for the DAG node named by multihash.
.. code-block:: python
>>> c.object_stat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'LinksSize': 256, 'NumLinks': 5,
'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'BlockSize': 258, 'CumulativeSize': 274169, 'DataSize': 2}
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
dict
"""
args = (multihash,)
return self._client.request('/object/stat', args,
decoder='json', **kwargs) | python | def object_stat(self, multihash, **kwargs):
"""Get stats for the DAG node named by multihash.
.. code-block:: python
>>> c.object_stat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'LinksSize': 256, 'NumLinks': 5,
'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'BlockSize': 258, 'CumulativeSize': 274169, 'DataSize': 2}
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
dict
"""
args = (multihash,)
return self._client.request('/object/stat', args,
decoder='json', **kwargs) | [
"def",
"object_stat",
"(",
"self",
",",
"multihash",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"multihash",
",",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/object/stat'",
",",
"args",
",",
"decoder",
"=",
"'json'",
",",
... | Get stats for the DAG node named by multihash.
.. code-block:: python
>>> c.object_stat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'LinksSize': 256, 'NumLinks': 5,
'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'BlockSize': 258, 'CumulativeSize': 274169, 'DataSize': 2}
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
dict | [
"Get",
"stats",
"for",
"the",
"DAG",
"node",
"named",
"by",
"multihash",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L583-L604 | train | 229,545 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.file_ls | def file_ls(self, multihash, **kwargs):
"""Lists directory contents for Unix filesystem objects.
The result contains size information. For files, the child size is the
total size of the file contents. For directories, the child size is the
IPFS link size.
The path can be a prefixless reference; in this case, it is assumed
that it is an ``/ipfs/`` reference and not ``/ipns/``.
.. code-block:: python
>>> c.file_ls('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Arguments': {'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D':
'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D'},
'Objects': {
'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D': {
'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Size': 0, 'Type': 'Directory',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 163, 'Type': 'File'},
{'Hash': 'QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX',
'Name': 'example', 'Size': 1463, 'Type': 'File'},
{'Hash': 'QmZAL3oHMQYqsV61tGvoAVtQLs1WzRe1zkkamv9qxqnDuK',
'Name': 'home', 'Size': 3947, 'Type': 'Directory'},
{'Hash': 'QmZNPyKVriMsZwJSNXeQtVQSNU4v4KEKGUQaMT61LPahso',
'Name': 'lib', 'Size': 268261, 'Type': 'Directory'},
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version',
'Size': 47, 'Type': 'File'}
]
}
}}
Parameters
----------
multihash : str
The path to the object(s) to list links from
Returns
-------
dict
"""
args = (multihash,)
return self._client.request('/file/ls', args, decoder='json', **kwargs) | python | def file_ls(self, multihash, **kwargs):
"""Lists directory contents for Unix filesystem objects.
The result contains size information. For files, the child size is the
total size of the file contents. For directories, the child size is the
IPFS link size.
The path can be a prefixless reference; in this case, it is assumed
that it is an ``/ipfs/`` reference and not ``/ipns/``.
.. code-block:: python
>>> c.file_ls('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Arguments': {'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D':
'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D'},
'Objects': {
'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D': {
'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Size': 0, 'Type': 'Directory',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 163, 'Type': 'File'},
{'Hash': 'QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX',
'Name': 'example', 'Size': 1463, 'Type': 'File'},
{'Hash': 'QmZAL3oHMQYqsV61tGvoAVtQLs1WzRe1zkkamv9qxqnDuK',
'Name': 'home', 'Size': 3947, 'Type': 'Directory'},
{'Hash': 'QmZNPyKVriMsZwJSNXeQtVQSNU4v4KEKGUQaMT61LPahso',
'Name': 'lib', 'Size': 268261, 'Type': 'Directory'},
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version',
'Size': 47, 'Type': 'File'}
]
}
}}
Parameters
----------
multihash : str
The path to the object(s) to list links from
Returns
-------
dict
"""
args = (multihash,)
return self._client.request('/file/ls', args, decoder='json', **kwargs) | [
"def",
"file_ls",
"(",
"self",
",",
"multihash",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"multihash",
",",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/file/ls'",
",",
"args",
",",
"decoder",
"=",
"'json'",
",",
"*",
... | Lists directory contents for Unix filesystem objects.
The result contains size information. For files, the child size is the
total size of the file contents. For directories, the child size is the
IPFS link size.
The path can be a prefixless reference; in this case, it is assumed
that it is an ``/ipfs/`` reference and not ``/ipns/``.
.. code-block:: python
>>> c.file_ls('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Arguments': {'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D':
'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D'},
'Objects': {
'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D': {
'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Size': 0, 'Type': 'Directory',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 163, 'Type': 'File'},
{'Hash': 'QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX',
'Name': 'example', 'Size': 1463, 'Type': 'File'},
{'Hash': 'QmZAL3oHMQYqsV61tGvoAVtQLs1WzRe1zkkamv9qxqnDuK',
'Name': 'home', 'Size': 3947, 'Type': 'Directory'},
{'Hash': 'QmZNPyKVriMsZwJSNXeQtVQSNU4v4KEKGUQaMT61LPahso',
'Name': 'lib', 'Size': 268261, 'Type': 'Directory'},
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version',
'Size': 47, 'Type': 'File'}
]
}
}}
Parameters
----------
multihash : str
The path to the object(s) to list links from
Returns
-------
dict | [
"Lists",
"directory",
"contents",
"for",
"Unix",
"filesystem",
"objects",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L728-L773 | train | 229,546 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.resolve | def resolve(self, name, recursive=False, **kwargs):
"""Accepts an identifier and resolves it to the referenced item.
There are a number of mutable name protocols that can link among
themselves and into IPNS. For example IPNS references can (currently)
point at an IPFS object, and DNS links can point at other DNS links,
IPNS entries, or IPFS objects. This command accepts any of these
identifiers.
.. code-block:: python
>>> c.resolve("/ipfs/QmTkzDwWqPbnAh5YiV5VwcTLnGdw … ca7D/Makefile")
{'Path': '/ipfs/Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV'}
>>> c.resolve("/ipns/ipfs.io")
{'Path': '/ipfs/QmTzQ1JRkWErjk39mryYw2WVaphAZNAREyMchXzYQ7c15n'}
Parameters
----------
name : str
The name to resolve
recursive : bool
Resolve until the result is an IPFS name
Returns
-------
dict : IPFS path of resource
"""
kwargs.setdefault("opts", {"recursive": recursive})
args = (name,)
return self._client.request('/resolve', args, decoder='json', **kwargs) | python | def resolve(self, name, recursive=False, **kwargs):
"""Accepts an identifier and resolves it to the referenced item.
There are a number of mutable name protocols that can link among
themselves and into IPNS. For example IPNS references can (currently)
point at an IPFS object, and DNS links can point at other DNS links,
IPNS entries, or IPFS objects. This command accepts any of these
identifiers.
.. code-block:: python
>>> c.resolve("/ipfs/QmTkzDwWqPbnAh5YiV5VwcTLnGdw … ca7D/Makefile")
{'Path': '/ipfs/Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV'}
>>> c.resolve("/ipns/ipfs.io")
{'Path': '/ipfs/QmTzQ1JRkWErjk39mryYw2WVaphAZNAREyMchXzYQ7c15n'}
Parameters
----------
name : str
The name to resolve
recursive : bool
Resolve until the result is an IPFS name
Returns
-------
dict : IPFS path of resource
"""
kwargs.setdefault("opts", {"recursive": recursive})
args = (name,)
return self._client.request('/resolve', args, decoder='json', **kwargs) | [
"def",
"resolve",
"(",
"self",
",",
"name",
",",
"recursive",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",",
"{",
"\"recursive\"",
":",
"recursive",
"}",
")",
"args",
"=",
"(",
"name",
",",
")",
... | Accepts an identifier and resolves it to the referenced item.
There are a number of mutable name protocols that can link among
themselves and into IPNS. For example IPNS references can (currently)
point at an IPFS object, and DNS links can point at other DNS links,
IPNS entries, or IPFS objects. This command accepts any of these
identifiers.
.. code-block:: python
>>> c.resolve("/ipfs/QmTkzDwWqPbnAh5YiV5VwcTLnGdw … ca7D/Makefile")
{'Path': '/ipfs/Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV'}
>>> c.resolve("/ipns/ipfs.io")
{'Path': '/ipfs/QmTzQ1JRkWErjk39mryYw2WVaphAZNAREyMchXzYQ7c15n'}
Parameters
----------
name : str
The name to resolve
recursive : bool
Resolve until the result is an IPFS name
Returns
-------
dict : IPFS path of resource | [
"Accepts",
"an",
"identifier",
"and",
"resolves",
"it",
"to",
"the",
"referenced",
"item",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L775-L805 | train | 229,547 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.key_gen | def key_gen(self, key_name, type, size=2048, **kwargs):
"""Adds a new public key that can be used for name_publish.
.. code-block:: python
>>> c.key_gen('example_key_name')
{'Name': 'example_key_name',
'Id': 'QmQLaT5ZrCfSkXTH6rUKtVidcxj8jrW3X2h75Lug1AV7g8'}
Parameters
----------
key_name : str
Name of the new Key to be generated. Used to reference the Keys.
type : str
Type of key to generate. The current possible keys types are:
* ``"rsa"``
* ``"ed25519"``
size : int
Bitsize of key to generate
Returns
-------
dict : Key name and Key Id
"""
opts = {"type": type, "size": size}
kwargs.setdefault("opts", opts)
args = (key_name,)
return self._client.request('/key/gen', args,
decoder='json', **kwargs) | python | def key_gen(self, key_name, type, size=2048, **kwargs):
"""Adds a new public key that can be used for name_publish.
.. code-block:: python
>>> c.key_gen('example_key_name')
{'Name': 'example_key_name',
'Id': 'QmQLaT5ZrCfSkXTH6rUKtVidcxj8jrW3X2h75Lug1AV7g8'}
Parameters
----------
key_name : str
Name of the new Key to be generated. Used to reference the Keys.
type : str
Type of key to generate. The current possible keys types are:
* ``"rsa"``
* ``"ed25519"``
size : int
Bitsize of key to generate
Returns
-------
dict : Key name and Key Id
"""
opts = {"type": type, "size": size}
kwargs.setdefault("opts", opts)
args = (key_name,)
return self._client.request('/key/gen', args,
decoder='json', **kwargs) | [
"def",
"key_gen",
"(",
"self",
",",
"key_name",
",",
"type",
",",
"size",
"=",
"2048",
",",
"*",
"*",
"kwargs",
")",
":",
"opts",
"=",
"{",
"\"type\"",
":",
"type",
",",
"\"size\"",
":",
"size",
"}",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",... | Adds a new public key that can be used for name_publish.
.. code-block:: python
>>> c.key_gen('example_key_name')
{'Name': 'example_key_name',
'Id': 'QmQLaT5ZrCfSkXTH6rUKtVidcxj8jrW3X2h75Lug1AV7g8'}
Parameters
----------
key_name : str
Name of the new Key to be generated. Used to reference the Keys.
type : str
Type of key to generate. The current possible keys types are:
* ``"rsa"``
* ``"ed25519"``
size : int
Bitsize of key to generate
Returns
-------
dict : Key name and Key Id | [
"Adds",
"a",
"new",
"public",
"key",
"that",
"can",
"be",
"used",
"for",
"name_publish",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L825-L856 | train | 229,548 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.key_rm | def key_rm(self, key_name, *key_names, **kwargs):
"""Remove a keypair
.. code-block:: python
>>> c.key_rm("bla")
{"Keys": [
{"Name": "bla",
"Id": "QmfJpR6paB6h891y7SYXGe6gapyNgepBeAYMbyejWA4FWA"}
]}
Parameters
----------
key_name : str
Name of the key(s) to remove.
Returns
-------
dict : List of key names and IDs that have been removed
"""
args = (key_name,) + key_names
return self._client.request('/key/rm', args, decoder='json', **kwargs) | python | def key_rm(self, key_name, *key_names, **kwargs):
"""Remove a keypair
.. code-block:: python
>>> c.key_rm("bla")
{"Keys": [
{"Name": "bla",
"Id": "QmfJpR6paB6h891y7SYXGe6gapyNgepBeAYMbyejWA4FWA"}
]}
Parameters
----------
key_name : str
Name of the key(s) to remove.
Returns
-------
dict : List of key names and IDs that have been removed
"""
args = (key_name,) + key_names
return self._client.request('/key/rm', args, decoder='json', **kwargs) | [
"def",
"key_rm",
"(",
"self",
",",
"key_name",
",",
"*",
"key_names",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"key_name",
",",
")",
"+",
"key_names",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/key/rm'",
",",
"args",
",",
... | Remove a keypair
.. code-block:: python
>>> c.key_rm("bla")
{"Keys": [
{"Name": "bla",
"Id": "QmfJpR6paB6h891y7SYXGe6gapyNgepBeAYMbyejWA4FWA"}
]}
Parameters
----------
key_name : str
Name of the key(s) to remove.
Returns
-------
dict : List of key names and IDs that have been removed | [
"Remove",
"a",
"keypair"
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L858-L879 | train | 229,549 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.key_rename | def key_rename(self, key_name, new_key_name, **kwargs):
"""Rename a keypair
.. code-block:: python
>>> c.key_rename("bla", "personal")
{"Was": "bla",
"Now": "personal",
"Id": "QmeyrRNxXaasZaoDXcCZgryoBCga9shaHQ4suHAYXbNZF3",
"Overwrite": False}
Parameters
----------
key_name : str
Current name of the key to rename
new_key_name : str
New name of the key
Returns
-------
dict : List of key names and IDs that have been removed
"""
args = (key_name, new_key_name)
return self._client.request('/key/rename', args, decoder='json',
**kwargs) | python | def key_rename(self, key_name, new_key_name, **kwargs):
"""Rename a keypair
.. code-block:: python
>>> c.key_rename("bla", "personal")
{"Was": "bla",
"Now": "personal",
"Id": "QmeyrRNxXaasZaoDXcCZgryoBCga9shaHQ4suHAYXbNZF3",
"Overwrite": False}
Parameters
----------
key_name : str
Current name of the key to rename
new_key_name : str
New name of the key
Returns
-------
dict : List of key names and IDs that have been removed
"""
args = (key_name, new_key_name)
return self._client.request('/key/rename', args, decoder='json',
**kwargs) | [
"def",
"key_rename",
"(",
"self",
",",
"key_name",
",",
"new_key_name",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"key_name",
",",
"new_key_name",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/key/rename'",
",",
"args",
",",
... | Rename a keypair
.. code-block:: python
>>> c.key_rename("bla", "personal")
{"Was": "bla",
"Now": "personal",
"Id": "QmeyrRNxXaasZaoDXcCZgryoBCga9shaHQ4suHAYXbNZF3",
"Overwrite": False}
Parameters
----------
key_name : str
Current name of the key to rename
new_key_name : str
New name of the key
Returns
-------
dict : List of key names and IDs that have been removed | [
"Rename",
"a",
"keypair"
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L881-L905 | train | 229,550 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.name_publish | def name_publish(self, ipfs_path, resolve=True, lifetime="24h", ttl=None,
key=None, **kwargs):
"""Publishes an object to IPNS.
IPNS is a PKI namespace, where names are the hashes of public keys, and
the private key enables publishing new (signed) values. In publish, the
default value of *name* is your own identity public key.
.. code-block:: python
>>> c.name_publish('/ipfs/QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZK … GZ5d')
{'Value': '/ipfs/QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d',
'Name': 'QmVgNoP89mzpgEAAqK8owYoDEyB97MkcGvoWZir8otE9Uc'}
Parameters
----------
ipfs_path : str
IPFS path of the object to be published
resolve : bool
Resolve given path before publishing
lifetime : str
Time duration that the record will be valid for
Accepts durations such as ``"300s"``, ``"1.5h"`` or ``"2h45m"``.
Valid units are:
* ``"ns"``
* ``"us"`` (or ``"µs"``)
* ``"ms"``
* ``"s"``
* ``"m"``
* ``"h"``
ttl : int
Time duration this record should be cached for
key : string
Name of the key to be used, as listed by 'ipfs key list'.
Returns
-------
dict : IPNS hash and the IPFS path it points at
"""
opts = {"lifetime": lifetime, "resolve": resolve}
if ttl:
opts["ttl"] = ttl
if key:
opts["key"] = key
kwargs.setdefault("opts", opts)
args = (ipfs_path,)
return self._client.request('/name/publish', args,
decoder='json', **kwargs) | python | def name_publish(self, ipfs_path, resolve=True, lifetime="24h", ttl=None,
key=None, **kwargs):
"""Publishes an object to IPNS.
IPNS is a PKI namespace, where names are the hashes of public keys, and
the private key enables publishing new (signed) values. In publish, the
default value of *name* is your own identity public key.
.. code-block:: python
>>> c.name_publish('/ipfs/QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZK … GZ5d')
{'Value': '/ipfs/QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d',
'Name': 'QmVgNoP89mzpgEAAqK8owYoDEyB97MkcGvoWZir8otE9Uc'}
Parameters
----------
ipfs_path : str
IPFS path of the object to be published
resolve : bool
Resolve given path before publishing
lifetime : str
Time duration that the record will be valid for
Accepts durations such as ``"300s"``, ``"1.5h"`` or ``"2h45m"``.
Valid units are:
* ``"ns"``
* ``"us"`` (or ``"µs"``)
* ``"ms"``
* ``"s"``
* ``"m"``
* ``"h"``
ttl : int
Time duration this record should be cached for
key : string
Name of the key to be used, as listed by 'ipfs key list'.
Returns
-------
dict : IPNS hash and the IPFS path it points at
"""
opts = {"lifetime": lifetime, "resolve": resolve}
if ttl:
opts["ttl"] = ttl
if key:
opts["key"] = key
kwargs.setdefault("opts", opts)
args = (ipfs_path,)
return self._client.request('/name/publish', args,
decoder='json', **kwargs) | [
"def",
"name_publish",
"(",
"self",
",",
"ipfs_path",
",",
"resolve",
"=",
"True",
",",
"lifetime",
"=",
"\"24h\"",
",",
"ttl",
"=",
"None",
",",
"key",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"opts",
"=",
"{",
"\"lifetime\"",
":",
"lifetime"... | Publishes an object to IPNS.
IPNS is a PKI namespace, where names are the hashes of public keys, and
the private key enables publishing new (signed) values. In publish, the
default value of *name* is your own identity public key.
.. code-block:: python
>>> c.name_publish('/ipfs/QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZK … GZ5d')
{'Value': '/ipfs/QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d',
'Name': 'QmVgNoP89mzpgEAAqK8owYoDEyB97MkcGvoWZir8otE9Uc'}
Parameters
----------
ipfs_path : str
IPFS path of the object to be published
resolve : bool
Resolve given path before publishing
lifetime : str
Time duration that the record will be valid for
Accepts durations such as ``"300s"``, ``"1.5h"`` or ``"2h45m"``.
Valid units are:
* ``"ns"``
* ``"us"`` (or ``"µs"``)
* ``"ms"``
* ``"s"``
* ``"m"``
* ``"h"``
ttl : int
Time duration this record should be cached for
key : string
Name of the key to be used, as listed by 'ipfs key list'.
Returns
-------
dict : IPNS hash and the IPFS path it points at | [
"Publishes",
"an",
"object",
"to",
"IPNS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L907-L957 | train | 229,551 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.name_resolve | def name_resolve(self, name=None, recursive=False,
nocache=False, **kwargs):
"""Gets the value currently published at an IPNS name.
IPNS is a PKI namespace, where names are the hashes of public keys, and
the private key enables publishing new (signed) values. In resolve, the
default value of ``name`` is your own identity public key.
.. code-block:: python
>>> c.name_resolve()
{'Path': '/ipfs/QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d'}
Parameters
----------
name : str
The IPNS name to resolve (defaults to the connected node)
recursive : bool
Resolve until the result is not an IPFS name (default: false)
nocache : bool
Do not use cached entries (default: false)
Returns
-------
dict : The IPFS path the IPNS hash points at
"""
kwargs.setdefault("opts", {"recursive": recursive,
"nocache": nocache})
args = (name,) if name is not None else ()
return self._client.request('/name/resolve', args,
decoder='json', **kwargs) | python | def name_resolve(self, name=None, recursive=False,
nocache=False, **kwargs):
"""Gets the value currently published at an IPNS name.
IPNS is a PKI namespace, where names are the hashes of public keys, and
the private key enables publishing new (signed) values. In resolve, the
default value of ``name`` is your own identity public key.
.. code-block:: python
>>> c.name_resolve()
{'Path': '/ipfs/QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d'}
Parameters
----------
name : str
The IPNS name to resolve (defaults to the connected node)
recursive : bool
Resolve until the result is not an IPFS name (default: false)
nocache : bool
Do not use cached entries (default: false)
Returns
-------
dict : The IPFS path the IPNS hash points at
"""
kwargs.setdefault("opts", {"recursive": recursive,
"nocache": nocache})
args = (name,) if name is not None else ()
return self._client.request('/name/resolve', args,
decoder='json', **kwargs) | [
"def",
"name_resolve",
"(",
"self",
",",
"name",
"=",
"None",
",",
"recursive",
"=",
"False",
",",
"nocache",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",",
"{",
"\"recursive\"",
":",
"recursive",
",... | Gets the value currently published at an IPNS name.
IPNS is a PKI namespace, where names are the hashes of public keys, and
the private key enables publishing new (signed) values. In resolve, the
default value of ``name`` is your own identity public key.
.. code-block:: python
>>> c.name_resolve()
{'Path': '/ipfs/QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d'}
Parameters
----------
name : str
The IPNS name to resolve (defaults to the connected node)
recursive : bool
Resolve until the result is not an IPFS name (default: false)
nocache : bool
Do not use cached entries (default: false)
Returns
-------
dict : The IPFS path the IPNS hash points at | [
"Gets",
"the",
"value",
"currently",
"published",
"at",
"an",
"IPNS",
"name",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L959-L989 | train | 229,552 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.dns | def dns(self, domain_name, recursive=False, **kwargs):
"""Resolves DNS links to the referenced object.
Multihashes are hard to remember, but domain names are usually easy to
remember. To create memorable aliases for multihashes, DNS TXT records
can point to other DNS links, IPFS objects, IPNS keys, etc.
This command resolves those links to the referenced object.
For example, with this DNS TXT record::
>>> import dns.resolver
>>> a = dns.resolver.query("ipfs.io", "TXT")
>>> a.response.answer[0].items[0].to_text()
'"dnslink=/ipfs/QmTzQ1JRkWErjk39mryYw2WVaphAZNAREyMchXzYQ7c15n"'
The resolver will give::
>>> c.dns("ipfs.io")
{'Path': '/ipfs/QmTzQ1JRkWErjk39mryYw2WVaphAZNAREyMchXzYQ7c15n'}
Parameters
----------
domain_name : str
The domain-name name to resolve
recursive : bool
Resolve until the name is not a DNS link
Returns
-------
dict : Resource were a DNS entry points to
"""
kwargs.setdefault("opts", {"recursive": recursive})
args = (domain_name,)
return self._client.request('/dns', args, decoder='json', **kwargs) | python | def dns(self, domain_name, recursive=False, **kwargs):
"""Resolves DNS links to the referenced object.
Multihashes are hard to remember, but domain names are usually easy to
remember. To create memorable aliases for multihashes, DNS TXT records
can point to other DNS links, IPFS objects, IPNS keys, etc.
This command resolves those links to the referenced object.
For example, with this DNS TXT record::
>>> import dns.resolver
>>> a = dns.resolver.query("ipfs.io", "TXT")
>>> a.response.answer[0].items[0].to_text()
'"dnslink=/ipfs/QmTzQ1JRkWErjk39mryYw2WVaphAZNAREyMchXzYQ7c15n"'
The resolver will give::
>>> c.dns("ipfs.io")
{'Path': '/ipfs/QmTzQ1JRkWErjk39mryYw2WVaphAZNAREyMchXzYQ7c15n'}
Parameters
----------
domain_name : str
The domain-name name to resolve
recursive : bool
Resolve until the name is not a DNS link
Returns
-------
dict : Resource were a DNS entry points to
"""
kwargs.setdefault("opts", {"recursive": recursive})
args = (domain_name,)
return self._client.request('/dns', args, decoder='json', **kwargs) | [
"def",
"dns",
"(",
"self",
",",
"domain_name",
",",
"recursive",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",",
"{",
"\"recursive\"",
":",
"recursive",
"}",
")",
"args",
"=",
"(",
"domain_name",
",",... | Resolves DNS links to the referenced object.
Multihashes are hard to remember, but domain names are usually easy to
remember. To create memorable aliases for multihashes, DNS TXT records
can point to other DNS links, IPFS objects, IPNS keys, etc.
This command resolves those links to the referenced object.
For example, with this DNS TXT record::
>>> import dns.resolver
>>> a = dns.resolver.query("ipfs.io", "TXT")
>>> a.response.answer[0].items[0].to_text()
'"dnslink=/ipfs/QmTzQ1JRkWErjk39mryYw2WVaphAZNAREyMchXzYQ7c15n"'
The resolver will give::
>>> c.dns("ipfs.io")
{'Path': '/ipfs/QmTzQ1JRkWErjk39mryYw2WVaphAZNAREyMchXzYQ7c15n'}
Parameters
----------
domain_name : str
The domain-name name to resolve
recursive : bool
Resolve until the name is not a DNS link
Returns
-------
dict : Resource were a DNS entry points to | [
"Resolves",
"DNS",
"links",
"to",
"the",
"referenced",
"object",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L991-L1025 | train | 229,553 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.pin_add | def pin_add(self, path, *paths, **kwargs):
"""Pins objects to local storage.
Stores an IPFS object(s) from a given path locally to disk.
.. code-block:: python
>>> c.pin_add("QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d")
{'Pins': ['QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d']}
Parameters
----------
path : str
Path to object(s) to be pinned
recursive : bool
Recursively unpin the object linked to by the specified object(s)
Returns
-------
dict : List of IPFS objects that have been pinned
"""
#PY2: No support for kw-only parameters after glob parameters
if "recursive" in kwargs:
kwargs.setdefault("opts", {"recursive": kwargs.pop("recursive")})
args = (path,) + paths
return self._client.request('/pin/add', args, decoder='json', **kwargs) | python | def pin_add(self, path, *paths, **kwargs):
"""Pins objects to local storage.
Stores an IPFS object(s) from a given path locally to disk.
.. code-block:: python
>>> c.pin_add("QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d")
{'Pins': ['QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d']}
Parameters
----------
path : str
Path to object(s) to be pinned
recursive : bool
Recursively unpin the object linked to by the specified object(s)
Returns
-------
dict : List of IPFS objects that have been pinned
"""
#PY2: No support for kw-only parameters after glob parameters
if "recursive" in kwargs:
kwargs.setdefault("opts", {"recursive": kwargs.pop("recursive")})
args = (path,) + paths
return self._client.request('/pin/add', args, decoder='json', **kwargs) | [
"def",
"pin_add",
"(",
"self",
",",
"path",
",",
"*",
"paths",
",",
"*",
"*",
"kwargs",
")",
":",
"#PY2: No support for kw-only parameters after glob parameters",
"if",
"\"recursive\"",
"in",
"kwargs",
":",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",",
"{",... | Pins objects to local storage.
Stores an IPFS object(s) from a given path locally to disk.
.. code-block:: python
>>> c.pin_add("QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d")
{'Pins': ['QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d']}
Parameters
----------
path : str
Path to object(s) to be pinned
recursive : bool
Recursively unpin the object linked to by the specified object(s)
Returns
-------
dict : List of IPFS objects that have been pinned | [
"Pins",
"objects",
"to",
"local",
"storage",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1027-L1053 | train | 229,554 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.pin_rm | def pin_rm(self, path, *paths, **kwargs):
"""Removes a pinned object from local storage.
Removes the pin from the given object allowing it to be garbage
collected if needed.
.. code-block:: python
>>> c.pin_rm('QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d')
{'Pins': ['QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d']}
Parameters
----------
path : str
Path to object(s) to be unpinned
recursive : bool
Recursively unpin the object linked to by the specified object(s)
Returns
-------
dict : List of IPFS objects that have been unpinned
"""
#PY2: No support for kw-only parameters after glob parameters
if "recursive" in kwargs:
kwargs.setdefault("opts", {"recursive": kwargs["recursive"]})
del kwargs["recursive"]
args = (path,) + paths
return self._client.request('/pin/rm', args, decoder='json', **kwargs) | python | def pin_rm(self, path, *paths, **kwargs):
"""Removes a pinned object from local storage.
Removes the pin from the given object allowing it to be garbage
collected if needed.
.. code-block:: python
>>> c.pin_rm('QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d')
{'Pins': ['QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d']}
Parameters
----------
path : str
Path to object(s) to be unpinned
recursive : bool
Recursively unpin the object linked to by the specified object(s)
Returns
-------
dict : List of IPFS objects that have been unpinned
"""
#PY2: No support for kw-only parameters after glob parameters
if "recursive" in kwargs:
kwargs.setdefault("opts", {"recursive": kwargs["recursive"]})
del kwargs["recursive"]
args = (path,) + paths
return self._client.request('/pin/rm', args, decoder='json', **kwargs) | [
"def",
"pin_rm",
"(",
"self",
",",
"path",
",",
"*",
"paths",
",",
"*",
"*",
"kwargs",
")",
":",
"#PY2: No support for kw-only parameters after glob parameters",
"if",
"\"recursive\"",
"in",
"kwargs",
":",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",",
"{",
... | Removes a pinned object from local storage.
Removes the pin from the given object allowing it to be garbage
collected if needed.
.. code-block:: python
>>> c.pin_rm('QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d')
{'Pins': ['QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d']}
Parameters
----------
path : str
Path to object(s) to be unpinned
recursive : bool
Recursively unpin the object linked to by the specified object(s)
Returns
-------
dict : List of IPFS objects that have been unpinned | [
"Removes",
"a",
"pinned",
"object",
"from",
"local",
"storage",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1055-L1083 | train | 229,555 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.pin_ls | def pin_ls(self, type="all", **kwargs):
"""Lists objects pinned to local storage.
By default, all pinned objects are returned, but the ``type`` flag or
arguments can restrict that to a specific pin type or to some specific
objects respectively.
.. code-block:: python
>>> c.pin_ls()
{'Keys': {
'QmNNPMA1eGUbKxeph6yqV8ZmRkdVat … YMuz': {'Type': 'recursive'},
'QmNPZUCeSN5458Uwny8mXSWubjjr6J … kP5e': {'Type': 'recursive'},
'QmNg5zWpRMxzRAVg7FTQ3tUxVbKj8E … gHPz': {'Type': 'indirect'},
…
'QmNiuVapnYCrLjxyweHeuk6Xdqfvts … wCCe': {'Type': 'indirect'}}}
Parameters
----------
type : "str"
The type of pinned keys to list. Can be:
* ``"direct"``
* ``"indirect"``
* ``"recursive"``
* ``"all"``
Returns
-------
dict : Hashes of pinned IPFS objects and why they are pinned
"""
kwargs.setdefault("opts", {"type": type})
return self._client.request('/pin/ls', decoder='json', **kwargs) | python | def pin_ls(self, type="all", **kwargs):
"""Lists objects pinned to local storage.
By default, all pinned objects are returned, but the ``type`` flag or
arguments can restrict that to a specific pin type or to some specific
objects respectively.
.. code-block:: python
>>> c.pin_ls()
{'Keys': {
'QmNNPMA1eGUbKxeph6yqV8ZmRkdVat … YMuz': {'Type': 'recursive'},
'QmNPZUCeSN5458Uwny8mXSWubjjr6J … kP5e': {'Type': 'recursive'},
'QmNg5zWpRMxzRAVg7FTQ3tUxVbKj8E … gHPz': {'Type': 'indirect'},
…
'QmNiuVapnYCrLjxyweHeuk6Xdqfvts … wCCe': {'Type': 'indirect'}}}
Parameters
----------
type : "str"
The type of pinned keys to list. Can be:
* ``"direct"``
* ``"indirect"``
* ``"recursive"``
* ``"all"``
Returns
-------
dict : Hashes of pinned IPFS objects and why they are pinned
"""
kwargs.setdefault("opts", {"type": type})
return self._client.request('/pin/ls', decoder='json', **kwargs) | [
"def",
"pin_ls",
"(",
"self",
",",
"type",
"=",
"\"all\"",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",",
"{",
"\"type\"",
":",
"type",
"}",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/pin/ls'... | Lists objects pinned to local storage.
By default, all pinned objects are returned, but the ``type`` flag or
arguments can restrict that to a specific pin type or to some specific
objects respectively.
.. code-block:: python
>>> c.pin_ls()
{'Keys': {
'QmNNPMA1eGUbKxeph6yqV8ZmRkdVat … YMuz': {'Type': 'recursive'},
'QmNPZUCeSN5458Uwny8mXSWubjjr6J … kP5e': {'Type': 'recursive'},
'QmNg5zWpRMxzRAVg7FTQ3tUxVbKj8E … gHPz': {'Type': 'indirect'},
…
'QmNiuVapnYCrLjxyweHeuk6Xdqfvts … wCCe': {'Type': 'indirect'}}}
Parameters
----------
type : "str"
The type of pinned keys to list. Can be:
* ``"direct"``
* ``"indirect"``
* ``"recursive"``
* ``"all"``
Returns
-------
dict : Hashes of pinned IPFS objects and why they are pinned | [
"Lists",
"objects",
"pinned",
"to",
"local",
"storage",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1085-L1118 | train | 229,556 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.pin_update | def pin_update(self, from_path, to_path, **kwargs):
"""Replaces one pin with another.
Updates one pin to another, making sure that all objects in the new pin
are local. Then removes the old pin. This is an optimized version of
using first using :meth:`~ipfsapi.Client.pin_add` to add a new pin
for an object and then using :meth:`~ipfsapi.Client.pin_rm` to remove
the pin for the old object.
.. code-block:: python
>>> c.pin_update("QmXMqez83NU77ifmcPs5CkNRTMQksBLkyfBf4H5g1NZ52P",
... "QmUykHAi1aSjMzHw3KmBoJjqRUQYNkFXm8K1y7ZsJxpfPH")
{"Pins": ["/ipfs/QmXMqez83NU77ifmcPs5CkNRTMQksBLkyfBf4H5g1NZ52P",
"/ipfs/QmUykHAi1aSjMzHw3KmBoJjqRUQYNkFXm8K1y7ZsJxpfPH"]}
Parameters
----------
from_path : str
Path to the old object
to_path : str
Path to the new object to be pinned
unpin : bool
Should the pin of the old object be removed? (Default: ``True``)
Returns
-------
dict : List of IPFS objects affected by the pinning operation
"""
#PY2: No support for kw-only parameters after glob parameters
if "unpin" in kwargs:
kwargs.setdefault("opts", {"unpin": kwargs["unpin"]})
del kwargs["unpin"]
args = (from_path, to_path)
return self._client.request('/pin/update', args, decoder='json',
**kwargs) | python | def pin_update(self, from_path, to_path, **kwargs):
"""Replaces one pin with another.
Updates one pin to another, making sure that all objects in the new pin
are local. Then removes the old pin. This is an optimized version of
using first using :meth:`~ipfsapi.Client.pin_add` to add a new pin
for an object and then using :meth:`~ipfsapi.Client.pin_rm` to remove
the pin for the old object.
.. code-block:: python
>>> c.pin_update("QmXMqez83NU77ifmcPs5CkNRTMQksBLkyfBf4H5g1NZ52P",
... "QmUykHAi1aSjMzHw3KmBoJjqRUQYNkFXm8K1y7ZsJxpfPH")
{"Pins": ["/ipfs/QmXMqez83NU77ifmcPs5CkNRTMQksBLkyfBf4H5g1NZ52P",
"/ipfs/QmUykHAi1aSjMzHw3KmBoJjqRUQYNkFXm8K1y7ZsJxpfPH"]}
Parameters
----------
from_path : str
Path to the old object
to_path : str
Path to the new object to be pinned
unpin : bool
Should the pin of the old object be removed? (Default: ``True``)
Returns
-------
dict : List of IPFS objects affected by the pinning operation
"""
#PY2: No support for kw-only parameters after glob parameters
if "unpin" in kwargs:
kwargs.setdefault("opts", {"unpin": kwargs["unpin"]})
del kwargs["unpin"]
args = (from_path, to_path)
return self._client.request('/pin/update', args, decoder='json',
**kwargs) | [
"def",
"pin_update",
"(",
"self",
",",
"from_path",
",",
"to_path",
",",
"*",
"*",
"kwargs",
")",
":",
"#PY2: No support for kw-only parameters after glob parameters",
"if",
"\"unpin\"",
"in",
"kwargs",
":",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",",
"{",
... | Replaces one pin with another.
Updates one pin to another, making sure that all objects in the new pin
are local. Then removes the old pin. This is an optimized version of
using first using :meth:`~ipfsapi.Client.pin_add` to add a new pin
for an object and then using :meth:`~ipfsapi.Client.pin_rm` to remove
the pin for the old object.
.. code-block:: python
>>> c.pin_update("QmXMqez83NU77ifmcPs5CkNRTMQksBLkyfBf4H5g1NZ52P",
... "QmUykHAi1aSjMzHw3KmBoJjqRUQYNkFXm8K1y7ZsJxpfPH")
{"Pins": ["/ipfs/QmXMqez83NU77ifmcPs5CkNRTMQksBLkyfBf4H5g1NZ52P",
"/ipfs/QmUykHAi1aSjMzHw3KmBoJjqRUQYNkFXm8K1y7ZsJxpfPH"]}
Parameters
----------
from_path : str
Path to the old object
to_path : str
Path to the new object to be pinned
unpin : bool
Should the pin of the old object be removed? (Default: ``True``)
Returns
-------
dict : List of IPFS objects affected by the pinning operation | [
"Replaces",
"one",
"pin",
"with",
"another",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1120-L1156 | train | 229,557 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.pin_verify | def pin_verify(self, path, *paths, **kwargs):
"""Verify that recursive pins are complete.
Scan the repo for pinned object graphs and check their integrity.
Issues will be reported back with a helpful human-readable error
message to aid in error recovery. This is useful to help recover
from datastore corruptions (such as when accidentally deleting
files added using the filestore backend).
This function returns an iterator needs to be closed using a context
manager (``with``-statement) or using the ``.close()`` method.
.. code-block:: python
>>> with c.pin_verify("QmN…TTZ", verbose=True) as pin_verify_iter:
... for item in pin_verify_iter:
... print(item)
...
{"Cid":"QmVkNdzCBukBRdpyFiKPyL2R15qPExMr9rV9RFV2kf9eeV","Ok":True}
{"Cid":"QmbPzQruAEFjUU3gQfupns6b8USr8VrD9H71GrqGDXQSxm","Ok":True}
{"Cid":"Qmcns1nUvbeWiecdGDPw8JxWeUfxCV8JKhTfgzs3F8JM4P","Ok":True}
…
Parameters
----------
path : str
Path to object(s) to be checked
verbose : bool
Also report status of items that were OK? (Default: ``False``)
Returns
-------
iterable
"""
#PY2: No support for kw-only parameters after glob parameters
if "verbose" in kwargs:
kwargs.setdefault("opts", {"verbose": kwargs["verbose"]})
del kwargs["verbose"]
args = (path,) + paths
return self._client.request('/pin/verify', args, decoder='json',
stream=True, **kwargs) | python | def pin_verify(self, path, *paths, **kwargs):
"""Verify that recursive pins are complete.
Scan the repo for pinned object graphs and check their integrity.
Issues will be reported back with a helpful human-readable error
message to aid in error recovery. This is useful to help recover
from datastore corruptions (such as when accidentally deleting
files added using the filestore backend).
This function returns an iterator needs to be closed using a context
manager (``with``-statement) or using the ``.close()`` method.
.. code-block:: python
>>> with c.pin_verify("QmN…TTZ", verbose=True) as pin_verify_iter:
... for item in pin_verify_iter:
... print(item)
...
{"Cid":"QmVkNdzCBukBRdpyFiKPyL2R15qPExMr9rV9RFV2kf9eeV","Ok":True}
{"Cid":"QmbPzQruAEFjUU3gQfupns6b8USr8VrD9H71GrqGDXQSxm","Ok":True}
{"Cid":"Qmcns1nUvbeWiecdGDPw8JxWeUfxCV8JKhTfgzs3F8JM4P","Ok":True}
…
Parameters
----------
path : str
Path to object(s) to be checked
verbose : bool
Also report status of items that were OK? (Default: ``False``)
Returns
-------
iterable
"""
#PY2: No support for kw-only parameters after glob parameters
if "verbose" in kwargs:
kwargs.setdefault("opts", {"verbose": kwargs["verbose"]})
del kwargs["verbose"]
args = (path,) + paths
return self._client.request('/pin/verify', args, decoder='json',
stream=True, **kwargs) | [
"def",
"pin_verify",
"(",
"self",
",",
"path",
",",
"*",
"paths",
",",
"*",
"*",
"kwargs",
")",
":",
"#PY2: No support for kw-only parameters after glob parameters",
"if",
"\"verbose\"",
"in",
"kwargs",
":",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",",
"{"... | Verify that recursive pins are complete.
Scan the repo for pinned object graphs and check their integrity.
Issues will be reported back with a helpful human-readable error
message to aid in error recovery. This is useful to help recover
from datastore corruptions (such as when accidentally deleting
files added using the filestore backend).
This function returns an iterator needs to be closed using a context
manager (``with``-statement) or using the ``.close()`` method.
.. code-block:: python
>>> with c.pin_verify("QmN…TTZ", verbose=True) as pin_verify_iter:
... for item in pin_verify_iter:
... print(item)
...
{"Cid":"QmVkNdzCBukBRdpyFiKPyL2R15qPExMr9rV9RFV2kf9eeV","Ok":True}
{"Cid":"QmbPzQruAEFjUU3gQfupns6b8USr8VrD9H71GrqGDXQSxm","Ok":True}
{"Cid":"Qmcns1nUvbeWiecdGDPw8JxWeUfxCV8JKhTfgzs3F8JM4P","Ok":True}
…
Parameters
----------
path : str
Path to object(s) to be checked
verbose : bool
Also report status of items that were OK? (Default: ``False``)
Returns
-------
iterable | [
"Verify",
"that",
"recursive",
"pins",
"are",
"complete",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1158-L1199 | train | 229,558 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.id | def id(self, peer=None, **kwargs):
"""Shows IPFS Node ID info.
Returns the PublicKey, ProtocolVersion, ID, AgentVersion and
Addresses of the connected daemon or some other node.
.. code-block:: python
>>> c.id()
{'ID': 'QmVgNoP89mzpgEAAqK8owYoDEyB97MkcGvoWZir8otE9Uc',
'PublicKey': 'CAASpgIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggE … BAAE=',
'AgentVersion': 'go-libp2p/3.3.4',
'ProtocolVersion': 'ipfs/0.1.0',
'Addresses': [
'/ip4/127.0.0.1/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8owYo … E9Uc',
'/ip4/10.1.0.172/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8owY … E9Uc',
'/ip4/172.18.0.1/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8owY … E9Uc',
'/ip6/::1/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8owYoDEyB97 … E9Uc',
'/ip6/fccc:7904:b05b:a579:957b:deef:f066:cad9/tcp/400 … E9Uc',
'/ip6/fd56:1966:efd8::212/tcp/4001/ipfs/QmVgNoP89mzpg … E9Uc',
'/ip6/fd56:1966:efd8:0:def1:34d0:773:48f/tcp/4001/ipf … E9Uc',
'/ip6/2001:db8:1::1/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8 … E9Uc',
'/ip4/77.116.233.54/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8 … E9Uc',
'/ip4/77.116.233.54/tcp/10842/ipfs/QmVgNoP89mzpgEAAqK … E9Uc']}
Parameters
----------
peer : str
Peer.ID of the node to look up (local node if ``None``)
Returns
-------
dict : Information about the IPFS node
"""
args = (peer,) if peer is not None else ()
return self._client.request('/id', args, decoder='json', **kwargs) | python | def id(self, peer=None, **kwargs):
"""Shows IPFS Node ID info.
Returns the PublicKey, ProtocolVersion, ID, AgentVersion and
Addresses of the connected daemon or some other node.
.. code-block:: python
>>> c.id()
{'ID': 'QmVgNoP89mzpgEAAqK8owYoDEyB97MkcGvoWZir8otE9Uc',
'PublicKey': 'CAASpgIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggE … BAAE=',
'AgentVersion': 'go-libp2p/3.3.4',
'ProtocolVersion': 'ipfs/0.1.0',
'Addresses': [
'/ip4/127.0.0.1/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8owYo … E9Uc',
'/ip4/10.1.0.172/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8owY … E9Uc',
'/ip4/172.18.0.1/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8owY … E9Uc',
'/ip6/::1/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8owYoDEyB97 … E9Uc',
'/ip6/fccc:7904:b05b:a579:957b:deef:f066:cad9/tcp/400 … E9Uc',
'/ip6/fd56:1966:efd8::212/tcp/4001/ipfs/QmVgNoP89mzpg … E9Uc',
'/ip6/fd56:1966:efd8:0:def1:34d0:773:48f/tcp/4001/ipf … E9Uc',
'/ip6/2001:db8:1::1/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8 … E9Uc',
'/ip4/77.116.233.54/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8 … E9Uc',
'/ip4/77.116.233.54/tcp/10842/ipfs/QmVgNoP89mzpgEAAqK … E9Uc']}
Parameters
----------
peer : str
Peer.ID of the node to look up (local node if ``None``)
Returns
-------
dict : Information about the IPFS node
"""
args = (peer,) if peer is not None else ()
return self._client.request('/id', args, decoder='json', **kwargs) | [
"def",
"id",
"(",
"self",
",",
"peer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"peer",
",",
")",
"if",
"peer",
"is",
"not",
"None",
"else",
"(",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/id'",
",",... | Shows IPFS Node ID info.
Returns the PublicKey, ProtocolVersion, ID, AgentVersion and
Addresses of the connected daemon or some other node.
.. code-block:: python
>>> c.id()
{'ID': 'QmVgNoP89mzpgEAAqK8owYoDEyB97MkcGvoWZir8otE9Uc',
'PublicKey': 'CAASpgIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggE … BAAE=',
'AgentVersion': 'go-libp2p/3.3.4',
'ProtocolVersion': 'ipfs/0.1.0',
'Addresses': [
'/ip4/127.0.0.1/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8owYo … E9Uc',
'/ip4/10.1.0.172/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8owY … E9Uc',
'/ip4/172.18.0.1/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8owY … E9Uc',
'/ip6/::1/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8owYoDEyB97 … E9Uc',
'/ip6/fccc:7904:b05b:a579:957b:deef:f066:cad9/tcp/400 … E9Uc',
'/ip6/fd56:1966:efd8::212/tcp/4001/ipfs/QmVgNoP89mzpg … E9Uc',
'/ip6/fd56:1966:efd8:0:def1:34d0:773:48f/tcp/4001/ipf … E9Uc',
'/ip6/2001:db8:1::1/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8 … E9Uc',
'/ip4/77.116.233.54/tcp/4001/ipfs/QmVgNoP89mzpgEAAqK8 … E9Uc',
'/ip4/77.116.233.54/tcp/10842/ipfs/QmVgNoP89mzpgEAAqK … E9Uc']}
Parameters
----------
peer : str
Peer.ID of the node to look up (local node if ``None``)
Returns
-------
dict : Information about the IPFS node | [
"Shows",
"IPFS",
"Node",
"ID",
"info",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1254-L1289 | train | 229,559 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.bootstrap_add | def bootstrap_add(self, peer, *peers, **kwargs):
"""Adds peers to the bootstrap list.
Parameters
----------
peer : str
IPFS MultiAddr of a peer to add to the list
Returns
-------
dict
"""
args = (peer,) + peers
return self._client.request('/bootstrap/add', args,
decoder='json', **kwargs) | python | def bootstrap_add(self, peer, *peers, **kwargs):
"""Adds peers to the bootstrap list.
Parameters
----------
peer : str
IPFS MultiAddr of a peer to add to the list
Returns
-------
dict
"""
args = (peer,) + peers
return self._client.request('/bootstrap/add', args,
decoder='json', **kwargs) | [
"def",
"bootstrap_add",
"(",
"self",
",",
"peer",
",",
"*",
"peers",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"peer",
",",
")",
"+",
"peers",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/bootstrap/add'",
",",
"args",
",",
"... | Adds peers to the bootstrap list.
Parameters
----------
peer : str
IPFS MultiAddr of a peer to add to the list
Returns
-------
dict | [
"Adds",
"peers",
"to",
"the",
"bootstrap",
"list",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1317-L1331 | train | 229,560 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.swarm_filters_add | def swarm_filters_add(self, address, *addresses, **kwargs):
"""Adds a given multiaddr filter to the filter list.
This will add an address filter to the daemons swarm. Filters applied
this way will not persist daemon reboots, to achieve that, add your
filters to the configuration file.
.. code-block:: python
>>> c.swarm_filters_add("/ip4/192.168.0.0/ipcidr/16")
{'Strings': ['/ip4/192.168.0.0/ipcidr/16']}
Parameters
----------
address : str
Multiaddr to filter
Returns
-------
dict : List of swarm filters added
"""
args = (address,) + addresses
return self._client.request('/swarm/filters/add', args,
decoder='json', **kwargs) | python | def swarm_filters_add(self, address, *addresses, **kwargs):
"""Adds a given multiaddr filter to the filter list.
This will add an address filter to the daemons swarm. Filters applied
this way will not persist daemon reboots, to achieve that, add your
filters to the configuration file.
.. code-block:: python
>>> c.swarm_filters_add("/ip4/192.168.0.0/ipcidr/16")
{'Strings': ['/ip4/192.168.0.0/ipcidr/16']}
Parameters
----------
address : str
Multiaddr to filter
Returns
-------
dict : List of swarm filters added
"""
args = (address,) + addresses
return self._client.request('/swarm/filters/add', args,
decoder='json', **kwargs) | [
"def",
"swarm_filters_add",
"(",
"self",
",",
"address",
",",
"*",
"addresses",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"address",
",",
")",
"+",
"addresses",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/swarm/filters/add'",
","... | Adds a given multiaddr filter to the filter list.
This will add an address filter to the daemons swarm. Filters applied
this way will not persist daemon reboots, to achieve that, add your
filters to the configuration file.
.. code-block:: python
>>> c.swarm_filters_add("/ip4/192.168.0.0/ipcidr/16")
{'Strings': ['/ip4/192.168.0.0/ipcidr/16']}
Parameters
----------
address : str
Multiaddr to filter
Returns
-------
dict : List of swarm filters added | [
"Adds",
"a",
"given",
"multiaddr",
"filter",
"to",
"the",
"filter",
"list",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1456-L1479 | train | 229,561 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.dht_query | def dht_query(self, peer_id, *peer_ids, **kwargs):
"""Finds the closest Peer IDs to a given Peer ID by querying the DHT.
.. code-block:: python
>>> c.dht_query("/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDM … uvuJ")
[{'ID': 'QmPkFbxAQ7DeKD5VGSh9HQrdS574pyNzDmxJeGrRJxoucF',
'Extra': '', 'Type': 2, 'Responses': None},
{'ID': 'QmR1MhHVLJSLt9ZthsNNhudb1ny1WdhY4FPW21ZYFWec4f',
'Extra': '', 'Type': 2, 'Responses': None},
{'ID': 'Qmcwx1K5aVme45ab6NYWb52K2TFBeABgCLccC7ntUeDsAs',
'Extra': '', 'Type': 2, 'Responses': None},
…
{'ID': 'QmYYy8L3YD1nsF4xtt4xmsc14yqvAAnKksjo3F3iZs5jPv',
'Extra': '', 'Type': 1, 'Responses': []}]
Parameters
----------
peer_id : str
The peerID to run the query against
Returns
-------
dict : List of peers IDs
"""
args = (peer_id,) + peer_ids
return self._client.request('/dht/query', args,
decoder='json', **kwargs) | python | def dht_query(self, peer_id, *peer_ids, **kwargs):
"""Finds the closest Peer IDs to a given Peer ID by querying the DHT.
.. code-block:: python
>>> c.dht_query("/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDM … uvuJ")
[{'ID': 'QmPkFbxAQ7DeKD5VGSh9HQrdS574pyNzDmxJeGrRJxoucF',
'Extra': '', 'Type': 2, 'Responses': None},
{'ID': 'QmR1MhHVLJSLt9ZthsNNhudb1ny1WdhY4FPW21ZYFWec4f',
'Extra': '', 'Type': 2, 'Responses': None},
{'ID': 'Qmcwx1K5aVme45ab6NYWb52K2TFBeABgCLccC7ntUeDsAs',
'Extra': '', 'Type': 2, 'Responses': None},
…
{'ID': 'QmYYy8L3YD1nsF4xtt4xmsc14yqvAAnKksjo3F3iZs5jPv',
'Extra': '', 'Type': 1, 'Responses': []}]
Parameters
----------
peer_id : str
The peerID to run the query against
Returns
-------
dict : List of peers IDs
"""
args = (peer_id,) + peer_ids
return self._client.request('/dht/query', args,
decoder='json', **kwargs) | [
"def",
"dht_query",
"(",
"self",
",",
"peer_id",
",",
"*",
"peer_ids",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"peer_id",
",",
")",
"+",
"peer_ids",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/dht/query'",
",",
"args",
",",... | Finds the closest Peer IDs to a given Peer ID by querying the DHT.
.. code-block:: python
>>> c.dht_query("/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDM … uvuJ")
[{'ID': 'QmPkFbxAQ7DeKD5VGSh9HQrdS574pyNzDmxJeGrRJxoucF',
'Extra': '', 'Type': 2, 'Responses': None},
{'ID': 'QmR1MhHVLJSLt9ZthsNNhudb1ny1WdhY4FPW21ZYFWec4f',
'Extra': '', 'Type': 2, 'Responses': None},
{'ID': 'Qmcwx1K5aVme45ab6NYWb52K2TFBeABgCLccC7ntUeDsAs',
'Extra': '', 'Type': 2, 'Responses': None},
…
{'ID': 'QmYYy8L3YD1nsF4xtt4xmsc14yqvAAnKksjo3F3iZs5jPv',
'Extra': '', 'Type': 1, 'Responses': []}]
Parameters
----------
peer_id : str
The peerID to run the query against
Returns
-------
dict : List of peers IDs | [
"Finds",
"the",
"closest",
"Peer",
"IDs",
"to",
"a",
"given",
"Peer",
"ID",
"by",
"querying",
"the",
"DHT",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1506-L1533 | train | 229,562 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.dht_findprovs | def dht_findprovs(self, multihash, *multihashes, **kwargs):
"""Finds peers in the DHT that can provide a specific value.
.. code-block:: python
>>> c.dht_findprovs("QmNPXDC6wTXVmZ9Uoc8X1oqxRRJr4f1sDuyQu … mpW2")
[{'ID': 'QmaxqKpiYNr62uSFBhxJAMmEMkT6dvc3oHkrZNpH2VMTLZ',
'Extra': '', 'Type': 6, 'Responses': None},
{'ID': 'QmaK6Aj5WXkfnWGoWq7V8pGUYzcHPZp4jKQ5JtmRvSzQGk',
'Extra': '', 'Type': 6, 'Responses': None},
{'ID': 'QmdUdLu8dNvr4MVW1iWXxKoQrbG6y1vAVWPdkeGK4xppds',
'Extra': '', 'Type': 6, 'Responses': None},
…
{'ID': '', 'Extra': '', 'Type': 4, 'Responses': [
{'ID': 'QmVgNoP89mzpgEAAqK8owYoDEyB97Mk … E9Uc', 'Addrs': None}
]},
{'ID': 'QmaxqKpiYNr62uSFBhxJAMmEMkT6dvc3oHkrZNpH2VMTLZ',
'Extra': '', 'Type': 1, 'Responses': [
{'ID': 'QmSHXfsmN3ZduwFDjeqBn1C8b1tcLkxK6yd … waXw', 'Addrs': [
'/ip4/127.0.0.1/tcp/4001',
'/ip4/172.17.0.8/tcp/4001',
'/ip6/::1/tcp/4001',
'/ip4/52.32.109.74/tcp/1028'
]}
]}]
Parameters
----------
multihash : str
The DHT key to find providers for
Returns
-------
dict : List of provider Peer IDs
"""
args = (multihash,) + multihashes
return self._client.request('/dht/findprovs', args,
decoder='json', **kwargs) | python | def dht_findprovs(self, multihash, *multihashes, **kwargs):
"""Finds peers in the DHT that can provide a specific value.
.. code-block:: python
>>> c.dht_findprovs("QmNPXDC6wTXVmZ9Uoc8X1oqxRRJr4f1sDuyQu … mpW2")
[{'ID': 'QmaxqKpiYNr62uSFBhxJAMmEMkT6dvc3oHkrZNpH2VMTLZ',
'Extra': '', 'Type': 6, 'Responses': None},
{'ID': 'QmaK6Aj5WXkfnWGoWq7V8pGUYzcHPZp4jKQ5JtmRvSzQGk',
'Extra': '', 'Type': 6, 'Responses': None},
{'ID': 'QmdUdLu8dNvr4MVW1iWXxKoQrbG6y1vAVWPdkeGK4xppds',
'Extra': '', 'Type': 6, 'Responses': None},
…
{'ID': '', 'Extra': '', 'Type': 4, 'Responses': [
{'ID': 'QmVgNoP89mzpgEAAqK8owYoDEyB97Mk … E9Uc', 'Addrs': None}
]},
{'ID': 'QmaxqKpiYNr62uSFBhxJAMmEMkT6dvc3oHkrZNpH2VMTLZ',
'Extra': '', 'Type': 1, 'Responses': [
{'ID': 'QmSHXfsmN3ZduwFDjeqBn1C8b1tcLkxK6yd … waXw', 'Addrs': [
'/ip4/127.0.0.1/tcp/4001',
'/ip4/172.17.0.8/tcp/4001',
'/ip6/::1/tcp/4001',
'/ip4/52.32.109.74/tcp/1028'
]}
]}]
Parameters
----------
multihash : str
The DHT key to find providers for
Returns
-------
dict : List of provider Peer IDs
"""
args = (multihash,) + multihashes
return self._client.request('/dht/findprovs', args,
decoder='json', **kwargs) | [
"def",
"dht_findprovs",
"(",
"self",
",",
"multihash",
",",
"*",
"multihashes",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"multihash",
",",
")",
"+",
"multihashes",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/dht/findprovs'",
","... | Finds peers in the DHT that can provide a specific value.
.. code-block:: python
>>> c.dht_findprovs("QmNPXDC6wTXVmZ9Uoc8X1oqxRRJr4f1sDuyQu … mpW2")
[{'ID': 'QmaxqKpiYNr62uSFBhxJAMmEMkT6dvc3oHkrZNpH2VMTLZ',
'Extra': '', 'Type': 6, 'Responses': None},
{'ID': 'QmaK6Aj5WXkfnWGoWq7V8pGUYzcHPZp4jKQ5JtmRvSzQGk',
'Extra': '', 'Type': 6, 'Responses': None},
{'ID': 'QmdUdLu8dNvr4MVW1iWXxKoQrbG6y1vAVWPdkeGK4xppds',
'Extra': '', 'Type': 6, 'Responses': None},
…
{'ID': '', 'Extra': '', 'Type': 4, 'Responses': [
{'ID': 'QmVgNoP89mzpgEAAqK8owYoDEyB97Mk … E9Uc', 'Addrs': None}
]},
{'ID': 'QmaxqKpiYNr62uSFBhxJAMmEMkT6dvc3oHkrZNpH2VMTLZ',
'Extra': '', 'Type': 1, 'Responses': [
{'ID': 'QmSHXfsmN3ZduwFDjeqBn1C8b1tcLkxK6yd … waXw', 'Addrs': [
'/ip4/127.0.0.1/tcp/4001',
'/ip4/172.17.0.8/tcp/4001',
'/ip6/::1/tcp/4001',
'/ip4/52.32.109.74/tcp/1028'
]}
]}]
Parameters
----------
multihash : str
The DHT key to find providers for
Returns
-------
dict : List of provider Peer IDs | [
"Finds",
"peers",
"in",
"the",
"DHT",
"that",
"can",
"provide",
"a",
"specific",
"value",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1535-L1572 | train | 229,563 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.dht_get | def dht_get(self, key, *keys, **kwargs):
"""Queries the DHT for its best value related to given key.
There may be several different values for a given key stored in the
DHT; in this context *best* means the record that is most desirable.
There is no one metric for *best*: it depends entirely on the key type.
For IPNS, *best* is the record that is both valid and has the highest
sequence number (freshest). Different key types may specify other rules
for they consider to be the *best*.
Parameters
----------
key : str
One or more keys whose values should be looked up
Returns
-------
str
"""
args = (key,) + keys
res = self._client.request('/dht/get', args, decoder='json', **kwargs)
if isinstance(res, dict) and "Extra" in res:
return res["Extra"]
else:
for r in res:
if "Extra" in r and len(r["Extra"]) > 0:
return r["Extra"]
raise exceptions.Error("empty response from DHT") | python | def dht_get(self, key, *keys, **kwargs):
"""Queries the DHT for its best value related to given key.
There may be several different values for a given key stored in the
DHT; in this context *best* means the record that is most desirable.
There is no one metric for *best*: it depends entirely on the key type.
For IPNS, *best* is the record that is both valid and has the highest
sequence number (freshest). Different key types may specify other rules
for they consider to be the *best*.
Parameters
----------
key : str
One or more keys whose values should be looked up
Returns
-------
str
"""
args = (key,) + keys
res = self._client.request('/dht/get', args, decoder='json', **kwargs)
if isinstance(res, dict) and "Extra" in res:
return res["Extra"]
else:
for r in res:
if "Extra" in r and len(r["Extra"]) > 0:
return r["Extra"]
raise exceptions.Error("empty response from DHT") | [
"def",
"dht_get",
"(",
"self",
",",
"key",
",",
"*",
"keys",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"key",
",",
")",
"+",
"keys",
"res",
"=",
"self",
".",
"_client",
".",
"request",
"(",
"'/dht/get'",
",",
"args",
",",
"decoder",
... | Queries the DHT for its best value related to given key.
There may be several different values for a given key stored in the
DHT; in this context *best* means the record that is most desirable.
There is no one metric for *best*: it depends entirely on the key type.
For IPNS, *best* is the record that is both valid and has the highest
sequence number (freshest). Different key types may specify other rules
for they consider to be the *best*.
Parameters
----------
key : str
One or more keys whose values should be looked up
Returns
-------
str | [
"Queries",
"the",
"DHT",
"for",
"its",
"best",
"value",
"related",
"to",
"given",
"key",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1610-L1638 | train | 229,564 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.ping | def ping(self, peer, *peers, **kwargs):
"""Provides round-trip latency information for the routing system.
Finds nodes via the routing system, sends pings, waits for pongs,
and prints out round-trip latency information.
.. code-block:: python
>>> c.ping("QmTzQ1JRkWErjk39mryYw2WVaphAZNAREyMchXzYQ7c15n")
[{'Success': True, 'Time': 0,
'Text': 'Looking up peer QmTzQ1JRkWErjk39mryYw2WVaphAZN … c15n'},
{'Success': False, 'Time': 0,
'Text': 'Peer lookup error: routing: not found'}]
Parameters
----------
peer : str
ID of peer to be pinged
count : int
Number of ping messages to send (Default: ``10``)
Returns
-------
list : Progress reports from the ping
"""
#PY2: No support for kw-only parameters after glob parameters
if "count" in kwargs:
kwargs.setdefault("opts", {"count": kwargs["count"]})
del kwargs["count"]
args = (peer,) + peers
return self._client.request('/ping', args, decoder='json', **kwargs) | python | def ping(self, peer, *peers, **kwargs):
"""Provides round-trip latency information for the routing system.
Finds nodes via the routing system, sends pings, waits for pongs,
and prints out round-trip latency information.
.. code-block:: python
>>> c.ping("QmTzQ1JRkWErjk39mryYw2WVaphAZNAREyMchXzYQ7c15n")
[{'Success': True, 'Time': 0,
'Text': 'Looking up peer QmTzQ1JRkWErjk39mryYw2WVaphAZN … c15n'},
{'Success': False, 'Time': 0,
'Text': 'Peer lookup error: routing: not found'}]
Parameters
----------
peer : str
ID of peer to be pinged
count : int
Number of ping messages to send (Default: ``10``)
Returns
-------
list : Progress reports from the ping
"""
#PY2: No support for kw-only parameters after glob parameters
if "count" in kwargs:
kwargs.setdefault("opts", {"count": kwargs["count"]})
del kwargs["count"]
args = (peer,) + peers
return self._client.request('/ping', args, decoder='json', **kwargs) | [
"def",
"ping",
"(",
"self",
",",
"peer",
",",
"*",
"peers",
",",
"*",
"*",
"kwargs",
")",
":",
"#PY2: No support for kw-only parameters after glob parameters",
"if",
"\"count\"",
"in",
"kwargs",
":",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",",
"{",
"\"c... | Provides round-trip latency information for the routing system.
Finds nodes via the routing system, sends pings, waits for pongs,
and prints out round-trip latency information.
.. code-block:: python
>>> c.ping("QmTzQ1JRkWErjk39mryYw2WVaphAZNAREyMchXzYQ7c15n")
[{'Success': True, 'Time': 0,
'Text': 'Looking up peer QmTzQ1JRkWErjk39mryYw2WVaphAZN … c15n'},
{'Success': False, 'Time': 0,
'Text': 'Peer lookup error: routing: not found'}]
Parameters
----------
peer : str
ID of peer to be pinged
count : int
Number of ping messages to send (Default: ``10``)
Returns
-------
list : Progress reports from the ping | [
"Provides",
"round",
"-",
"trip",
"latency",
"information",
"for",
"the",
"routing",
"system",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1685-L1716 | train | 229,565 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.config | def config(self, key, value=None, **kwargs):
"""Controls configuration variables.
.. code-block:: python
>>> c.config("Addresses.Gateway")
{'Key': 'Addresses.Gateway', 'Value': '/ip4/127.0.0.1/tcp/8080'}
>>> c.config("Addresses.Gateway", "/ip4/127.0.0.1/tcp/8081")
{'Key': 'Addresses.Gateway', 'Value': '/ip4/127.0.0.1/tcp/8081'}
Parameters
----------
key : str
The key of the configuration entry (e.g. "Addresses.API")
value : dict
The value to set the configuration entry to
Returns
-------
dict : Requested/updated key and its (new) value
"""
args = (key, value)
return self._client.request('/config', args, decoder='json', **kwargs) | python | def config(self, key, value=None, **kwargs):
"""Controls configuration variables.
.. code-block:: python
>>> c.config("Addresses.Gateway")
{'Key': 'Addresses.Gateway', 'Value': '/ip4/127.0.0.1/tcp/8080'}
>>> c.config("Addresses.Gateway", "/ip4/127.0.0.1/tcp/8081")
{'Key': 'Addresses.Gateway', 'Value': '/ip4/127.0.0.1/tcp/8081'}
Parameters
----------
key : str
The key of the configuration entry (e.g. "Addresses.API")
value : dict
The value to set the configuration entry to
Returns
-------
dict : Requested/updated key and its (new) value
"""
args = (key, value)
return self._client.request('/config', args, decoder='json', **kwargs) | [
"def",
"config",
"(",
"self",
",",
"key",
",",
"value",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"key",
",",
"value",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/config'",
",",
"args",
",",
"decoder",
"... | Controls configuration variables.
.. code-block:: python
>>> c.config("Addresses.Gateway")
{'Key': 'Addresses.Gateway', 'Value': '/ip4/127.0.0.1/tcp/8080'}
>>> c.config("Addresses.Gateway", "/ip4/127.0.0.1/tcp/8081")
{'Key': 'Addresses.Gateway', 'Value': '/ip4/127.0.0.1/tcp/8081'}
Parameters
----------
key : str
The key of the configuration entry (e.g. "Addresses.API")
value : dict
The value to set the configuration entry to
Returns
-------
dict : Requested/updated key and its (new) value | [
"Controls",
"configuration",
"variables",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1718-L1740 | train | 229,566 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.config_replace | def config_replace(self, *args, **kwargs):
"""Replaces the existing config with a user-defined config.
Make sure to back up the config file first if neccessary, as this
operation can't be undone.
"""
return self._client.request('/config/replace', args,
decoder='json', **kwargs) | python | def config_replace(self, *args, **kwargs):
"""Replaces the existing config with a user-defined config.
Make sure to back up the config file first if neccessary, as this
operation can't be undone.
"""
return self._client.request('/config/replace', args,
decoder='json', **kwargs) | [
"def",
"config_replace",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/config/replace'",
",",
"args",
",",
"decoder",
"=",
"'json'",
",",
"*",
"*",
"kwargs",
")"
] | Replaces the existing config with a user-defined config.
Make sure to back up the config file first if neccessary, as this
operation can't be undone. | [
"Replaces",
"the",
"existing",
"config",
"with",
"a",
"user",
"-",
"defined",
"config",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1766-L1773 | train | 229,567 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.log_level | def log_level(self, subsystem, level, **kwargs):
r"""Changes the logging output of a running daemon.
.. code-block:: python
>>> c.log_level("path", "info")
{'Message': "Changed log level of 'path' to 'info'\n"}
Parameters
----------
subsystem : str
The subsystem logging identifier (Use ``"all"`` for all subsystems)
level : str
The desired logging level. Must be one of:
* ``"debug"``
* ``"info"``
* ``"warning"``
* ``"error"``
* ``"fatal"``
* ``"panic"``
Returns
-------
dict : Status message
"""
args = (subsystem, level)
return self._client.request('/log/level', args,
decoder='json', **kwargs) | python | def log_level(self, subsystem, level, **kwargs):
r"""Changes the logging output of a running daemon.
.. code-block:: python
>>> c.log_level("path", "info")
{'Message': "Changed log level of 'path' to 'info'\n"}
Parameters
----------
subsystem : str
The subsystem logging identifier (Use ``"all"`` for all subsystems)
level : str
The desired logging level. Must be one of:
* ``"debug"``
* ``"info"``
* ``"warning"``
* ``"error"``
* ``"fatal"``
* ``"panic"``
Returns
-------
dict : Status message
"""
args = (subsystem, level)
return self._client.request('/log/level', args,
decoder='json', **kwargs) | [
"def",
"log_level",
"(",
"self",
",",
"subsystem",
",",
"level",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"subsystem",
",",
"level",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/log/level'",
",",
"args",
",",
"decoder",
... | r"""Changes the logging output of a running daemon.
.. code-block:: python
>>> c.log_level("path", "info")
{'Message': "Changed log level of 'path' to 'info'\n"}
Parameters
----------
subsystem : str
The subsystem logging identifier (Use ``"all"`` for all subsystems)
level : str
The desired logging level. Must be one of:
* ``"debug"``
* ``"info"``
* ``"warning"``
* ``"error"``
* ``"fatal"``
* ``"panic"``
Returns
-------
dict : Status message | [
"r",
"Changes",
"the",
"logging",
"output",
"of",
"a",
"running",
"daemon",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1775-L1803 | train | 229,568 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.log_tail | def log_tail(self, **kwargs):
r"""Reads log outputs as they are written.
This function returns an iterator needs to be closed using a context
manager (``with``-statement) or using the ``.close()`` method.
.. code-block:: python
>>> with c.log_tail() as log_tail_iter:
... for item in log_tail_iter:
... print(item)
...
{"event":"updatePeer","system":"dht",
"peerID":"QmepsDPxWtLDuKvEoafkpJxGij4kMax11uTH7WnKqD25Dq",
"session":"7770b5e0-25ec-47cd-aa64-f42e65a10023",
"time":"2016-08-22T13:25:27.43353297Z"}
{"event":"handleAddProviderBegin","system":"dht",
"peer":"QmepsDPxWtLDuKvEoafkpJxGij4kMax11uTH7WnKqD25Dq",
"session":"7770b5e0-25ec-47cd-aa64-f42e65a10023",
"time":"2016-08-22T13:25:27.433642581Z"}
{"event":"handleAddProvider","system":"dht","duration":91704,
"key":"QmNT9Tejg6t57Vs8XM2TVJXCwevWiGsZh3kB4HQXUZRK1o",
"peer":"QmepsDPxWtLDuKvEoafkpJxGij4kMax11uTH7WnKqD25Dq",
"session":"7770b5e0-25ec-47cd-aa64-f42e65a10023",
"time":"2016-08-22T13:25:27.433747513Z"}
{"event":"updatePeer","system":"dht",
"peerID":"QmepsDPxWtLDuKvEoafkpJxGij4kMax11uTH7WnKqD25Dq",
"session":"7770b5e0-25ec-47cd-aa64-f42e65a10023",
"time":"2016-08-22T13:25:27.435843012Z"}
…
Returns
-------
iterable
"""
return self._client.request('/log/tail', decoder='json',
stream=True, **kwargs) | python | def log_tail(self, **kwargs):
r"""Reads log outputs as they are written.
This function returns an iterator needs to be closed using a context
manager (``with``-statement) or using the ``.close()`` method.
.. code-block:: python
>>> with c.log_tail() as log_tail_iter:
... for item in log_tail_iter:
... print(item)
...
{"event":"updatePeer","system":"dht",
"peerID":"QmepsDPxWtLDuKvEoafkpJxGij4kMax11uTH7WnKqD25Dq",
"session":"7770b5e0-25ec-47cd-aa64-f42e65a10023",
"time":"2016-08-22T13:25:27.43353297Z"}
{"event":"handleAddProviderBegin","system":"dht",
"peer":"QmepsDPxWtLDuKvEoafkpJxGij4kMax11uTH7WnKqD25Dq",
"session":"7770b5e0-25ec-47cd-aa64-f42e65a10023",
"time":"2016-08-22T13:25:27.433642581Z"}
{"event":"handleAddProvider","system":"dht","duration":91704,
"key":"QmNT9Tejg6t57Vs8XM2TVJXCwevWiGsZh3kB4HQXUZRK1o",
"peer":"QmepsDPxWtLDuKvEoafkpJxGij4kMax11uTH7WnKqD25Dq",
"session":"7770b5e0-25ec-47cd-aa64-f42e65a10023",
"time":"2016-08-22T13:25:27.433747513Z"}
{"event":"updatePeer","system":"dht",
"peerID":"QmepsDPxWtLDuKvEoafkpJxGij4kMax11uTH7WnKqD25Dq",
"session":"7770b5e0-25ec-47cd-aa64-f42e65a10023",
"time":"2016-08-22T13:25:27.435843012Z"}
…
Returns
-------
iterable
"""
return self._client.request('/log/tail', decoder='json',
stream=True, **kwargs) | [
"def",
"log_tail",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/log/tail'",
",",
"decoder",
"=",
"'json'",
",",
"stream",
"=",
"True",
",",
"*",
"*",
"kwargs",
")"
] | r"""Reads log outputs as they are written.
This function returns an iterator needs to be closed using a context
manager (``with``-statement) or using the ``.close()`` method.
.. code-block:: python
>>> with c.log_tail() as log_tail_iter:
... for item in log_tail_iter:
... print(item)
...
{"event":"updatePeer","system":"dht",
"peerID":"QmepsDPxWtLDuKvEoafkpJxGij4kMax11uTH7WnKqD25Dq",
"session":"7770b5e0-25ec-47cd-aa64-f42e65a10023",
"time":"2016-08-22T13:25:27.43353297Z"}
{"event":"handleAddProviderBegin","system":"dht",
"peer":"QmepsDPxWtLDuKvEoafkpJxGij4kMax11uTH7WnKqD25Dq",
"session":"7770b5e0-25ec-47cd-aa64-f42e65a10023",
"time":"2016-08-22T13:25:27.433642581Z"}
{"event":"handleAddProvider","system":"dht","duration":91704,
"key":"QmNT9Tejg6t57Vs8XM2TVJXCwevWiGsZh3kB4HQXUZRK1o",
"peer":"QmepsDPxWtLDuKvEoafkpJxGij4kMax11uTH7WnKqD25Dq",
"session":"7770b5e0-25ec-47cd-aa64-f42e65a10023",
"time":"2016-08-22T13:25:27.433747513Z"}
{"event":"updatePeer","system":"dht",
"peerID":"QmepsDPxWtLDuKvEoafkpJxGij4kMax11uTH7WnKqD25Dq",
"session":"7770b5e0-25ec-47cd-aa64-f42e65a10023",
"time":"2016-08-22T13:25:27.435843012Z"}
…
Returns
-------
iterable | [
"r",
"Reads",
"log",
"outputs",
"as",
"they",
"are",
"written",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1836-L1872 | train | 229,569 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.files_cp | def files_cp(self, source, dest, **kwargs):
"""Copies files within the MFS.
Due to the nature of IPFS this will not actually involve any of the
file's content being copied.
.. code-block:: python
>>> c.files_ls("/")
{'Entries': [
{'Size': 0, 'Hash': '', 'Name': 'Software', 'Type': 0},
{'Size': 0, 'Hash': '', 'Name': 'test', 'Type': 0}
]}
>>> c.files_cp("/test", "/bla")
''
>>> c.files_ls("/")
{'Entries': [
{'Size': 0, 'Hash': '', 'Name': 'Software', 'Type': 0},
{'Size': 0, 'Hash': '', 'Name': 'bla', 'Type': 0},
{'Size': 0, 'Hash': '', 'Name': 'test', 'Type': 0}
]}
Parameters
----------
source : str
Filepath within the MFS to copy from
dest : str
Destination filepath with the MFS to which the file will be
copied to
"""
args = (source, dest)
return self._client.request('/files/cp', args, **kwargs) | python | def files_cp(self, source, dest, **kwargs):
"""Copies files within the MFS.
Due to the nature of IPFS this will not actually involve any of the
file's content being copied.
.. code-block:: python
>>> c.files_ls("/")
{'Entries': [
{'Size': 0, 'Hash': '', 'Name': 'Software', 'Type': 0},
{'Size': 0, 'Hash': '', 'Name': 'test', 'Type': 0}
]}
>>> c.files_cp("/test", "/bla")
''
>>> c.files_ls("/")
{'Entries': [
{'Size': 0, 'Hash': '', 'Name': 'Software', 'Type': 0},
{'Size': 0, 'Hash': '', 'Name': 'bla', 'Type': 0},
{'Size': 0, 'Hash': '', 'Name': 'test', 'Type': 0}
]}
Parameters
----------
source : str
Filepath within the MFS to copy from
dest : str
Destination filepath with the MFS to which the file will be
copied to
"""
args = (source, dest)
return self._client.request('/files/cp', args, **kwargs) | [
"def",
"files_cp",
"(",
"self",
",",
"source",
",",
"dest",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"source",
",",
"dest",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/files/cp'",
",",
"args",
",",
"*",
"*",
"kwargs",... | Copies files within the MFS.
Due to the nature of IPFS this will not actually involve any of the
file's content being copied.
.. code-block:: python
>>> c.files_ls("/")
{'Entries': [
{'Size': 0, 'Hash': '', 'Name': 'Software', 'Type': 0},
{'Size': 0, 'Hash': '', 'Name': 'test', 'Type': 0}
]}
>>> c.files_cp("/test", "/bla")
''
>>> c.files_ls("/")
{'Entries': [
{'Size': 0, 'Hash': '', 'Name': 'Software', 'Type': 0},
{'Size': 0, 'Hash': '', 'Name': 'bla', 'Type': 0},
{'Size': 0, 'Hash': '', 'Name': 'test', 'Type': 0}
]}
Parameters
----------
source : str
Filepath within the MFS to copy from
dest : str
Destination filepath with the MFS to which the file will be
copied to | [
"Copies",
"files",
"within",
"the",
"MFS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1889-L1920 | train | 229,570 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.files_ls | def files_ls(self, path, **kwargs):
"""Lists contents of a directory in the MFS.
.. code-block:: python
>>> c.files_ls("/")
{'Entries': [
{'Size': 0, 'Hash': '', 'Name': 'Software', 'Type': 0}
]}
Parameters
----------
path : str
Filepath within the MFS
Returns
-------
dict : Directory entries
"""
args = (path,)
return self._client.request('/files/ls', args,
decoder='json', **kwargs) | python | def files_ls(self, path, **kwargs):
"""Lists contents of a directory in the MFS.
.. code-block:: python
>>> c.files_ls("/")
{'Entries': [
{'Size': 0, 'Hash': '', 'Name': 'Software', 'Type': 0}
]}
Parameters
----------
path : str
Filepath within the MFS
Returns
-------
dict : Directory entries
"""
args = (path,)
return self._client.request('/files/ls', args,
decoder='json', **kwargs) | [
"def",
"files_ls",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"path",
",",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/files/ls'",
",",
"args",
",",
"decoder",
"=",
"'json'",
",",
"*",
"*",
"... | Lists contents of a directory in the MFS.
.. code-block:: python
>>> c.files_ls("/")
{'Entries': [
{'Size': 0, 'Hash': '', 'Name': 'Software', 'Type': 0}
]}
Parameters
----------
path : str
Filepath within the MFS
Returns
-------
dict : Directory entries | [
"Lists",
"contents",
"of",
"a",
"directory",
"in",
"the",
"MFS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1922-L1943 | train | 229,571 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.files_mkdir | def files_mkdir(self, path, parents=False, **kwargs):
"""Creates a directory within the MFS.
.. code-block:: python
>>> c.files_mkdir("/test")
b''
Parameters
----------
path : str
Filepath within the MFS
parents : bool
Create parent directories as needed and do not raise an exception
if the requested directory already exists
"""
kwargs.setdefault("opts", {"parents": parents})
args = (path,)
return self._client.request('/files/mkdir', args, **kwargs) | python | def files_mkdir(self, path, parents=False, **kwargs):
"""Creates a directory within the MFS.
.. code-block:: python
>>> c.files_mkdir("/test")
b''
Parameters
----------
path : str
Filepath within the MFS
parents : bool
Create parent directories as needed and do not raise an exception
if the requested directory already exists
"""
kwargs.setdefault("opts", {"parents": parents})
args = (path,)
return self._client.request('/files/mkdir', args, **kwargs) | [
"def",
"files_mkdir",
"(",
"self",
",",
"path",
",",
"parents",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",",
"{",
"\"parents\"",
":",
"parents",
"}",
")",
"args",
"=",
"(",
"path",
",",
")",
"r... | Creates a directory within the MFS.
.. code-block:: python
>>> c.files_mkdir("/test")
b''
Parameters
----------
path : str
Filepath within the MFS
parents : bool
Create parent directories as needed and do not raise an exception
if the requested directory already exists | [
"Creates",
"a",
"directory",
"within",
"the",
"MFS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1945-L1964 | train | 229,572 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.files_rm | def files_rm(self, path, recursive=False, **kwargs):
"""Removes a file from the MFS.
.. code-block:: python
>>> c.files_rm("/bla/file")
b''
Parameters
----------
path : str
Filepath within the MFS
recursive : bool
Recursively remove directories?
"""
kwargs.setdefault("opts", {"recursive": recursive})
args = (path,)
return self._client.request('/files/rm', args, **kwargs) | python | def files_rm(self, path, recursive=False, **kwargs):
"""Removes a file from the MFS.
.. code-block:: python
>>> c.files_rm("/bla/file")
b''
Parameters
----------
path : str
Filepath within the MFS
recursive : bool
Recursively remove directories?
"""
kwargs.setdefault("opts", {"recursive": recursive})
args = (path,)
return self._client.request('/files/rm', args, **kwargs) | [
"def",
"files_rm",
"(",
"self",
",",
"path",
",",
"recursive",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"opts\"",
",",
"{",
"\"recursive\"",
":",
"recursive",
"}",
")",
"args",
"=",
"(",
"path",
",",
")",
... | Removes a file from the MFS.
.. code-block:: python
>>> c.files_rm("/bla/file")
b''
Parameters
----------
path : str
Filepath within the MFS
recursive : bool
Recursively remove directories? | [
"Removes",
"a",
"file",
"from",
"the",
"MFS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L1989-L2007 | train | 229,573 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.files_read | def files_read(self, path, offset=0, count=None, **kwargs):
"""Reads a file stored in the MFS.
.. code-block:: python
>>> c.files_read("/bla/file")
b'hi'
Parameters
----------
path : str
Filepath within the MFS
offset : int
Byte offset at which to begin reading at
count : int
Maximum number of bytes to read
Returns
-------
str : MFS file contents
"""
opts = {"offset": offset}
if count is not None:
opts["count"] = count
kwargs.setdefault("opts", opts)
args = (path,)
return self._client.request('/files/read', args, **kwargs) | python | def files_read(self, path, offset=0, count=None, **kwargs):
"""Reads a file stored in the MFS.
.. code-block:: python
>>> c.files_read("/bla/file")
b'hi'
Parameters
----------
path : str
Filepath within the MFS
offset : int
Byte offset at which to begin reading at
count : int
Maximum number of bytes to read
Returns
-------
str : MFS file contents
"""
opts = {"offset": offset}
if count is not None:
opts["count"] = count
kwargs.setdefault("opts", opts)
args = (path,)
return self._client.request('/files/read', args, **kwargs) | [
"def",
"files_read",
"(",
"self",
",",
"path",
",",
"offset",
"=",
"0",
",",
"count",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"opts",
"=",
"{",
"\"offset\"",
":",
"offset",
"}",
"if",
"count",
"is",
"not",
"None",
":",
"opts",
"[",
"\"cou... | Reads a file stored in the MFS.
.. code-block:: python
>>> c.files_read("/bla/file")
b'hi'
Parameters
----------
path : str
Filepath within the MFS
offset : int
Byte offset at which to begin reading at
count : int
Maximum number of bytes to read
Returns
-------
str : MFS file contents | [
"Reads",
"a",
"file",
"stored",
"in",
"the",
"MFS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L2009-L2036 | train | 229,574 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.files_write | def files_write(self, path, file, offset=0, create=False, truncate=False,
count=None, **kwargs):
"""Writes to a mutable file in the MFS.
.. code-block:: python
>>> c.files_write("/test/file", io.BytesIO(b"hi"), create=True)
b''
Parameters
----------
path : str
Filepath within the MFS
file : io.RawIOBase
IO stream object with data that should be written
offset : int
Byte offset at which to begin writing at
create : bool
Create the file if it does not exist
truncate : bool
Truncate the file to size zero before writing
count : int
Maximum number of bytes to read from the source ``file``
"""
opts = {"offset": offset, "create": create, "truncate": truncate}
if count is not None:
opts["count"] = count
kwargs.setdefault("opts", opts)
args = (path,)
body, headers = multipart.stream_files(file, self.chunk_size)
return self._client.request('/files/write', args,
data=body, headers=headers, **kwargs) | python | def files_write(self, path, file, offset=0, create=False, truncate=False,
count=None, **kwargs):
"""Writes to a mutable file in the MFS.
.. code-block:: python
>>> c.files_write("/test/file", io.BytesIO(b"hi"), create=True)
b''
Parameters
----------
path : str
Filepath within the MFS
file : io.RawIOBase
IO stream object with data that should be written
offset : int
Byte offset at which to begin writing at
create : bool
Create the file if it does not exist
truncate : bool
Truncate the file to size zero before writing
count : int
Maximum number of bytes to read from the source ``file``
"""
opts = {"offset": offset, "create": create, "truncate": truncate}
if count is not None:
opts["count"] = count
kwargs.setdefault("opts", opts)
args = (path,)
body, headers = multipart.stream_files(file, self.chunk_size)
return self._client.request('/files/write', args,
data=body, headers=headers, **kwargs) | [
"def",
"files_write",
"(",
"self",
",",
"path",
",",
"file",
",",
"offset",
"=",
"0",
",",
"create",
"=",
"False",
",",
"truncate",
"=",
"False",
",",
"count",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"opts",
"=",
"{",
"\"offset\"",
":",
"... | Writes to a mutable file in the MFS.
.. code-block:: python
>>> c.files_write("/test/file", io.BytesIO(b"hi"), create=True)
b''
Parameters
----------
path : str
Filepath within the MFS
file : io.RawIOBase
IO stream object with data that should be written
offset : int
Byte offset at which to begin writing at
create : bool
Create the file if it does not exist
truncate : bool
Truncate the file to size zero before writing
count : int
Maximum number of bytes to read from the source ``file`` | [
"Writes",
"to",
"a",
"mutable",
"file",
"in",
"the",
"MFS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L2038-L2070 | train | 229,575 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.files_mv | def files_mv(self, source, dest, **kwargs):
"""Moves files and directories within the MFS.
.. code-block:: python
>>> c.files_mv("/test/file", "/bla/file")
b''
Parameters
----------
source : str
Existing filepath within the MFS
dest : str
Destination to which the file will be moved in the MFS
"""
args = (source, dest)
return self._client.request('/files/mv', args, **kwargs) | python | def files_mv(self, source, dest, **kwargs):
"""Moves files and directories within the MFS.
.. code-block:: python
>>> c.files_mv("/test/file", "/bla/file")
b''
Parameters
----------
source : str
Existing filepath within the MFS
dest : str
Destination to which the file will be moved in the MFS
"""
args = (source, dest)
return self._client.request('/files/mv', args, **kwargs) | [
"def",
"files_mv",
"(",
"self",
",",
"source",
",",
"dest",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"source",
",",
"dest",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/files/mv'",
",",
"args",
",",
"*",
"*",
"kwargs",... | Moves files and directories within the MFS.
.. code-block:: python
>>> c.files_mv("/test/file", "/bla/file")
b''
Parameters
----------
source : str
Existing filepath within the MFS
dest : str
Destination to which the file will be moved in the MFS | [
"Moves",
"files",
"and",
"directories",
"within",
"the",
"MFS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L2072-L2088 | train | 229,576 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.add_bytes | def add_bytes(self, data, **kwargs):
"""Adds a set of bytes as a file to IPFS.
.. code-block:: python
>>> c.add_bytes(b"Mary had a little lamb")
'QmZfF6C9j4VtoCsTp4KSrhYH47QMd3DNXVZBKaxJdhaPab'
Also accepts and will stream generator objects.
Parameters
----------
data : bytes
Content to be added as a file
Returns
-------
str : Hash of the added IPFS object
"""
body, headers = multipart.stream_bytes(data, self.chunk_size)
return self._client.request('/add', decoder='json',
data=body, headers=headers, **kwargs) | python | def add_bytes(self, data, **kwargs):
"""Adds a set of bytes as a file to IPFS.
.. code-block:: python
>>> c.add_bytes(b"Mary had a little lamb")
'QmZfF6C9j4VtoCsTp4KSrhYH47QMd3DNXVZBKaxJdhaPab'
Also accepts and will stream generator objects.
Parameters
----------
data : bytes
Content to be added as a file
Returns
-------
str : Hash of the added IPFS object
"""
body, headers = multipart.stream_bytes(data, self.chunk_size)
return self._client.request('/add', decoder='json',
data=body, headers=headers, **kwargs) | [
"def",
"add_bytes",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"body",
",",
"headers",
"=",
"multipart",
".",
"stream_bytes",
"(",
"data",
",",
"self",
".",
"chunk_size",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"... | Adds a set of bytes as a file to IPFS.
.. code-block:: python
>>> c.add_bytes(b"Mary had a little lamb")
'QmZfF6C9j4VtoCsTp4KSrhYH47QMd3DNXVZBKaxJdhaPab'
Also accepts and will stream generator objects.
Parameters
----------
data : bytes
Content to be added as a file
Returns
-------
str : Hash of the added IPFS object | [
"Adds",
"a",
"set",
"of",
"bytes",
"as",
"a",
"file",
"to",
"IPFS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L2109-L2130 | train | 229,577 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.add_str | def add_str(self, string, **kwargs):
"""Adds a Python string as a file to IPFS.
.. code-block:: python
>>> c.add_str(u"Mary had a little lamb")
'QmZfF6C9j4VtoCsTp4KSrhYH47QMd3DNXVZBKaxJdhaPab'
Also accepts and will stream generator objects.
Parameters
----------
string : str
Content to be added as a file
Returns
-------
str : Hash of the added IPFS object
"""
body, headers = multipart.stream_text(string, self.chunk_size)
return self._client.request('/add', decoder='json',
data=body, headers=headers, **kwargs) | python | def add_str(self, string, **kwargs):
"""Adds a Python string as a file to IPFS.
.. code-block:: python
>>> c.add_str(u"Mary had a little lamb")
'QmZfF6C9j4VtoCsTp4KSrhYH47QMd3DNXVZBKaxJdhaPab'
Also accepts and will stream generator objects.
Parameters
----------
string : str
Content to be added as a file
Returns
-------
str : Hash of the added IPFS object
"""
body, headers = multipart.stream_text(string, self.chunk_size)
return self._client.request('/add', decoder='json',
data=body, headers=headers, **kwargs) | [
"def",
"add_str",
"(",
"self",
",",
"string",
",",
"*",
"*",
"kwargs",
")",
":",
"body",
",",
"headers",
"=",
"multipart",
".",
"stream_text",
"(",
"string",
",",
"self",
".",
"chunk_size",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
... | Adds a Python string as a file to IPFS.
.. code-block:: python
>>> c.add_str(u"Mary had a little lamb")
'QmZfF6C9j4VtoCsTp4KSrhYH47QMd3DNXVZBKaxJdhaPab'
Also accepts and will stream generator objects.
Parameters
----------
string : str
Content to be added as a file
Returns
-------
str : Hash of the added IPFS object | [
"Adds",
"a",
"Python",
"string",
"as",
"a",
"file",
"to",
"IPFS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L2133-L2154 | train | 229,578 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.add_json | def add_json(self, json_obj, **kwargs):
"""Adds a json-serializable Python dict as a json file to IPFS.
.. code-block:: python
>>> c.add_json({'one': 1, 'two': 2, 'three': 3})
'QmVz9g7m5u3oHiNKHj2CJX1dbG1gtismRS3g9NaPBBLbob'
Parameters
----------
json_obj : dict
A json-serializable Python dictionary
Returns
-------
str : Hash of the added IPFS object
"""
return self.add_bytes(encoding.Json().encode(json_obj), **kwargs) | python | def add_json(self, json_obj, **kwargs):
"""Adds a json-serializable Python dict as a json file to IPFS.
.. code-block:: python
>>> c.add_json({'one': 1, 'two': 2, 'three': 3})
'QmVz9g7m5u3oHiNKHj2CJX1dbG1gtismRS3g9NaPBBLbob'
Parameters
----------
json_obj : dict
A json-serializable Python dictionary
Returns
-------
str : Hash of the added IPFS object
"""
return self.add_bytes(encoding.Json().encode(json_obj), **kwargs) | [
"def",
"add_json",
"(",
"self",
",",
"json_obj",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"add_bytes",
"(",
"encoding",
".",
"Json",
"(",
")",
".",
"encode",
"(",
"json_obj",
")",
",",
"*",
"*",
"kwargs",
")"
] | Adds a json-serializable Python dict as a json file to IPFS.
.. code-block:: python
>>> c.add_json({'one': 1, 'two': 2, 'three': 3})
'QmVz9g7m5u3oHiNKHj2CJX1dbG1gtismRS3g9NaPBBLbob'
Parameters
----------
json_obj : dict
A json-serializable Python dictionary
Returns
-------
str : Hash of the added IPFS object | [
"Adds",
"a",
"json",
"-",
"serializable",
"Python",
"dict",
"as",
"a",
"json",
"file",
"to",
"IPFS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L2156-L2173 | train | 229,579 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.add_pyobj | def add_pyobj(self, py_obj, **kwargs):
"""Adds a picklable Python object as a file to IPFS.
.. deprecated:: 0.4.2
The ``*_pyobj`` APIs allow for arbitrary code execution if abused.
Either switch to :meth:`~ipfsapi.Client.add_json` or use
``client.add_bytes(pickle.dumps(py_obj))`` instead.
Please see :meth:`~ipfsapi.Client.get_pyobj` for the
**security risks** of using these methods!
.. code-block:: python
>>> c.add_pyobj([0, 1.0, 2j, '3', 4e5])
'QmWgXZSUTNNDD8LdkdJ8UXSn55KfFnNvTP1r7SyaQd74Ji'
Parameters
----------
py_obj : object
A picklable Python object
Returns
-------
str : Hash of the added IPFS object
"""
warnings.warn("Using `*_pyobj` on untrusted data is a security risk",
DeprecationWarning)
return self.add_bytes(encoding.Pickle().encode(py_obj), **kwargs) | python | def add_pyobj(self, py_obj, **kwargs):
"""Adds a picklable Python object as a file to IPFS.
.. deprecated:: 0.4.2
The ``*_pyobj`` APIs allow for arbitrary code execution if abused.
Either switch to :meth:`~ipfsapi.Client.add_json` or use
``client.add_bytes(pickle.dumps(py_obj))`` instead.
Please see :meth:`~ipfsapi.Client.get_pyobj` for the
**security risks** of using these methods!
.. code-block:: python
>>> c.add_pyobj([0, 1.0, 2j, '3', 4e5])
'QmWgXZSUTNNDD8LdkdJ8UXSn55KfFnNvTP1r7SyaQd74Ji'
Parameters
----------
py_obj : object
A picklable Python object
Returns
-------
str : Hash of the added IPFS object
"""
warnings.warn("Using `*_pyobj` on untrusted data is a security risk",
DeprecationWarning)
return self.add_bytes(encoding.Pickle().encode(py_obj), **kwargs) | [
"def",
"add_pyobj",
"(",
"self",
",",
"py_obj",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Using `*_pyobj` on untrusted data is a security risk\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"add_bytes",
"(",
"encoding",
".",
... | Adds a picklable Python object as a file to IPFS.
.. deprecated:: 0.4.2
The ``*_pyobj`` APIs allow for arbitrary code execution if abused.
Either switch to :meth:`~ipfsapi.Client.add_json` or use
``client.add_bytes(pickle.dumps(py_obj))`` instead.
Please see :meth:`~ipfsapi.Client.get_pyobj` for the
**security risks** of using these methods!
.. code-block:: python
>>> c.add_pyobj([0, 1.0, 2j, '3', 4e5])
'QmWgXZSUTNNDD8LdkdJ8UXSn55KfFnNvTP1r7SyaQd74Ji'
Parameters
----------
py_obj : object
A picklable Python object
Returns
-------
str : Hash of the added IPFS object | [
"Adds",
"a",
"picklable",
"Python",
"object",
"as",
"a",
"file",
"to",
"IPFS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L2194-L2221 | train | 229,580 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.get_pyobj | def get_pyobj(self, multihash, **kwargs):
"""Loads a pickled Python object from IPFS.
.. deprecated:: 0.4.2
The ``*_pyobj`` APIs allow for arbitrary code execution if abused.
Either switch to :meth:`~ipfsapi.Client.get_json` or use
``pickle.loads(client.cat(multihash))`` instead.
.. caution::
The pickle module is not intended to be secure against erroneous or
maliciously constructed data. Never unpickle data received from an
untrusted or unauthenticated source.
Please **read**
`this article <https://www.cs.uic.edu/%7Es/musings/pickle/>`_ to
understand the security risks of using this method!
.. code-block:: python
>>> c.get_pyobj('QmWgXZSUTNNDD8LdkdJ8UXSn55KfFnNvTP1r7SyaQd74Ji')
[0, 1.0, 2j, '3', 400000.0]
Parameters
----------
multihash : str
Multihash of the IPFS object to load
Returns
-------
object : Deserialized IPFS Python object
"""
warnings.warn("Using `*_pyobj` on untrusted data is a security risk",
DeprecationWarning)
return self.cat(multihash, decoder='pickle', **kwargs) | python | def get_pyobj(self, multihash, **kwargs):
"""Loads a pickled Python object from IPFS.
.. deprecated:: 0.4.2
The ``*_pyobj`` APIs allow for arbitrary code execution if abused.
Either switch to :meth:`~ipfsapi.Client.get_json` or use
``pickle.loads(client.cat(multihash))`` instead.
.. caution::
The pickle module is not intended to be secure against erroneous or
maliciously constructed data. Never unpickle data received from an
untrusted or unauthenticated source.
Please **read**
`this article <https://www.cs.uic.edu/%7Es/musings/pickle/>`_ to
understand the security risks of using this method!
.. code-block:: python
>>> c.get_pyobj('QmWgXZSUTNNDD8LdkdJ8UXSn55KfFnNvTP1r7SyaQd74Ji')
[0, 1.0, 2j, '3', 400000.0]
Parameters
----------
multihash : str
Multihash of the IPFS object to load
Returns
-------
object : Deserialized IPFS Python object
"""
warnings.warn("Using `*_pyobj` on untrusted data is a security risk",
DeprecationWarning)
return self.cat(multihash, decoder='pickle', **kwargs) | [
"def",
"get_pyobj",
"(",
"self",
",",
"multihash",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Using `*_pyobj` on untrusted data is a security risk\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"cat",
"(",
"multihash",
",",
"... | Loads a pickled Python object from IPFS.
.. deprecated:: 0.4.2
The ``*_pyobj`` APIs allow for arbitrary code execution if abused.
Either switch to :meth:`~ipfsapi.Client.get_json` or use
``pickle.loads(client.cat(multihash))`` instead.
.. caution::
The pickle module is not intended to be secure against erroneous or
maliciously constructed data. Never unpickle data received from an
untrusted or unauthenticated source.
Please **read**
`this article <https://www.cs.uic.edu/%7Es/musings/pickle/>`_ to
understand the security risks of using this method!
.. code-block:: python
>>> c.get_pyobj('QmWgXZSUTNNDD8LdkdJ8UXSn55KfFnNvTP1r7SyaQd74Ji')
[0, 1.0, 2j, '3', 400000.0]
Parameters
----------
multihash : str
Multihash of the IPFS object to load
Returns
-------
object : Deserialized IPFS Python object | [
"Loads",
"a",
"pickled",
"Python",
"object",
"from",
"IPFS",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L2223-L2257 | train | 229,581 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.pubsub_peers | def pubsub_peers(self, topic=None, **kwargs):
"""List the peers we are pubsubbing with.
Lists the id's of other IPFS users who we
are connected to via some topic. Without specifying
a topic, IPFS peers from all subscribed topics
will be returned in the data. If a topic is specified
only the IPFS id's of the peers from the specified
topic will be returned in the data.
.. code-block:: python
>>> c.pubsub_peers()
{'Strings':
[
'QmPbZ3SDgmTNEB1gNSE9DEf4xT8eag3AFn5uo7X39TbZM8',
'QmQKiXYzoFpiGZ93DaFBFDMDWDJCRjXDARu4wne2PRtSgA',
...
'QmepgFW7BHEtU4pZJdxaNiv75mKLLRQnPi1KaaXmQN4V1a'
]
}
## with a topic
# subscribe to a channel
>>> with c.pubsub_sub('hello') as sub:
... c.pubsub_peers(topic='hello')
{'String':
[
'QmPbZ3SDgmTNEB1gNSE9DEf4xT8eag3AFn5uo7X39TbZM8',
...
# other peers connected to the same channel
]
}
Parameters
----------
topic : str
The topic to list connected peers of
(defaults to None which lists peers for all topics)
Returns
-------
dict : Dictionary with the ke "Strings" who's value is id of IPFS
peers we're pubsubbing with
"""
args = (topic,) if topic is not None else ()
return self._client.request('/pubsub/peers', args,
decoder='json', **kwargs) | python | def pubsub_peers(self, topic=None, **kwargs):
"""List the peers we are pubsubbing with.
Lists the id's of other IPFS users who we
are connected to via some topic. Without specifying
a topic, IPFS peers from all subscribed topics
will be returned in the data. If a topic is specified
only the IPFS id's of the peers from the specified
topic will be returned in the data.
.. code-block:: python
>>> c.pubsub_peers()
{'Strings':
[
'QmPbZ3SDgmTNEB1gNSE9DEf4xT8eag3AFn5uo7X39TbZM8',
'QmQKiXYzoFpiGZ93DaFBFDMDWDJCRjXDARu4wne2PRtSgA',
...
'QmepgFW7BHEtU4pZJdxaNiv75mKLLRQnPi1KaaXmQN4V1a'
]
}
## with a topic
# subscribe to a channel
>>> with c.pubsub_sub('hello') as sub:
... c.pubsub_peers(topic='hello')
{'String':
[
'QmPbZ3SDgmTNEB1gNSE9DEf4xT8eag3AFn5uo7X39TbZM8',
...
# other peers connected to the same channel
]
}
Parameters
----------
topic : str
The topic to list connected peers of
(defaults to None which lists peers for all topics)
Returns
-------
dict : Dictionary with the ke "Strings" who's value is id of IPFS
peers we're pubsubbing with
"""
args = (topic,) if topic is not None else ()
return self._client.request('/pubsub/peers', args,
decoder='json', **kwargs) | [
"def",
"pubsub_peers",
"(",
"self",
",",
"topic",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"topic",
",",
")",
"if",
"topic",
"is",
"not",
"None",
"else",
"(",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'... | List the peers we are pubsubbing with.
Lists the id's of other IPFS users who we
are connected to via some topic. Without specifying
a topic, IPFS peers from all subscribed topics
will be returned in the data. If a topic is specified
only the IPFS id's of the peers from the specified
topic will be returned in the data.
.. code-block:: python
>>> c.pubsub_peers()
{'Strings':
[
'QmPbZ3SDgmTNEB1gNSE9DEf4xT8eag3AFn5uo7X39TbZM8',
'QmQKiXYzoFpiGZ93DaFBFDMDWDJCRjXDARu4wne2PRtSgA',
...
'QmepgFW7BHEtU4pZJdxaNiv75mKLLRQnPi1KaaXmQN4V1a'
]
}
## with a topic
# subscribe to a channel
>>> with c.pubsub_sub('hello') as sub:
... c.pubsub_peers(topic='hello')
{'String':
[
'QmPbZ3SDgmTNEB1gNSE9DEf4xT8eag3AFn5uo7X39TbZM8',
...
# other peers connected to the same channel
]
}
Parameters
----------
topic : str
The topic to list connected peers of
(defaults to None which lists peers for all topics)
Returns
-------
dict : Dictionary with the ke "Strings" who's value is id of IPFS
peers we're pubsubbing with | [
"List",
"the",
"peers",
"we",
"are",
"pubsubbing",
"with",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L2282-L2330 | train | 229,582 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.pubsub_pub | def pubsub_pub(self, topic, payload, **kwargs):
"""Publish a message to a given pubsub topic
Publishing will publish the given payload (string) to
everyone currently subscribed to the given topic.
All data (including the id of the publisher) is automatically
base64 encoded when published.
.. code-block:: python
# publishes the message 'message' to the topic 'hello'
>>> c.pubsub_pub('hello', 'message')
[]
Parameters
----------
topic : str
Topic to publish to
payload : Data to be published to the given topic
Returns
-------
list : empty list
"""
args = (topic, payload)
return self._client.request('/pubsub/pub', args,
decoder='json', **kwargs) | python | def pubsub_pub(self, topic, payload, **kwargs):
"""Publish a message to a given pubsub topic
Publishing will publish the given payload (string) to
everyone currently subscribed to the given topic.
All data (including the id of the publisher) is automatically
base64 encoded when published.
.. code-block:: python
# publishes the message 'message' to the topic 'hello'
>>> c.pubsub_pub('hello', 'message')
[]
Parameters
----------
topic : str
Topic to publish to
payload : Data to be published to the given topic
Returns
-------
list : empty list
"""
args = (topic, payload)
return self._client.request('/pubsub/pub', args,
decoder='json', **kwargs) | [
"def",
"pubsub_pub",
"(",
"self",
",",
"topic",
",",
"payload",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"topic",
",",
"payload",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/pubsub/pub'",
",",
"args",
",",
"decoder",
"=... | Publish a message to a given pubsub topic
Publishing will publish the given payload (string) to
everyone currently subscribed to the given topic.
All data (including the id of the publisher) is automatically
base64 encoded when published.
.. code-block:: python
# publishes the message 'message' to the topic 'hello'
>>> c.pubsub_pub('hello', 'message')
[]
Parameters
----------
topic : str
Topic to publish to
payload : Data to be published to the given topic
Returns
-------
list : empty list | [
"Publish",
"a",
"message",
"to",
"a",
"given",
"pubsub",
"topic"
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L2332-L2359 | train | 229,583 |
ipfs/py-ipfs-api | ipfsapi/client.py | Client.pubsub_sub | def pubsub_sub(self, topic, discover=False, **kwargs):
"""Subscribe to mesages on a given topic
Subscribing to a topic in IPFS means anytime
a message is published to a topic, the subscribers
will be notified of the publication.
The connection with the pubsub topic is opened and read.
The Subscription returned should be used inside a context
manager to ensure that it is closed properly and not left
hanging.
.. code-block:: python
>>> sub = c.pubsub_sub('testing')
>>> with c.pubsub_sub('testing') as sub:
# publish a message 'hello' to the topic 'testing'
... c.pubsub_pub('testing', 'hello')
... for message in sub:
... print(message)
... # Stop reading the subscription after
... # we receive one publication
... break
{'from': '<base64encoded IPFS id>',
'data': 'aGVsbG8=',
'topicIDs': ['testing']}
# NOTE: in order to receive published data
# you must already be subscribed to the topic at publication
# time.
Parameters
----------
topic : str
Name of a topic to subscribe to
discover : bool
Try to discover other peers subscibed to the same topic
(defaults to False)
Returns
-------
Generator wrapped in a context
manager that maintains a connection
stream to the given topic.
"""
args = (topic, discover)
return SubChannel(self._client.request('/pubsub/sub', args,
stream=True, decoder='json')) | python | def pubsub_sub(self, topic, discover=False, **kwargs):
"""Subscribe to mesages on a given topic
Subscribing to a topic in IPFS means anytime
a message is published to a topic, the subscribers
will be notified of the publication.
The connection with the pubsub topic is opened and read.
The Subscription returned should be used inside a context
manager to ensure that it is closed properly and not left
hanging.
.. code-block:: python
>>> sub = c.pubsub_sub('testing')
>>> with c.pubsub_sub('testing') as sub:
# publish a message 'hello' to the topic 'testing'
... c.pubsub_pub('testing', 'hello')
... for message in sub:
... print(message)
... # Stop reading the subscription after
... # we receive one publication
... break
{'from': '<base64encoded IPFS id>',
'data': 'aGVsbG8=',
'topicIDs': ['testing']}
# NOTE: in order to receive published data
# you must already be subscribed to the topic at publication
# time.
Parameters
----------
topic : str
Name of a topic to subscribe to
discover : bool
Try to discover other peers subscibed to the same topic
(defaults to False)
Returns
-------
Generator wrapped in a context
manager that maintains a connection
stream to the given topic.
"""
args = (topic, discover)
return SubChannel(self._client.request('/pubsub/sub', args,
stream=True, decoder='json')) | [
"def",
"pubsub_sub",
"(",
"self",
",",
"topic",
",",
"discover",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"topic",
",",
"discover",
")",
"return",
"SubChannel",
"(",
"self",
".",
"_client",
".",
"request",
"(",
"'/pubsub/sub'"... | Subscribe to mesages on a given topic
Subscribing to a topic in IPFS means anytime
a message is published to a topic, the subscribers
will be notified of the publication.
The connection with the pubsub topic is opened and read.
The Subscription returned should be used inside a context
manager to ensure that it is closed properly and not left
hanging.
.. code-block:: python
>>> sub = c.pubsub_sub('testing')
>>> with c.pubsub_sub('testing') as sub:
# publish a message 'hello' to the topic 'testing'
... c.pubsub_pub('testing', 'hello')
... for message in sub:
... print(message)
... # Stop reading the subscription after
... # we receive one publication
... break
{'from': '<base64encoded IPFS id>',
'data': 'aGVsbG8=',
'topicIDs': ['testing']}
# NOTE: in order to receive published data
# you must already be subscribed to the topic at publication
# time.
Parameters
----------
topic : str
Name of a topic to subscribe to
discover : bool
Try to discover other peers subscibed to the same topic
(defaults to False)
Returns
-------
Generator wrapped in a context
manager that maintains a connection
stream to the given topic. | [
"Subscribe",
"to",
"mesages",
"on",
"a",
"given",
"topic"
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/client.py#L2361-L2409 | train | 229,584 |
ipfs/py-ipfs-api | ipfsapi/utils.py | guess_mimetype | def guess_mimetype(filename):
"""Guesses the mimetype of a file based on the given ``filename``.
.. code-block:: python
>>> guess_mimetype('example.txt')
'text/plain'
>>> guess_mimetype('/foo/bar/example')
'application/octet-stream'
Parameters
----------
filename : str
The file name or path for which the mimetype is to be guessed
"""
fn = os.path.basename(filename)
return mimetypes.guess_type(fn)[0] or 'application/octet-stream' | python | def guess_mimetype(filename):
"""Guesses the mimetype of a file based on the given ``filename``.
.. code-block:: python
>>> guess_mimetype('example.txt')
'text/plain'
>>> guess_mimetype('/foo/bar/example')
'application/octet-stream'
Parameters
----------
filename : str
The file name or path for which the mimetype is to be guessed
"""
fn = os.path.basename(filename)
return mimetypes.guess_type(fn)[0] or 'application/octet-stream' | [
"def",
"guess_mimetype",
"(",
"filename",
")",
":",
"fn",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"return",
"mimetypes",
".",
"guess_type",
"(",
"fn",
")",
"[",
"0",
"]",
"or",
"'application/octet-stream'"
] | Guesses the mimetype of a file based on the given ``filename``.
.. code-block:: python
>>> guess_mimetype('example.txt')
'text/plain'
>>> guess_mimetype('/foo/bar/example')
'application/octet-stream'
Parameters
----------
filename : str
The file name or path for which the mimetype is to be guessed | [
"Guesses",
"the",
"mimetype",
"of",
"a",
"file",
"based",
"on",
"the",
"given",
"filename",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/utils.py#L13-L29 | train | 229,585 |
ipfs/py-ipfs-api | ipfsapi/utils.py | ls_dir | def ls_dir(dirname):
"""Returns files and subdirectories within a given directory.
Returns a pair of lists, containing the names of directories and files
in ``dirname``.
Raises
------
OSError : Accessing the given directory path failed
Parameters
----------
dirname : str
The path of the directory to be listed
"""
ls = os.listdir(dirname)
files = [p for p in ls if os.path.isfile(os.path.join(dirname, p))]
dirs = [p for p in ls if os.path.isdir(os.path.join(dirname, p))]
return files, dirs | python | def ls_dir(dirname):
"""Returns files and subdirectories within a given directory.
Returns a pair of lists, containing the names of directories and files
in ``dirname``.
Raises
------
OSError : Accessing the given directory path failed
Parameters
----------
dirname : str
The path of the directory to be listed
"""
ls = os.listdir(dirname)
files = [p for p in ls if os.path.isfile(os.path.join(dirname, p))]
dirs = [p for p in ls if os.path.isdir(os.path.join(dirname, p))]
return files, dirs | [
"def",
"ls_dir",
"(",
"dirname",
")",
":",
"ls",
"=",
"os",
".",
"listdir",
"(",
"dirname",
")",
"files",
"=",
"[",
"p",
"for",
"p",
"in",
"ls",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
... | Returns files and subdirectories within a given directory.
Returns a pair of lists, containing the names of directories and files
in ``dirname``.
Raises
------
OSError : Accessing the given directory path failed
Parameters
----------
dirname : str
The path of the directory to be listed | [
"Returns",
"files",
"and",
"subdirectories",
"within",
"a",
"given",
"directory",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/utils.py#L32-L50 | train | 229,586 |
ipfs/py-ipfs-api | ipfsapi/utils.py | clean_files | def clean_files(files):
"""Generates tuples with a ``file``-like object and a close indicator.
This is a generator of tuples, where the first element is the file object
and the second element is a boolean which is True if this module opened the
file (and thus should close it).
Raises
------
OSError : Accessing the given file path failed
Parameters
----------
files : list | io.IOBase | str
Collection or single instance of a filepath and file-like object
"""
if isinstance(files, (list, tuple)):
for f in files:
yield clean_file(f)
else:
yield clean_file(files) | python | def clean_files(files):
"""Generates tuples with a ``file``-like object and a close indicator.
This is a generator of tuples, where the first element is the file object
and the second element is a boolean which is True if this module opened the
file (and thus should close it).
Raises
------
OSError : Accessing the given file path failed
Parameters
----------
files : list | io.IOBase | str
Collection or single instance of a filepath and file-like object
"""
if isinstance(files, (list, tuple)):
for f in files:
yield clean_file(f)
else:
yield clean_file(files) | [
"def",
"clean_files",
"(",
"files",
")",
":",
"if",
"isinstance",
"(",
"files",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"f",
"in",
"files",
":",
"yield",
"clean_file",
"(",
"f",
")",
"else",
":",
"yield",
"clean_file",
"(",
"files",
"... | Generates tuples with a ``file``-like object and a close indicator.
This is a generator of tuples, where the first element is the file object
and the second element is a boolean which is True if this module opened the
file (and thus should close it).
Raises
------
OSError : Accessing the given file path failed
Parameters
----------
files : list | io.IOBase | str
Collection or single instance of a filepath and file-like object | [
"Generates",
"tuples",
"with",
"a",
"file",
"-",
"like",
"object",
"and",
"a",
"close",
"indicator",
"."
] | 7574dad04877b45dbe4ad321dcfa9e880eb2d90c | https://github.com/ipfs/py-ipfs-api/blob/7574dad04877b45dbe4ad321dcfa9e880eb2d90c/ipfsapi/utils.py#L75-L95 | train | 229,587 |
miguelgrinberg/Flask-Migrate | flask_migrate/cli.py | merge | def merge(directory, message, branch_label, rev_id, revisions):
"""Merge two revisions together, creating a new revision file"""
_merge(directory, revisions, message, branch_label, rev_id) | python | def merge(directory, message, branch_label, rev_id, revisions):
"""Merge two revisions together, creating a new revision file"""
_merge(directory, revisions, message, branch_label, rev_id) | [
"def",
"merge",
"(",
"directory",
",",
"message",
",",
"branch_label",
",",
"rev_id",
",",
"revisions",
")",
":",
"_merge",
"(",
"directory",
",",
"revisions",
",",
"message",
",",
"branch_label",
",",
"rev_id",
")"
] | Merge two revisions together, creating a new revision file | [
"Merge",
"two",
"revisions",
"together",
"creating",
"a",
"new",
"revision",
"file"
] | 65fbd978681bdf2eddf8940edd04ed7272a94480 | https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/cli.py#L114-L116 | train | 229,588 |
miguelgrinberg/Flask-Migrate | flask_migrate/cli.py | downgrade | def downgrade(directory, sql, tag, x_arg, revision):
"""Revert to a previous version"""
_downgrade(directory, revision, sql, tag, x_arg) | python | def downgrade(directory, sql, tag, x_arg, revision):
"""Revert to a previous version"""
_downgrade(directory, revision, sql, tag, x_arg) | [
"def",
"downgrade",
"(",
"directory",
",",
"sql",
",",
"tag",
",",
"x_arg",
",",
"revision",
")",
":",
"_downgrade",
"(",
"directory",
",",
"revision",
",",
"sql",
",",
"tag",
",",
"x_arg",
")"
] | Revert to a previous version | [
"Revert",
"to",
"a",
"previous",
"version"
] | 65fbd978681bdf2eddf8940edd04ed7272a94480 | https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/cli.py#L150-L152 | train | 229,589 |
miguelgrinberg/Flask-Migrate | flask_migrate/templates/flask-multidb/env.py | get_metadata | def get_metadata(bind):
"""Return the metadata for a bind."""
if bind == '':
bind = None
m = MetaData()
for t in target_metadata.tables.values():
if t.info.get('bind_key') == bind:
t.tometadata(m)
return m | python | def get_metadata(bind):
"""Return the metadata for a bind."""
if bind == '':
bind = None
m = MetaData()
for t in target_metadata.tables.values():
if t.info.get('bind_key') == bind:
t.tometadata(m)
return m | [
"def",
"get_metadata",
"(",
"bind",
")",
":",
"if",
"bind",
"==",
"''",
":",
"bind",
"=",
"None",
"m",
"=",
"MetaData",
"(",
")",
"for",
"t",
"in",
"target_metadata",
".",
"tables",
".",
"values",
"(",
")",
":",
"if",
"t",
".",
"info",
".",
"get"... | Return the metadata for a bind. | [
"Return",
"the",
"metadata",
"for",
"a",
"bind",
"."
] | 65fbd978681bdf2eddf8940edd04ed7272a94480 | https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/templates/flask-multidb/env.py#L44-L52 | train | 229,590 |
miguelgrinberg/Flask-Migrate | flask_migrate/__init__.py | init | def init(directory=None, multidb=False):
"""Creates a new migration repository"""
if directory is None:
directory = current_app.extensions['migrate'].directory
config = Config()
config.set_main_option('script_location', directory)
config.config_file_name = os.path.join(directory, 'alembic.ini')
config = current_app.extensions['migrate'].\
migrate.call_configure_callbacks(config)
if multidb:
command.init(config, directory, 'flask-multidb')
else:
command.init(config, directory, 'flask') | python | def init(directory=None, multidb=False):
"""Creates a new migration repository"""
if directory is None:
directory = current_app.extensions['migrate'].directory
config = Config()
config.set_main_option('script_location', directory)
config.config_file_name = os.path.join(directory, 'alembic.ini')
config = current_app.extensions['migrate'].\
migrate.call_configure_callbacks(config)
if multidb:
command.init(config, directory, 'flask-multidb')
else:
command.init(config, directory, 'flask') | [
"def",
"init",
"(",
"directory",
"=",
"None",
",",
"multidb",
"=",
"False",
")",
":",
"if",
"directory",
"is",
"None",
":",
"directory",
"=",
"current_app",
".",
"extensions",
"[",
"'migrate'",
"]",
".",
"directory",
"config",
"=",
"Config",
"(",
")",
... | Creates a new migration repository | [
"Creates",
"a",
"new",
"migration",
"repository"
] | 65fbd978681bdf2eddf8940edd04ed7272a94480 | https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L122-L134 | train | 229,591 |
miguelgrinberg/Flask-Migrate | flask_migrate/__init__.py | edit | def edit(directory=None, revision='current'):
"""Edit current revision."""
if alembic_version >= (0, 8, 0):
config = current_app.extensions['migrate'].migrate.get_config(
directory)
command.edit(config, revision)
else:
raise RuntimeError('Alembic 0.8.0 or greater is required') | python | def edit(directory=None, revision='current'):
"""Edit current revision."""
if alembic_version >= (0, 8, 0):
config = current_app.extensions['migrate'].migrate.get_config(
directory)
command.edit(config, revision)
else:
raise RuntimeError('Alembic 0.8.0 or greater is required') | [
"def",
"edit",
"(",
"directory",
"=",
"None",
",",
"revision",
"=",
"'current'",
")",
":",
"if",
"alembic_version",
">=",
"(",
"0",
",",
"8",
",",
"0",
")",
":",
"config",
"=",
"current_app",
".",
"extensions",
"[",
"'migrate'",
"]",
".",
"migrate",
... | Edit current revision. | [
"Edit",
"current",
"revision",
"."
] | 65fbd978681bdf2eddf8940edd04ed7272a94480 | https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L226-L233 | train | 229,592 |
miguelgrinberg/Flask-Migrate | flask_migrate/__init__.py | merge | def merge(directory=None, revisions='', message=None, branch_label=None,
rev_id=None):
"""Merge two revisions together. Creates a new migration file"""
if alembic_version >= (0, 7, 0):
config = current_app.extensions['migrate'].migrate.get_config(
directory)
command.merge(config, revisions, message=message,
branch_label=branch_label, rev_id=rev_id)
else:
raise RuntimeError('Alembic 0.7.0 or greater is required') | python | def merge(directory=None, revisions='', message=None, branch_label=None,
rev_id=None):
"""Merge two revisions together. Creates a new migration file"""
if alembic_version >= (0, 7, 0):
config = current_app.extensions['migrate'].migrate.get_config(
directory)
command.merge(config, revisions, message=message,
branch_label=branch_label, rev_id=rev_id)
else:
raise RuntimeError('Alembic 0.7.0 or greater is required') | [
"def",
"merge",
"(",
"directory",
"=",
"None",
",",
"revisions",
"=",
"''",
",",
"message",
"=",
"None",
",",
"branch_label",
"=",
"None",
",",
"rev_id",
"=",
"None",
")",
":",
"if",
"alembic_version",
">=",
"(",
"0",
",",
"7",
",",
"0",
")",
":",
... | Merge two revisions together. Creates a new migration file | [
"Merge",
"two",
"revisions",
"together",
".",
"Creates",
"a",
"new",
"migration",
"file"
] | 65fbd978681bdf2eddf8940edd04ed7272a94480 | https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L249-L258 | train | 229,593 |
miguelgrinberg/Flask-Migrate | flask_migrate/__init__.py | heads | def heads(directory=None, verbose=False, resolve_dependencies=False):
"""Show current available heads in the script directory"""
if alembic_version >= (0, 7, 0):
config = current_app.extensions['migrate'].migrate.get_config(
directory)
command.heads(config, verbose=verbose,
resolve_dependencies=resolve_dependencies)
else:
raise RuntimeError('Alembic 0.7.0 or greater is required') | python | def heads(directory=None, verbose=False, resolve_dependencies=False):
"""Show current available heads in the script directory"""
if alembic_version >= (0, 7, 0):
config = current_app.extensions['migrate'].migrate.get_config(
directory)
command.heads(config, verbose=verbose,
resolve_dependencies=resolve_dependencies)
else:
raise RuntimeError('Alembic 0.7.0 or greater is required') | [
"def",
"heads",
"(",
"directory",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"resolve_dependencies",
"=",
"False",
")",
":",
"if",
"alembic_version",
">=",
"(",
"0",
",",
"7",
",",
"0",
")",
":",
"config",
"=",
"current_app",
".",
"extensions",
"[... | Show current available heads in the script directory | [
"Show",
"current",
"available",
"heads",
"in",
"the",
"script",
"directory"
] | 65fbd978681bdf2eddf8940edd04ed7272a94480 | https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L353-L361 | train | 229,594 |
miguelgrinberg/Flask-Migrate | flask_migrate/__init__.py | branches | def branches(directory=None, verbose=False):
"""Show current branch points"""
config = current_app.extensions['migrate'].migrate.get_config(directory)
if alembic_version >= (0, 7, 0):
command.branches(config, verbose=verbose)
else:
command.branches(config) | python | def branches(directory=None, verbose=False):
"""Show current branch points"""
config = current_app.extensions['migrate'].migrate.get_config(directory)
if alembic_version >= (0, 7, 0):
command.branches(config, verbose=verbose)
else:
command.branches(config) | [
"def",
"branches",
"(",
"directory",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"config",
"=",
"current_app",
".",
"extensions",
"[",
"'migrate'",
"]",
".",
"migrate",
".",
"get_config",
"(",
"directory",
")",
"if",
"alembic_version",
">=",
"(",
... | Show current branch points | [
"Show",
"current",
"branch",
"points"
] | 65fbd978681bdf2eddf8940edd04ed7272a94480 | https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L370-L376 | train | 229,595 |
miguelgrinberg/Flask-Migrate | flask_migrate/__init__.py | current | def current(directory=None, verbose=False, head_only=False):
"""Display the current revision for each database."""
config = current_app.extensions['migrate'].migrate.get_config(directory)
if alembic_version >= (0, 7, 0):
command.current(config, verbose=verbose, head_only=head_only)
else:
command.current(config) | python | def current(directory=None, verbose=False, head_only=False):
"""Display the current revision for each database."""
config = current_app.extensions['migrate'].migrate.get_config(directory)
if alembic_version >= (0, 7, 0):
command.current(config, verbose=verbose, head_only=head_only)
else:
command.current(config) | [
"def",
"current",
"(",
"directory",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"head_only",
"=",
"False",
")",
":",
"config",
"=",
"current_app",
".",
"extensions",
"[",
"'migrate'",
"]",
".",
"migrate",
".",
"get_config",
"(",
"directory",
")",
"if... | Display the current revision for each database. | [
"Display",
"the",
"current",
"revision",
"for",
"each",
"database",
"."
] | 65fbd978681bdf2eddf8940edd04ed7272a94480 | https://github.com/miguelgrinberg/Flask-Migrate/blob/65fbd978681bdf2eddf8940edd04ed7272a94480/flask_migrate/__init__.py#L388-L394 | train | 229,596 |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.to_json | def to_json(self, content, pretty_print=False):
""" Convert a string to a JSON object
``content`` String content to convert into JSON
``pretty_print`` If defined, will output JSON is pretty print format
"""
if PY3:
if isinstance(content, bytes):
content = content.decode(encoding='utf-8')
if pretty_print:
json_ = self._json_pretty_print(content)
else:
json_ = json.loads(content)
logger.info('To JSON using : content=%s ' % (content))
logger.info('To JSON using : pretty_print=%s ' % (pretty_print))
return json_ | python | def to_json(self, content, pretty_print=False):
""" Convert a string to a JSON object
``content`` String content to convert into JSON
``pretty_print`` If defined, will output JSON is pretty print format
"""
if PY3:
if isinstance(content, bytes):
content = content.decode(encoding='utf-8')
if pretty_print:
json_ = self._json_pretty_print(content)
else:
json_ = json.loads(content)
logger.info('To JSON using : content=%s ' % (content))
logger.info('To JSON using : pretty_print=%s ' % (pretty_print))
return json_ | [
"def",
"to_json",
"(",
"self",
",",
"content",
",",
"pretty_print",
"=",
"False",
")",
":",
"if",
"PY3",
":",
"if",
"isinstance",
"(",
"content",
",",
"bytes",
")",
":",
"content",
"=",
"content",
".",
"decode",
"(",
"encoding",
"=",
"'utf-8'",
")",
... | Convert a string to a JSON object
``content`` String content to convert into JSON
``pretty_print`` If defined, will output JSON is pretty print format | [
"Convert",
"a",
"string",
"to",
"a",
"JSON",
"object"
] | 11baa3277f1cb728712e26d996200703c15254a8 | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L460-L477 | train | 229,597 |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.get_request | def get_request(
self,
alias,
uri,
headers=None,
json=None,
params=None,
allow_redirects=None,
timeout=None):
""" Send a GET request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the GET request to
``params`` url parameters to append to the uri
``headers`` a dictionary of headers to use with the request
``json`` json data to send in the body of the :class:`Request`.
``allow_redirects`` Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
``timeout`` connection timeout
"""
session = self._cache.switch(alias)
redir = True if allow_redirects is None else allow_redirects
response = self._get_request(
session, uri, params, headers, json, redir, timeout)
logger.info(
'Get Request using : alias=%s, uri=%s, headers=%s json=%s' %
(alias, uri, headers, json))
return response | python | def get_request(
self,
alias,
uri,
headers=None,
json=None,
params=None,
allow_redirects=None,
timeout=None):
""" Send a GET request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the GET request to
``params`` url parameters to append to the uri
``headers`` a dictionary of headers to use with the request
``json`` json data to send in the body of the :class:`Request`.
``allow_redirects`` Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
``timeout`` connection timeout
"""
session = self._cache.switch(alias)
redir = True if allow_redirects is None else allow_redirects
response = self._get_request(
session, uri, params, headers, json, redir, timeout)
logger.info(
'Get Request using : alias=%s, uri=%s, headers=%s json=%s' %
(alias, uri, headers, json))
return response | [
"def",
"get_request",
"(",
"self",
",",
"alias",
",",
"uri",
",",
"headers",
"=",
"None",
",",
"json",
"=",
"None",
",",
"params",
"=",
"None",
",",
"allow_redirects",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"session",
"=",
"self",
".",
... | Send a GET request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the GET request to
``params`` url parameters to append to the uri
``headers`` a dictionary of headers to use with the request
``json`` json data to send in the body of the :class:`Request`.
``allow_redirects`` Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
``timeout`` connection timeout | [
"Send",
"a",
"GET",
"request",
"on",
"the",
"session",
"object",
"found",
"using",
"the",
"given",
"alias"
] | 11baa3277f1cb728712e26d996200703c15254a8 | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L479-L515 | train | 229,598 |
bulkan/robotframework-requests | src/RequestsLibrary/RequestsKeywords.py | RequestsKeywords.post_request | def post_request(
self,
alias,
uri,
data=None,
json=None,
params=None,
headers=None,
files=None,
allow_redirects=None,
timeout=None):
""" Send a POST request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the POST request to
``data`` a dictionary of key-value pairs that will be urlencoded
and sent as POST data
or binary data that is sent as the raw body content
or passed as such for multipart form data if ``files`` is also
defined
``json`` a value that will be json encoded
and sent as POST data if files or data is not specified
``params`` url parameters to append to the uri
``headers`` a dictionary of headers to use with the request
``files`` a dictionary of file names containing file data to POST to the server
``allow_redirects`` Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
``timeout`` connection timeout
"""
session = self._cache.switch(alias)
if not files:
data = self._format_data_according_to_header(session, data, headers)
redir = True if allow_redirects is None else allow_redirects
response = self._body_request(
"post",
session,
uri,
data,
json,
params,
files,
headers,
redir,
timeout)
dataStr = self._format_data_to_log_string_according_to_header(data, headers)
logger.info('Post Request using : alias=%s, uri=%s, data=%s, headers=%s, files=%s, allow_redirects=%s '
% (alias, uri, dataStr, headers, files, redir))
return response | python | def post_request(
self,
alias,
uri,
data=None,
json=None,
params=None,
headers=None,
files=None,
allow_redirects=None,
timeout=None):
""" Send a POST request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the POST request to
``data`` a dictionary of key-value pairs that will be urlencoded
and sent as POST data
or binary data that is sent as the raw body content
or passed as such for multipart form data if ``files`` is also
defined
``json`` a value that will be json encoded
and sent as POST data if files or data is not specified
``params`` url parameters to append to the uri
``headers`` a dictionary of headers to use with the request
``files`` a dictionary of file names containing file data to POST to the server
``allow_redirects`` Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
``timeout`` connection timeout
"""
session = self._cache.switch(alias)
if not files:
data = self._format_data_according_to_header(session, data, headers)
redir = True if allow_redirects is None else allow_redirects
response = self._body_request(
"post",
session,
uri,
data,
json,
params,
files,
headers,
redir,
timeout)
dataStr = self._format_data_to_log_string_according_to_header(data, headers)
logger.info('Post Request using : alias=%s, uri=%s, data=%s, headers=%s, files=%s, allow_redirects=%s '
% (alias, uri, dataStr, headers, files, redir))
return response | [
"def",
"post_request",
"(",
"self",
",",
"alias",
",",
"uri",
",",
"data",
"=",
"None",
",",
"json",
"=",
"None",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"files",
"=",
"None",
",",
"allow_redirects",
"=",
"None",
",",
"timeout",... | Send a POST request on the session object found using the
given `alias`
``alias`` that will be used to identify the Session object in the cache
``uri`` to send the POST request to
``data`` a dictionary of key-value pairs that will be urlencoded
and sent as POST data
or binary data that is sent as the raw body content
or passed as such for multipart form data if ``files`` is also
defined
``json`` a value that will be json encoded
and sent as POST data if files or data is not specified
``params`` url parameters to append to the uri
``headers`` a dictionary of headers to use with the request
``files`` a dictionary of file names containing file data to POST to the server
``allow_redirects`` Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
``timeout`` connection timeout | [
"Send",
"a",
"POST",
"request",
"on",
"the",
"session",
"object",
"found",
"using",
"the",
"given",
"alias"
] | 11baa3277f1cb728712e26d996200703c15254a8 | https://github.com/bulkan/robotframework-requests/blob/11baa3277f1cb728712e26d996200703c15254a8/src/RequestsLibrary/RequestsKeywords.py#L550-L607 | train | 229,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.