index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
9,126 | geonamescache | get_us_states | null | def get_us_states(self):
return self.us_states
| (self) |
9,127 | geonamescache | get_us_states_by_names | null | def get_us_states_by_names(self):
return self.get_dataset_by_key(self.get_us_states(), 'name')
| (self) |
9,128 | geonamescache | search_cities | Search all city records and return list of records, that match query for given attribute. | def search_cities(self, query, attribute='alternatenames', case_sensitive=False, contains_search=True):
"""Search all city records and return list of records, that match query for given attribute."""
results = []
query = (case_sensitive and query) or query.casefold()
for record in self.get_cities().values():
record_value = record[attribute]
if contains_search:
if isinstance(record_value, list):
if any(query in ((case_sensitive and value) or value.casefold()) for value in record_value):
results.append(record)
elif query in ((case_sensitive and record_value) or record_value.casefold()):
results.append(record)
else:
if isinstance(record_value, list):
if case_sensitive:
if query in record_value:
results.append(record)
else:
if any(query == value.casefold() for value in record_value):
results.append(record)
elif query == ((case_sensitive and record_value) or record_value.casefold()):
results.append(record)
return results
| (self, query, attribute='alternatenames', case_sensitive=False, contains_search=True) |
9,132 | freqtrade_client.ft_rest_client | FtRestClient | null | class FtRestClient:
def __init__(self, serverurl, username=None, password=None, *,
pool_connections=10, pool_maxsize=10):
self._serverurl = serverurl
self._session = requests.Session()
# allow configuration of pool
adapter = requests.adapters.HTTPAdapter(
pool_connections=pool_connections,
pool_maxsize=pool_maxsize
)
self._session.mount('http://', adapter)
self._session.auth = (username, password)
def _call(self, method, apipath, params: Optional[dict] = None, data=None, files=None):
if str(method).upper() not in ('GET', 'POST', 'PUT', 'DELETE'):
raise ValueError(f'invalid method <{method}>')
basepath = f"{self._serverurl}/api/v1/{apipath}"
hd = {"Accept": "application/json",
"Content-Type": "application/json"
}
# Split url
schema, netloc, path, par, query, fragment = urlparse(basepath)
# URLEncode query string
query = urlencode(params) if params else ""
# recombine url
url = urlunparse((schema, netloc, path, par, query, fragment))
try:
resp = self._session.request(method, url, headers=hd, data=json.dumps(data))
# return resp.text
return resp.json()
except ConnectionError:
logger.warning("Connection error")
def _get(self, apipath, params: ParamsT = None):
return self._call("GET", apipath, params=params)
def _delete(self, apipath, params: ParamsT = None):
return self._call("DELETE", apipath, params=params)
def _post(self, apipath, params: ParamsT = None, data: PostDataT = None):
return self._call("POST", apipath, params=params, data=data)
def start(self):
"""Start the bot if it's in the stopped state.
:return: json object
"""
return self._post("start")
def stop(self):
"""Stop the bot. Use `start` to restart.
:return: json object
"""
return self._post("stop")
def stopbuy(self):
"""Stop buying (but handle sells gracefully). Use `reload_config` to reset.
:return: json object
"""
return self._post("stopbuy")
def reload_config(self):
"""Reload configuration.
:return: json object
"""
return self._post("reload_config")
def balance(self):
"""Get the account balance.
:return: json object
"""
return self._get("balance")
def count(self):
"""Return the amount of open trades.
:return: json object
"""
return self._get("count")
def entries(self, pair=None):
"""Returns List of dicts containing all Trades, based on buy tag performance
Can either be average for all pairs or a specific pair provided
:return: json object
"""
return self._get("entries", params={"pair": pair} if pair else None)
def exits(self, pair=None):
"""Returns List of dicts containing all Trades, based on exit reason performance
Can either be average for all pairs or a specific pair provided
:return: json object
"""
return self._get("exits", params={"pair": pair} if pair else None)
def mix_tags(self, pair=None):
"""Returns List of dicts containing all Trades, based on entry_tag + exit_reason performance
Can either be average for all pairs or a specific pair provided
:return: json object
"""
return self._get("mix_tags", params={"pair": pair} if pair else None)
def locks(self):
"""Return current locks
:return: json object
"""
return self._get("locks")
def delete_lock(self, lock_id):
"""Delete (disable) lock from the database.
:param lock_id: ID for the lock to delete
:return: json object
"""
return self._delete(f"locks/{lock_id}")
def lock_add(self, pair: str, until: str, side: str = '*', reason: str = ''):
"""Lock pair
:param pair: Pair to lock
:param until: Lock until this date (format "2024-03-30 16:00:00Z")
:param side: Side to lock (long, short, *)
:param reason: Reason for the lock
:return: json object
"""
data = [
{
"pair": pair,
"until": until,
"side": side,
"reason": reason
}
]
return self._post("locks", data=data)
def daily(self, days=None):
"""Return the profits for each day, and amount of trades.
:return: json object
"""
return self._get("daily", params={"timescale": days} if days else None)
def weekly(self, weeks=None):
"""Return the profits for each week, and amount of trades.
:return: json object
"""
return self._get("weekly", params={"timescale": weeks} if weeks else None)
def monthly(self, months=None):
"""Return the profits for each month, and amount of trades.
:return: json object
"""
return self._get("monthly", params={"timescale": months} if months else None)
def edge(self):
"""Return information about edge.
:return: json object
"""
return self._get("edge")
def profit(self):
"""Return the profit summary.
:return: json object
"""
return self._get("profit")
def stats(self):
"""Return the stats report (durations, sell-reasons).
:return: json object
"""
return self._get("stats")
def performance(self):
"""Return the performance of the different coins.
:return: json object
"""
return self._get("performance")
def status(self):
"""Get the status of open trades.
:return: json object
"""
return self._get("status")
def version(self):
"""Return the version of the bot.
:return: json object containing the version
"""
return self._get("version")
def show_config(self):
""" Returns part of the configuration, relevant for trading operations.
:return: json object containing the version
"""
return self._get("show_config")
def ping(self):
"""simple ping"""
configstatus = self.show_config()
if not configstatus:
return {"status": "not_running"}
elif configstatus['state'] == "running":
return {"status": "pong"}
else:
return {"status": "not_running"}
def logs(self, limit=None):
"""Show latest logs.
:param limit: Limits log messages to the last <limit> logs. No limit to get the entire log.
:return: json object
"""
return self._get("logs", params={"limit": limit} if limit else 0)
def trades(self, limit=None, offset=None):
"""Return trades history, sorted by id
:param limit: Limits trades to the X last trades. Max 500 trades.
:param offset: Offset by this amount of trades.
:return: json object
"""
params = {}
if limit:
params['limit'] = limit
if offset:
params['offset'] = offset
return self._get("trades", params)
def trade(self, trade_id):
"""Return specific trade
:param trade_id: Specify which trade to get.
:return: json object
"""
return self._get(f"trade/{trade_id}")
def delete_trade(self, trade_id):
"""Delete trade from the database.
Tries to close open orders. Requires manual handling of this asset on the exchange.
:param trade_id: Deletes the trade with this ID from the database.
:return: json object
"""
return self._delete(f"trades/{trade_id}")
def cancel_open_order(self, trade_id):
"""Cancel open order for trade.
:param trade_id: Cancels open orders for this trade.
:return: json object
"""
return self._delete(f"trades/{trade_id}/open-order")
def whitelist(self):
"""Show the current whitelist.
:return: json object
"""
return self._get("whitelist")
def blacklist(self, *args):
"""Show the current blacklist.
:param add: List of coins to add (example: "BNB/BTC")
:return: json object
"""
if not args:
return self._get("blacklist")
else:
return self._post("blacklist", data={"blacklist": args})
def forcebuy(self, pair, price=None):
"""Buy an asset.
:param pair: Pair to buy (ETH/BTC)
:param price: Optional - price to buy
:return: json object of the trade
"""
data = {"pair": pair,
"price": price
}
return self._post("forcebuy", data=data)
def forceenter(self, pair, side, price=None):
"""Force entering a trade
:param pair: Pair to buy (ETH/BTC)
:param side: 'long' or 'short'
:param price: Optional - price to buy
:return: json object of the trade
"""
data = {"pair": pair,
"side": side,
}
if price:
data['price'] = price
return self._post("forceenter", data=data)
def forceexit(self, tradeid, ordertype=None, amount=None):
"""Force-exit a trade.
:param tradeid: Id of the trade (can be received via status command)
:param ordertype: Order type to use (must be market or limit)
:param amount: Amount to sell. Full sell if not given
:return: json object
"""
return self._post("forceexit", data={
"tradeid": tradeid,
"ordertype": ordertype,
"amount": amount,
})
def strategies(self):
"""Lists available strategies
:return: json object
"""
return self._get("strategies")
def strategy(self, strategy):
"""Get strategy details
:param strategy: Strategy class name
:return: json object
"""
return self._get(f"strategy/{strategy}")
def pairlists_available(self):
"""Lists available pairlist providers
:return: json object
"""
return self._get("pairlists/available")
def plot_config(self):
"""Return plot configuration if the strategy defines one.
:return: json object
"""
return self._get("plot_config")
def available_pairs(self, timeframe=None, stake_currency=None):
"""Return available pair (backtest data) based on timeframe / stake_currency selection
:param timeframe: Only pairs with this timeframe available.
:param stake_currency: Only pairs that include this timeframe
:return: json object
"""
return self._get("available_pairs", params={
"stake_currency": stake_currency if timeframe else '',
"timeframe": timeframe if timeframe else '',
})
def pair_candles(self, pair, timeframe, limit=None, columns=None):
"""Return live dataframe for <pair><timeframe>.
:param pair: Pair to get data for
:param timeframe: Only pairs with this timeframe available.
:param limit: Limit result to the last n candles.
:param columns: List of dataframe columns to return. Empty list will return OHLCV.
:return: json object
"""
params = {
"pair": pair,
"timeframe": timeframe,
}
if limit:
params['limit'] = limit
if columns is not None:
params['columns'] = columns
return self._post(
"pair_candles",
data=params
)
return self._get("pair_candles", params=params)
def pair_history(self, pair, timeframe, strategy, timerange=None, freqaimodel=None):
"""Return historic, analyzed dataframe
:param pair: Pair to get data for
:param timeframe: Only pairs with this timeframe available.
:param strategy: Strategy to analyze and get values for
:param freqaimodel: FreqAI model to use for analysis
:param timerange: Timerange to get data for (same format than --timerange endpoints)
:return: json object
"""
return self._get("pair_history", params={
"pair": pair,
"timeframe": timeframe,
"strategy": strategy,
"freqaimodel": freqaimodel,
"timerange": timerange if timerange else '',
})
def sysinfo(self):
"""Provides system information (CPU, RAM usage)
:return: json object
"""
return self._get("sysinfo")
def health(self):
"""Provides a quick health check of the running bot.
:return: json object
"""
return self._get("health")
| (serverurl, username=None, password=None, *, pool_connections=10, pool_maxsize=10) |
9,133 | freqtrade_client.ft_rest_client | __init__ | null | def __init__(self, serverurl, username=None, password=None, *,
pool_connections=10, pool_maxsize=10):
self._serverurl = serverurl
self._session = requests.Session()
# allow configuration of pool
adapter = requests.adapters.HTTPAdapter(
pool_connections=pool_connections,
pool_maxsize=pool_maxsize
)
self._session.mount('http://', adapter)
self._session.auth = (username, password)
| (self, serverurl, username=None, password=None, *, pool_connections=10, pool_maxsize=10) |
9,134 | freqtrade_client.ft_rest_client | _call | null | def _call(self, method, apipath, params: Optional[dict] = None, data=None, files=None):
if str(method).upper() not in ('GET', 'POST', 'PUT', 'DELETE'):
raise ValueError(f'invalid method <{method}>')
basepath = f"{self._serverurl}/api/v1/{apipath}"
hd = {"Accept": "application/json",
"Content-Type": "application/json"
}
# Split url
schema, netloc, path, par, query, fragment = urlparse(basepath)
# URLEncode query string
query = urlencode(params) if params else ""
# recombine url
url = urlunparse((schema, netloc, path, par, query, fragment))
try:
resp = self._session.request(method, url, headers=hd, data=json.dumps(data))
# return resp.text
return resp.json()
except ConnectionError:
logger.warning("Connection error")
| (self, method, apipath, params: Optional[dict] = None, data=None, files=None) |
9,135 | freqtrade_client.ft_rest_client | _delete | null | def _delete(self, apipath, params: ParamsT = None):
return self._call("DELETE", apipath, params=params)
| (self, apipath, params: Optional[Dict[str, Any]] = None) |
9,136 | freqtrade_client.ft_rest_client | _get | null | def _get(self, apipath, params: ParamsT = None):
return self._call("GET", apipath, params=params)
| (self, apipath, params: Optional[Dict[str, Any]] = None) |
9,137 | freqtrade_client.ft_rest_client | _post | null | def _post(self, apipath, params: ParamsT = None, data: PostDataT = None):
return self._call("POST", apipath, params=params, data=data)
| (self, apipath, params: Optional[Dict[str, Any]] = None, data: Union[Dict[str, Any], List[Dict[str, Any]], NoneType] = None) |
9,138 | freqtrade_client.ft_rest_client | available_pairs | Return available pair (backtest data) based on timeframe / stake_currency selection
:param timeframe: Only pairs with this timeframe available.
:param stake_currency: Only pairs that include this timeframe
:return: json object
| def available_pairs(self, timeframe=None, stake_currency=None):
"""Return available pair (backtest data) based on timeframe / stake_currency selection
:param timeframe: Only pairs with this timeframe available.
:param stake_currency: Only pairs that include this timeframe
:return: json object
"""
return self._get("available_pairs", params={
"stake_currency": stake_currency if timeframe else '',
"timeframe": timeframe if timeframe else '',
})
| (self, timeframe=None, stake_currency=None) |
9,139 | freqtrade_client.ft_rest_client | balance | Get the account balance.
:return: json object
| def balance(self):
"""Get the account balance.
:return: json object
"""
return self._get("balance")
| (self) |
9,140 | freqtrade_client.ft_rest_client | blacklist | Show the current blacklist.
:param add: List of coins to add (example: "BNB/BTC")
:return: json object
| def blacklist(self, *args):
"""Show the current blacklist.
:param add: List of coins to add (example: "BNB/BTC")
:return: json object
"""
if not args:
return self._get("blacklist")
else:
return self._post("blacklist", data={"blacklist": args})
| (self, *args) |
9,141 | freqtrade_client.ft_rest_client | cancel_open_order | Cancel open order for trade.
:param trade_id: Cancels open orders for this trade.
:return: json object
| def cancel_open_order(self, trade_id):
"""Cancel open order for trade.
:param trade_id: Cancels open orders for this trade.
:return: json object
"""
return self._delete(f"trades/{trade_id}/open-order")
| (self, trade_id) |
9,142 | freqtrade_client.ft_rest_client | count | Return the amount of open trades.
:return: json object
| def count(self):
"""Return the amount of open trades.
:return: json object
"""
return self._get("count")
| (self) |
9,143 | freqtrade_client.ft_rest_client | daily | Return the profits for each day, and amount of trades.
:return: json object
| def daily(self, days=None):
"""Return the profits for each day, and amount of trades.
:return: json object
"""
return self._get("daily", params={"timescale": days} if days else None)
| (self, days=None) |
9,144 | freqtrade_client.ft_rest_client | delete_lock | Delete (disable) lock from the database.
:param lock_id: ID for the lock to delete
:return: json object
| def delete_lock(self, lock_id):
"""Delete (disable) lock from the database.
:param lock_id: ID for the lock to delete
:return: json object
"""
return self._delete(f"locks/{lock_id}")
| (self, lock_id) |
9,145 | freqtrade_client.ft_rest_client | delete_trade | Delete trade from the database.
Tries to close open orders. Requires manual handling of this asset on the exchange.
:param trade_id: Deletes the trade with this ID from the database.
:return: json object
| def delete_trade(self, trade_id):
"""Delete trade from the database.
Tries to close open orders. Requires manual handling of this asset on the exchange.
:param trade_id: Deletes the trade with this ID from the database.
:return: json object
"""
return self._delete(f"trades/{trade_id}")
| (self, trade_id) |
9,146 | freqtrade_client.ft_rest_client | edge | Return information about edge.
:return: json object
| def edge(self):
"""Return information about edge.
:return: json object
"""
return self._get("edge")
| (self) |
9,147 | freqtrade_client.ft_rest_client | entries | Returns List of dicts containing all Trades, based on buy tag performance
Can either be average for all pairs or a specific pair provided
:return: json object
| def entries(self, pair=None):
"""Returns List of dicts containing all Trades, based on buy tag performance
Can either be average for all pairs or a specific pair provided
:return: json object
"""
return self._get("entries", params={"pair": pair} if pair else None)
| (self, pair=None) |
9,148 | freqtrade_client.ft_rest_client | exits | Returns List of dicts containing all Trades, based on exit reason performance
Can either be average for all pairs or a specific pair provided
:return: json object
| def exits(self, pair=None):
"""Returns List of dicts containing all Trades, based on exit reason performance
Can either be average for all pairs or a specific pair provided
:return: json object
"""
return self._get("exits", params={"pair": pair} if pair else None)
| (self, pair=None) |
9,149 | freqtrade_client.ft_rest_client | forcebuy | Buy an asset.
:param pair: Pair to buy (ETH/BTC)
:param price: Optional - price to buy
:return: json object of the trade
| def forcebuy(self, pair, price=None):
"""Buy an asset.
:param pair: Pair to buy (ETH/BTC)
:param price: Optional - price to buy
:return: json object of the trade
"""
data = {"pair": pair,
"price": price
}
return self._post("forcebuy", data=data)
| (self, pair, price=None) |
9,150 | freqtrade_client.ft_rest_client | forceenter | Force entering a trade
:param pair: Pair to buy (ETH/BTC)
:param side: 'long' or 'short'
:param price: Optional - price to buy
:return: json object of the trade
| def forceenter(self, pair, side, price=None):
"""Force entering a trade
:param pair: Pair to buy (ETH/BTC)
:param side: 'long' or 'short'
:param price: Optional - price to buy
:return: json object of the trade
"""
data = {"pair": pair,
"side": side,
}
if price:
data['price'] = price
return self._post("forceenter", data=data)
| (self, pair, side, price=None) |
9,151 | freqtrade_client.ft_rest_client | forceexit | Force-exit a trade.
:param tradeid: Id of the trade (can be received via status command)
:param ordertype: Order type to use (must be market or limit)
:param amount: Amount to sell. Full sell if not given
:return: json object
| def forceexit(self, tradeid, ordertype=None, amount=None):
"""Force-exit a trade.
:param tradeid: Id of the trade (can be received via status command)
:param ordertype: Order type to use (must be market or limit)
:param amount: Amount to sell. Full sell if not given
:return: json object
"""
return self._post("forceexit", data={
"tradeid": tradeid,
"ordertype": ordertype,
"amount": amount,
})
| (self, tradeid, ordertype=None, amount=None) |
9,152 | freqtrade_client.ft_rest_client | health | Provides a quick health check of the running bot.
:return: json object
| def health(self):
"""Provides a quick health check of the running bot.
:return: json object
"""
return self._get("health")
| (self) |
9,153 | freqtrade_client.ft_rest_client | lock_add | Lock pair
:param pair: Pair to lock
:param until: Lock until this date (format "2024-03-30 16:00:00Z")
:param side: Side to lock (long, short, *)
:param reason: Reason for the lock
:return: json object
| def lock_add(self, pair: str, until: str, side: str = '*', reason: str = ''):
"""Lock pair
:param pair: Pair to lock
:param until: Lock until this date (format "2024-03-30 16:00:00Z")
:param side: Side to lock (long, short, *)
:param reason: Reason for the lock
:return: json object
"""
data = [
{
"pair": pair,
"until": until,
"side": side,
"reason": reason
}
]
return self._post("locks", data=data)
| (self, pair: str, until: str, side: str = '*', reason: str = '') |
9,154 | freqtrade_client.ft_rest_client | locks | Return current locks
:return: json object
| def locks(self):
"""Return current locks
:return: json object
"""
return self._get("locks")
| (self) |
9,155 | freqtrade_client.ft_rest_client | logs | Show latest logs.
:param limit: Limits log messages to the last <limit> logs. No limit to get the entire log.
:return: json object
| def logs(self, limit=None):
"""Show latest logs.
:param limit: Limits log messages to the last <limit> logs. No limit to get the entire log.
:return: json object
"""
return self._get("logs", params={"limit": limit} if limit else 0)
| (self, limit=None) |
9,156 | freqtrade_client.ft_rest_client | mix_tags | Returns List of dicts containing all Trades, based on entry_tag + exit_reason performance
Can either be average for all pairs or a specific pair provided
:return: json object
| def mix_tags(self, pair=None):
"""Returns List of dicts containing all Trades, based on entry_tag + exit_reason performance
Can either be average for all pairs or a specific pair provided
:return: json object
"""
return self._get("mix_tags", params={"pair": pair} if pair else None)
| (self, pair=None) |
9,157 | freqtrade_client.ft_rest_client | monthly | Return the profits for each month, and amount of trades.
:return: json object
| def monthly(self, months=None):
"""Return the profits for each month, and amount of trades.
:return: json object
"""
return self._get("monthly", params={"timescale": months} if months else None)
| (self, months=None) |
9,158 | freqtrade_client.ft_rest_client | pair_candles | Return live dataframe for <pair><timeframe>.
:param pair: Pair to get data for
:param timeframe: Only pairs with this timeframe available.
:param limit: Limit result to the last n candles.
:param columns: List of dataframe columns to return. Empty list will return OHLCV.
:return: json object
| def pair_candles(self, pair, timeframe, limit=None, columns=None):
"""Return live dataframe for <pair><timeframe>.
:param pair: Pair to get data for
:param timeframe: Only pairs with this timeframe available.
:param limit: Limit result to the last n candles.
:param columns: List of dataframe columns to return. Empty list will return OHLCV.
:return: json object
"""
params = {
"pair": pair,
"timeframe": timeframe,
}
if limit:
params['limit'] = limit
if columns is not None:
params['columns'] = columns
return self._post(
"pair_candles",
data=params
)
return self._get("pair_candles", params=params)
| (self, pair, timeframe, limit=None, columns=None) |
9,159 | freqtrade_client.ft_rest_client | pair_history | Return historic, analyzed dataframe
:param pair: Pair to get data for
:param timeframe: Only pairs with this timeframe available.
:param strategy: Strategy to analyze and get values for
:param freqaimodel: FreqAI model to use for analysis
:param timerange: Timerange to get data for (same format than --timerange endpoints)
:return: json object
| def pair_history(self, pair, timeframe, strategy, timerange=None, freqaimodel=None):
"""Return historic, analyzed dataframe
:param pair: Pair to get data for
:param timeframe: Only pairs with this timeframe available.
:param strategy: Strategy to analyze and get values for
:param freqaimodel: FreqAI model to use for analysis
:param timerange: Timerange to get data for (same format than --timerange endpoints)
:return: json object
"""
return self._get("pair_history", params={
"pair": pair,
"timeframe": timeframe,
"strategy": strategy,
"freqaimodel": freqaimodel,
"timerange": timerange if timerange else '',
})
| (self, pair, timeframe, strategy, timerange=None, freqaimodel=None) |
9,160 | freqtrade_client.ft_rest_client | pairlists_available | Lists available pairlist providers
:return: json object
| def pairlists_available(self):
"""Lists available pairlist providers
:return: json object
"""
return self._get("pairlists/available")
| (self) |
9,161 | freqtrade_client.ft_rest_client | performance | Return the performance of the different coins.
:return: json object
| def performance(self):
"""Return the performance of the different coins.
:return: json object
"""
return self._get("performance")
| (self) |
9,162 | freqtrade_client.ft_rest_client | ping | simple ping | def ping(self):
"""simple ping"""
configstatus = self.show_config()
if not configstatus:
return {"status": "not_running"}
elif configstatus['state'] == "running":
return {"status": "pong"}
else:
return {"status": "not_running"}
| (self) |
9,163 | freqtrade_client.ft_rest_client | plot_config | Return plot configuration if the strategy defines one.
:return: json object
| def plot_config(self):
"""Return plot configuration if the strategy defines one.
:return: json object
"""
return self._get("plot_config")
| (self) |
9,164 | freqtrade_client.ft_rest_client | profit | Return the profit summary.
:return: json object
| def profit(self):
"""Return the profit summary.
:return: json object
"""
return self._get("profit")
| (self) |
9,165 | freqtrade_client.ft_rest_client | reload_config | Reload configuration.
:return: json object
| def reload_config(self):
"""Reload configuration.
:return: json object
"""
return self._post("reload_config")
| (self) |
9,166 | freqtrade_client.ft_rest_client | show_config | Returns part of the configuration, relevant for trading operations.
:return: json object containing the version
| def show_config(self):
""" Returns part of the configuration, relevant for trading operations.
:return: json object containing the version
"""
return self._get("show_config")
| (self) |
9,167 | freqtrade_client.ft_rest_client | start | Start the bot if it's in the stopped state.
:return: json object
| def start(self):
"""Start the bot if it's in the stopped state.
:return: json object
"""
return self._post("start")
| (self) |
9,168 | freqtrade_client.ft_rest_client | stats | Return the stats report (durations, sell-reasons).
:return: json object
| def stats(self):
"""Return the stats report (durations, sell-reasons).
:return: json object
"""
return self._get("stats")
| (self) |
9,169 | freqtrade_client.ft_rest_client | status | Get the status of open trades.
:return: json object
| def status(self):
"""Get the status of open trades.
:return: json object
"""
return self._get("status")
| (self) |
9,170 | freqtrade_client.ft_rest_client | stop | Stop the bot. Use `start` to restart.
:return: json object
| def stop(self):
"""Stop the bot. Use `start` to restart.
:return: json object
"""
return self._post("stop")
| (self) |
9,171 | freqtrade_client.ft_rest_client | stopbuy | Stop buying (but handle sells gracefully). Use `reload_config` to reset.
:return: json object
| def stopbuy(self):
"""Stop buying (but handle sells gracefully). Use `reload_config` to reset.
:return: json object
"""
return self._post("stopbuy")
| (self) |
9,172 | freqtrade_client.ft_rest_client | strategies | Lists available strategies
:return: json object
| def strategies(self):
"""Lists available strategies
:return: json object
"""
return self._get("strategies")
| (self) |
9,173 | freqtrade_client.ft_rest_client | strategy | Get strategy details
:param strategy: Strategy class name
:return: json object
| def strategy(self, strategy):
"""Get strategy details
:param strategy: Strategy class name
:return: json object
"""
return self._get(f"strategy/{strategy}")
| (self, strategy) |
9,174 | freqtrade_client.ft_rest_client | sysinfo | Provides system information (CPU, RAM usage)
:return: json object
| def sysinfo(self):
"""Provides system information (CPU, RAM usage)
:return: json object
"""
return self._get("sysinfo")
| (self) |
9,175 | freqtrade_client.ft_rest_client | trade | Return specific trade
:param trade_id: Specify which trade to get.
:return: json object
| def trade(self, trade_id):
"""Return specific trade
:param trade_id: Specify which trade to get.
:return: json object
"""
return self._get(f"trade/{trade_id}")
| (self, trade_id) |
9,176 | freqtrade_client.ft_rest_client | trades | Return trades history, sorted by id
:param limit: Limits trades to the X last trades. Max 500 trades.
:param offset: Offset by this amount of trades.
:return: json object
| def trades(self, limit=None, offset=None):
"""Return trades history, sorted by id
:param limit: Limits trades to the X last trades. Max 500 trades.
:param offset: Offset by this amount of trades.
:return: json object
"""
params = {}
if limit:
params['limit'] = limit
if offset:
params['offset'] = offset
return self._get("trades", params)
| (self, limit=None, offset=None) |
9,177 | freqtrade_client.ft_rest_client | version | Return the version of the bot.
:return: json object containing the version
| def version(self):
"""Return the version of the bot.
:return: json object containing the version
"""
return self._get("version")
| (self) |
9,178 | freqtrade_client.ft_rest_client | weekly | Return the profits for each week, and amount of trades.
:return: json object
| def weekly(self, weeks=None):
"""Return the profits for each week, and amount of trades.
:return: json object
"""
return self._get("weekly", params={"timescale": weeks} if weeks else None)
| (self, weeks=None) |
9,179 | freqtrade_client.ft_rest_client | whitelist | Show the current whitelist.
:return: json object
| def whitelist(self):
"""Show the current whitelist.
:return: json object
"""
return self._get("whitelist")
| (self) |
9,184 | wulkanowy_qr | decode | null | def decode(password: str, content: str) -> str:
cipher = AES.new(password.encode(), AES.MODE_ECB)
bytes = cipher.decrypt(base64.b64decode(content))
return Padding.unpad(bytes, 16).decode()
| (password: str, content: str) -> str |
9,185 | wulkanowy_qr | encode | null | def encode(password: str, content: str) -> str:
cipher = AES.new(password.encode(), AES.MODE_ECB)
bytes = cipher.encrypt(Padding.pad(content.encode(), 16))
return base64.b64encode(bytes).decode()
| (password: str, content: str) -> str |
9,186 | flask_basicauth | BasicAuth |
A Flask extension for adding HTTP basic access authentication to the
application.
:param app: a :class:`~flask.Flask` instance. Defaults to `None`. If no
application is provided on creation, then it can be provided later on
via :meth:`init_app`.
| class BasicAuth(object):
"""
A Flask extension for adding HTTP basic access authentication to the
application.
:param app: a :class:`~flask.Flask` instance. Defaults to `None`. If no
application is provided on creation, then it can be provided later on
via :meth:`init_app`.
"""
def __init__(self, app=None):
if app is not None:
self.app = app
self.init_app(app)
else:
self.app = None
def init_app(self, app):
"""
Initialize this BasicAuth extension for the given application.
:param app: a :class:`~flask.Flask` instance
"""
app.config.setdefault('BASIC_AUTH_FORCE', False)
app.config.setdefault('BASIC_AUTH_REALM', '')
@app.before_request
def require_basic_auth():
if not current_app.config['BASIC_AUTH_FORCE']:
return
if not self.authenticate():
return self.challenge()
def check_credentials(self, username, password):
"""
Check if the given username and password are correct.
By default compares the given username and password to
``HTTP_BASIC_AUTH_USERNAME`` and ``HTTP_BASIC_AUTH_PASSWORD``
configuration variables.
:param username: a username provided by the client
:param password: a password provided by the client
:returns: `True` if the username and password combination was correct,
and `False` otherwise.
"""
correct_username = current_app.config['BASIC_AUTH_USERNAME']
correct_password = current_app.config['BASIC_AUTH_PASSWORD']
return username == correct_username and password == correct_password
def authenticate(self):
"""
Check the request for HTTP basic access authentication header and try
to authenticate the user.
:returns: `True` if the user is authorized, or `False` otherwise.
"""
auth = request.authorization
return (
auth and auth.type == 'basic' and
self.check_credentials(auth.username, auth.password)
)
def challenge(self):
"""
Challenge the client for username and password.
This method is called when the client did not provide username and
password in the request, or the username and password combination was
wrong.
:returns: a :class:`~flask.Response` with 401 response code, including
the required authentication scheme and authentication realm.
"""
realm = current_app.config['BASIC_AUTH_REALM']
return Response(
status=401,
headers={'WWW-Authenticate': 'Basic realm="%s"' % realm}
)
def required(self, view_func):
"""
A decorator that can be used to protect specific views with HTTP
basic access authentication.
"""
@wraps(view_func)
def wrapper(*args, **kwargs):
if self.authenticate():
return view_func(*args, **kwargs)
else:
return self.challenge()
return wrapper
| (app=None) |
9,187 | flask_basicauth | __init__ | null | def __init__(self, app=None):
if app is not None:
self.app = app
self.init_app(app)
else:
self.app = None
| (self, app=None) |
9,188 | flask_basicauth | authenticate |
Check the request for HTTP basic access authentication header and try
to authenticate the user.
:returns: `True` if the user is authorized, or `False` otherwise.
| def authenticate(self):
"""
Check the request for HTTP basic access authentication header and try
to authenticate the user.
:returns: `True` if the user is authorized, or `False` otherwise.
"""
auth = request.authorization
return (
auth and auth.type == 'basic' and
self.check_credentials(auth.username, auth.password)
)
| (self) |
9,189 | flask_basicauth | challenge |
Challenge the client for username and password.
This method is called when the client did not provide username and
password in the request, or the username and password combination was
wrong.
:returns: a :class:`~flask.Response` with 401 response code, including
the required authentication scheme and authentication realm.
| def challenge(self):
"""
Challenge the client for username and password.
This method is called when the client did not provide username and
password in the request, or the username and password combination was
wrong.
:returns: a :class:`~flask.Response` with 401 response code, including
the required authentication scheme and authentication realm.
"""
realm = current_app.config['BASIC_AUTH_REALM']
return Response(
status=401,
headers={'WWW-Authenticate': 'Basic realm="%s"' % realm}
)
| (self) |
9,190 | flask_basicauth | check_credentials |
Check if the given username and password are correct.
By default compares the given username and password to
``HTTP_BASIC_AUTH_USERNAME`` and ``HTTP_BASIC_AUTH_PASSWORD``
configuration variables.
:param username: a username provided by the client
:param password: a password provided by the client
:returns: `True` if the username and password combination was correct,
and `False` otherwise.
| def check_credentials(self, username, password):
"""
Check if the given username and password are correct.
By default compares the given username and password to
``HTTP_BASIC_AUTH_USERNAME`` and ``HTTP_BASIC_AUTH_PASSWORD``
configuration variables.
:param username: a username provided by the client
:param password: a password provided by the client
:returns: `True` if the username and password combination was correct,
and `False` otherwise.
"""
correct_username = current_app.config['BASIC_AUTH_USERNAME']
correct_password = current_app.config['BASIC_AUTH_PASSWORD']
return username == correct_username and password == correct_password
| (self, username, password) |
9,191 | flask_basicauth | init_app |
Initialize this BasicAuth extension for the given application.
:param app: a :class:`~flask.Flask` instance
| def init_app(self, app):
"""
Initialize this BasicAuth extension for the given application.
:param app: a :class:`~flask.Flask` instance
"""
app.config.setdefault('BASIC_AUTH_FORCE', False)
app.config.setdefault('BASIC_AUTH_REALM', '')
@app.before_request
def require_basic_auth():
if not current_app.config['BASIC_AUTH_FORCE']:
return
if not self.authenticate():
return self.challenge()
| (self, app) |
9,192 | flask_basicauth | required |
A decorator that can be used to protect specific views with HTTP
basic access authentication.
| def required(self, view_func):
"""
A decorator that can be used to protect specific views with HTTP
basic access authentication.
"""
@wraps(view_func)
def wrapper(*args, **kwargs):
if self.authenticate():
return view_func(*args, **kwargs)
else:
return self.challenge()
return wrapper
| (self, view_func) |
9,193 | flask.wrappers | Response | The response object that is used by default in Flask. Works like the
response object from Werkzeug but is set to have an HTML mimetype by
default. Quite often you don't have to create this object yourself because
:meth:`~flask.Flask.make_response` will take care of that for you.
If you want to replace the response object used you can subclass this and
set :attr:`~flask.Flask.response_class` to your subclass.
.. versionchanged:: 1.0
JSON support is added to the response, like the request. This is useful
when testing to get the test client response data as JSON.
.. versionchanged:: 1.0
Added :attr:`max_cookie_size`.
| class Response(ResponseBase):
"""The response object that is used by default in Flask. Works like the
response object from Werkzeug but is set to have an HTML mimetype by
default. Quite often you don't have to create this object yourself because
:meth:`~flask.Flask.make_response` will take care of that for you.
If you want to replace the response object used you can subclass this and
set :attr:`~flask.Flask.response_class` to your subclass.
.. versionchanged:: 1.0
JSON support is added to the response, like the request. This is useful
when testing to get the test client response data as JSON.
.. versionchanged:: 1.0
Added :attr:`max_cookie_size`.
"""
default_mimetype: str | None = "text/html"
json_module = json
autocorrect_location_header = False
@property
def max_cookie_size(self) -> int: # type: ignore
"""Read-only view of the :data:`MAX_COOKIE_SIZE` config key.
See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in
Werkzeug's docs.
"""
if current_app:
return current_app.config["MAX_COOKIE_SIZE"] # type: ignore[no-any-return]
# return Werkzeug's default when not in an app context
return super().max_cookie_size
| (response: Union[Iterable[str], Iterable[bytes]] = None, status: 'int | str | HTTPStatus | None' = None, headers: werkzeug.datastructures.headers.Headers = None, mimetype: 'str | None' = None, content_type: 'str | None' = None, direct_passthrough: 'bool' = False) -> 'None' |
9,194 | werkzeug.wrappers.response | __call__ | Process this response as WSGI application.
:param environ: the WSGI environment.
:param start_response: the response callable provided by the WSGI
server.
:return: an application iterator
| def __call__(
self, environ: WSGIEnvironment, start_response: StartResponse
) -> t.Iterable[bytes]:
"""Process this response as WSGI application.
:param environ: the WSGI environment.
:param start_response: the response callable provided by the WSGI
server.
:return: an application iterator
"""
app_iter, status, headers = self.get_wsgi_response(environ)
start_response(status, headers)
return app_iter
| (self, environ: 'WSGIEnvironment', start_response: 'StartResponse') -> 't.Iterable[bytes]' |
9,195 | werkzeug.wrappers.response | __enter__ | null | def __enter__(self) -> Response:
return self
| (self) -> werkzeug.wrappers.response.Response |
9,196 | werkzeug.wrappers.response | __exit__ | null | def __exit__(self, exc_type, exc_value, tb): # type: ignore
self.close()
| (self, exc_type, exc_value, tb) |
9,197 | werkzeug.wrappers.response | __init__ | null | def __init__(
self,
response: t.Iterable[bytes] | bytes | t.Iterable[str] | str | None = None,
status: int | str | HTTPStatus | None = None,
headers: t.Mapping[str, str | t.Iterable[str]]
| t.Iterable[tuple[str, str]]
| None = None,
mimetype: str | None = None,
content_type: str | None = None,
direct_passthrough: bool = False,
) -> None:
super().__init__(
status=status,
headers=headers,
mimetype=mimetype,
content_type=content_type,
)
#: Pass the response body directly through as the WSGI iterable.
#: This can be used when the body is a binary file or other
#: iterator of bytes, to skip some unnecessary checks. Use
#: :func:`~werkzeug.utils.send_file` instead of setting this
#: manually.
self.direct_passthrough = direct_passthrough
self._on_close: list[t.Callable[[], t.Any]] = []
# we set the response after the headers so that if a class changes
# the charset attribute, the data is set in the correct charset.
if response is None:
self.response = []
elif isinstance(response, (str, bytes, bytearray)):
self.set_data(response)
else:
self.response = response
| (self, response: Union[Iterable[bytes], bytes, Iterable[str], str, NoneType] = None, status: Union[int, str, http.HTTPStatus, NoneType] = None, headers: Union[Mapping[str, Union[str, Iterable[str]]], Iterable[tuple[str, str]], NoneType] = None, mimetype: Optional[str] = None, content_type: Optional[str] = None, direct_passthrough: bool = False) -> NoneType |
9,198 | werkzeug.wrappers.response | __repr__ | null | def __repr__(self) -> str:
if self.is_sequence:
body_info = f"{sum(map(len, self.iter_encoded()))} bytes"
else:
body_info = "streamed" if self.is_streamed else "likely-streamed"
return f"<{type(self).__name__} {body_info} [{self.status}]>"
| (self) -> str |
9,199 | werkzeug.sansio.response | _clean_status | null | def _clean_status(self, value: str | int | HTTPStatus) -> tuple[str, int]:
if isinstance(value, (int, HTTPStatus)):
status_code = int(value)
else:
value = value.strip()
if not value:
raise ValueError("Empty status argument")
code_str, sep, _ = value.partition(" ")
try:
status_code = int(code_str)
except ValueError:
# only message
return f"0 {value}", 0
if sep:
# code and message
return value, status_code
# only code, look up message
try:
status = f"{status_code} {HTTP_STATUS_CODES[status_code].upper()}"
except KeyError:
status = f"{status_code} UNKNOWN"
return status, status_code
| (self, value: str | int | http.HTTPStatus) -> tuple[str, int] |
9,200 | werkzeug.wrappers.response | _ensure_sequence | This method can be called by methods that need a sequence. If
`mutable` is true, it will also ensure that the response sequence
is a standard Python list.
.. versionadded:: 0.6
| def _ensure_sequence(self, mutable: bool = False) -> None:
"""This method can be called by methods that need a sequence. If
`mutable` is true, it will also ensure that the response sequence
is a standard Python list.
.. versionadded:: 0.6
"""
if self.is_sequence:
# if we need a mutable object, we ensure it's a list.
if mutable and not isinstance(self.response, list):
self.response = list(self.response) # type: ignore
return
if self.direct_passthrough:
raise RuntimeError(
"Attempted implicit sequence conversion but the"
" response object is in direct passthrough mode."
)
if not self.implicit_sequence_conversion:
raise RuntimeError(
"The response object required the iterable to be a"
" sequence, but the implicit conversion was disabled."
" Call make_sequence() yourself."
)
self.make_sequence()
| (self, mutable: bool = False) -> NoneType |
9,201 | werkzeug.wrappers.response | _is_range_request_processable | Return ``True`` if `Range` header is present and if underlying
resource is considered unchanged when compared with `If-Range` header.
| def _is_range_request_processable(self, environ: WSGIEnvironment) -> bool:
"""Return ``True`` if `Range` header is present and if underlying
resource is considered unchanged when compared with `If-Range` header.
"""
return (
"HTTP_IF_RANGE" not in environ
or not is_resource_modified(
environ,
self.headers.get("etag"),
None,
self.headers.get("last-modified"),
ignore_if_range=False,
)
) and "HTTP_RANGE" in environ
| (self, environ: 'WSGIEnvironment') -> 'bool' |
9,202 | werkzeug.wrappers.response | _process_range_request | Handle Range Request related headers (RFC7233). If `Accept-Ranges`
header is valid, and Range Request is processable, we set the headers
as described by the RFC, and wrap the underlying response in a
RangeWrapper.
Returns ``True`` if Range Request can be fulfilled, ``False`` otherwise.
:raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
if `Range` header could not be parsed or satisfied.
.. versionchanged:: 2.0
Returns ``False`` if the length is 0.
| def _process_range_request(
self,
environ: WSGIEnvironment,
complete_length: int | None,
accept_ranges: bool | str,
) -> bool:
"""Handle Range Request related headers (RFC7233). If `Accept-Ranges`
header is valid, and Range Request is processable, we set the headers
as described by the RFC, and wrap the underlying response in a
RangeWrapper.
Returns ``True`` if Range Request can be fulfilled, ``False`` otherwise.
:raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
if `Range` header could not be parsed or satisfied.
.. versionchanged:: 2.0
Returns ``False`` if the length is 0.
"""
from ..exceptions import RequestedRangeNotSatisfiable
if (
not accept_ranges
or complete_length is None
or complete_length == 0
or not self._is_range_request_processable(environ)
):
return False
if accept_ranges is True:
accept_ranges = "bytes"
parsed_range = parse_range_header(environ.get("HTTP_RANGE"))
if parsed_range is None:
raise RequestedRangeNotSatisfiable(complete_length)
range_tuple = parsed_range.range_for_length(complete_length)
content_range_header = parsed_range.to_content_range_header(complete_length)
if range_tuple is None or content_range_header is None:
raise RequestedRangeNotSatisfiable(complete_length)
content_length = range_tuple[1] - range_tuple[0]
self.headers["Content-Length"] = str(content_length)
self.headers["Accept-Ranges"] = accept_ranges
self.content_range = content_range_header # type: ignore
self.status_code = 206
self._wrap_range_response(range_tuple[0], content_length)
return True
| (self, environ: 'WSGIEnvironment', complete_length: 'int | None', accept_ranges: 'bool | str') -> 'bool' |
9,203 | werkzeug.wrappers.response | _wrap_range_response | Wrap existing Response in case of Range Request context. | def _wrap_range_response(self, start: int, length: int) -> None:
"""Wrap existing Response in case of Range Request context."""
if self.status_code == 206:
self.response = _RangeWrapper(self.response, start, length) # type: ignore
| (self, start: int, length: int) -> NoneType |
9,204 | werkzeug.wrappers.response | add_etag | Add an etag for the current response if there is none yet.
.. versionchanged:: 2.0
SHA-1 is used to generate the value. MD5 may not be
available in some environments.
| def add_etag(self, overwrite: bool = False, weak: bool = False) -> None:
"""Add an etag for the current response if there is none yet.
.. versionchanged:: 2.0
SHA-1 is used to generate the value. MD5 may not be
available in some environments.
"""
if overwrite or "etag" not in self.headers:
self.set_etag(generate_etag(self.get_data()), weak)
| (self, overwrite: bool = False, weak: bool = False) -> NoneType |
9,205 | werkzeug.wrappers.response | calculate_content_length | Returns the content length if available or `None` otherwise. | def calculate_content_length(self) -> int | None:
"""Returns the content length if available or `None` otherwise."""
try:
self._ensure_sequence()
except RuntimeError:
return None
return sum(len(x) for x in self.iter_encoded())
| (self) -> int | None |
9,206 | werkzeug.wrappers.response | call_on_close | Adds a function to the internal list of functions that should
be called as part of closing down the response. Since 0.7 this
function also returns the function that was passed so that this
can be used as a decorator.
.. versionadded:: 0.6
| def call_on_close(self, func: t.Callable[[], t.Any]) -> t.Callable[[], t.Any]:
"""Adds a function to the internal list of functions that should
be called as part of closing down the response. Since 0.7 this
function also returns the function that was passed so that this
can be used as a decorator.
.. versionadded:: 0.6
"""
self._on_close.append(func)
return func
| (self, func: Callable[[], Any]) -> Callable[[], Any] |
9,207 | werkzeug.wrappers.response | close | Close the wrapped response if possible. You can also use the object
in a with statement which will automatically close it.
.. versionadded:: 0.9
Can now be used in a with statement.
| def close(self) -> None:
"""Close the wrapped response if possible. You can also use the object
in a with statement which will automatically close it.
.. versionadded:: 0.9
Can now be used in a with statement.
"""
if hasattr(self.response, "close"):
self.response.close()
for func in self._on_close:
func()
| (self) -> NoneType |
9,208 | werkzeug.sansio.response | delete_cookie | Delete a cookie. Fails silently if key doesn't exist.
:param key: the key (name) of the cookie to be deleted.
:param path: if the cookie that should be deleted was limited to a
path, the path has to be defined here.
:param domain: if the cookie that should be deleted was limited to a
domain, that domain has to be defined here.
:param secure: If ``True``, the cookie will only be available
via HTTPS.
:param httponly: Disallow JavaScript access to the cookie.
:param samesite: Limit the scope of the cookie to only be
attached to requests that are "same-site".
| def delete_cookie(
self,
key: str,
path: str | None = "/",
domain: str | None = None,
secure: bool = False,
httponly: bool = False,
samesite: str | None = None,
) -> None:
"""Delete a cookie. Fails silently if key doesn't exist.
:param key: the key (name) of the cookie to be deleted.
:param path: if the cookie that should be deleted was limited to a
path, the path has to be defined here.
:param domain: if the cookie that should be deleted was limited to a
domain, that domain has to be defined here.
:param secure: If ``True``, the cookie will only be available
via HTTPS.
:param httponly: Disallow JavaScript access to the cookie.
:param samesite: Limit the scope of the cookie to only be
attached to requests that are "same-site".
"""
self.set_cookie(
key,
expires=0,
max_age=0,
path=path,
domain=domain,
secure=secure,
httponly=httponly,
samesite=samesite,
)
| (self, key: str, path: str | None = '/', domain: Optional[str] = None, secure: bool = False, httponly: bool = False, samesite: Optional[str] = None) -> NoneType |
9,209 | werkzeug.wrappers.response | freeze | Make the response object ready to be pickled. Does the
following:
* Buffer the response into a list, ignoring
:attr:`implicity_sequence_conversion` and
:attr:`direct_passthrough`.
* Set the ``Content-Length`` header.
* Generate an ``ETag`` header if one is not already set.
.. versionchanged:: 2.1
Removed the ``no_etag`` parameter.
.. versionchanged:: 2.0
An ``ETag`` header is always added.
.. versionchanged:: 0.6
The ``Content-Length`` header is set.
| def freeze(self) -> None:
"""Make the response object ready to be pickled. Does the
following:
* Buffer the response into a list, ignoring
:attr:`implicity_sequence_conversion` and
:attr:`direct_passthrough`.
* Set the ``Content-Length`` header.
* Generate an ``ETag`` header if one is not already set.
.. versionchanged:: 2.1
Removed the ``no_etag`` parameter.
.. versionchanged:: 2.0
An ``ETag`` header is always added.
.. versionchanged:: 0.6
The ``Content-Length`` header is set.
"""
# Always freeze the encoded response body, ignore
# implicit_sequence_conversion and direct_passthrough.
self.response = list(self.iter_encoded())
self.headers["Content-Length"] = str(sum(map(len, self.response)))
self.add_etag()
| (self) -> NoneType |
9,210 | werkzeug.wrappers.response | get_app_iter | Returns the application iterator for the given environ. Depending
on the request method and the current status code the return value
might be an empty response rather than the one from the response.
If the request method is `HEAD` or the status code is in a range
where the HTTP specification requires an empty response, an empty
iterable is returned.
.. versionadded:: 0.6
:param environ: the WSGI environment of the request.
:return: a response iterable.
| def get_app_iter(self, environ: WSGIEnvironment) -> t.Iterable[bytes]:
"""Returns the application iterator for the given environ. Depending
on the request method and the current status code the return value
might be an empty response rather than the one from the response.
If the request method is `HEAD` or the status code is in a range
where the HTTP specification requires an empty response, an empty
iterable is returned.
.. versionadded:: 0.6
:param environ: the WSGI environment of the request.
:return: a response iterable.
"""
status = self.status_code
if (
environ["REQUEST_METHOD"] == "HEAD"
or 100 <= status < 200
or status in (204, 304)
):
iterable: t.Iterable[bytes] = ()
elif self.direct_passthrough:
return self.response # type: ignore
else:
iterable = self.iter_encoded()
return ClosingIterator(iterable, self.close)
| (self, environ: 'WSGIEnvironment') -> 't.Iterable[bytes]' |
9,211 | werkzeug.wrappers.response | get_data | The string representation of the response body. Whenever you call
this property the response iterable is encoded and flattened. This
can lead to unwanted behavior if you stream big data.
This behavior can be disabled by setting
:attr:`implicit_sequence_conversion` to `False`.
If `as_text` is set to `True` the return value will be a decoded
string.
.. versionadded:: 0.9
| def get_data(self, as_text: bool = False) -> bytes | str:
"""The string representation of the response body. Whenever you call
this property the response iterable is encoded and flattened. This
can lead to unwanted behavior if you stream big data.
This behavior can be disabled by setting
:attr:`implicit_sequence_conversion` to `False`.
If `as_text` is set to `True` the return value will be a decoded
string.
.. versionadded:: 0.9
"""
self._ensure_sequence()
rv = b"".join(self.iter_encoded())
if as_text:
return rv.decode()
return rv
| (self, as_text: bool = False) -> bytes | str |
9,212 | werkzeug.sansio.response | get_etag | Return a tuple in the form ``(etag, is_weak)``. If there is no
ETag the return value is ``(None, None)``.
| def get_etag(self) -> tuple[str, bool] | tuple[None, None]:
"""Return a tuple in the form ``(etag, is_weak)``. If there is no
ETag the return value is ``(None, None)``.
"""
return unquote_etag(self.headers.get("ETag"))
| (self) -> tuple[str, bool] | tuple[None, None] |
9,213 | werkzeug.wrappers.response | get_json | Parse :attr:`data` as JSON. Useful during testing.
If the mimetype does not indicate JSON
(:mimetype:`application/json`, see :attr:`is_json`), this
returns ``None``.
Unlike :meth:`Request.get_json`, the result is not cached.
:param force: Ignore the mimetype and always try to parse JSON.
:param silent: Silence parsing errors and return ``None``
instead.
| def get_json(self, force: bool = False, silent: bool = False) -> t.Any | None:
"""Parse :attr:`data` as JSON. Useful during testing.
If the mimetype does not indicate JSON
(:mimetype:`application/json`, see :attr:`is_json`), this
returns ``None``.
Unlike :meth:`Request.get_json`, the result is not cached.
:param force: Ignore the mimetype and always try to parse JSON.
:param silent: Silence parsing errors and return ``None``
instead.
"""
if not (force or self.is_json):
return None
data = self.get_data()
try:
return self.json_module.loads(data)
except ValueError:
if not silent:
raise
return None
| (self, force: bool = False, silent: bool = False) -> Optional[Any] |
9,214 | werkzeug.wrappers.response | get_wsgi_headers | This is automatically called right before the response is started
and returns headers modified for the given environment. It returns a
copy of the headers from the response with some modifications applied
if necessary.
For example the location header (if present) is joined with the root
URL of the environment. Also the content length is automatically set
to zero here for certain status codes.
.. versionchanged:: 0.6
Previously that function was called `fix_headers` and modified
the response object in place. Also since 0.6, IRIs in location
and content-location headers are handled properly.
Also starting with 0.6, Werkzeug will attempt to set the content
length if it is able to figure it out on its own. This is the
case if all the strings in the response iterable are already
encoded and the iterable is buffered.
:param environ: the WSGI environment of the request.
:return: returns a new :class:`~werkzeug.datastructures.Headers`
object.
| def get_wsgi_headers(self, environ: WSGIEnvironment) -> Headers:
"""This is automatically called right before the response is started
and returns headers modified for the given environment. It returns a
copy of the headers from the response with some modifications applied
if necessary.
For example the location header (if present) is joined with the root
URL of the environment. Also the content length is automatically set
to zero here for certain status codes.
.. versionchanged:: 0.6
Previously that function was called `fix_headers` and modified
the response object in place. Also since 0.6, IRIs in location
and content-location headers are handled properly.
Also starting with 0.6, Werkzeug will attempt to set the content
length if it is able to figure it out on its own. This is the
case if all the strings in the response iterable are already
encoded and the iterable is buffered.
:param environ: the WSGI environment of the request.
:return: returns a new :class:`~werkzeug.datastructures.Headers`
object.
"""
headers = Headers(self.headers)
location: str | None = None
content_location: str | None = None
content_length: str | int | None = None
status = self.status_code
# iterate over the headers to find all values in one go. Because
# get_wsgi_headers is used each response that gives us a tiny
# speedup.
for key, value in headers:
ikey = key.lower()
if ikey == "location":
location = value
elif ikey == "content-location":
content_location = value
elif ikey == "content-length":
content_length = value
if location is not None:
location = iri_to_uri(location)
if self.autocorrect_location_header:
# Make the location header an absolute URL.
current_url = get_current_url(environ, strip_querystring=True)
current_url = iri_to_uri(current_url)
location = urljoin(current_url, location)
headers["Location"] = location
# make sure the content location is a URL
if content_location is not None:
headers["Content-Location"] = iri_to_uri(content_location)
if 100 <= status < 200 or status == 204:
# Per section 3.3.2 of RFC 7230, "a server MUST NOT send a
# Content-Length header field in any response with a status
# code of 1xx (Informational) or 204 (No Content)."
headers.remove("Content-Length")
elif status == 304:
remove_entity_headers(headers)
# if we can determine the content length automatically, we
# should try to do that. But only if this does not involve
# flattening the iterator or encoding of strings in the
# response. We however should not do that if we have a 304
# response.
if (
self.automatically_set_content_length
and self.is_sequence
and content_length is None
and status not in (204, 304)
and not (100 <= status < 200)
):
content_length = sum(len(x) for x in self.iter_encoded())
headers["Content-Length"] = str(content_length)
return headers
| (self, environ: 'WSGIEnvironment') -> 'Headers' |
9,215 | werkzeug.wrappers.response | get_wsgi_response | Returns the final WSGI response as tuple. The first item in
the tuple is the application iterator, the second the status and
the third the list of headers. The response returned is created
specially for the given environment. For example if the request
method in the WSGI environment is ``'HEAD'`` the response will
be empty and only the headers and status code will be present.
.. versionadded:: 0.6
:param environ: the WSGI environment of the request.
:return: an ``(app_iter, status, headers)`` tuple.
| def get_wsgi_response(
self, environ: WSGIEnvironment
) -> tuple[t.Iterable[bytes], str, list[tuple[str, str]]]:
"""Returns the final WSGI response as tuple. The first item in
the tuple is the application iterator, the second the status and
the third the list of headers. The response returned is created
specially for the given environment. For example if the request
method in the WSGI environment is ``'HEAD'`` the response will
be empty and only the headers and status code will be present.
.. versionadded:: 0.6
:param environ: the WSGI environment of the request.
:return: an ``(app_iter, status, headers)`` tuple.
"""
headers = self.get_wsgi_headers(environ)
app_iter = self.get_app_iter(environ)
return app_iter, self.status, headers.to_wsgi_list()
| (self, environ: 'WSGIEnvironment') -> 'tuple[t.Iterable[bytes], str, list[tuple[str, str]]]' |
9,216 | werkzeug.wrappers.response | iter_encoded | Iter the response encoded with the encoding of the response.
If the response object is invoked as WSGI application the return
value of this method is used as application iterator unless
:attr:`direct_passthrough` was activated.
| def iter_encoded(self) -> t.Iterator[bytes]:
"""Iter the response encoded with the encoding of the response.
If the response object is invoked as WSGI application the return
value of this method is used as application iterator unless
:attr:`direct_passthrough` was activated.
"""
# Encode in a separate function so that self.response is fetched
# early. This allows us to wrap the response with the return
# value from get_app_iter or iter_encoded.
return _iter_encoded(self.response)
| (self) -> Iterator[bytes] |
9,217 | werkzeug.wrappers.response | make_conditional | Make the response conditional to the request. This method works
best if an etag was defined for the response already. The `add_etag`
method can be used to do that. If called without etag just the date
header is set.
This does nothing if the request method in the request or environ is
anything but GET or HEAD.
For optimal performance when handling range requests, it's recommended
that your response data object implements `seekable`, `seek` and `tell`
methods as described by :py:class:`io.IOBase`. Objects returned by
:meth:`~werkzeug.wsgi.wrap_file` automatically implement those methods.
It does not remove the body of the response because that's something
the :meth:`__call__` function does for us automatically.
Returns self so that you can do ``return resp.make_conditional(req)``
but modifies the object in-place.
:param request_or_environ: a request object or WSGI environment to be
used to make the response conditional
against.
:param accept_ranges: This parameter dictates the value of
`Accept-Ranges` header. If ``False`` (default),
the header is not set. If ``True``, it will be set
to ``"bytes"``. If it's a string, it will use this
value.
:param complete_length: Will be used only in valid Range Requests.
It will set `Content-Range` complete length
value and compute `Content-Length` real value.
This parameter is mandatory for successful
Range Requests completion.
:raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
if `Range` header could not be parsed or satisfied.
.. versionchanged:: 2.0
Range processing is skipped if length is 0 instead of
raising a 416 Range Not Satisfiable error.
| def make_conditional(
self,
request_or_environ: WSGIEnvironment | Request,
accept_ranges: bool | str = False,
complete_length: int | None = None,
) -> Response:
"""Make the response conditional to the request. This method works
best if an etag was defined for the response already. The `add_etag`
method can be used to do that. If called without etag just the date
header is set.
This does nothing if the request method in the request or environ is
anything but GET or HEAD.
For optimal performance when handling range requests, it's recommended
that your response data object implements `seekable`, `seek` and `tell`
methods as described by :py:class:`io.IOBase`. Objects returned by
:meth:`~werkzeug.wsgi.wrap_file` automatically implement those methods.
It does not remove the body of the response because that's something
the :meth:`__call__` function does for us automatically.
Returns self so that you can do ``return resp.make_conditional(req)``
but modifies the object in-place.
:param request_or_environ: a request object or WSGI environment to be
used to make the response conditional
against.
:param accept_ranges: This parameter dictates the value of
`Accept-Ranges` header. If ``False`` (default),
the header is not set. If ``True``, it will be set
to ``"bytes"``. If it's a string, it will use this
value.
:param complete_length: Will be used only in valid Range Requests.
It will set `Content-Range` complete length
value and compute `Content-Length` real value.
This parameter is mandatory for successful
Range Requests completion.
:raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable`
if `Range` header could not be parsed or satisfied.
.. versionchanged:: 2.0
Range processing is skipped if length is 0 instead of
raising a 416 Range Not Satisfiable error.
"""
environ = _get_environ(request_or_environ)
if environ["REQUEST_METHOD"] in ("GET", "HEAD"):
# if the date is not in the headers, add it now. We however
# will not override an already existing header. Unfortunately
# this header will be overridden by many WSGI servers including
# wsgiref.
if "date" not in self.headers:
self.headers["Date"] = http_date()
is206 = self._process_range_request(environ, complete_length, accept_ranges)
if not is206 and not is_resource_modified(
environ,
self.headers.get("etag"),
None,
self.headers.get("last-modified"),
):
if parse_etags(environ.get("HTTP_IF_MATCH")):
self.status_code = 412
else:
self.status_code = 304
if (
self.automatically_set_content_length
and "content-length" not in self.headers
):
length = self.calculate_content_length()
if length is not None:
self.headers["Content-Length"] = str(length)
return self
| (self, request_or_environ: 'WSGIEnvironment | Request', accept_ranges: 'bool | str' = False, complete_length: 'int | None' = None) -> 'Response' |
9,218 | werkzeug.wrappers.response | make_sequence | Converts the response iterator in a list. By default this happens
automatically if required. If `implicit_sequence_conversion` is
disabled, this method is not automatically called and some properties
might raise exceptions. This also encodes all the items.
.. versionadded:: 0.6
| def make_sequence(self) -> None:
"""Converts the response iterator in a list. By default this happens
automatically if required. If `implicit_sequence_conversion` is
disabled, this method is not automatically called and some properties
might raise exceptions. This also encodes all the items.
.. versionadded:: 0.6
"""
if not self.is_sequence:
# if we consume an iterable we have to ensure that the close
# method of the iterable is called if available when we tear
# down the response
close = getattr(self.response, "close", None)
self.response = list(self.iter_encoded())
if close is not None:
self.call_on_close(close)
| (self) -> NoneType |
9,219 | werkzeug.sansio.response | set_cookie | Sets a cookie.
A warning is raised if the size of the cookie header exceeds
:attr:`max_cookie_size`, but the header will still be set.
:param key: the key (name) of the cookie to be set.
:param value: the value of the cookie.
:param max_age: should be a number of seconds, or `None` (default) if
the cookie should last only as long as the client's
browser session.
:param expires: should be a `datetime` object or UNIX timestamp.
:param path: limits the cookie to a given path, per default it will
span the whole domain.
:param domain: if you want to set a cross-domain cookie. For example,
``domain="example.com"`` will set a cookie that is
readable by the domain ``www.example.com``,
``foo.example.com`` etc. Otherwise, a cookie will only
be readable by the domain that set it.
:param secure: If ``True``, the cookie will only be available
via HTTPS.
:param httponly: Disallow JavaScript access to the cookie.
:param samesite: Limit the scope of the cookie to only be
attached to requests that are "same-site".
| def set_cookie(
self,
key: str,
value: str = "",
max_age: timedelta | int | None = None,
expires: str | datetime | int | float | None = None,
path: str | None = "/",
domain: str | None = None,
secure: bool = False,
httponly: bool = False,
samesite: str | None = None,
) -> None:
"""Sets a cookie.
A warning is raised if the size of the cookie header exceeds
:attr:`max_cookie_size`, but the header will still be set.
:param key: the key (name) of the cookie to be set.
:param value: the value of the cookie.
:param max_age: should be a number of seconds, or `None` (default) if
the cookie should last only as long as the client's
browser session.
:param expires: should be a `datetime` object or UNIX timestamp.
:param path: limits the cookie to a given path, per default it will
span the whole domain.
:param domain: if you want to set a cross-domain cookie. For example,
``domain="example.com"`` will set a cookie that is
readable by the domain ``www.example.com``,
``foo.example.com`` etc. Otherwise, a cookie will only
be readable by the domain that set it.
:param secure: If ``True``, the cookie will only be available
via HTTPS.
:param httponly: Disallow JavaScript access to the cookie.
:param samesite: Limit the scope of the cookie to only be
attached to requests that are "same-site".
"""
self.headers.add(
"Set-Cookie",
dump_cookie(
key,
value=value,
max_age=max_age,
expires=expires,
path=path,
domain=domain,
secure=secure,
httponly=httponly,
max_size=self.max_cookie_size,
samesite=samesite,
),
)
| (self, key: str, value: str = '', max_age: Union[datetime.timedelta, int, NoneType] = None, expires: Union[str, datetime.datetime, int, float, NoneType] = None, path: str | None = '/', domain: Optional[str] = None, secure: bool = False, httponly: bool = False, samesite: Optional[str] = None) -> NoneType |
9,220 | werkzeug.wrappers.response | set_data | Sets a new string as response. The value must be a string or
bytes. If a string is set it's encoded to the charset of the
response (utf-8 by default).
.. versionadded:: 0.9
| def set_data(self, value: bytes | str) -> None:
"""Sets a new string as response. The value must be a string or
bytes. If a string is set it's encoded to the charset of the
response (utf-8 by default).
.. versionadded:: 0.9
"""
if isinstance(value, str):
value = value.encode()
self.response = [value]
if self.automatically_set_content_length:
self.headers["Content-Length"] = str(len(value))
| (self, value: bytes | str) -> NoneType |
9,221 | werkzeug.sansio.response | set_etag | Set the etag, and override the old one if there was one. | def set_etag(self, etag: str, weak: bool = False) -> None:
"""Set the etag, and override the old one if there was one."""
self.headers["ETag"] = quote_etag(etag, weak)
| (self, etag: str, weak: bool = False) -> NoneType |
9,223 | functools | wraps | Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
| def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
"""
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)
| (wrapped, assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'), updated=('__dict__',)) |
9,225 | dagster_docker.docker_run_launcher | DockerRunLauncher | Launches runs in a Docker container. | class DockerRunLauncher(RunLauncher, ConfigurableClass):
"""Launches runs in a Docker container."""
def __init__(
self,
inst_data: Optional[ConfigurableClassData] = None,
image=None,
registry=None,
env_vars=None,
network=None,
networks=None,
container_kwargs=None,
):
self._inst_data = inst_data
self.image = image
self.registry = registry
self.env_vars = env_vars
validate_docker_config(network, networks, container_kwargs)
if network:
self.networks = [network]
elif networks:
self.networks = networks
else:
self.networks = []
self.container_kwargs = check.opt_dict_param(
container_kwargs, "container_kwargs", key_type=str
)
super().__init__()
@property
def inst_data(self):
return self._inst_data
@classmethod
def config_type(cls):
return DOCKER_CONFIG_SCHEMA
@classmethod
def from_config_value(
cls, inst_data: ConfigurableClassData, config_value: Mapping[str, Any]
) -> Self:
return cls(inst_data=inst_data, **config_value)
def get_container_context(self, dagster_run: DagsterRun) -> DockerContainerContext:
return DockerContainerContext.create_for_run(dagster_run, self)
def _get_client(self, container_context: DockerContainerContext):
client = docker.client.from_env()
if container_context.registry:
client.login(
registry=container_context.registry["url"],
username=container_context.registry["username"],
password=container_context.registry["password"],
)
return client
def _get_docker_image(self, job_code_origin):
docker_image = job_code_origin.repository_origin.container_image
if not docker_image:
docker_image = self.image
if not docker_image:
raise Exception("No docker image specified by the instance config or repository")
validate_docker_image(docker_image)
return docker_image
def _launch_container_with_command(self, run, docker_image, command):
container_context = self.get_container_context(run)
docker_env = dict([parse_env_var(env_var) for env_var in container_context.env_vars])
docker_env["DAGSTER_RUN_JOB_NAME"] = run.job_name
client = self._get_client(container_context)
try:
container = client.containers.create(
image=docker_image,
command=command,
detach=True,
environment=docker_env,
network=container_context.networks[0] if len(container_context.networks) else None,
**container_context.container_kwargs,
)
except docker.errors.ImageNotFound:
client.images.pull(docker_image)
container = client.containers.create(
image=docker_image,
command=command,
detach=True,
environment=docker_env,
network=container_context.networks[0] if len(container_context.networks) else None,
**container_context.container_kwargs,
)
if len(container_context.networks) > 1:
for network_name in container_context.networks[1:]:
network = client.networks.get(network_name)
network.connect(container)
self._instance.report_engine_event(
message=f"Launching run in a new container {container.id} with image {docker_image}",
dagster_run=run,
cls=self.__class__,
)
self._instance.add_run_tags(
run.run_id,
{DOCKER_CONTAINER_ID_TAG: container.id, DOCKER_IMAGE_TAG: docker_image},
)
container.start()
def launch_run(self, context: LaunchRunContext) -> None:
run = context.dagster_run
job_code_origin = check.not_none(context.job_code_origin)
docker_image = self._get_docker_image(job_code_origin)
command = ExecuteRunArgs(
job_origin=job_code_origin,
run_id=run.run_id,
instance_ref=self._instance.get_ref(),
).get_command_args()
self._launch_container_with_command(run, docker_image, command)
@property
def supports_resume_run(self):
return True
def resume_run(self, context: ResumeRunContext) -> None:
run = context.dagster_run
job_code_origin = check.not_none(context.job_code_origin)
docker_image = self._get_docker_image(job_code_origin)
command = ResumeRunArgs(
job_origin=job_code_origin,
run_id=run.run_id,
instance_ref=self._instance.get_ref(),
).get_command_args()
self._launch_container_with_command(run, docker_image, command)
def _get_container(self, run):
if not run or run.is_finished:
return None
container_id = run.tags.get(DOCKER_CONTAINER_ID_TAG)
if not container_id:
return None
container_context = self.get_container_context(run)
try:
return self._get_client(container_context).containers.get(container_id)
except Exception:
return None
def terminate(self, run_id):
run = self._instance.get_run_by_id(run_id)
if not run:
return False
self._instance.report_run_canceling(run)
container = self._get_container(run)
if not container:
self._instance.report_engine_event(
message="Unable to get docker container to send termination request to.",
dagster_run=run,
cls=self.__class__,
)
return False
container.stop()
return True
@property
def supports_check_run_worker_health(self):
return True
def check_run_worker_health(self, run: DagsterRun):
container = self._get_container(run)
if container is None:
return CheckRunHealthResult(WorkerStatus.NOT_FOUND)
if container.status == "running":
return CheckRunHealthResult(WorkerStatus.RUNNING)
return CheckRunHealthResult(
WorkerStatus.FAILED, msg=f"Container status is {container.status}"
)
| (inst_data: Optional[dagster._serdes.config_class.ConfigurableClassData] = None, image=None, registry=None, env_vars=None, network=None, networks=None, container_kwargs=None) |
9,226 | dagster_docker.docker_run_launcher | __init__ | null | def __init__(
self,
inst_data: Optional[ConfigurableClassData] = None,
image=None,
registry=None,
env_vars=None,
network=None,
networks=None,
container_kwargs=None,
):
self._inst_data = inst_data
self.image = image
self.registry = registry
self.env_vars = env_vars
validate_docker_config(network, networks, container_kwargs)
if network:
self.networks = [network]
elif networks:
self.networks = networks
else:
self.networks = []
self.container_kwargs = check.opt_dict_param(
container_kwargs, "container_kwargs", key_type=str
)
super().__init__()
| (self, inst_data: Optional[dagster._serdes.config_class.ConfigurableClassData] = None, image=None, registry=None, env_vars=None, network=None, networks=None, container_kwargs=None) |
9,227 | dagster_docker.docker_run_launcher | _get_client | null | def _get_client(self, container_context: DockerContainerContext):
client = docker.client.from_env()
if container_context.registry:
client.login(
registry=container_context.registry["url"],
username=container_context.registry["username"],
password=container_context.registry["password"],
)
return client
| (self, container_context: dagster_docker.container_context.DockerContainerContext) |
9,228 | dagster_docker.docker_run_launcher | _get_container | null | def _get_container(self, run):
if not run or run.is_finished:
return None
container_id = run.tags.get(DOCKER_CONTAINER_ID_TAG)
if not container_id:
return None
container_context = self.get_container_context(run)
try:
return self._get_client(container_context).containers.get(container_id)
except Exception:
return None
| (self, run) |
9,229 | dagster_docker.docker_run_launcher | _get_docker_image | null | def _get_docker_image(self, job_code_origin):
docker_image = job_code_origin.repository_origin.container_image
if not docker_image:
docker_image = self.image
if not docker_image:
raise Exception("No docker image specified by the instance config or repository")
validate_docker_image(docker_image)
return docker_image
| (self, job_code_origin) |
9,230 | dagster_docker.docker_run_launcher | _launch_container_with_command | null | def _launch_container_with_command(self, run, docker_image, command):
container_context = self.get_container_context(run)
docker_env = dict([parse_env_var(env_var) for env_var in container_context.env_vars])
docker_env["DAGSTER_RUN_JOB_NAME"] = run.job_name
client = self._get_client(container_context)
try:
container = client.containers.create(
image=docker_image,
command=command,
detach=True,
environment=docker_env,
network=container_context.networks[0] if len(container_context.networks) else None,
**container_context.container_kwargs,
)
except docker.errors.ImageNotFound:
client.images.pull(docker_image)
container = client.containers.create(
image=docker_image,
command=command,
detach=True,
environment=docker_env,
network=container_context.networks[0] if len(container_context.networks) else None,
**container_context.container_kwargs,
)
if len(container_context.networks) > 1:
for network_name in container_context.networks[1:]:
network = client.networks.get(network_name)
network.connect(container)
self._instance.report_engine_event(
message=f"Launching run in a new container {container.id} with image {docker_image}",
dagster_run=run,
cls=self.__class__,
)
self._instance.add_run_tags(
run.run_id,
{DOCKER_CONTAINER_ID_TAG: container.id, DOCKER_IMAGE_TAG: docker_image},
)
container.start()
| (self, run, docker_image, command) |
9,231 | dagster_docker.docker_run_launcher | check_run_worker_health | null | def check_run_worker_health(self, run: DagsterRun):
container = self._get_container(run)
if container is None:
return CheckRunHealthResult(WorkerStatus.NOT_FOUND)
if container.status == "running":
return CheckRunHealthResult(WorkerStatus.RUNNING)
return CheckRunHealthResult(
WorkerStatus.FAILED, msg=f"Container status is {container.status}"
)
| (self, run: dagster._core.storage.dagster_run.DagsterRun) |
9,232 | dagster._core.launcher.base | dispose | Do any resource cleanup that should happen when the DagsterInstance is
cleaning itself up.
| def dispose(self) -> None:
"""Do any resource cleanup that should happen when the DagsterInstance is
cleaning itself up.
"""
| (self) -> NoneType |
9,233 | dagster_docker.docker_run_launcher | get_container_context | null | def get_container_context(self, dagster_run: DagsterRun) -> DockerContainerContext:
return DockerContainerContext.create_for_run(dagster_run, self)
| (self, dagster_run: dagster._core.storage.dagster_run.DagsterRun) -> dagster_docker.container_context.DockerContainerContext |
9,234 | dagster._core.launcher.base | get_run_worker_debug_info | null | def get_run_worker_debug_info(
self, run: DagsterRun, include_container_logs: Optional[bool] = True
) -> Optional[str]:
return None
| (self, run: dagster._core.storage.dagster_run.DagsterRun, include_container_logs: Optional[bool] = True) -> Optional[str] |
Subsets and Splits