code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def lifespan(self, app: AsgiV3LifespanApp | str) -> None:
"""Interface that allows user to define their own lifespan app
within the current ReactPy application.
Parameters:
app: The ASGI application to route to.
"""
if self.extra_lifespan_app:
raise Value... | Interface that allows user to define their own lifespan app
within the current ReactPy application.
Parameters:
app: The ASGI application to route to.
| lifespan | python | reactive-python/reactpy | src/reactpy/executors/asgi/standalone.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/executors/asgi/standalone.py | MIT |
def pyscript_component(
*file_paths: str | Path,
initial: str | VdomDict | ComponentType = "",
root: str = "root",
key: Key | None = None,
) -> ComponentType:
"""
Args:
file_paths: File path to your client-side ReactPy component. If multiple paths are \
provided, the contents... |
Args:
file_paths: File path to your client-side ReactPy component. If multiple paths are provided, the contents are automatically merged.
Kwargs:
initial: The initial HTML that is displayed prior to the PyScript component loads. This can either be a string containing ra... | pyscript_component | python | reactive-python/reactpy | src/reactpy/pyscript/components.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/pyscript/components.py | MIT |
def update_model(update, root_model):
"""Apply an update ReactPy's internal DOM model."""
if update["path"]:
set_pointer(root_model, update["path"], update["model"])
else:
root_model.update(update["model"]) | Apply an update ReactPy's internal DOM model. | update_model | python | reactive-python/reactpy | src/reactpy/pyscript/layout_handler.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/pyscript/layout_handler.py | MIT |
def build_element_tree(self, layout, parent, model):
"""Recursively build an element tree, starting from the root component."""
# If the model is a string, add it as a text node
if isinstance(model, str):
parent.appendChild(js.document.createTextNode(model))
# If the model i... | Recursively build an element tree, starting from the root component. | build_element_tree | python | reactive-python/reactpy | src/reactpy/pyscript/layout_handler.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/pyscript/layout_handler.py | MIT |
def create_event_handler(self, layout, element, event_name, event_handler_model):
"""Create an event handler for an element. This function is used as an
adapter between ReactPy and browser events."""
target = event_handler_model["target"]
def event_handler(*args):
# When the... | Create an event handler for an element. This function is used as an
adapter between ReactPy and browser events. | create_event_handler | python | reactive-python/reactpy | src/reactpy/pyscript/layout_handler.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/pyscript/layout_handler.py | MIT |
def delete_old_workspaces():
"""To prevent memory leaks, we must delete all user generated Python code when
it is no longer in use (removed from the page). To do this, we compare what
UUIDs exist on the DOM, versus what UUIDs exist within the PyScript global
interpreter."""
# Fin... | To prevent memory leaks, we must delete all user generated Python code when
it is no longer in use (removed from the page). To do this, we compare what
UUIDs exist on the DOM, versus what UUIDs exist within the PyScript global
interpreter. | delete_old_workspaces | python | reactive-python/reactpy | src/reactpy/pyscript/layout_handler.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/pyscript/layout_handler.py | MIT |
async def run(self, workspace_function):
"""Run the layout handler. This function is main executor for all user generated code."""
self.delete_old_workspaces()
root_model: dict = {}
async with Layout(workspace_function()) as root_layout:
while True:
update = ... | Run the layout handler. This function is main executor for all user generated code. | run | python | reactive-python/reactpy | src/reactpy/pyscript/layout_handler.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/pyscript/layout_handler.py | MIT |
def pyscript_executor_html(file_paths: Sequence[str], uuid: str, root: str) -> str:
"""Inserts the user's code into the PyScript template using pattern matching."""
# Create a valid PyScript executor by replacing the template values
executor = PYSCRIPT_COMPONENT_TEMPLATE.replace("UUID", uuid)
executor =... | Inserts the user's code into the PyScript template using pattern matching. | pyscript_executor_html | python | reactive-python/reactpy | src/reactpy/pyscript/utils.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/pyscript/utils.py | MIT |
def pyscript_component_html(
file_paths: Sequence[str], initial: str | VdomDict, root: str
) -> str:
"""Renders a PyScript component with the user's code."""
_initial = initial if isinstance(initial, str) else reactpy_to_string(initial)
uuid = uuid4().hex
executor_code = pyscript_executor_html(file_... | Renders a PyScript component with the user's code. | pyscript_component_html | python | reactive-python/reactpy | src/reactpy/pyscript/utils.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/pyscript/utils.py | MIT |
def url(self, path: str = "", query: Any | None = None) -> str:
"""Return a URL string pointing to the host and point of the server
Args:
path: the path to a resource on the server
query: a dictionary or list of query parameters
"""
return urlunparse(
... | Return a URL string pointing to the host and point of the server
Args:
path: the path to a resource on the server
query: a dictionary or list of query parameters
| url | python | reactive-python/reactpy | src/reactpy/testing/backend.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/testing/backend.py | MIT |
def list_logged_exceptions(
self,
pattern: str = "",
types: type[Any] | tuple[type[Any], ...] = Exception,
log_level: int = logging.ERROR,
del_log_records: bool = True,
) -> list[BaseException]:
"""Return a list of logged exception matching the given criteria
... | Return a list of logged exception matching the given criteria
Args:
log_level: The level of log to check
exclude_exc_types: Any exception types to ignore
del_log_records: Whether to delete the log records for yielded exceptions
| list_logged_exceptions | python | reactive-python/reactpy | src/reactpy/testing/backend.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/testing/backend.py | MIT |
def _hotswap(update_on_change: bool = False) -> tuple[_MountFunc, ComponentConstructor]:
"""Swap out components from a layout on the fly.
Since you can't change the component functions used to create a layout
in an imperative manner, you can use ``hotswap`` to do this so
long as you set things up ahead... | Swap out components from a layout on the fly.
Since you can't change the component functions used to create a layout
in an imperative manner, you can use ``hotswap`` to do this so
long as you set things up ahead of time.
Parameters:
update_on_change: Whether or not all views of the layout shou... | _hotswap | python | reactive-python/reactpy | src/reactpy/testing/backend.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/testing/backend.py | MIT |
def clear_reactpy_web_modules_dir() -> None:
"""Clear the directory where ReactPy stores registered web modules"""
for path in REACTPY_WEB_MODULES_DIR.current.iterdir():
shutil.rmtree(path) if path.is_dir() else path.unlink() | Clear the directory where ReactPy stores registered web modules | clear_reactpy_web_modules_dir | python | reactive-python/reactpy | src/reactpy/testing/common.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/testing/common.py | MIT |
async def until(
self,
condition: Callable[[_R], bool],
timeout: float = REACTPY_TESTS_DEFAULT_TIMEOUT.current,
delay: float = _DEFAULT_POLL_DELAY,
description: str = "condition to be true",
) -> None:
"""Check that the coroutines result meets a condition within the t... | Check that the coroutines result meets a condition within the timeout | until | python | reactive-python/reactpy | src/reactpy/testing/common.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/testing/common.py | MIT |
async def until_is(
self,
right: _R,
timeout: float = REACTPY_TESTS_DEFAULT_TIMEOUT.current,
delay: float = _DEFAULT_POLL_DELAY,
) -> None:
"""Wait until the result is identical to the given value"""
return await self.until(
lambda left: left is right,
... | Wait until the result is identical to the given value | until_is | python | reactive-python/reactpy | src/reactpy/testing/common.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/testing/common.py | MIT |
async def until_equals(
self,
right: _R,
timeout: float = REACTPY_TESTS_DEFAULT_TIMEOUT.current,
delay: float = _DEFAULT_POLL_DELAY,
) -> None:
"""Wait until the result is equal to the given value"""
return await self.until(
lambda left: left == right,
... | Wait until the result is equal to the given value | until_equals | python | reactive-python/reactpy | src/reactpy/testing/common.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/testing/common.py | MIT |
def capture(self, render_function: Callable[..., Any]) -> Callable[..., Any]:
"""Decorator for capturing a ``LifeCycleHook`` on each render of a component"""
# The render function holds a reference to `self` and, via the `LifeCycleHook`,
# the component. Some tests check whether components are ... | Decorator for capturing a ``LifeCycleHook`` on each render of a component | capture | python | reactive-python/reactpy | src/reactpy/testing/common.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/testing/common.py | MIT |
def assert_reactpy_did_log(
match_message: str = "",
error_type: type[Exception] | None = None,
match_error: str = "",
) -> Iterator[None]:
"""Assert that ReactPy produced a log matching the described message or error.
Args:
match_message: Must match a logged message.
error_type: Ch... | Assert that ReactPy produced a log matching the described message or error.
Args:
match_message: Must match a logged message.
error_type: Checks the type of logged exceptions.
match_error: Must match an error message.
| assert_reactpy_did_log | python | reactive-python/reactpy | src/reactpy/testing/logs.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/testing/logs.py | MIT |
def list_logged_exceptions(
log_records: list[logging.LogRecord],
pattern: str = "",
types: type[Any] | tuple[type[Any], ...] = Exception,
log_level: int = logging.ERROR,
del_log_records: bool = True,
) -> list[BaseException]:
"""Return a list of logged exception matching the given criteria
... | Return a list of logged exception matching the given criteria
Args:
log_level: The level of log to check
exclude_exc_types: Any exception types to ignore
del_log_records: Whether to delete the log records for yielded exceptions
| list_logged_exceptions | python | reactive-python/reactpy | src/reactpy/testing/logs.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/testing/logs.py | MIT |
def capture_reactpy_logs() -> Iterator[list[logging.LogRecord]]:
"""Capture logs from ReactPy
Any logs produced in this context are cleared afterwards
"""
original_level = ROOT_LOGGER.level
ROOT_LOGGER.setLevel(logging.DEBUG)
try:
if _LOG_RECORD_CAPTOR in ROOT_LOGGER.handlers:
... | Capture logs from ReactPy
Any logs produced in this context are cleared afterwards
| capture_reactpy_logs | python | reactive-python/reactpy | src/reactpy/testing/logs.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/testing/logs.py | MIT |
def find_available_port(
host: str, port_min: int = 8000, port_max: int = 9000
) -> int: # nocov
"""Get a port that's available for the given host and port range"""
for port in range(port_min, port_max):
with closing(socket.socket()) as sock:
try:
if sys.platform in ("li... | Get a port that's available for the given host and port range | find_available_port | python | reactive-python/reactpy | src/reactpy/testing/utils.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/testing/utils.py | MIT |
def module_from_url(
url: str,
fallback: Any | None = None,
resolve_exports: bool | None = None,
resolve_exports_depth: int = 5,
unmount_before_update: bool = False,
) -> WebModule:
"""Load a :class:`WebModule` from a :data:`URL_SOURCE`
Parameters:
url:
Where the javascr... | Load a :class:`WebModule` from a :data:`URL_SOURCE`
Parameters:
url:
Where the javascript module will be loaded from which conforms to the
interface for :ref:`Custom Javascript Components`
fallback:
What to temporarily display while the module is being loaded.
... | module_from_url | python | reactive-python/reactpy | src/reactpy/web/module.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/web/module.py | MIT |
def module_from_file(
name: str,
file: str | Path,
fallback: Any | None = None,
resolve_exports: bool | None = None,
resolve_exports_depth: int = 5,
unmount_before_update: bool = False,
symlink: bool = False,
) -> WebModule:
"""Load a :class:`WebModule` from a given ``file``
Paramet... | Load a :class:`WebModule` from a given ``file``
Parameters:
name:
The name of the package
file:
The file from which the content of the web module will be created.
fallback:
What to temporarily display while the module is being loaded.
resolve_impo... | module_from_file | python | reactive-python/reactpy | src/reactpy/web/module.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/web/module.py | MIT |
def module_from_string(
name: str,
content: str,
fallback: Any | None = None,
resolve_exports: bool | None = None,
resolve_exports_depth: int = 5,
unmount_before_update: bool = False,
) -> WebModule:
"""Load a :class:`WebModule` whose ``content`` comes from a string.
Parameters:
... | Load a :class:`WebModule` whose ``content`` comes from a string.
Parameters:
name:
The name of the package
content:
The contents of the web module
fallback:
What to temporarily display while the module is being loaded.
resolve_imports:
... | module_from_string | python | reactive-python/reactpy | src/reactpy/web/module.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/web/module.py | MIT |
def export(
web_module: WebModule,
export_names: str | list[str] | tuple[str, ...],
fallback: Any | None = None,
allow_children: bool = True,
) -> VdomConstructor | list[VdomConstructor]:
"""Return one or more VDOM constructors from a :class:`WebModule`
Parameters:
export_names:
... | Return one or more VDOM constructors from a :class:`WebModule`
Parameters:
export_names:
One or more names to export. If given as a string, a single component
will be returned. If a list is given, then a list of components will be
returned.
fallback:
... | export | python | reactive-python/reactpy | src/reactpy/web/module.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/web/module.py | MIT |
def rewrite_props(paths: list[str]) -> None:
"""Rewrite snake_case props to camelCase within <PATHS>."""
for p in map(Path, paths):
# Process each file or recursively process each Python file in directories
for f in [p] if p.is_file() else p.rglob("*.py"):
result = generate_rewrite(f... | Rewrite snake_case props to camelCase within <PATHS>. | rewrite_props | python | reactive-python/reactpy | src/reactpy/_console/rewrite_props.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/_console/rewrite_props.py | MIT |
def generate_rewrite(file: Path, source: str) -> str | None:
"""Generate the rewritten source code if changes are detected"""
tree = ast.parse(source) # Parse the source code into an AST
changed = find_nodes_to_change(tree) # Find nodes that need to be changed
if not changed:
return None # R... | Generate the rewritten source code if changes are detected | generate_rewrite | python | reactive-python/reactpy | src/reactpy/_console/rewrite_props.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/_console/rewrite_props.py | MIT |
def find_nodes_to_change(tree: ast.AST) -> list[ChangedNode]:
"""Find nodes in the AST that need to be changed"""
changed: list[ChangedNode] = []
for el_info in find_element_constructor_usages(tree):
# Check if the props need to be rewritten
if _rewrite_props(el_info.props, _construct_prop_i... | Find nodes in the AST that need to be changed | find_nodes_to_change | python | reactive-python/reactpy | src/reactpy/_console/rewrite_props.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/_console/rewrite_props.py | MIT |
def _construct_prop_item(key: str, value: ast.expr) -> tuple[str, ast.expr]:
"""Construct a new prop item with the converted key and possibly modified value"""
if key == "style" and isinstance(value, (ast.Dict, ast.Call)):
# Create a copy of the value to avoid modifying the original
new_value = ... | Construct a new prop item with the converted key and possibly modified value | _construct_prop_item | python | reactive-python/reactpy | src/reactpy/_console/rewrite_props.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/_console/rewrite_props.py | MIT |
def _rewrite_props(
props_node: ast.Dict | ast.Call,
constructor: Callable[[str, ast.expr], tuple[str, ast.expr]],
) -> bool:
"""Rewrite the props in the given AST node using the provided constructor"""
did_change = False
if isinstance(props_node, ast.Dict):
keys: list[ast.expr | None] = []
... | Rewrite the props in the given AST node using the provided constructor | _rewrite_props | python | reactive-python/reactpy | src/reactpy/_console/rewrite_props.py | https://github.com/reactive-python/reactpy/blob/master/src/reactpy/_console/rewrite_props.py | MIT |
def create_hook_state():
"""This fixture is a bug fix related to `pytest_asyncio`.
Usually the hook stack is created automatically within the display fixture, but context
variables aren't retained within `pytest_asyncio` async fixtures. As a workaround,
this fixture ensures that the hook stack is creat... | This fixture is a bug fix related to `pytest_asyncio`.
Usually the hook stack is created automatically within the display fixture, but context
variables aren't retained within `pytest_asyncio` async fixtures. As a workaround,
this fixture ensures that the hook stack is created before each test is run.
... | create_hook_state | python | reactive-python/reactpy | tests/conftest.py | https://github.com/reactive-python/reactpy/blob/master/tests/conftest.py | MIT |
async def test_style_can_be_changed(display: DisplayFixture):
"""This test was introduced to verify the client does not mutate the model
A bug was introduced where the client-side model was mutated and React was relying
on the model to have been copied in order to determine if something had changed.
S... | This test was introduced to verify the client does not mutate the model
A bug was introduced where the client-side model was mutated and React was relying
on the model to have been copied in order to determine if something had changed.
See for more info: https://github.com/reactive-python/reactpy/issues/4... | test_style_can_be_changed | python | reactive-python/reactpy | tests/test_client.py | https://github.com/reactive-python/reactpy/blob/master/tests/test_client.py | MIT |
async def test_slow_server_response_on_input_change(display: DisplayFixture):
"""A delay server-side could cause input values to be overwritten.
For more info see: https://github.com/reactive-python/reactpy/issues/684
"""
delay = 0.2
@reactpy.component
def SomeComponent():
value, set_... | A delay server-side could cause input values to be overwritten.
For more info see: https://github.com/reactive-python/reactpy/issues/684
| test_slow_server_response_on_input_change | python | reactive-python/reactpy | tests/test_client.py | https://github.com/reactive-python/reactpy/blob/master/tests/test_client.py | MIT |
async def test_hotswap_update_on_change(display: DisplayFixture):
"""Ensure shared hotswapping works
This basically means that previously rendered views of a hotswap component get updated
when a new view is mounted, not just the next time it is re-displayed
In this test we construct a scenario where c... | Ensure shared hotswapping works
This basically means that previously rendered views of a hotswap component get updated
when a new view is mounted, not just the next time it is re-displayed
In this test we construct a scenario where clicking a button will cause a pre-existing
hotswap component to be up... | test_hotswap_update_on_change | python | reactive-python/reactpy | tests/test_testing.py | https://github.com/reactive-python/reactpy/blob/master/tests/test_testing.py | MIT |
async def display(page):
"""Override for the display fixture that uses ReactPyMiddleware."""
templates = Jinja2Templates(
env=JinjaEnvironment(
loader=JinjaFileSystemLoader("tests/templates"),
extensions=["reactpy.templatetags.Jinja"],
)
)
async def homepage(requ... | Override for the display fixture that uses ReactPyMiddleware. | display | python | reactive-python/reactpy | tests/test_asgi/test_middleware.py | https://github.com/reactive-python/reactpy/blob/master/tests/test_asgi/test_middleware.py | MIT |
async def poll_location():
"""This needs to be async to allow the server to respond"""
return getattr(location, "current", None) | This needs to be async to allow the server to respond | poll_location | python | reactive-python/reactpy | tests/test_asgi/test_standalone.py | https://github.com/reactive-python/reactpy/blob/master/tests/test_asgi/test_standalone.py | MIT |
async def test_element_keys_inside_components_do_not_reset_state_of_component():
"""This is a regression test for a bug.
You would not expect that calling `set_child_key_num` would trigger state to be
reset in any `Child()` components but there was a bug where that happened.
"""
effect_calls_witho... | This is a regression test for a bug.
You would not expect that calling `set_child_key_num` would trigger state to be
reset in any `Child()` components but there was a bug where that happened.
| test_element_keys_inside_components_do_not_reset_state_of_component | python | reactive-python/reactpy | tests/test_core/test_layout.py | https://github.com/reactive-python/reactpy/blob/master/tests/test_core/test_layout.py | MIT |
async def test_does_render_children_after_component():
"""Regression test for bug where layout was appending children to a stale ref
The stale reference was created when a component got rendered. Thus, everything
after the component failed to display.
"""
@reactpy.component
def Parent():
... | Regression test for bug where layout was appending children to a stale ref
The stale reference was created when a component got rendered. Thus, everything
after the component failed to display.
| test_does_render_children_after_component | python | reactive-python/reactpy | tests/test_core/test_layout.py | https://github.com/reactive-python/reactpy/blob/master/tests/test_core/test_layout.py | MIT |
async def test_ensure_model_path_udpates():
"""
This is regression test for a bug in which we failed to update the path of a bug
that arose when the "path" of a component within the overall model was not updated
when the component changes position amongst its siblings. This meant that when
a compone... |
This is regression test for a bug in which we failed to update the path of a bug
that arose when the "path" of a component within the overall model was not updated
when the component changes position amongst its siblings. This meant that when
a component whose position had changed would attempt to upda... | test_ensure_model_path_udpates | python | reactive-python/reactpy | tests/test_core/test_layout.py | https://github.com/reactive-python/reactpy/blob/master/tests/test_core/test_layout.py | MIT |
async def test_keys_properly_propagated(display: DisplayFixture):
"""
Fix https://github.com/reactive-python/reactpy/issues/1275
The `key` property was being lost in its propagation from the server-side ReactPy
definition to the front-end JavaScript.
This property is required for certain JS compon... |
Fix https://github.com/reactive-python/reactpy/issues/1275
The `key` property was being lost in its propagation from the server-side ReactPy
definition to the front-end JavaScript.
This property is required for certain JS components, such as the GridLayout from
react-grid-layout.
| test_keys_properly_propagated | python | reactive-python/reactpy | tests/test_web/test_module.py | https://github.com/reactive-python/reactpy/blob/master/tests/test_web/test_module.py | MIT |
def find_element(
element: VdomJson,
selector: Selector,
*,
first: bool = False,
) -> tuple[VdomJson, ElementInfo]:
"""Find an element by a selector.
Parameters:
element:
The tree to search.
selector:
A function that returns True if the element matches.
... | Find an element by a selector.
Parameters:
element:
The tree to search.
selector:
A function that returns True if the element matches.
first:
If True, return the first element found. If False, raise an error if
multiple elements are found.
... | find_element | python | reactive-python/reactpy | tests/tooling/select.py | https://github.com/reactive-python/reactpy/blob/master/tests/tooling/select.py | MIT |
def find_elements(
element: VdomJson, selector: Selector
) -> Iterator[tuple[VdomJson, ElementInfo]]:
"""Find an element by a selector.
Parameters:
element:
The tree to search.
selector:
A function that returns True if the element matches.
Returns:
Eleme... | Find an element by a selector.
Parameters:
element:
The tree to search.
selector:
A function that returns True if the element matches.
Returns:
Element info, or None if not found.
| find_elements | python | reactive-python/reactpy | tests/tooling/select.py | https://github.com/reactive-python/reactpy/blob/master/tests/tooling/select.py | MIT |
def __load_fingerprinted_audio_hashes(self) -> None:
"""
Keeps a dictionary with the hashes of the fingerprinted songs, in that way is possible to check
whether or not an audio file was already processed.
"""
# get songs previously indexed
self.songs = self.db.get_songs()... |
Keeps a dictionary with the hashes of the fingerprinted songs, in that way is possible to check
whether or not an audio file was already processed.
| __load_fingerprinted_audio_hashes | python | worldveil/dejavu | dejavu/__init__.py | https://github.com/worldveil/dejavu/blob/master/dejavu/__init__.py | MIT |
def fingerprint_directory(self, path: str, extensions: str, nprocesses: int = None) -> None:
"""
Given a directory and a set of extensions it fingerprints all files that match each extension specified.
:param path: path to the directory.
:param extensions: list of file extensions to con... |
Given a directory and a set of extensions it fingerprints all files that match each extension specified.
:param path: path to the directory.
:param extensions: list of file extensions to consider.
:param nprocesses: amount of processes to fingerprint the files within the directory.
... | fingerprint_directory | python | worldveil/dejavu | dejavu/__init__.py | https://github.com/worldveil/dejavu/blob/master/dejavu/__init__.py | MIT |
def fingerprint_file(self, file_path: str, song_name: str = None) -> None:
"""
Given a path to a file the method generates hashes for it and stores them in the database
for later be queried.
:param file_path: path to the file.
:param song_name: song name associated to the audio ... |
Given a path to a file the method generates hashes for it and stores them in the database
for later be queried.
:param file_path: path to the file.
:param song_name: song name associated to the audio file.
| fingerprint_file | python | worldveil/dejavu | dejavu/__init__.py | https://github.com/worldveil/dejavu/blob/master/dejavu/__init__.py | MIT |
def generate_fingerprints(self, samples: List[int], Fs=DEFAULT_FS) -> Tuple[List[Tuple[str, int]], float]:
f"""
Generate the fingerprints for the given sample data (channel).
:param samples: list of ints which represents the channel info of the given audio file.
:param Fs: sampling rate... |
Generate the fingerprints for the given sample data (channel).
:param samples: list of ints which represents the channel info of the given audio file.
:param Fs: sampling rate which defaults to {DEFAULT_FS}.
:return: a list of tuples for hash and its corresponding offset, together with... | generate_fingerprints | python | worldveil/dejavu | dejavu/__init__.py | https://github.com/worldveil/dejavu/blob/master/dejavu/__init__.py | MIT |
def find_matches(self, hashes: List[Tuple[str, int]]) -> Tuple[List[Tuple[int, int]], Dict[str, int], float]:
"""
Finds the corresponding matches on the fingerprinted audios for the given hashes.
:param hashes: list of tuples for hashes and their corresponding offsets
:return: a tuple c... |
Finds the corresponding matches on the fingerprinted audios for the given hashes.
:param hashes: list of tuples for hashes and their corresponding offsets
:return: a tuple containing the matches found against the db, a dictionary which counts the different
hashes matched for each song... | find_matches | python | worldveil/dejavu | dejavu/__init__.py | https://github.com/worldveil/dejavu/blob/master/dejavu/__init__.py | MIT |
def align_matches(self, matches: List[Tuple[int, int]], dedup_hashes: Dict[str, int], queried_hashes: int,
topn: int = TOPN) -> List[Dict[str, any]]:
"""
Finds hash matches that align in time with other matches and finds
consensus about which hashes are "true" signal from t... |
Finds hash matches that align in time with other matches and finds
consensus about which hashes are "true" signal from the audio.
:param matches: matches from the database
:param dedup_hashes: dictionary containing the hashes matched without duplicates for each song
(key is the... | align_matches | python | worldveil/dejavu | dejavu/__init__.py | https://github.com/worldveil/dejavu/blob/master/dejavu/__init__.py | MIT |
def insert_hashes(self, song_id: int, hashes: List[Tuple[str, int]], batch_size: int = 1000) -> None:
"""
Insert a multitude of fingerprints.
:param song_id: Song identifier the fingerprints belong to
:param hashes: A sequence of tuples in the format (hash, offset)
- hash: P... |
Insert a multitude of fingerprints.
:param song_id: Song identifier the fingerprints belong to
:param hashes: A sequence of tuples in the format (hash, offset)
- hash: Part of a sha1 hash, in hexadecimal format
- offset: Offset this hash was created from/at.
:pa... | insert_hashes | python | worldveil/dejavu | dejavu/base_classes/base_database.py | https://github.com/worldveil/dejavu/blob/master/dejavu/base_classes/base_database.py | MIT |
def return_matches(self, hashes: List[Tuple[str, int]], batch_size: int = 1000) \
-> Tuple[List[Tuple[int, int]], Dict[int, int]]:
"""
Searches the database for pairs of (hash, offset) values.
:param hashes: A sequence of tuples in the format (hash, offset)
- hash: Part ... |
Searches the database for pairs of (hash, offset) values.
:param hashes: A sequence of tuples in the format (hash, offset)
- hash: Part of a sha1 hash, in hexadecimal format
- offset: Offset this hash was created from/at.
:param batch_size: number of query's batches.
... | return_matches | python | worldveil/dejavu | dejavu/base_classes/base_database.py | https://github.com/worldveil/dejavu/blob/master/dejavu/base_classes/base_database.py | MIT |
def get_database(database_type: str = "mysql") -> BaseDatabase:
"""
Given a database type it returns a database instance for that type.
:param database_type: type of the database.
:return: an instance of BaseDatabase depending on given database_type.
"""
try:
path, db_class_name = DATAB... |
Given a database type it returns a database instance for that type.
:param database_type: type of the database.
:return: an instance of BaseDatabase depending on given database_type.
| get_database | python | worldveil/dejavu | dejavu/base_classes/base_database.py | https://github.com/worldveil/dejavu/blob/master/dejavu/base_classes/base_database.py | MIT |
def setup(self) -> None:
"""
Called on creation or shortly afterwards.
"""
with self.cursor() as cur:
cur.execute(self.CREATE_SONGS_TABLE)
cur.execute(self.CREATE_FINGERPRINTS_TABLE)
cur.execute(self.DELETE_UNFINGERPRINTED) |
Called on creation or shortly afterwards.
| setup | python | worldveil/dejavu | dejavu/base_classes/common_database.py | https://github.com/worldveil/dejavu/blob/master/dejavu/base_classes/common_database.py | MIT |
def empty(self) -> None:
"""
Called when the database should be cleared of all data.
"""
with self.cursor() as cur:
cur.execute(self.DROP_FINGERPRINTS)
cur.execute(self.DROP_SONGS)
self.setup() |
Called when the database should be cleared of all data.
| empty | python | worldveil/dejavu | dejavu/base_classes/common_database.py | https://github.com/worldveil/dejavu/blob/master/dejavu/base_classes/common_database.py | MIT |
def get_num_songs(self) -> int:
"""
Returns the song's count stored.
:return: the amount of songs in the database.
"""
with self.cursor(buffered=True) as cur:
cur.execute(self.SELECT_UNIQUE_SONG_IDS)
count = cur.fetchone()[0] if cur.rowcount != 0 else 0
... |
Returns the song's count stored.
:return: the amount of songs in the database.
| get_num_songs | python | worldveil/dejavu | dejavu/base_classes/common_database.py | https://github.com/worldveil/dejavu/blob/master/dejavu/base_classes/common_database.py | MIT |
def get_num_fingerprints(self) -> int:
"""
Returns the fingerprints' count stored.
:return: the number of fingerprints in the database.
"""
with self.cursor(buffered=True) as cur:
cur.execute(self.SELECT_NUM_FINGERPRINTS)
count = cur.fetchone()[0] if cur.... |
Returns the fingerprints' count stored.
:return: the number of fingerprints in the database.
| get_num_fingerprints | python | worldveil/dejavu | dejavu/base_classes/common_database.py | https://github.com/worldveil/dejavu/blob/master/dejavu/base_classes/common_database.py | MIT |
def get_songs(self) -> List[Dict[str, str]]:
"""
Returns all fully fingerprinted songs in the database
:return: a dictionary with the songs info.
"""
with self.cursor(dictionary=True) as cur:
cur.execute(self.SELECT_SONGS)
return list(cur) |
Returns all fully fingerprinted songs in the database
:return: a dictionary with the songs info.
| get_songs | python | worldveil/dejavu | dejavu/base_classes/common_database.py | https://github.com/worldveil/dejavu/blob/master/dejavu/base_classes/common_database.py | MIT |
def get_song_by_id(self, song_id: int) -> Dict[str, str]:
"""
Brings the song info from the database.
:param song_id: song identifier.
:return: a song by its identifier. Result must be a Dictionary.
"""
with self.cursor(dictionary=True) as cur:
cur.execute(se... |
Brings the song info from the database.
:param song_id: song identifier.
:return: a song by its identifier. Result must be a Dictionary.
| get_song_by_id | python | worldveil/dejavu | dejavu/base_classes/common_database.py | https://github.com/worldveil/dejavu/blob/master/dejavu/base_classes/common_database.py | MIT |
def insert(self, fingerprint: str, song_id: int, offset: int):
"""
Inserts a single fingerprint into the database.
:param fingerprint: Part of a sha1 hash, in hexadecimal format
:param song_id: Song identifier this fingerprint is off
:param offset: The offset this fingerprint is... |
Inserts a single fingerprint into the database.
:param fingerprint: Part of a sha1 hash, in hexadecimal format
:param song_id: Song identifier this fingerprint is off
:param offset: The offset this fingerprint is from.
| insert | python | worldveil/dejavu | dejavu/base_classes/common_database.py | https://github.com/worldveil/dejavu/blob/master/dejavu/base_classes/common_database.py | MIT |
def query(self, fingerprint: str = None) -> List[Tuple]:
"""
Returns all matching fingerprint entries associated with
the given hash as parameter, if None is passed it returns all entries.
:param fingerprint: part of a sha1 hash, in hexadecimal format
:return: a list of fingerpr... |
Returns all matching fingerprint entries associated with
the given hash as parameter, if None is passed it returns all entries.
:param fingerprint: part of a sha1 hash, in hexadecimal format
:return: a list of fingerprint records stored in the db.
| query | python | worldveil/dejavu | dejavu/base_classes/common_database.py | https://github.com/worldveil/dejavu/blob/master/dejavu/base_classes/common_database.py | MIT |
def delete_songs_by_id(self, song_ids: List[int], batch_size: int = 1000) -> None:
"""
Given a list of song ids it deletes all songs specified and their corresponding fingerprints.
:param song_ids: song ids to be deleted from the database.
:param batch_size: number of query's batches.
... |
Given a list of song ids it deletes all songs specified and their corresponding fingerprints.
:param song_ids: song ids to be deleted from the database.
:param batch_size: number of query's batches.
| delete_songs_by_id | python | worldveil/dejavu | dejavu/base_classes/common_database.py | https://github.com/worldveil/dejavu/blob/master/dejavu/base_classes/common_database.py | MIT |
def insert_song(self, song_name: str, file_hash: str, total_hashes: int) -> int:
"""
Inserts a song name into the database, returns the new
identifier of the song.
:param song_name: The name of the song.
:param file_hash: Hash from the fingerprinted file.
:param total_ha... |
Inserts a song name into the database, returns the new
identifier of the song.
:param song_name: The name of the song.
:param file_hash: Hash from the fingerprinted file.
:param total_hashes: amount of hashes to be inserted on fingerprint table.
:return: the inserted id... | insert_song | python | worldveil/dejavu | dejavu/database_handler/mysql_database.py | https://github.com/worldveil/dejavu/blob/master/dejavu/database_handler/mysql_database.py | MIT |
def unique_hash(file_path: str, block_size: int = 2**20) -> str:
""" Small function to generate a hash to uniquely generate
a file. Inspired by MD5 version here:
http://stackoverflow.com/a/1131255/712997
Works with large files.
:param file_path: path to file.
:param block_size: read block size... | Small function to generate a hash to uniquely generate
a file. Inspired by MD5 version here:
http://stackoverflow.com/a/1131255/712997
Works with large files.
:param file_path: path to file.
:param block_size: read block size.
:return: a hash in an hexagesimal string form.
| unique_hash | python | worldveil/dejavu | dejavu/logic/decoder.py | https://github.com/worldveil/dejavu/blob/master/dejavu/logic/decoder.py | MIT |
def find_files(path: str, extensions: List[str]) -> List[Tuple[str, str]]:
"""
Get all files that meet the specified extensions.
:param path: path to a directory with audio files.
:param extensions: file extensions to look for.
:return: a list of tuples with file name and its extension.
"""
... |
Get all files that meet the specified extensions.
:param path: path to a directory with audio files.
:param extensions: file extensions to look for.
:return: a list of tuples with file name and its extension.
| find_files | python | worldveil/dejavu | dejavu/logic/decoder.py | https://github.com/worldveil/dejavu/blob/master/dejavu/logic/decoder.py | MIT |
def fingerprint(channel_samples: List[int],
Fs: int = DEFAULT_FS,
wsize: int = DEFAULT_WINDOW_SIZE,
wratio: float = DEFAULT_OVERLAP_RATIO,
fan_value: int = DEFAULT_FAN_VALUE,
amp_min: int = DEFAULT_AMP_MIN) -> List[Tuple[str, int]]:
"""... |
FFT the channel, log transform output, find local maxima, then return locally sensitive hashes.
:param channel_samples: channel samples to fingerprint.
:param Fs: audio sampling rate.
:param wsize: FFT windows size.
:param wratio: ratio by which each sequential window overlaps the last and the nex... | fingerprint | python | worldveil/dejavu | dejavu/logic/fingerprint.py | https://github.com/worldveil/dejavu/blob/master/dejavu/logic/fingerprint.py | MIT |
def get_2D_peaks(arr2D: np.array, plot: bool = False, amp_min: int = DEFAULT_AMP_MIN)\
-> List[Tuple[List[int], List[int]]]:
"""
Extract maximum peaks from the spectogram matrix (arr2D).
:param arr2D: matrix representing the spectogram.
:param plot: for plotting the results.
:param amp_min:... |
Extract maximum peaks from the spectogram matrix (arr2D).
:param arr2D: matrix representing the spectogram.
:param plot: for plotting the results.
:param amp_min: minimum amplitude in spectrogram in order to be considered a peak.
:return: a list composed by a list of frequencies and times.
| get_2D_peaks | python | worldveil/dejavu | dejavu/logic/fingerprint.py | https://github.com/worldveil/dejavu/blob/master/dejavu/logic/fingerprint.py | MIT |
def generate_hashes(peaks: List[Tuple[int, int]], fan_value: int = DEFAULT_FAN_VALUE) -> List[Tuple[str, int]]:
"""
Hash list structure:
sha1_hash[0:FINGERPRINT_REDUCTION] time_offset
[(e05b341a9b77a51fd26, 32), ... ]
:param peaks: list of peak frequencies and times.
:param fan_value:... |
Hash list structure:
sha1_hash[0:FINGERPRINT_REDUCTION] time_offset
[(e05b341a9b77a51fd26, 32), ... ]
:param peaks: list of peak frequencies and times.
:param fan_value: degree to which a fingerprint can be paired with its neighbors.
:return: a list of hashes with their corresponding... | generate_hashes | python | worldveil/dejavu | dejavu/logic/fingerprint.py | https://github.com/worldveil/dejavu/blob/master/dejavu/logic/fingerprint.py | MIT |
def get_files_recursive(src, fmt):
"""
`src` is the source directory.
`fmt` is the extension, ie ".mp3" or "mp3", etc.
"""
files = []
for root, dirnames, filenames in walk(src):
for filename in fnmatch.filter(filenames, '*' + fmt):
files.append(join(root, filename))
retu... |
`src` is the source directory.
`fmt` is the extension, ie ".mp3" or "mp3", etc.
| get_files_recursive | python | worldveil/dejavu | dejavu/tests/dejavu_test.py | https://github.com/worldveil/dejavu/blob/master/dejavu/tests/dejavu_test.py | MIT |
def get_length_audio(audiopath, extension):
"""
Returns length of audio in seconds.
Returns None if format isn't supported or in case of error.
"""
try:
audio = AudioSegment.from_file(audiopath, extension.replace(".", ""))
except Exception:
print(f"Error in get_length_audio(): {t... |
Returns length of audio in seconds.
Returns None if format isn't supported or in case of error.
| get_length_audio | python | worldveil/dejavu | dejavu/tests/dejavu_test.py | https://github.com/worldveil/dejavu/blob/master/dejavu/tests/dejavu_test.py | MIT |
def _wav2array(nchannels, sampwidth, data):
"""data must be the string containing the bytes from the wav file."""
num_samples, remainder = divmod(len(data), sampwidth * nchannels)
if remainder > 0:
raise ValueError('The length of data is not a multiple of '
'sampwidth * num_... | data must be the string containing the bytes from the wav file. | _wav2array | python | worldveil/dejavu | dejavu/third_party/wavio.py | https://github.com/worldveil/dejavu/blob/master/dejavu/third_party/wavio.py | MIT |
def _array2wav(a, sampwidth):
"""
Convert the input array `a` to a string of WAV data.
a.dtype must be one of uint8, int16 or int32. Allowed sampwidth
values are:
dtype sampwidth
uint8 1
int16 2
int32 3 or 4
When sampwidth is 3, the *low* bytes ... |
Convert the input array `a` to a string of WAV data.
a.dtype must be one of uint8, int16 or int32. Allowed sampwidth
values are:
dtype sampwidth
uint8 1
int16 2
int32 3 or 4
When sampwidth is 3, the *low* bytes of `a` are assumed to contain
the... | _array2wav | python | worldveil/dejavu | dejavu/third_party/wavio.py | https://github.com/worldveil/dejavu/blob/master/dejavu/third_party/wavio.py | MIT |
def create(cls, **params: Unpack["Account.CreateParams"]) -> "Account":
"""
With [Connect](https://docs.stripe.com/docs/connect), you can create Stripe accounts for your users.
To do this, you'll first need to [register your platform](https://dashboard.stripe.com/account/applications/settings).
... |
With [Connect](https://docs.stripe.com/docs/connect), you can create Stripe accounts for your users.
To do this, you'll first need to [register your platform](https://dashboard.stripe.com/account/applications/settings).
If you've already collected information for your connected accounts, you [... | create | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def _cls_delete(
cls, sid: str, **params: Unpack["Account.DeleteParams"]
) -> "Account":
"""
With [Connect](https://docs.stripe.com/connect), you can delete accounts you manage.
Test-mode accounts can be deleted at any time.
Live-mode accounts where Stripe is responsible fo... |
With [Connect](https://docs.stripe.com/connect), you can delete accounts you manage.
Test-mode accounts can be deleted at any time.
Live-mode accounts where Stripe is responsible for negative account balances cannot be deleted, which includes Standard accounts. Live-mode accounts where your p... | _cls_delete | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def list(
cls, **params: Unpack["Account.ListParams"]
) -> ListObject["Account"]:
"""
Returns a list of accounts connected to your platform via [Connect](https://docs.stripe.com/docs/connect). If you're not a platform, the list is empty.
"""
result = cls._static_request(
... |
Returns a list of accounts connected to your platform via [Connect](https://docs.stripe.com/docs/connect). If you're not a platform, the list is empty.
| list | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def _cls_persons(
cls, account: str, **params: Unpack["Account.PersonsParams"]
) -> ListObject["Person"]:
"""
Returns a list of people associated with the account's legal entity. The people are returned sorted by creation date, with the most recent people appearing first.
"""
... |
Returns a list of people associated with the account's legal entity. The people are returned sorted by creation date, with the most recent people appearing first.
| _cls_persons | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def _cls_reject(
cls, account: str, **params: Unpack["Account.RejectParams"]
) -> "Account":
"""
With [Connect](https://docs.stripe.com/connect), you can reject accounts that you have flagged as suspicious.
Only accounts where your platform is liable for negative account balances, w... |
With [Connect](https://docs.stripe.com/connect), you can reject accounts that you have flagged as suspicious.
Only accounts where your platform is liable for negative account balances, which includes Custom and Express accounts, can be rejected. Test-mode accounts can be rejected at any time. Live-mod... | _cls_reject | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def list_capabilities(
cls, account: str, **params: Unpack["Account.ListCapabilitiesParams"]
) -> ListObject["Capability"]:
"""
Returns a list of capabilities associated with the account. The capabilities are returned sorted by creation date, with the most recent capability appearing first.
... |
Returns a list of capabilities associated with the account. The capabilities are returned sorted by creation date, with the most recent capability appearing first.
| list_capabilities | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def retrieve_capability(
cls,
account: str,
capability: str,
**params: Unpack["Account.RetrieveCapabilityParams"],
) -> "Capability":
"""
Retrieves information about the specified Account Capability.
"""
return cast(
"Capability",
... |
Retrieves information about the specified Account Capability.
| retrieve_capability | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def modify_capability(
cls,
account: str,
capability: str,
**params: Unpack["Account.ModifyCapabilityParams"],
) -> "Capability":
"""
Updates an existing Account Capability. Request or remove a capability by updating its requested parameter.
"""
return... |
Updates an existing Account Capability. Request or remove a capability by updating its requested parameter.
| modify_capability | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def delete_external_account(
cls,
account: str,
id: str,
**params: Unpack["Account.DeleteExternalAccountParams"],
) -> Union["BankAccount", "Card"]:
"""
Delete a specified external account for a given account.
"""
return cast(
Union["BankAc... |
Delete a specified external account for a given account.
| delete_external_account | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def retrieve_external_account(
cls,
account: str,
id: str,
**params: Unpack["Account.RetrieveExternalAccountParams"],
) -> Union["BankAccount", "Card"]:
"""
Retrieve a specified external account for a given account.
"""
return cast(
Union["... |
Retrieve a specified external account for a given account.
| retrieve_external_account | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def modify_external_account(
cls,
account: str,
id: str,
**params: Unpack["Account.ModifyExternalAccountParams"],
) -> Union["BankAccount", "Card"]:
"""
Updates the metadata, account holder name, account holder type of a bank account belonging to
a connected a... |
Updates the metadata, account holder name, account holder type of a bank account belonging to
a connected account and optionally sets it as the default for its currency. Other bank account
details are not editable by design.
You can only update bank accounts when [account.controller.re... | modify_external_account | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def list_external_accounts(
cls,
account: str,
**params: Unpack["Account.ListExternalAccountsParams"],
) -> ListObject[Union["BankAccount", "Card"]]:
"""
List external accounts for an account.
"""
return cast(
ListObject[Union["BankAccount", "Card"... |
List external accounts for an account.
| list_external_accounts | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def create_external_account(
cls,
account: str,
**params: Unpack["Account.CreateExternalAccountParams"],
) -> Union["BankAccount", "Card"]:
"""
Create an external account for a given account.
"""
return cast(
Union["BankAccount", "Card"],
... |
Create an external account for a given account.
| create_external_account | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def create_login_link(
cls, account: str, **params: Unpack["Account.CreateLoginLinkParams"]
) -> "LoginLink":
"""
Creates a login link for a connected account to access the Express Dashboard.
You can only create login links for accounts that use the [Express Dashboard](https://docs.... |
Creates a login link for a connected account to access the Express Dashboard.
You can only create login links for accounts that use the [Express Dashboard](https://docs.stripe.com/connect/express-dashboard) and are connected to your platform.
| create_login_link | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def delete_person(
cls,
account: str,
person: str,
**params: Unpack["Account.DeletePersonParams"],
) -> "Person":
"""
Deletes an existing person's relationship to the account's legal entity. Any person with a relationship for an account can be deleted through the API,... |
Deletes an existing person's relationship to the account's legal entity. Any person with a relationship for an account can be deleted through the API, except if the person is the account_opener. If your integration is using the executive parameter, you cannot delete the only verified executive on file.
... | delete_person | python | stripe/stripe-python | stripe/_account.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account.py | MIT |
def create(
cls, **params: Unpack["AccountLink.CreateParams"]
) -> "AccountLink":
"""
Creates an AccountLink object that includes a single-use Stripe URL that the platform can redirect their user to in order to take them through the Connect Onboarding flow.
"""
return cast(
... |
Creates an AccountLink object that includes a single-use Stripe URL that the platform can redirect their user to in order to take them through the Connect Onboarding flow.
| create | python | stripe/stripe-python | stripe/_account_link.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account_link.py | MIT |
def retrieve(
self,
account: str,
params: "AccountService.RetrieveParams" = {},
options: RequestOptions = {},
) -> Account:
"""
Retrieves the details of an account.
"""
return cast(
Account,
self._request(
"get",... |
Retrieves the details of an account.
| retrieve | python | stripe/stripe-python | stripe/_account_service.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account_service.py | MIT |
def update(
self,
account: str,
params: "AccountService.UpdateParams" = {},
options: RequestOptions = {},
) -> Account:
"""
Updates a [connected account](https://docs.stripe.com/connect/accounts) by setting the values of the parameters passed. Any parameters not provi... |
Updates a [connected account](https://docs.stripe.com/connect/accounts) by setting the values of the parameters passed. Any parameters not provided are
left unchanged.
For accounts where [controller.requirement_collection](https://docs.stripe.com/api/accounts/object#account_object-controller-r... | update | python | stripe/stripe-python | stripe/_account_service.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account_service.py | MIT |
def create(
cls, **params: Unpack["AccountSession.CreateParams"]
) -> "AccountSession":
"""
Creates a AccountSession object that includes a single-use token that the platform can use on their front-end to grant client-side API access.
"""
return cast(
"AccountSess... |
Creates a AccountSession object that includes a single-use token that the platform can use on their front-end to grant client-side API access.
| create | python | stripe/stripe-python | stripe/_account_session.py | https://github.com/stripe/stripe-python/blob/master/stripe/_account_session.py | MIT |
def _global_instance(cls):
"""
Returns the singleton instance of _APIRequestor, to be used when
calling a static method such as stripe.Customer.create(...)
"""
# Lazily initialize.
if cls._instance is None:
cls._instance = cls(options=_GlobalRequestorOptions(... |
Returns the singleton instance of _APIRequestor, to be used when
calling a static method such as stripe.Customer.create(...)
| _global_instance | python | stripe/stripe-python | stripe/_api_requestor.py | https://github.com/stripe/stripe-python/blob/master/stripe/_api_requestor.py | MIT |
def _args_for_request_with_retries(
self,
method: str,
url: str,
params: Optional[Mapping[str, Any]] = None,
options: Optional[RequestOptions] = None,
*,
base_address: BaseAddress,
api_mode: ApiMode,
usage: Optional[List[str]] = None,
):
... |
Mechanism for issuing an API call. Used by request_raw and request_raw_async.
| _args_for_request_with_retries | python | stripe/stripe-python | stripe/_api_requestor.py | https://github.com/stripe/stripe-python/blob/master/stripe/_api_requestor.py | MIT |
async def request_raw_async(
self,
method: str,
url: str,
params: Optional[Mapping[str, Any]] = None,
options: Optional[RequestOptions] = None,
is_streaming: bool = False,
*,
base_address: BaseAddress,
api_mode: ApiMode,
usage: Optional[Lis... |
Mechanism for issuing an API call
| request_raw_async | python | stripe/stripe-python | stripe/_api_requestor.py | https://github.com/stripe/stripe-python/blob/master/stripe/_api_requestor.py | MIT |
def list(
cls, **params: Unpack["ApplicationFee.ListParams"]
) -> ListObject["ApplicationFee"]:
"""
Returns a list of application fees you've previously collected. The application fees are returned in sorted order, with the most recent fees appearing first.
"""
result = cls._... |
Returns a list of application fees you've previously collected. The application fees are returned in sorted order, with the most recent fees appearing first.
| list | python | stripe/stripe-python | stripe/_application_fee.py | https://github.com/stripe/stripe-python/blob/master/stripe/_application_fee.py | MIT |
def _cls_refund(
cls, id: str, **params: Unpack["ApplicationFee.RefundParams"]
) -> "ApplicationFeeRefund":
"""
Refunds an application fee that has previously been collected but not yet refunded.
Funds will be refunded to the Stripe account from which the fee was originally collected... |
Refunds an application fee that has previously been collected but not yet refunded.
Funds will be refunded to the Stripe account from which the fee was originally collected.
You can optionally refund only part of an application fee.
You can do so multiple times, until the entire fee ha... | _cls_refund | python | stripe/stripe-python | stripe/_application_fee.py | https://github.com/stripe/stripe-python/blob/master/stripe/_application_fee.py | MIT |
def retrieve(
cls, id: str, **params: Unpack["ApplicationFee.RetrieveParams"]
) -> "ApplicationFee":
"""
Retrieves the details of an application fee that your account has collected. The same information is returned when refunding the application fee.
"""
instance = cls(id, **... |
Retrieves the details of an application fee that your account has collected. The same information is returned when refunding the application fee.
| retrieve | python | stripe/stripe-python | stripe/_application_fee.py | https://github.com/stripe/stripe-python/blob/master/stripe/_application_fee.py | MIT |
def retrieve_refund(
cls,
fee: str,
id: str,
**params: Unpack["ApplicationFee.RetrieveRefundParams"],
) -> "ApplicationFeeRefund":
"""
By default, you can see the 10 most recent refunds stored directly on the application fee object, but you can also retrieve details a... |
By default, you can see the 10 most recent refunds stored directly on the application fee object, but you can also retrieve details about a specific refund stored on the application fee.
| retrieve_refund | python | stripe/stripe-python | stripe/_application_fee.py | https://github.com/stripe/stripe-python/blob/master/stripe/_application_fee.py | MIT |
def modify_refund(
cls,
fee: str,
id: str,
**params: Unpack["ApplicationFee.ModifyRefundParams"],
) -> "ApplicationFeeRefund":
"""
Updates the specified application fee refund by setting the values of the parameters passed. Any parameters not provided will be left unc... |
Updates the specified application fee refund by setting the values of the parameters passed. Any parameters not provided will be left unchanged.
This request only accepts metadata as an argument.
| modify_refund | python | stripe/stripe-python | stripe/_application_fee.py | https://github.com/stripe/stripe-python/blob/master/stripe/_application_fee.py | MIT |
def retrieve(cls, **params: Unpack["Balance.RetrieveParams"]) -> "Balance":
"""
Retrieves the current account balance, based on the authentication that was used to make the request.
For a sample request, see [Accounting for negative balances](https://docs.stripe.com/docs/connect/account-balance... |
Retrieves the current account balance, based on the authentication that was used to make the request.
For a sample request, see [Accounting for negative balances](https://docs.stripe.com/docs/connect/account-balances#accounting-for-negative-balances).
| retrieve | python | stripe/stripe-python | stripe/_balance.py | https://github.com/stripe/stripe-python/blob/master/stripe/_balance.py | MIT |
def retrieve(
cls, id: str, **params: Unpack["BalanceTransaction.RetrieveParams"]
) -> "BalanceTransaction":
"""
Retrieves the balance transaction with the given ID.
Note that this endpoint previously used the path /v1/balance/history/:id.
"""
instance = cls(id, **pa... |
Retrieves the balance transaction with the given ID.
Note that this endpoint previously used the path /v1/balance/history/:id.
| retrieve | python | stripe/stripe-python | stripe/_balance_transaction.py | https://github.com/stripe/stripe-python/blob/master/stripe/_balance_transaction.py | MIT |
def _cls_capture(
cls, charge: str, **params: Unpack["Charge.CaptureParams"]
) -> "Charge":
"""
Capture the payment of an existing, uncaptured charge that was created with the capture option set to false.
Uncaptured payments expire a set number of days after they are created ([7 by ... |
Capture the payment of an existing, uncaptured charge that was created with the capture option set to false.
Uncaptured payments expire a set number of days after they are created ([7 by default](https://docs.stripe.com/docs/charges/placing-a-hold)), after which they are marked as refunded and capture... | _cls_capture | python | stripe/stripe-python | stripe/_charge.py | https://github.com/stripe/stripe-python/blob/master/stripe/_charge.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.