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
21,941
twod.constants
Quadrant
An enumeration.
class Quadrant(IntEnum): ORIGIN: int = -1 I: int = 0 II: int = 1 III: int = 2 IV: int = 3
(value, names=None, *, module=None, qualname=None, type=None, start=1)
21,942
twod.rect
Rect
A rectangle specified by an origin at (x,y) and dimensions (w,h).
class Rect(Point): """A rectangle specified by an origin at (x,y) and dimensions (w,h). """ w: int = 0 h: int = 0 @property def A(self) -> Point: """Point at (x,y).""" return Point(self.x, self.y) @property def B(self) -> Point: """Point at (x+w, y).""" return Point(self.x + self.w, self.y) @property def C(self) -> Point: """Point at (x+w, y+h).""" return Point(self.x + self.w, self.y + self.h) @property def D(self) -> Point: """Point at (x, y+h).""" return Point(self.x, self.y + self.h) @property def vertices(self) -> List[Point]: """The points A, B, C, and D in a list. """ return [self.A, self.B, self.C, self.D] @property def sides(self) -> List[float]: """The lengths of each side: AB, BC, CD, and DA. """ return [ max(abs(self.A - self.B)), max(abs(self.B - self.C)), max(abs(self.C - self.D)), max(abs(self.D - self.A)), ] @property def center(self) -> Point: """Point at the center of the rectangle (midpoint of AC). """ return self.A.midpoint(self.C) @center.setter def center(self, new_center): self.x, self.y = Point(*new_center) - (Point(self.w, self.h) / 2) @property def perimeter(self) -> float: """The distance around this rectangle. """ return sum(self.sides) @property def area(self) -> float: """The area of this rectangle. """ return self.w * self.h def __contains__(self, other) -> bool: """If other is a twod.Point, returns True if the point is inside this rectangle. If other is a twod.Rect, returns True if any of other's vertices are inside or any of the target rectangle's verices are inside other. Otherwise returns False. Raises TypeError if other is not a Point or Rect. """ if not isinstance(other, Rect): try: return other.between(self.A, self.C) except AttributeError: pass raise TypeError(f"expected Point or Rect, received {type(other)}") for v in other.vertices: if v.between(self.A, self.C): return True for v in self.vertices: if v.between(other.A, other.C): return True return False def __add__(self, other): """ :param Point|Rect other: :return: Rect """ x = self.x + other.x y = self.y + other.y try: w = self.w + other.w h = self.h + other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h) def __iadd__(self, other): """ :param Point|Rect other: :return: Rect """ self.x += other.x self.y += other.y try: self.w += other.w self.h += other.h except AttributeError: pass return self def __sub__(self, other): """ :param Point|Rect other: :return: Rect """ x = self.x - other.x y = self.y - other.y try: w = self.w - other.w h = self.h - other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h) def __isub__(self, other): """ :param Point|Rect other: :return: Rect """ self.x -= other.x self.y -= other.y try: self.w -= other.w self.h -= other.h except AttributeError: pass return self def __mul__(self, other): """ :param Point|Rect other: :return: Rect """ x = self.x * other.x y = self.y * other.y try: w = self.w * other.w h = self.h * other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h) def __imul__(self, other): """ :param Point|Rect other: :return: Rect """ self.x *= other.x self.y *= other.y try: self.w *= other.w self.h *= other.h except AttributeError: pass return self def __truediv__(self, other): """ :param Point|Rect other: :return: Rect """ try: x = self.x / other.x y = self.y / other.y try: w = self.w / other.w h = self.h / other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h) except ZeroDivisionError: pass raise ZeroDivisionError(other) def __itruediv__(self, other): """ :param Point|Rect other: :return: Rect """ try: self.x /= other.x self.y /= other.y try: self.w /= other.w self.h /= other.h except AttributeError: pass return self except ZeroDivisionError: pass raise ZeroDivisionError(other) def __floordiv__(self, other): """ :param Point|Rect other: :return: Rect """ try: x = self.x // other.x y = self.y // other.y try: w = self.w // other.w h = self.h // other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h) except ZeroDivisionError: pass raise ZeroDivisionError(other) def __ifloordiv__(self, other): """ :param Point|Rect other: :return: Rect """ try: self.x //= other.x self.y //= other.y try: self.w //= other.w self.h //= other.h except AttributeError: pass return self except ZeroDivisionError: pass raise ZeroDivisionError(other)
(x: float = 0, y: float = 0, w: int = 0, h: int = 0) -> None
21,946
twod.rect
__add__
:param Point|Rect other: :return: Rect
def __add__(self, other): """ :param Point|Rect other: :return: Rect """ x = self.x + other.x y = self.y + other.y try: w = self.w + other.w h = self.h + other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h)
(self, other)
21,947
twod.rect
__contains__
If other is a twod.Point, returns True if the point is inside this rectangle. If other is a twod.Rect, returns True if any of other's vertices are inside or any of the target rectangle's verices are inside other. Otherwise returns False. Raises TypeError if other is not a Point or Rect.
def __contains__(self, other) -> bool: """If other is a twod.Point, returns True if the point is inside this rectangle. If other is a twod.Rect, returns True if any of other's vertices are inside or any of the target rectangle's verices are inside other. Otherwise returns False. Raises TypeError if other is not a Point or Rect. """ if not isinstance(other, Rect): try: return other.between(self.A, self.C) except AttributeError: pass raise TypeError(f"expected Point or Rect, received {type(other)}") for v in other.vertices: if v.between(self.A, self.C): return True for v in self.vertices: if v.between(other.A, other.C): return True return False
(self, other) -> bool
21,948
twod.rect
__eq__
null
"""a rectangle for humans™ """ from dataclasses import astuple, dataclass from .point import Point from typing import Any from typing import Dict from typing import List @dataclass class Rect(Point): """A rectangle specified by an origin at (x,y) and dimensions (w,h). """ w: int = 0 h: int = 0 @property def A(self) -> Point: """Point at (x,y).""" return Point(self.x, self.y) @property def B(self) -> Point: """Point at (x+w, y).""" return Point(self.x + self.w, self.y) @property def C(self) -> Point: """Point at (x+w, y+h).""" return Point(self.x + self.w, self.y + self.h) @property def D(self) -> Point: """Point at (x, y+h).""" return Point(self.x, self.y + self.h) @property def vertices(self) -> List[Point]: """The points A, B, C, and D in a list. """ return [self.A, self.B, self.C, self.D] @property def sides(self) -> List[float]: """The lengths of each side: AB, BC, CD, and DA. """ return [ max(abs(self.A - self.B)), max(abs(self.B - self.C)), max(abs(self.C - self.D)), max(abs(self.D - self.A)), ] @property def center(self) -> Point: """Point at the center of the rectangle (midpoint of AC). """ return self.A.midpoint(self.C) @center.setter def center(self, new_center): self.x, self.y = Point(*new_center) - (Point(self.w, self.h) / 2) @property def perimeter(self) -> float: """The distance around this rectangle. """ return sum(self.sides) @property def area(self) -> float: """The area of this rectangle. """ return self.w * self.h def __contains__(self, other) -> bool: """If other is a twod.Point, returns True if the point is inside this rectangle. If other is a twod.Rect, returns True if any of other's vertices are inside or any of the target rectangle's verices are inside other. Otherwise returns False. Raises TypeError if other is not a Point or Rect. """ if not isinstance(other, Rect): try: return other.between(self.A, self.C) except AttributeError: pass raise TypeError(f"expected Point or Rect, received {type(other)}") for v in other.vertices: if v.between(self.A, self.C): return True for v in self.vertices: if v.between(other.A, other.C): return True return False def __add__(self, other): """ :param Point|Rect other: :return: Rect """ x = self.x + other.x y = self.y + other.y try: w = self.w + other.w h = self.h + other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h) def __iadd__(self, other): """ :param Point|Rect other: :return: Rect """ self.x += other.x self.y += other.y try: self.w += other.w self.h += other.h except AttributeError: pass return self def __sub__(self, other): """ :param Point|Rect other: :return: Rect """ x = self.x - other.x y = self.y - other.y try: w = self.w - other.w h = self.h - other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h) def __isub__(self, other): """ :param Point|Rect other: :return: Rect """ self.x -= other.x self.y -= other.y try: self.w -= other.w self.h -= other.h except AttributeError: pass return self def __mul__(self, other): """ :param Point|Rect other: :return: Rect """ x = self.x * other.x y = self.y * other.y try: w = self.w * other.w h = self.h * other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h) def __imul__(self, other): """ :param Point|Rect other: :return: Rect """ self.x *= other.x self.y *= other.y try: self.w *= other.w self.h *= other.h except AttributeError: pass return self def __truediv__(self, other): """ :param Point|Rect other: :return: Rect """ try: x = self.x / other.x y = self.y / other.y try: w = self.w / other.w h = self.h / other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h) except ZeroDivisionError: pass raise ZeroDivisionError(other) def __itruediv__(self, other): """ :param Point|Rect other: :return: Rect """ try: self.x /= other.x self.y /= other.y try: self.w /= other.w self.h /= other.h except AttributeError: pass return self except ZeroDivisionError: pass raise ZeroDivisionError(other) def __floordiv__(self, other): """ :param Point|Rect other: :return: Rect """ try: x = self.x // other.x y = self.y // other.y try: w = self.w // other.w h = self.h // other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h) except ZeroDivisionError: pass raise ZeroDivisionError(other) def __ifloordiv__(self, other): """ :param Point|Rect other: :return: Rect """ try: self.x //= other.x self.y //= other.y try: self.w //= other.w self.h //= other.h except AttributeError: pass return self except ZeroDivisionError: pass raise ZeroDivisionError(other)
(self, other)
21,949
twod.rect
__floordiv__
:param Point|Rect other: :return: Rect
def __floordiv__(self, other): """ :param Point|Rect other: :return: Rect """ try: x = self.x // other.x y = self.y // other.y try: w = self.w // other.w h = self.h // other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h) except ZeroDivisionError: pass raise ZeroDivisionError(other)
(self, other)
21,951
twod.rect
__iadd__
:param Point|Rect other: :return: Rect
def __iadd__(self, other): """ :param Point|Rect other: :return: Rect """ self.x += other.x self.y += other.y try: self.w += other.w self.h += other.h except AttributeError: pass return self
(self, other)
21,952
twod.rect
__ifloordiv__
:param Point|Rect other: :return: Rect
def __ifloordiv__(self, other): """ :param Point|Rect other: :return: Rect """ try: self.x //= other.x self.y //= other.y try: self.w //= other.w self.h //= other.h except AttributeError: pass return self except ZeroDivisionError: pass raise ZeroDivisionError(other)
(self, other)
21,953
twod.rect
__imul__
:param Point|Rect other: :return: Rect
def __imul__(self, other): """ :param Point|Rect other: :return: Rect """ self.x *= other.x self.y *= other.y try: self.w *= other.w self.h *= other.h except AttributeError: pass return self
(self, other)
21,957
twod.rect
__isub__
:param Point|Rect other: :return: Rect
def __isub__(self, other): """ :param Point|Rect other: :return: Rect """ self.x -= other.x self.y -= other.y try: self.w -= other.w self.h -= other.h except AttributeError: pass return self
(self, other)
21,959
twod.rect
__itruediv__
:param Point|Rect other: :return: Rect
def __itruediv__(self, other): """ :param Point|Rect other: :return: Rect """ try: self.x /= other.x self.y /= other.y try: self.w /= other.w self.h /= other.h except AttributeError: pass return self except ZeroDivisionError: pass raise ZeroDivisionError(other)
(self, other)
21,961
twod.rect
__mul__
:param Point|Rect other: :return: Rect
def __mul__(self, other): """ :param Point|Rect other: :return: Rect """ x = self.x * other.x y = self.y * other.y try: w = self.w * other.w h = self.h * other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h)
(self, other)
21,964
twod.rect
__repr__
null
def __itruediv__(self, other): """ :param Point|Rect other: :return: Rect """ try: self.x /= other.x self.y /= other.y try: self.w /= other.w self.h /= other.h except AttributeError: pass return self except ZeroDivisionError: pass raise ZeroDivisionError(other)
(self)
21,966
twod.rect
__sub__
:param Point|Rect other: :return: Rect
def __sub__(self, other): """ :param Point|Rect other: :return: Rect """ x = self.x - other.x y = self.y - other.y try: w = self.w - other.w h = self.h - other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h)
(self, other)
21,967
twod.rect
__truediv__
:param Point|Rect other: :return: Rect
def __truediv__(self, other): """ :param Point|Rect other: :return: Rect """ try: x = self.x / other.x y = self.y / other.y try: w = self.w / other.w h = self.h / other.h except AttributeError: w = self.w h = self.h return Rect(x, y, w, h) except ZeroDivisionError: pass raise ZeroDivisionError(other)
(self, other)
21,984
env2cli
Argument
null
class Argument: def __init__( self, env : str, arg_key : str =None, func : Callable[[str, str], List[str]] = None, required : bool = False ): self.env = env self.arg_key = arg_key self.func = func self.required = required
(env: str, arg_key: str = None, func: Callable[[str, str], List[str]] = None, required: bool = False)
21,985
env2cli
__init__
null
def __init__( self, env : str, arg_key : str =None, func : Callable[[str, str], List[str]] = None, required : bool = False ): self.env = env self.arg_key = arg_key self.func = func self.required = required
(self, env: str, arg_key: Optional[str] = None, func: Optional[Callable[[str, str], List[str]]] = None, required: bool = False)
21,986
env2cli
RequiredArgumentNotExistsError
null
class RequiredArgumentNotExistsError(Exception): def __init__(self, env): self.env = env def __str__(self): return 'Required argument is empty or does not exists'
(env)
21,987
env2cli
__init__
null
def __init__(self, env): self.env = env
(self, env)
21,988
env2cli
__str__
null
def __str__(self): return 'Required argument is empty or does not exists'
(self)
21,989
env2cli
apply_arg
null
def apply_arg(argv : List[str], argument : Argument): val = getenv(argument.env) if val: func = argument.func if argument.func else default_func argv += func(argument.arg_key, val) elif argument.required: raise RequiredArgumentNotExistsError(argument.env)
(argv: List[str], argument: env2cli.Argument)
21,990
env2cli
bulk_apply
null
def bulk_apply(arguments : List[Argument], argv : List[str] = []): for arg in arguments: apply_arg(argv, arg) return argv
(arguments: List[env2cli.Argument], argv: List[str] = [])
21,991
env2cli
<lambda>
null
default_func = lambda key, val: [key, val]
(key, val)
21,992
env2cli
flag_argument_func
For flags argument example: Dockerfile: ENV MY_FLAG TRUE converted into " ... --my-flag"
def flag_argument_func(key, val : str): """ For flags argument example: Dockerfile: ENV MY_FLAG TRUE converted into " ... --my-flag" """ if val.lower() == 'true': return [key] return []
(key, val: str)
21,993
os
getenv
Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default. key, default and the result are str.
def getenv(key, default=None): """Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default. key, default and the result are str.""" return environ.get(key, default)
(key, default=None)
21,994
env2cli
<lambda>
null
positional_argument_func = lambda _, val: [val]
(_, val)
21,996
dse_data_loader.dse_data_loader
FundamentalData
null
class FundamentalData(object): DSE_COMPANY_URL = "http://dsebd.org/displayCompany.php?name=" CURRENT_PRICE_URL = 'https://www.dsebd.org/dseX_share.php' @staticmethod def parse_float(str_val): new_val = str_val.replace( ',', '' ).replace('--', '0') return float(new_val) @staticmethod def parse_int(str_val): new_val = str_val.replace( ',', '' ).replace('--', '0') return int(new_val) @staticmethod def append_company(company_info, fin_interim_info, df_company, symbol): company_dict = { 'symbol': symbol, 'auth_capital': company_info['basic'][0][0], 'trade_start': company_info['basic'][0][1], 'paid_up_capital': company_info['basic'][1][0], 'instrument_type': company_info['basic'][1][1], 'face_value': company_info['basic'][2][0], 'market_lot': company_info['basic'][2][1], 'ltp': company_info['ltp'], 'last_agm_date': company_info['last_agm_date'], 'market_cap': company_info['market_cap'], 'outstanding_share': company_info['basic'][3][0], 'sector': company_info['basic'][3][1], 'right_issue': company_info['dividend'][2][0], 'year_end': company_info['dividend'][3][0], 'reserve_w_oci': company_info['dividend'][4][0], 'others_oci': company_info['dividend'][5][0], # 'present_st_loan', # 'present_lt_loan', 'cash_dividend_p': company_info['dividend'][0][0].split(',')[0].split('%')[0] \ if len(company_info['dividend'][0][0]) > 6 else '-', 'cash_dividend_year': company_info['dividend'][0][0].split(',')[0].split('%')[1] \ if len(company_info['dividend'][0][0]) > 6 else '-', # 'stock_dividend_p': company_info['dividend'][1][0].split(',')[0].split('%')[0] \ # if len(company_info['dividend'][1][0]) > 6 else '-', # 'stock_dividend_year': company_info['dividend'][1][0].split(',')[0].split('%')[1] \ # if len(company_info['dividend'][1][0]) > 6 else '-', 'listing_year': company_info['other'][0][1], 'market_category': company_info['other'][1][1], 'sh_director': company_info['other'][3][1].split(' ')[0].split(':')[1], 'sh_govt': company_info['other'][3][1].split(' ')[1].split(':')[1], 'sh_inst': company_info['other'][3][1].split(' ')[2].split(':')[1], 'sh_foreign': company_info['other'][3][1].split(' ')[3].split(':')[1], 'sh_public': company_info['other'][3][1].split(' ')[4].split(':')[1], 'turnover_q1': fin_interim_info['main'][4][1], 'turnover_q2': fin_interim_info['main'][4][2], 'turnover_q3': fin_interim_info['main'][4][4], 'profit_cop_q1': fin_interim_info['main'][5][1], 'profit_cop_q2': fin_interim_info['main'][5][2], 'profit_cop_q3': fin_interim_info['main'][5][4], 'profit_period_q1': fin_interim_info['main'][6][1], 'profit_period_q2': fin_interim_info['main'][6][2], 'profit_period_q3': fin_interim_info['main'][6][4], 'tci_period_q1': fin_interim_info['main'][7][1], 'tci_period_q2': fin_interim_info['main'][7][2], 'tci_period_q3': fin_interim_info['main'][7][4], 'eps_basic_q1': fin_interim_info['main'][9][1], 'eps_basic_q2': fin_interim_info['main'][9][2], 'eps_basic_q3': fin_interim_info['main'][9][4], 'eps_diluted_q1': fin_interim_info['main'][10][1], 'eps_diluted_q2': fin_interim_info['main'][10][2], 'eps_diluted_q3': fin_interim_info['main'][10][4], 'eps_cop_basic_q1': fin_interim_info['main'][12][1], 'eps_cop_basic_q2': fin_interim_info['main'][12][2], 'eps_cop_basic_q3': fin_interim_info['main'][12][4], 'eps_cop_diluted_q1': fin_interim_info['main'][13][1], 'eps_cop_diluted_q2': fin_interim_info['main'][13][2], 'eps_cop_diluted_q3': fin_interim_info['main'][13][4], 'price_period_q1': fin_interim_info['main'][14][1], 'price_period_q2': fin_interim_info['main'][14][2], 'price_period_q3': fin_interim_info['main'][14][4], } try: df_company = df_company.append(company_dict, ignore_index=True) except Exception as e: print(str(e)) return df_company @staticmethod def append_fin_perf(fin_perf_info, df_fin_perf, symbol): for eps, pe in zip(fin_perf_info['eps'][3:], fin_perf_info['pe'][4:]): i = 0 if len(eps) > 13: i = 1 eps_dict = { 'symbol': symbol, 'year': " ".join(eps[0:i + 1]) if i else eps[0], 'eps_original': eps[i + 1], 'eps_restated': eps[i + 2], 'eps_diluted': eps[i + 3], 'eps_cop_original': eps[i + 4], 'eps_cop_restated': eps[i + 5], 'eps_cop_diluted': eps[i + 6], 'nav_original': eps[i + 7], 'nav_restated': eps[i + 8], 'nav_diluted': eps[i + 9], 'pco': eps[i + 10], 'profit': eps[i + 11], 'tci': eps[i + 12], 'pe_original': pe[i + 1], 'pe_restated': pe[i + 2], 'pe_diluted': pe[i + 3], 'pe_cop_original': pe[i + 4], 'pe_cop_restated': pe[i + 5], 'pe_cop_diluted': pe[i + 6], 'dividend_p': pe[i + 7], 'dividend_yield_p': pe[i + 8] } # print(eps_dict['year']) try: df_fin_perf = df_fin_perf.append(eps_dict, ignore_index=True) except Exception as e: print(str(e)) return df_fin_perf @staticmethod def parse_company_data_rows(soup, symbol): company_info = {} fin_perf_info = {} fin_interim_info = {} agm_info = soup.find( "div", attrs={ "class": "col-sm-6 pull-left" } ) # print(agm_info.text) date_txt = " ".join(agm_info.text.split('on:')[1].strip().split()) last_agm_date = parser.parse(date_txt).date() company_tables = soup.find_all( "table", attrs={ "class": "table table-bordered background-white", } ) count = 1 for table in company_tables: # print(">>>>>>>>>Contents in table no: ", count) table_rows = table.find_all("tr") # print(table_rows) # if count not in (1, ): cur_list = [] for row in table_rows: row_data = [" ".join(td.get_text().split()) for td in row.find_all("td")] cur_list.append(row_data) # print(cur_list) if count == 1: company_info.update({ 'ltp': cur_list[0][1], 'market_cap': cur_list[6][1], 'last_agm_date': last_agm_date }) if count == 2: company_info.update({ 'basic': cur_list }) elif count == 3: company_info.update({ 'dividend': cur_list }) elif count == 10: company_info.update({ 'other': cur_list }) elif count == 4: fin_interim_info.update({ 'main': cur_list }) elif count == 5: fin_interim_info.update({ 'pe_audited': cur_list }) elif count == 6: fin_interim_info.update({ 'pe_unaudited': cur_list }) elif count == 7: fin_perf_info.update({ 'eps': cur_list }) elif count == 8: fin_perf_info.update({ 'pe': cur_list }) else: pass count += 1 dict_company = { 'company_info': company_info, 'fin_interim_info': fin_interim_info, 'symbol': symbol } dict_fin_perf = { 'fin_perf_info': fin_perf_info, 'symbol': symbol } return dict_company, dict_fin_perf def get_company_df( self, symbols, df_company=pd.DataFrame(), df_fin_perf=pd.DataFrame() ): if type(symbols) is not list: raise TypeError("Either list or tuple is allowed for 'symbols' parameter!") for symbol in symbols: full_url = self.DSE_COMPANY_URL + symbol target_page = requests.get(full_url, verify=False) page_html = BeautifulSoup(target_page.text, 'html.parser') dict_company, dict_fin_perf = self.parse_company_data_rows( page_html, symbol ) print("Fetching data for: ", symbol) df_company = self.append_company( company_info=dict_company['company_info'], fin_interim_info=dict_company['fin_interim_info'], df_company=df_company, symbol=symbol ) df_fin_perf = self.append_fin_perf( fin_perf_info=dict_fin_perf['fin_perf_info'], df_fin_perf=df_fin_perf, symbol=symbol ) print("Fetch complete!") return df_company, df_fin_perf def save_company_data(self, symbols, path=''): if type(symbols) is not list: raise TypeError("Either list or tuple is allowed for 'symbols' parameter!") company_df = pd.DataFrame() fin_df = pd.DataFrame() company_df, fin_df = self.get_company_df(symbols, company_df, fin_df) company_df.to_csv(os.path.join(path, 'company_data.csv')) fin_df.to_csv(os.path.join(path, 'financial_data.csv'))
()
21,997
dse_data_loader.dse_data_loader
append_company
null
@staticmethod def append_company(company_info, fin_interim_info, df_company, symbol): company_dict = { 'symbol': symbol, 'auth_capital': company_info['basic'][0][0], 'trade_start': company_info['basic'][0][1], 'paid_up_capital': company_info['basic'][1][0], 'instrument_type': company_info['basic'][1][1], 'face_value': company_info['basic'][2][0], 'market_lot': company_info['basic'][2][1], 'ltp': company_info['ltp'], 'last_agm_date': company_info['last_agm_date'], 'market_cap': company_info['market_cap'], 'outstanding_share': company_info['basic'][3][0], 'sector': company_info['basic'][3][1], 'right_issue': company_info['dividend'][2][0], 'year_end': company_info['dividend'][3][0], 'reserve_w_oci': company_info['dividend'][4][0], 'others_oci': company_info['dividend'][5][0], # 'present_st_loan', # 'present_lt_loan', 'cash_dividend_p': company_info['dividend'][0][0].split(',')[0].split('%')[0] \ if len(company_info['dividend'][0][0]) > 6 else '-', 'cash_dividend_year': company_info['dividend'][0][0].split(',')[0].split('%')[1] \ if len(company_info['dividend'][0][0]) > 6 else '-', # 'stock_dividend_p': company_info['dividend'][1][0].split(',')[0].split('%')[0] \ # if len(company_info['dividend'][1][0]) > 6 else '-', # 'stock_dividend_year': company_info['dividend'][1][0].split(',')[0].split('%')[1] \ # if len(company_info['dividend'][1][0]) > 6 else '-', 'listing_year': company_info['other'][0][1], 'market_category': company_info['other'][1][1], 'sh_director': company_info['other'][3][1].split(' ')[0].split(':')[1], 'sh_govt': company_info['other'][3][1].split(' ')[1].split(':')[1], 'sh_inst': company_info['other'][3][1].split(' ')[2].split(':')[1], 'sh_foreign': company_info['other'][3][1].split(' ')[3].split(':')[1], 'sh_public': company_info['other'][3][1].split(' ')[4].split(':')[1], 'turnover_q1': fin_interim_info['main'][4][1], 'turnover_q2': fin_interim_info['main'][4][2], 'turnover_q3': fin_interim_info['main'][4][4], 'profit_cop_q1': fin_interim_info['main'][5][1], 'profit_cop_q2': fin_interim_info['main'][5][2], 'profit_cop_q3': fin_interim_info['main'][5][4], 'profit_period_q1': fin_interim_info['main'][6][1], 'profit_period_q2': fin_interim_info['main'][6][2], 'profit_period_q3': fin_interim_info['main'][6][4], 'tci_period_q1': fin_interim_info['main'][7][1], 'tci_period_q2': fin_interim_info['main'][7][2], 'tci_period_q3': fin_interim_info['main'][7][4], 'eps_basic_q1': fin_interim_info['main'][9][1], 'eps_basic_q2': fin_interim_info['main'][9][2], 'eps_basic_q3': fin_interim_info['main'][9][4], 'eps_diluted_q1': fin_interim_info['main'][10][1], 'eps_diluted_q2': fin_interim_info['main'][10][2], 'eps_diluted_q3': fin_interim_info['main'][10][4], 'eps_cop_basic_q1': fin_interim_info['main'][12][1], 'eps_cop_basic_q2': fin_interim_info['main'][12][2], 'eps_cop_basic_q3': fin_interim_info['main'][12][4], 'eps_cop_diluted_q1': fin_interim_info['main'][13][1], 'eps_cop_diluted_q2': fin_interim_info['main'][13][2], 'eps_cop_diluted_q3': fin_interim_info['main'][13][4], 'price_period_q1': fin_interim_info['main'][14][1], 'price_period_q2': fin_interim_info['main'][14][2], 'price_period_q3': fin_interim_info['main'][14][4], } try: df_company = df_company.append(company_dict, ignore_index=True) except Exception as e: print(str(e)) return df_company
(company_info, fin_interim_info, df_company, symbol)
21,998
dse_data_loader.dse_data_loader
append_fin_perf
null
@staticmethod def append_fin_perf(fin_perf_info, df_fin_perf, symbol): for eps, pe in zip(fin_perf_info['eps'][3:], fin_perf_info['pe'][4:]): i = 0 if len(eps) > 13: i = 1 eps_dict = { 'symbol': symbol, 'year': " ".join(eps[0:i + 1]) if i else eps[0], 'eps_original': eps[i + 1], 'eps_restated': eps[i + 2], 'eps_diluted': eps[i + 3], 'eps_cop_original': eps[i + 4], 'eps_cop_restated': eps[i + 5], 'eps_cop_diluted': eps[i + 6], 'nav_original': eps[i + 7], 'nav_restated': eps[i + 8], 'nav_diluted': eps[i + 9], 'pco': eps[i + 10], 'profit': eps[i + 11], 'tci': eps[i + 12], 'pe_original': pe[i + 1], 'pe_restated': pe[i + 2], 'pe_diluted': pe[i + 3], 'pe_cop_original': pe[i + 4], 'pe_cop_restated': pe[i + 5], 'pe_cop_diluted': pe[i + 6], 'dividend_p': pe[i + 7], 'dividend_yield_p': pe[i + 8] } # print(eps_dict['year']) try: df_fin_perf = df_fin_perf.append(eps_dict, ignore_index=True) except Exception as e: print(str(e)) return df_fin_perf
(fin_perf_info, df_fin_perf, symbol)
21,999
dse_data_loader.dse_data_loader
get_company_df
null
def get_company_df( self, symbols, df_company=pd.DataFrame(), df_fin_perf=pd.DataFrame() ): if type(symbols) is not list: raise TypeError("Either list or tuple is allowed for 'symbols' parameter!") for symbol in symbols: full_url = self.DSE_COMPANY_URL + symbol target_page = requests.get(full_url, verify=False) page_html = BeautifulSoup(target_page.text, 'html.parser') dict_company, dict_fin_perf = self.parse_company_data_rows( page_html, symbol ) print("Fetching data for: ", symbol) df_company = self.append_company( company_info=dict_company['company_info'], fin_interim_info=dict_company['fin_interim_info'], df_company=df_company, symbol=symbol ) df_fin_perf = self.append_fin_perf( fin_perf_info=dict_fin_perf['fin_perf_info'], df_fin_perf=df_fin_perf, symbol=symbol ) print("Fetch complete!") return df_company, df_fin_perf
(self, symbols, df_company=Empty DataFrame Columns: [] Index: [], df_fin_perf=Empty DataFrame Columns: [] Index: [])
22,000
dse_data_loader.dse_data_loader
parse_company_data_rows
null
@staticmethod def parse_company_data_rows(soup, symbol): company_info = {} fin_perf_info = {} fin_interim_info = {} agm_info = soup.find( "div", attrs={ "class": "col-sm-6 pull-left" } ) # print(agm_info.text) date_txt = " ".join(agm_info.text.split('on:')[1].strip().split()) last_agm_date = parser.parse(date_txt).date() company_tables = soup.find_all( "table", attrs={ "class": "table table-bordered background-white", } ) count = 1 for table in company_tables: # print(">>>>>>>>>Contents in table no: ", count) table_rows = table.find_all("tr") # print(table_rows) # if count not in (1, ): cur_list = [] for row in table_rows: row_data = [" ".join(td.get_text().split()) for td in row.find_all("td")] cur_list.append(row_data) # print(cur_list) if count == 1: company_info.update({ 'ltp': cur_list[0][1], 'market_cap': cur_list[6][1], 'last_agm_date': last_agm_date }) if count == 2: company_info.update({ 'basic': cur_list }) elif count == 3: company_info.update({ 'dividend': cur_list }) elif count == 10: company_info.update({ 'other': cur_list }) elif count == 4: fin_interim_info.update({ 'main': cur_list }) elif count == 5: fin_interim_info.update({ 'pe_audited': cur_list }) elif count == 6: fin_interim_info.update({ 'pe_unaudited': cur_list }) elif count == 7: fin_perf_info.update({ 'eps': cur_list }) elif count == 8: fin_perf_info.update({ 'pe': cur_list }) else: pass count += 1 dict_company = { 'company_info': company_info, 'fin_interim_info': fin_interim_info, 'symbol': symbol } dict_fin_perf = { 'fin_perf_info': fin_perf_info, 'symbol': symbol } return dict_company, dict_fin_perf
(soup, symbol)
22,001
dse_data_loader.dse_data_loader
parse_float
null
@staticmethod def parse_float(str_val): new_val = str_val.replace( ',', '' ).replace('--', '0') return float(new_val)
(str_val)
22,002
dse_data_loader.dse_data_loader
parse_int
null
@staticmethod def parse_int(str_val): new_val = str_val.replace( ',', '' ).replace('--', '0') return int(new_val)
(str_val)
22,003
dse_data_loader.dse_data_loader
save_company_data
null
def save_company_data(self, symbols, path=''): if type(symbols) is not list: raise TypeError("Either list or tuple is allowed for 'symbols' parameter!") company_df = pd.DataFrame() fin_df = pd.DataFrame() company_df, fin_df = self.get_company_df(symbols, company_df, fin_df) company_df.to_csv(os.path.join(path, 'company_data.csv')) fin_df.to_csv(os.path.join(path, 'financial_data.csv'))
(self, symbols, path='')
22,004
dse_data_loader.dse_data_loader
PriceData
null
class PriceData(object): HISTORY_URL = "https://www.dsebd.org/day_end_archive.php?endDate=<date>&archive=data" CURRENT_PRICE_URL = 'https://www.dsebd.org/dseX_share.php' @staticmethod def get_date(): return str(datetime.datetime.now().date()) @staticmethod def parse_float(str_val): new_val = str_val.replace( ',', '' ).replace('--', '0') return float(new_val) @staticmethod def parse_int(str_val): new_val = str_val.replace( ',', '' ).replace('--', '0') return int(new_val) @staticmethod def save_csv(dict_list, csv_path): keys = dict_list[0].keys() with open(csv_path, 'w+', newline='') as output_file: dict_writer = csv.DictWriter(output_file, keys) dict_writer.writeheader() dict_writer.writerows(dict_list) def get_history_url(self): cur_date = self.get_date() return self.HISTORY_URL.replace('<date>', cur_date) def parse_historical_data_rows(self, soup): dict_list = [] stock_table = soup.find( "table", attrs={ "class": "table table-bordered background-white shares-table fixedHeader" } ) table_rows = stock_table.find("tbody").find_all("tr") for row in table_rows: row_data = ["".join(td.get_text().split()) for td in row.find_all("td")] try: dict_list.append({ 'DATE': row_data[1], 'TRADING_CODE': row_data[2], 'LTP': self.parse_float(row_data[3]), 'HIGH': self.parse_float(row_data[4]), 'LOW': self.parse_float(row_data[5]), 'OPENP': self.parse_float(row_data[6]), 'CLOSEP': self.parse_float(row_data[7]), 'YCP': self.parse_float(row_data[8]), 'TRADE': self.parse_float(row_data[9].replace(',', '')), 'VALUE_MN': self.parse_float(row_data[10]), 'VOLUME': self.parse_float(row_data[11].replace(',', '')), }) except Exception as e: print(str(e)) return dict_list def parse_current_data_rows(self, soup): dict_list = [] table_header = soup.find( 'h2', attrs={ 'class': "BodyHead topBodyHead" } ) # print(table_header) date_txt = " ".join(table_header.text.split( 'On' )[1].split( 'at' )[0].strip().split( )) latest_trading_date = parser.parse(date_txt).date() stock_table = soup.find( "table", attrs={ "class": "table table-bordered background-white shares-table" } ) table_rows = stock_table.find_all("tr") # print(type(table_rows)) for row in table_rows: th_values = ["".join(th.get_text().split()) for th in row.find_all("th")] td_values = ["".join(td.get_text().split()) for td in row.find_all("td")] if len(th_values): # print(th_values) continue # print(td_values) dict_list.append({ 'DATE': latest_trading_date, 'TRADING_CODE': td_values[1], 'LTP': self.parse_float(td_values[2]), 'HIGH': self.parse_float(td_values[3]), 'LOW': self.parse_float(td_values[4]), 'CLOSEP': self.parse_float(td_values[5]), 'YCP': self.parse_float(td_values[6]), '% CHANGE': self.parse_float(td_values[7]), 'TRADE': self.parse_float(td_values[8]), 'VALUE_MN': self.parse_float(td_values[9]), 'VOLUME': self.parse_float(td_values[10]), }) return dict_list def save_history_csv(self, symbol, csv_path='', file_name='history_data.csv'): full_url = self.get_history_url() + "&inst=" + parse_url.quote(symbol) target_page = requests.get(full_url) bs_data = BeautifulSoup(target_page.text, 'html.parser') history_list = self. parse_historical_data_rows(bs_data) full_path = os.path.join(csv_path, file_name) self.save_csv(dict_list=history_list, csv_path=full_path) def save_current_csv(self, csv_path='', file_name='current_data.csv'): target_page = requests.get(self.CURRENT_PRICE_URL) bs_data = BeautifulSoup(target_page.text, 'html.parser') current_data = self.parse_current_data_rows(bs_data) full_path = os.path.join(csv_path, file_name) self.save_csv(dict_list=current_data, csv_path=full_path)
()
22,005
dse_data_loader.dse_data_loader
get_date
null
@staticmethod def get_date(): return str(datetime.datetime.now().date())
()
22,006
dse_data_loader.dse_data_loader
get_history_url
null
def get_history_url(self): cur_date = self.get_date() return self.HISTORY_URL.replace('<date>', cur_date)
(self)
22,007
dse_data_loader.dse_data_loader
parse_current_data_rows
null
def parse_current_data_rows(self, soup): dict_list = [] table_header = soup.find( 'h2', attrs={ 'class': "BodyHead topBodyHead" } ) # print(table_header) date_txt = " ".join(table_header.text.split( 'On' )[1].split( 'at' )[0].strip().split( )) latest_trading_date = parser.parse(date_txt).date() stock_table = soup.find( "table", attrs={ "class": "table table-bordered background-white shares-table" } ) table_rows = stock_table.find_all("tr") # print(type(table_rows)) for row in table_rows: th_values = ["".join(th.get_text().split()) for th in row.find_all("th")] td_values = ["".join(td.get_text().split()) for td in row.find_all("td")] if len(th_values): # print(th_values) continue # print(td_values) dict_list.append({ 'DATE': latest_trading_date, 'TRADING_CODE': td_values[1], 'LTP': self.parse_float(td_values[2]), 'HIGH': self.parse_float(td_values[3]), 'LOW': self.parse_float(td_values[4]), 'CLOSEP': self.parse_float(td_values[5]), 'YCP': self.parse_float(td_values[6]), '% CHANGE': self.parse_float(td_values[7]), 'TRADE': self.parse_float(td_values[8]), 'VALUE_MN': self.parse_float(td_values[9]), 'VOLUME': self.parse_float(td_values[10]), }) return dict_list
(self, soup)
22,009
dse_data_loader.dse_data_loader
parse_historical_data_rows
null
def parse_historical_data_rows(self, soup): dict_list = [] stock_table = soup.find( "table", attrs={ "class": "table table-bordered background-white shares-table fixedHeader" } ) table_rows = stock_table.find("tbody").find_all("tr") for row in table_rows: row_data = ["".join(td.get_text().split()) for td in row.find_all("td")] try: dict_list.append({ 'DATE': row_data[1], 'TRADING_CODE': row_data[2], 'LTP': self.parse_float(row_data[3]), 'HIGH': self.parse_float(row_data[4]), 'LOW': self.parse_float(row_data[5]), 'OPENP': self.parse_float(row_data[6]), 'CLOSEP': self.parse_float(row_data[7]), 'YCP': self.parse_float(row_data[8]), 'TRADE': self.parse_float(row_data[9].replace(',', '')), 'VALUE_MN': self.parse_float(row_data[10]), 'VOLUME': self.parse_float(row_data[11].replace(',', '')), }) except Exception as e: print(str(e)) return dict_list
(self, soup)
22,011
dse_data_loader.dse_data_loader
save_csv
null
@staticmethod def save_csv(dict_list, csv_path): keys = dict_list[0].keys() with open(csv_path, 'w+', newline='') as output_file: dict_writer = csv.DictWriter(output_file, keys) dict_writer.writeheader() dict_writer.writerows(dict_list)
(dict_list, csv_path)
22,012
dse_data_loader.dse_data_loader
save_current_csv
null
def save_current_csv(self, csv_path='', file_name='current_data.csv'): target_page = requests.get(self.CURRENT_PRICE_URL) bs_data = BeautifulSoup(target_page.text, 'html.parser') current_data = self.parse_current_data_rows(bs_data) full_path = os.path.join(csv_path, file_name) self.save_csv(dict_list=current_data, csv_path=full_path)
(self, csv_path='', file_name='current_data.csv')
22,013
dse_data_loader.dse_data_loader
save_history_csv
null
def save_history_csv(self, symbol, csv_path='', file_name='history_data.csv'): full_url = self.get_history_url() + "&inst=" + parse_url.quote(symbol) target_page = requests.get(full_url) bs_data = BeautifulSoup(target_page.text, 'html.parser') history_list = self. parse_historical_data_rows(bs_data) full_path = os.path.join(csv_path, file_name) self.save_csv(dict_list=history_list, csv_path=full_path)
(self, symbol, csv_path='', file_name='history_data.csv')
22,018
paypalrestsdk.api
Api
null
class Api(object): # User-Agent for HTTP request ssl_version = "" if util.older_than_27() else ssl.OPENSSL_VERSION ssl_version_info = None if util.older_than_27() else ssl.OPENSSL_VERSION_INFO library_details = "requests %s; python %s; %s" % ( requests.__version__, platform.python_version(), ssl_version) user_agent = "PayPalSDK/PayPal-Python-SDK %s (%s)" % ( __version__, library_details) def __init__(self, options=None, **kwargs): """Create API object Usage:: >>> import paypalrestsdk >>> api = paypalrestsdk.Api(mode="sandbox", client_id='CLIENT_ID', client_secret='CLIENT_SECRET', ssl_options={"cert": "/path/to/server.pem"}) """ kwargs = util.merge_dict(options or {}, kwargs) self.mode = kwargs.get("mode", "sandbox") if self.mode != "live" and self.mode != "sandbox": raise exceptions.InvalidConfig("Configuration Mode Invalid", "Received: %s" % (self.mode), "Required: live or sandbox") self.endpoint = kwargs.get("endpoint", self.default_endpoint()) self.token_endpoint = kwargs.get("token_endpoint", self.endpoint) # Mandatory parameter, so not using `dict.get` self.client_id = kwargs["client_id"] # Mandatory parameter, so not using `dict.get` self.client_secret = kwargs["client_secret"] self.proxies = kwargs.get("proxies", None) self.token_hash = None self.token_request_at = None # setup SSL certificate verification if private certificate provided ssl_options = kwargs.get("ssl_options", {}) if "cert" in ssl_options: os.environ["REQUESTS_CA_BUNDLE"] = ssl_options["cert"] if kwargs.get("token"): self.token_hash = { "access_token": kwargs["token"], "token_type": "Bearer"} self.options = kwargs def default_endpoint(self): return __endpoint_map__.get(self.mode) def basic_auth(self): """Find basic auth, and returns base64 encoded """ credentials = "%s:%s" % (self.client_id, self.client_secret) return base64.b64encode(credentials.encode('utf-8')).decode('utf-8').replace("\n", "") def get_token_hash(self, authorization_code=None, refresh_token=None, headers=None): """Generate new token by making a POST request 1. By using client credentials if validate_token_hash finds token to be invalid. This is useful during web flow so that an already authenticated user is not reprompted for login 2. Exchange authorization_code from mobile device for a long living refresh token that can be used to charge user who has consented to future payments 3. Exchange refresh_token for the user for a access_token of type Bearer which can be passed in to charge user """ path = "/v1/oauth2/token" payload = "grant_type=client_credentials" if authorization_code is not None: payload = "grant_type=authorization_code&response_type=token&redirect_uri=urn:ietf:wg:oauth:2.0:oob&code=" + \ authorization_code elif refresh_token is not None: payload = "grant_type=refresh_token&refresh_token=" + refresh_token else: self.validate_token_hash() if self.token_hash is not None: # return cached copy return self.token_hash token = self.http_call( util.join_url(self.token_endpoint, path), "POST", data=payload, headers=util.merge_dict({ "Authorization": ("Basic %s" % self.basic_auth()), "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json", "User-Agent": self.user_agent }, headers or {})) if refresh_token is None and authorization_code is None: # cache token for re-use in normal case self.token_request_at = datetime.datetime.now() self.token_hash = token return token def validate_token_hash(self): """Checks if token duration has expired and if so resets token """ if self.token_request_at and self.token_hash and self.token_hash.get("expires_in") is not None: delta = datetime.datetime.now() - self.token_request_at duration = ( delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 10 ** 6) / 10 ** 6 if duration > self.token_hash.get("expires_in"): self.token_hash = None def get_access_token(self, authorization_code=None, refresh_token=None, headers=None): """Wraps get_token_hash for getting access token """ return self.get_token_hash(authorization_code, refresh_token, headers=headers or {})['access_token'] def get_refresh_token(self, authorization_code=None, headers=None): """Exchange authorization code for refresh token for future payments """ if authorization_code is None: raise exceptions.MissingConfig("Authorization code needed to get new refresh token. \ Refer to https://developer.paypal.com/docs/integration/mobile/make-future-payment/#get-an-auth-code") return self.get_token_hash(authorization_code, headers=headers or {})["refresh_token"] def _check_openssl_version(self): """ Check that merchant server has PCI compliant version of TLS Print warning if it does not. """ if self.ssl_version_info and self.ssl_version_info < (1, 0, 1, 0, 0): log.warning( 'WARNING: openssl version ' + self.ssl_version + ' detected. Per PCI Security Council mandate \ (https://github.com/paypal/TLS-update), you MUST update to the latest security library.') def request(self, url, method, body=None, headers=None, refresh_token=None): """Make HTTP call, formats response and does error handling. Uses http_call method in API class. Usage:: >>> api.request("https://api.sandbox.paypal.com/v1/payments/payment?count=10", "GET", {}) >>> api.request("https://api.sandbox.paypal.com/v1/payments/payment", "POST", "{}", {} ) """ http_headers = util.merge_dict( self.headers(refresh_token=refresh_token, headers=headers or {}), headers or {}) if http_headers.get('PayPal-Request-Id'): log.info('PayPal-Request-Id: %s' % (http_headers['PayPal-Request-Id'])) self._check_openssl_version() try: return self.http_call(url, method, data=json.dumps(body), headers=http_headers) # Format Error message for bad request except exceptions.BadRequest as error: return {"error": json.loads(error.content)} # Handle Expired token except exceptions.UnauthorizedAccess as error: if(self.token_hash and self.client_id): self.token_hash = None return self.request(url, method, body, headers) else: raise error def http_call(self, url, method, **kwargs): """Makes a http call. Logs response information. """ log.info('Request[%s]: %s' % (method, url)) if self.mode.lower() != 'live': request_headers = kwargs.get("headers", {}) request_body = kwargs.get("data", {}) log.debug("Level: " + self.mode) log.debug('Request: \nHeaders: %s\nBody: %s' % ( str(request_headers), str(request_body))) else: log.info( 'Not logging full request/response headers and body in live mode for compliance') start_time = datetime.datetime.now() response = requests.request( method, url, proxies=self.proxies, **kwargs) duration = datetime.datetime.now() - start_time log.info('Response[%d]: %s, Duration: %s.%ss.' % ( response.status_code, response.reason, duration.seconds, duration.microseconds)) debug_id = response.headers.get('PayPal-Debug-Id') if debug_id: log.debug('debug_id: %s' % debug_id) if self.mode.lower() != 'live': log.debug('Headers: %s\nBody: %s' % ( str(response.headers), str(response.content))) return self.handle_response(response, response.content.decode('utf-8')) def handle_response(self, response, content): """Validate HTTP response """ status = response.status_code if status in (301, 302, 303, 307): raise exceptions.Redirection(response, content) elif 200 <= status <= 299: return json.loads(content) if content else {} elif status == 400: raise exceptions.BadRequest(response, content) elif status == 401: raise exceptions.UnauthorizedAccess(response, content) elif status == 403: raise exceptions.ForbiddenAccess(response, content) elif status == 404: raise exceptions.ResourceNotFound(response, content) elif status == 405: raise exceptions.MethodNotAllowed(response, content) elif status == 409: raise exceptions.ResourceConflict(response, content) elif status == 410: raise exceptions.ResourceGone(response, content) elif status == 422: raise exceptions.ResourceInvalid(response, content) elif 401 <= status <= 499: raise exceptions.ClientError(response, content) elif 500 <= status <= 599: raise exceptions.ServerError(response, content) else: raise exceptions.ConnectionError( response, content, "Unknown response code: #{response.code}") def headers(self, refresh_token=None, headers=None): """Default HTTP headers """ token_hash = self.get_token_hash(refresh_token=refresh_token, headers=headers or {}) return { "Authorization": ("%s %s" % (token_hash['token_type'], token_hash['access_token'])), "Content-Type": "application/json", "Accept": "application/json", "User-Agent": self.user_agent } def get(self, action, headers=None, refresh_token=None): """Make GET request Usage:: >>> api.get("v1/payments/payment?count=1") >>> api.get("v1/payments/payment/PAY-1234") """ return self.request(util.join_url(self.endpoint, action), 'GET', headers=headers or {}, refresh_token=refresh_token) def post(self, action, params=None, headers=None, refresh_token=None): """Make POST request Usage:: >>> api.post("v1/payments/payment", { 'indent': 'sale' }) >>> api.post("v1/payments/payment/PAY-1234/execute", { 'payer_id': '1234' }) """ return self.request(util.join_url(self.endpoint, action), 'POST', body=params or {}, headers=headers or {}, refresh_token=refresh_token) def put(self, action, params=None, headers=None, refresh_token=None): """Make PUT request Usage:: >>> api.put("v1/invoicing/invoices/INV2-RUVR-ADWQ", { 'id': 'INV2-RUVR-ADWQ', 'status': 'DRAFT'}) """ return self.request(util.join_url(self.endpoint, action), 'PUT', body=params or {}, headers=headers or {}, refresh_token=refresh_token) def patch(self, action, params=None, headers=None, refresh_token=None): """Make PATCH request Usage:: >>> api.patch("v1/payments/billing-plans/P-5VH69258TN786403SVUHBM6A", { 'op': 'replace', 'path': '/merchant-preferences'}) """ return self.request(util.join_url(self.endpoint, action), 'PATCH', body=params or {}, headers=headers or {}, refresh_token=refresh_token) def delete(self, action, headers=None, refresh_token=None): """Make DELETE request """ return self.request(util.join_url(self.endpoint, action), 'DELETE', headers=headers or {}, refresh_token=refresh_token)
(options=None, **kwargs)
22,019
paypalrestsdk.api
__init__
Create API object Usage:: >>> import paypalrestsdk >>> api = paypalrestsdk.Api(mode="sandbox", client_id='CLIENT_ID', client_secret='CLIENT_SECRET', ssl_options={"cert": "/path/to/server.pem"})
def __init__(self, options=None, **kwargs): """Create API object Usage:: >>> import paypalrestsdk >>> api = paypalrestsdk.Api(mode="sandbox", client_id='CLIENT_ID', client_secret='CLIENT_SECRET', ssl_options={"cert": "/path/to/server.pem"}) """ kwargs = util.merge_dict(options or {}, kwargs) self.mode = kwargs.get("mode", "sandbox") if self.mode != "live" and self.mode != "sandbox": raise exceptions.InvalidConfig("Configuration Mode Invalid", "Received: %s" % (self.mode), "Required: live or sandbox") self.endpoint = kwargs.get("endpoint", self.default_endpoint()) self.token_endpoint = kwargs.get("token_endpoint", self.endpoint) # Mandatory parameter, so not using `dict.get` self.client_id = kwargs["client_id"] # Mandatory parameter, so not using `dict.get` self.client_secret = kwargs["client_secret"] self.proxies = kwargs.get("proxies", None) self.token_hash = None self.token_request_at = None # setup SSL certificate verification if private certificate provided ssl_options = kwargs.get("ssl_options", {}) if "cert" in ssl_options: os.environ["REQUESTS_CA_BUNDLE"] = ssl_options["cert"] if kwargs.get("token"): self.token_hash = { "access_token": kwargs["token"], "token_type": "Bearer"} self.options = kwargs
(self, options=None, **kwargs)
22,020
paypalrestsdk.api
_check_openssl_version
Check that merchant server has PCI compliant version of TLS Print warning if it does not.
def _check_openssl_version(self): """ Check that merchant server has PCI compliant version of TLS Print warning if it does not. """ if self.ssl_version_info and self.ssl_version_info < (1, 0, 1, 0, 0): log.warning( 'WARNING: openssl version ' + self.ssl_version + ' detected. Per PCI Security Council mandate \ (https://github.com/paypal/TLS-update), you MUST update to the latest security library.')
(self)
22,021
paypalrestsdk.api
basic_auth
Find basic auth, and returns base64 encoded
def basic_auth(self): """Find basic auth, and returns base64 encoded """ credentials = "%s:%s" % (self.client_id, self.client_secret) return base64.b64encode(credentials.encode('utf-8')).decode('utf-8').replace("\n", "")
(self)
22,022
paypalrestsdk.api
default_endpoint
null
def default_endpoint(self): return __endpoint_map__.get(self.mode)
(self)
22,023
paypalrestsdk.api
delete
Make DELETE request
def delete(self, action, headers=None, refresh_token=None): """Make DELETE request """ return self.request(util.join_url(self.endpoint, action), 'DELETE', headers=headers or {}, refresh_token=refresh_token)
(self, action, headers=None, refresh_token=None)
22,024
paypalrestsdk.api
get
Make GET request Usage:: >>> api.get("v1/payments/payment?count=1") >>> api.get("v1/payments/payment/PAY-1234")
def get(self, action, headers=None, refresh_token=None): """Make GET request Usage:: >>> api.get("v1/payments/payment?count=1") >>> api.get("v1/payments/payment/PAY-1234") """ return self.request(util.join_url(self.endpoint, action), 'GET', headers=headers or {}, refresh_token=refresh_token)
(self, action, headers=None, refresh_token=None)
22,025
paypalrestsdk.api
get_access_token
Wraps get_token_hash for getting access token
def get_access_token(self, authorization_code=None, refresh_token=None, headers=None): """Wraps get_token_hash for getting access token """ return self.get_token_hash(authorization_code, refresh_token, headers=headers or {})['access_token']
(self, authorization_code=None, refresh_token=None, headers=None)
22,026
paypalrestsdk.api
get_refresh_token
Exchange authorization code for refresh token for future payments
def get_refresh_token(self, authorization_code=None, headers=None): """Exchange authorization code for refresh token for future payments """ if authorization_code is None: raise exceptions.MissingConfig("Authorization code needed to get new refresh token. \ Refer to https://developer.paypal.com/docs/integration/mobile/make-future-payment/#get-an-auth-code") return self.get_token_hash(authorization_code, headers=headers or {})["refresh_token"]
(self, authorization_code=None, headers=None)
22,027
paypalrestsdk.api
get_token_hash
Generate new token by making a POST request 1. By using client credentials if validate_token_hash finds token to be invalid. This is useful during web flow so that an already authenticated user is not reprompted for login 2. Exchange authorization_code from mobile device for a long living refresh token that can be used to charge user who has consented to future payments 3. Exchange refresh_token for the user for a access_token of type Bearer which can be passed in to charge user
def get_token_hash(self, authorization_code=None, refresh_token=None, headers=None): """Generate new token by making a POST request 1. By using client credentials if validate_token_hash finds token to be invalid. This is useful during web flow so that an already authenticated user is not reprompted for login 2. Exchange authorization_code from mobile device for a long living refresh token that can be used to charge user who has consented to future payments 3. Exchange refresh_token for the user for a access_token of type Bearer which can be passed in to charge user """ path = "/v1/oauth2/token" payload = "grant_type=client_credentials" if authorization_code is not None: payload = "grant_type=authorization_code&response_type=token&redirect_uri=urn:ietf:wg:oauth:2.0:oob&code=" + \ authorization_code elif refresh_token is not None: payload = "grant_type=refresh_token&refresh_token=" + refresh_token else: self.validate_token_hash() if self.token_hash is not None: # return cached copy return self.token_hash token = self.http_call( util.join_url(self.token_endpoint, path), "POST", data=payload, headers=util.merge_dict({ "Authorization": ("Basic %s" % self.basic_auth()), "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json", "User-Agent": self.user_agent }, headers or {})) if refresh_token is None and authorization_code is None: # cache token for re-use in normal case self.token_request_at = datetime.datetime.now() self.token_hash = token return token
(self, authorization_code=None, refresh_token=None, headers=None)
22,028
paypalrestsdk.api
handle_response
Validate HTTP response
def handle_response(self, response, content): """Validate HTTP response """ status = response.status_code if status in (301, 302, 303, 307): raise exceptions.Redirection(response, content) elif 200 <= status <= 299: return json.loads(content) if content else {} elif status == 400: raise exceptions.BadRequest(response, content) elif status == 401: raise exceptions.UnauthorizedAccess(response, content) elif status == 403: raise exceptions.ForbiddenAccess(response, content) elif status == 404: raise exceptions.ResourceNotFound(response, content) elif status == 405: raise exceptions.MethodNotAllowed(response, content) elif status == 409: raise exceptions.ResourceConflict(response, content) elif status == 410: raise exceptions.ResourceGone(response, content) elif status == 422: raise exceptions.ResourceInvalid(response, content) elif 401 <= status <= 499: raise exceptions.ClientError(response, content) elif 500 <= status <= 599: raise exceptions.ServerError(response, content) else: raise exceptions.ConnectionError( response, content, "Unknown response code: #{response.code}")
(self, response, content)
22,029
paypalrestsdk.api
headers
Default HTTP headers
def headers(self, refresh_token=None, headers=None): """Default HTTP headers """ token_hash = self.get_token_hash(refresh_token=refresh_token, headers=headers or {}) return { "Authorization": ("%s %s" % (token_hash['token_type'], token_hash['access_token'])), "Content-Type": "application/json", "Accept": "application/json", "User-Agent": self.user_agent }
(self, refresh_token=None, headers=None)
22,030
paypalrestsdk.api
http_call
Makes a http call. Logs response information.
def http_call(self, url, method, **kwargs): """Makes a http call. Logs response information. """ log.info('Request[%s]: %s' % (method, url)) if self.mode.lower() != 'live': request_headers = kwargs.get("headers", {}) request_body = kwargs.get("data", {}) log.debug("Level: " + self.mode) log.debug('Request: \nHeaders: %s\nBody: %s' % ( str(request_headers), str(request_body))) else: log.info( 'Not logging full request/response headers and body in live mode for compliance') start_time = datetime.datetime.now() response = requests.request( method, url, proxies=self.proxies, **kwargs) duration = datetime.datetime.now() - start_time log.info('Response[%d]: %s, Duration: %s.%ss.' % ( response.status_code, response.reason, duration.seconds, duration.microseconds)) debug_id = response.headers.get('PayPal-Debug-Id') if debug_id: log.debug('debug_id: %s' % debug_id) if self.mode.lower() != 'live': log.debug('Headers: %s\nBody: %s' % ( str(response.headers), str(response.content))) return self.handle_response(response, response.content.decode('utf-8'))
(self, url, method, **kwargs)
22,031
paypalrestsdk.api
patch
Make PATCH request Usage:: >>> api.patch("v1/payments/billing-plans/P-5VH69258TN786403SVUHBM6A", { 'op': 'replace', 'path': '/merchant-preferences'})
def patch(self, action, params=None, headers=None, refresh_token=None): """Make PATCH request Usage:: >>> api.patch("v1/payments/billing-plans/P-5VH69258TN786403SVUHBM6A", { 'op': 'replace', 'path': '/merchant-preferences'}) """ return self.request(util.join_url(self.endpoint, action), 'PATCH', body=params or {}, headers=headers or {}, refresh_token=refresh_token)
(self, action, params=None, headers=None, refresh_token=None)
22,032
paypalrestsdk.api
post
Make POST request Usage:: >>> api.post("v1/payments/payment", { 'indent': 'sale' }) >>> api.post("v1/payments/payment/PAY-1234/execute", { 'payer_id': '1234' })
def post(self, action, params=None, headers=None, refresh_token=None): """Make POST request Usage:: >>> api.post("v1/payments/payment", { 'indent': 'sale' }) >>> api.post("v1/payments/payment/PAY-1234/execute", { 'payer_id': '1234' }) """ return self.request(util.join_url(self.endpoint, action), 'POST', body=params or {}, headers=headers or {}, refresh_token=refresh_token)
(self, action, params=None, headers=None, refresh_token=None)
22,033
paypalrestsdk.api
put
Make PUT request Usage:: >>> api.put("v1/invoicing/invoices/INV2-RUVR-ADWQ", { 'id': 'INV2-RUVR-ADWQ', 'status': 'DRAFT'})
def put(self, action, params=None, headers=None, refresh_token=None): """Make PUT request Usage:: >>> api.put("v1/invoicing/invoices/INV2-RUVR-ADWQ", { 'id': 'INV2-RUVR-ADWQ', 'status': 'DRAFT'}) """ return self.request(util.join_url(self.endpoint, action), 'PUT', body=params or {}, headers=headers or {}, refresh_token=refresh_token)
(self, action, params=None, headers=None, refresh_token=None)
22,034
paypalrestsdk.api
request
Make HTTP call, formats response and does error handling. Uses http_call method in API class. Usage:: >>> api.request("https://api.sandbox.paypal.com/v1/payments/payment?count=10", "GET", {}) >>> api.request("https://api.sandbox.paypal.com/v1/payments/payment", "POST", "{}", {} )
def request(self, url, method, body=None, headers=None, refresh_token=None): """Make HTTP call, formats response and does error handling. Uses http_call method in API class. Usage:: >>> api.request("https://api.sandbox.paypal.com/v1/payments/payment?count=10", "GET", {}) >>> api.request("https://api.sandbox.paypal.com/v1/payments/payment", "POST", "{}", {} ) """ http_headers = util.merge_dict( self.headers(refresh_token=refresh_token, headers=headers or {}), headers or {}) if http_headers.get('PayPal-Request-Id'): log.info('PayPal-Request-Id: %s' % (http_headers['PayPal-Request-Id'])) self._check_openssl_version() try: return self.http_call(url, method, data=json.dumps(body), headers=http_headers) # Format Error message for bad request except exceptions.BadRequest as error: return {"error": json.loads(error.content)} # Handle Expired token except exceptions.UnauthorizedAccess as error: if(self.token_hash and self.client_id): self.token_hash = None return self.request(url, method, body, headers) else: raise error
(self, url, method, body=None, headers=None, refresh_token=None)
22,035
paypalrestsdk.api
validate_token_hash
Checks if token duration has expired and if so resets token
def validate_token_hash(self): """Checks if token duration has expired and if so resets token """ if self.token_request_at and self.token_hash and self.token_hash.get("expires_in") is not None: delta = datetime.datetime.now() - self.token_request_at duration = ( delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 10 ** 6) / 10 ** 6 if duration > self.token_hash.get("expires_in"): self.token_hash = None
(self)
22,036
paypalrestsdk.payments
Authorization
Enables looking up, voiding and capturing authorization and reauthorize payments Helpful links:: https://developer.paypal.com/docs/api/#authorizations https://developer.paypal.com/docs/integration/direct/capture-payment/#authorize-the-payment Usage:: >>> authorization = Authorization.find("<AUTHORIZATION_ID>") >>> capture = authorization.capture({ "amount": { "currency": "USD", "total": "1.00" } }) >>> authorization.void() # return True or False
class Authorization(Find, Post): """Enables looking up, voiding and capturing authorization and reauthorize payments Helpful links:: https://developer.paypal.com/docs/api/#authorizations https://developer.paypal.com/docs/integration/direct/capture-payment/#authorize-the-payment Usage:: >>> authorization = Authorization.find("<AUTHORIZATION_ID>") >>> capture = authorization.capture({ "amount": { "currency": "USD", "total": "1.00" } }) >>> authorization.void() # return True or False """ path = "v1/payments/authorization" def capture(self, attributes): return self.post('capture', attributes, Capture) def void(self): return self.post('void', {}, self) def reauthorize(self): return self.post('reauthorize', self, self)
(attributes=None, api=None)
22,037
paypalrestsdk.resource
__contains__
null
def __contains__(self, item): return item in self.__data__
(self, item)
22,038
paypalrestsdk.resource
__getattr__
null
def __getattr__(self, name): return self.__data__.get(name)
(self, name)
22,039
paypalrestsdk.resource
__getitem__
null
def __getitem__(self, key): return self.__data__[key]
(self, key)
22,040
paypalrestsdk.resource
__init__
null
def __init__(self, attributes=None, api=None): attributes = attributes or {} self.__dict__['api'] = api or default_api() super(Resource, self).__setattr__('__data__', {}) super(Resource, self).__setattr__('error', None) super(Resource, self).__setattr__('headers', {}) super(Resource, self).__setattr__('header', {}) super(Resource, self).__setattr__('request_id', None) self.merge(attributes)
(self, attributes=None, api=None)
22,041
paypalrestsdk.resource
__repr__
null
def __repr__(self): return self.__data__.__str__()
(self)
22,042
paypalrestsdk.resource
__setattr__
null
def __setattr__(self, name, value): try: # Handle attributes(error, header, request_id) super(Resource, self).__getattribute__(name) super(Resource, self).__setattr__(name, value) except AttributeError: self.__data__[name] = self.convert(name, value)
(self, name, value)
22,043
paypalrestsdk.resource
__setitem__
null
def __setitem__(self, key, value): self.__data__[key] = self.convert(key, value)
(self, key, value)
22,044
paypalrestsdk.resource
__str__
null
def __str__(self): return self.__data__.__str__()
(self)
22,045
paypalrestsdk.payments
capture
null
def capture(self, attributes): return self.post('capture', attributes, Capture)
(self, attributes)
22,046
paypalrestsdk.resource
convert
Convert the attribute values to configured class
def convert(self, name, value): """Convert the attribute values to configured class """ if isinstance(value, dict): cls = self.convert_resources.get(name, Resource) return cls(value, api=self.api) elif isinstance(value, list): new_list = [] for obj in value: new_list.append(self.convert(name, obj)) return new_list else: return value
(self, name, value)
22,047
paypalrestsdk.resource
generate_request_id
Generate uniq request id
def generate_request_id(self): """Generate uniq request id """ if self.request_id is None: self.request_id = str(uuid.uuid4()) return self.request_id
(self)
22,048
paypalrestsdk.resource
http_headers
Generate HTTP header
def http_headers(self): """Generate HTTP header """ return util.merge_dict(self.header, self.headers, {'PayPal-Request-Id': self.generate_request_id()})
(self)
22,049
paypalrestsdk.resource
merge
Merge new attributes e.g. response from a post to Resource
def merge(self, new_attributes): """Merge new attributes e.g. response from a post to Resource """ for k, v in new_attributes.items(): setattr(self, k, v)
(self, new_attributes)
22,050
paypalrestsdk.resource
post
Constructs url with passed in headers and makes post request via post method in api class. Usage:: >>> payment.post("execute", {'payer_id': '1234'}, payment) # return True or False >>> sale.post("refund", {'payer_id': '1234'}) # return Refund object
def post(self, name, attributes=None, cls=Resource, fieldname='id', refresh_token=None): """Constructs url with passed in headers and makes post request via post method in api class. Usage:: >>> payment.post("execute", {'payer_id': '1234'}, payment) # return True or False >>> sale.post("refund", {'payer_id': '1234'}) # return Refund object """ attributes = attributes or {} url = util.join_url(self.path, str(self[fieldname]), name) if not isinstance(attributes, Resource): attributes = Resource(attributes, api=self.api) new_attributes = self.api.post(url, attributes.to_dict(), attributes.http_headers(), refresh_token) if isinstance(cls, Resource): cls.error = None cls.merge(new_attributes) return self.success() else: return cls(new_attributes, api=self.api)
(self, name, attributes=None, cls=<class 'paypalrestsdk.resource.Resource'>, fieldname='id', refresh_token=None)
22,051
paypalrestsdk.payments
reauthorize
null
def reauthorize(self): return self.post('reauthorize', self, self)
(self)
22,052
paypalrestsdk.resource
success
null
def success(self): return self.error is None
(self)
22,053
paypalrestsdk.resource
to_dict
null
def to_dict(self): def parse_object(value): if isinstance(value, Resource): return value.to_dict() elif isinstance(value, list): return list(map(parse_object, value)) else: return value return dict((key, parse_object(value)) for (key, value) in self.__data__.items())
(self)
22,054
paypalrestsdk.payments
void
null
def void(self): return self.post('void', {}, self)
(self)
22,055
paypalrestsdk.payments
BillingAgreement
After billing plan is created and activated, the billing agreement resource can be used to have customers agree to subscribe to plan. Wraps the v1/payments/billing-agreements endpoint https://developer.paypal.com/webapps/developer/docs/integration/direct/create-billing-agreement/ Usage:: >>> billing_agreement = BillingAgreement.find("<AGREEMENT_ID>")
class BillingAgreement(Create, Find, Replace, Post): """After billing plan is created and activated, the billing agreement resource can be used to have customers agree to subscribe to plan. Wraps the v1/payments/billing-agreements endpoint https://developer.paypal.com/webapps/developer/docs/integration/direct/create-billing-agreement/ Usage:: >>> billing_agreement = BillingAgreement.find("<AGREEMENT_ID>") """ path = "v1/payments/billing-agreements" def suspend(self, attributes): return self.post('suspend', attributes, self) def cancel(self, attributes): return self.post('cancel', attributes, self) def reactivate(self, attributes): return self.post('re-activate', attributes, self) def bill_balance(self, attributes): return self.post('bill-balance', attributes, self) def set_balance(self, attributes): return self.post('set-balance', attributes, self) @classmethod def execute(cls, payment_token, params=None, api=None): api = api or default_api() params = params or {} url = util.join_url(cls.path, payment_token, 'agreement-execute') return Resource(api.post(url, params), api=api) def search_transactions(self, start_date, end_date, api=None): if not start_date or not end_date: raise exceptions.MissingParam("Search transactions needs valid start_date and end_date.") api = api or default_api() # Construct url similar to # /billing-agreements/I-HT38K76XPMGJ/transactions?start-date=2014-04-13&end-date=2014-04-30 endpoint = util.join_url(self.path, str(self['id']), 'transactions') date_range = [('start_date', start_date), ('end_date', end_date)] url = util.join_url_params(endpoint, date_range) return Resource(self.api.get(url), api=api)
(attributes=None, api=None)
22,064
paypalrestsdk.payments
bill_balance
null
def bill_balance(self, attributes): return self.post('bill-balance', attributes, self)
(self, attributes)
22,065
paypalrestsdk.payments
cancel
null
def cancel(self, attributes): return self.post('cancel', attributes, self)
(self, attributes)
22,067
paypalrestsdk.resource
create
Creates a resource e.g. payment Usage:: >>> payment = Payment({}) >>> payment.create() # return True or False
def create(self, refresh_token=None, correlation_id=None): """Creates a resource e.g. payment Usage:: >>> payment = Payment({}) >>> payment.create() # return True or False """ headers = {} if correlation_id is not None: headers = util.merge_dict( self.http_headers(), {'Paypal-Application-Correlation-Id': correlation_id, 'Paypal-Client-Metadata-Id': correlation_id} ) else: headers = self.http_headers() new_attributes = self.api.post(self.path, self.to_dict(), headers, refresh_token) self.error = None self.merge(new_attributes) return self.success()
(self, refresh_token=None, correlation_id=None)
22,072
paypalrestsdk.payments
reactivate
null
def reactivate(self, attributes): return self.post('re-activate', attributes, self)
(self, attributes)
22,073
paypalrestsdk.resource
replace
null
def replace(self, attributes=None, refresh_token=None): attributes = attributes or self.to_dict() url = util.join_url(self.path, str(self['id'])) new_attributes = self.api.patch(url, attributes, self.http_headers(), refresh_token) self.error = None self.merge(new_attributes) return self.success()
(self, attributes=None, refresh_token=None)
22,074
paypalrestsdk.payments
search_transactions
null
def search_transactions(self, start_date, end_date, api=None): if not start_date or not end_date: raise exceptions.MissingParam("Search transactions needs valid start_date and end_date.") api = api or default_api() # Construct url similar to # /billing-agreements/I-HT38K76XPMGJ/transactions?start-date=2014-04-13&end-date=2014-04-30 endpoint = util.join_url(self.path, str(self['id']), 'transactions') date_range = [('start_date', start_date), ('end_date', end_date)] url = util.join_url_params(endpoint, date_range) return Resource(self.api.get(url), api=api)
(self, start_date, end_date, api=None)
22,075
paypalrestsdk.payments
set_balance
null
def set_balance(self, attributes): return self.post('set-balance', attributes, self)
(self, attributes)
22,077
paypalrestsdk.payments
suspend
null
def suspend(self, attributes): return self.post('suspend', attributes, self)
(self, attributes)
22,079
paypalrestsdk.payments
BillingPlan
Merchants can create subscription payments i.e. planned sets of future recurring payments at periodic intervals. Billing Plans specify number of payments, their frequency and other details. Acts as a template for BillingAgreement, one BillingPlan can be used to create multiple agreements. Wraps the v1/payments/billing-plans endpoint https://developer.paypal.com/webapps/developer/docs/integration/direct/create-billing-plan/ Usage:: >>> billing_plans = BillingPlan.all({'status': CREATED})
class BillingPlan(List, Create, Find, Replace): """Merchants can create subscription payments i.e. planned sets of future recurring payments at periodic intervals. Billing Plans specify number of payments, their frequency and other details. Acts as a template for BillingAgreement, one BillingPlan can be used to create multiple agreements. Wraps the v1/payments/billing-plans endpoint https://developer.paypal.com/webapps/developer/docs/integration/direct/create-billing-plan/ Usage:: >>> billing_plans = BillingPlan.all({'status': CREATED}) """ path = "v1/payments/billing-plans" def activate(self): """Activate a billing plan, wraps billing plan replace.""" billing_plan_update_attributes = [{ "op": "replace", "path": "/", "value": { "state": "ACTIVE" } }] return self.replace(billing_plan_update_attributes) def inactivate(self): """Inactivate a billing plan, wraps billing plan replace.""" billing_plan_update_attributes = [{ "op": "replace", "path": "/", "value": { "state": "INACTIVE" } }] return self.replace(billing_plan_update_attributes)
(attributes=None, api=None)
22,088
paypalrestsdk.payments
activate
Activate a billing plan, wraps billing plan replace.
def activate(self): """Activate a billing plan, wraps billing plan replace.""" billing_plan_update_attributes = [{ "op": "replace", "path": "/", "value": { "state": "ACTIVE" } }] return self.replace(billing_plan_update_attributes)
(self)
22,093
paypalrestsdk.payments
inactivate
Inactivate a billing plan, wraps billing plan replace.
def inactivate(self): """Inactivate a billing plan, wraps billing plan replace.""" billing_plan_update_attributes = [{ "op": "replace", "path": "/", "value": { "state": "INACTIVE" } }] return self.replace(billing_plan_update_attributes)
(self)
22,098
paypalrestsdk.payments
Capture
Look up and refund captured payments and orders, wraps v1/payments/capture Usage:: >>> capture = Capture.find("<CAPTURE_ID>") >>> refund = capture.refund({ "amount": { "currency": "USD", "total": "1.00" }})
class Capture(Find, Post): """Look up and refund captured payments and orders, wraps v1/payments/capture Usage:: >>> capture = Capture.find("<CAPTURE_ID>") >>> refund = capture.refund({ "amount": { "currency": "USD", "total": "1.00" }}) """ path = "v1/payments/capture" def refund(self, attributes): return self.post('refund', attributes, Refund)
(attributes=None, api=None)
22,112
paypalrestsdk.payments
refund
null
def refund(self, attributes): return self.post('refund', attributes, Refund)
(self, attributes)
22,115
paypalrestsdk.vault
CreditCard
Use vault api to avoid having to store sensitive information such as credit card related details on your server. API docs at https://developer.paypal.com/docs/api/#vault Usage:: >>> credit_card = CreditCard.find("CARD-5BT058015C739554AKE2GCEI") >>> credit_card = CreditCard.new({'type': 'visa'}) >>> credit_card.create() # return True or False
class CreditCard(Find, Create, Delete, Replace, List): """Use vault api to avoid having to store sensitive information such as credit card related details on your server. API docs at https://developer.paypal.com/docs/api/#vault Usage:: >>> credit_card = CreditCard.find("CARD-5BT058015C739554AKE2GCEI") >>> credit_card = CreditCard.new({'type': 'visa'}) >>> credit_card.create() # return True or False """ path = "v1/vault/credit-cards"
(attributes=None, api=None)
22,126
paypalrestsdk.resource
delete
Deletes a resource e.g. credit_card Usage:: >>> credit_card.delete()
def delete(self): """Deletes a resource e.g. credit_card Usage:: >>> credit_card.delete() """ url = util.join_url(self.path, str(self['id'])) new_attributes = self.api.delete(url) self.error = None self.merge(new_attributes) return self.success()
(self)
22,133
paypalrestsdk.invoices
Invoice
Invoice class wrapping the REST v1/invoices/invoice endpoint Usage:: >>> invoice_history = Invoice.all({"count": 5}) >>> invoice = Invoice.new({}) >>> invoice.create() # return True or False
class Invoice(List, Find, Create, Delete, Update, Post): """Invoice class wrapping the REST v1/invoices/invoice endpoint Usage:: >>> invoice_history = Invoice.all({"count": 5}) >>> invoice = Invoice.new({}) >>> invoice.create() # return True or False """ path = "v1/invoicing/invoices" def send(self, refresh_token=None): return self.post('send', {}, self, refresh_token=refresh_token) def remind(self, attributes): return self.post('remind', attributes, self) def cancel(self, attributes): return self.post('cancel', attributes, self) def record_payment(self, attributes): return self.post('record-payment', attributes, self) def record_refund(self, attributes): return self.post('record-refund', attributes, self) def delete_external_payment(self, transactionId): # /invoicing/invoices/<INVOICE-ID>/payment-records/<TRANSACTION-ID> endpoint = util.join_url(self.path, str(self['id']), 'payment-records', str(transactionId)) return Resource(self.api.delete(endpoint), api=self.api) def delete_external_refund(self, transactionId): # /invoicing/invoices/<INVOICE-ID>/refund-records/<TRANSACTION-ID> endpoint = util.join_url(self.path, str(self['id']), 'refund-records', str(transactionId)) return Resource(self.api.delete(endpoint), api=self.api) def get_qr_code(self, height=500, width=500, api=None): # height and width have default value of 500 as in the APIs api = api or default_api() # Construct url similar to # /invoicing/invoices/<INVOICE-ID>/qr-code?height=<HEIGHT>&width=<WIDTH> endpoint = util.join_url(self.path, str(self['id']), 'qr-code') image_attributes = [('height', height), ('width', width)] url = util.join_url_params(endpoint, image_attributes) return Resource(self.api.get(url), api=api) @classmethod def next_invoice_number(cls, api=None): api = api or default_api() url = util.join_url(cls.path, 'next-invoice-number') return Resource(api.post(url), api=api) @classmethod def search(cls, params=None, api=None): api = api or default_api() params = params or {} path = "v1/invoicing" url = util.join_url(path, 'search') return Resource(api.post(url, params), api=api)
(attributes=None, api=None)
22,146
paypalrestsdk.invoices
delete_external_payment
null
def delete_external_payment(self, transactionId): # /invoicing/invoices/<INVOICE-ID>/payment-records/<TRANSACTION-ID> endpoint = util.join_url(self.path, str(self['id']), 'payment-records', str(transactionId)) return Resource(self.api.delete(endpoint), api=self.api)
(self, transactionId)
22,147
paypalrestsdk.invoices
delete_external_refund
null
def delete_external_refund(self, transactionId): # /invoicing/invoices/<INVOICE-ID>/refund-records/<TRANSACTION-ID> endpoint = util.join_url(self.path, str(self['id']), 'refund-records', str(transactionId)) return Resource(self.api.delete(endpoint), api=self.api)
(self, transactionId)
22,149
paypalrestsdk.invoices
get_qr_code
null
def get_qr_code(self, height=500, width=500, api=None): # height and width have default value of 500 as in the APIs api = api or default_api() # Construct url similar to # /invoicing/invoices/<INVOICE-ID>/qr-code?height=<HEIGHT>&width=<WIDTH> endpoint = util.join_url(self.path, str(self['id']), 'qr-code') image_attributes = [('height', height), ('width', width)] url = util.join_url_params(endpoint, image_attributes) return Resource(self.api.get(url), api=api)
(self, height=500, width=500, api=None)
22,153
paypalrestsdk.invoices
record_payment
null
def record_payment(self, attributes): return self.post('record-payment', attributes, self)
(self, attributes)