response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Parse command line arguments.
def parse_args(args: Optional[Sequence[str]] = None) -> argparse.Namespace: """Parse command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument("--stdio", action="store_true") parser.add_argument("--socket", type=int, default=None) parser.add_argument("--pipe", type=str, defau...
Convert bytes to string as needed.
def to_str(text) -> str: """Convert bytes to string as needed.""" return text.decode("utf-8") if isinstance(text, bytes) else text
Creates JSON-RPC wrapper for the readable and writable streams.
def create_json_rpc(readable: BinaryIO, writable: BinaryIO) -> JsonRpc: """Creates JSON-RPC wrapper for the readable and writable streams.""" return JsonRpc(readable, writable)
Gets an existing JSON-RPC connection or starts one and return it.
def get_or_start_json_rpc( workspace: str, interpreter: Sequence[str], cwd: str, env: Optional[Dict[str, str]] = None, ) -> Union[JsonRpc, None]: """Gets an existing JSON-RPC connection or starts one and return it.""" res = _get_json_rpc(workspace) if not res: args = [*interpreter, R...
Uses JSON-RPC to execute a command.
def run_over_json_rpc( workspace: str, interpreter: Sequence[str], module: str, argv: Sequence[str], use_stdin: bool, cwd: str, source: Optional[str] = None, env: Optional[Dict[str, str]] = None, ) -> RpcRunResult: """Uses JSON-RPC to execute a command.""" rpc: Union[JsonRpc, Non...
Shutdown all JSON-RPC processes.
def shutdown_json_rpc(): """Shutdown all JSON-RPC processes.""" _process_manager.stop_all_processes()
Add given path to `sys.path`.
def update_sys_path(path_to_add: str, strategy: str) -> None: """Add given path to `sys.path`.""" if path_to_add not in sys.path and os.path.isdir(path_to_add): if strategy == "useBundled": sys.path.insert(0, path_to_add) else: sys.path.append(path_to_add)
Add given path to `sys.path`.
def update_sys_path(path_to_add: str, strategy: str) -> None: """Add given path to `sys.path`.""" if path_to_add not in sys.path and os.path.isdir(path_to_add): if strategy == "useBundled": sys.path.insert(0, path_to_add) else: sys.path.append(path_to_add)
Update PATH environment variable with the 'scripts' directory. Windows: .venv/Scripts Linux/MacOS: .venv/bin
def update_environ_path() -> None: """Update PATH environment variable with the 'scripts' directory. Windows: .venv/Scripts Linux/MacOS: .venv/bin """ scripts = sysconfig.get_path("scripts") paths_variants = ["Path", "PATH"] for var_name in paths_variants: if var_name in os.environ...
LSP handler for textDocument/formatting request.
def formatting(params: lsp.DocumentFormattingParams) -> list[lsp.TextEdit] | None: """LSP handler for textDocument/formatting request.""" document = LSP_SERVER.workspace.get_text_document(params.text_document.uri) return _formatting_helper(document)
LSP handler for textDocument/rangeFormatting request.
def range_formatting( params: lsp.DocumentRangeFormattingParams, ) -> list[lsp.TextEdit] | None: """LSP handler for textDocument/rangeFormatting request.""" document = LSP_SERVER.workspace.get_text_document(params.text_document.uri) settings = _get_settings_by_document(document) version = VERSION_LO...
LSP handler for textDocument/rangesFormatting request.
def ranges_formatting( params: lsp.DocumentRangesFormattingParams, ) -> list[lsp.TextEdit] | None: """LSP handler for textDocument/rangesFormatting request.""" document = LSP_SERVER.workspace.get_text_document(params.text_document.uri) settings = _get_settings_by_document(document) version = VERSION...
Ensures that the code provided is python.
def is_python(code: str, file_path: str) -> bool: """Ensures that the code provided is python.""" try: ast.parse(code, file_path) except SyntaxError: log_error(f"Syntax error in code: {traceback.format_exc()}") return False return True
Gets or generates a file name to use with black when formatting.
def _get_filename_for_black(document: workspace.Document) -> str: """Gets or generates a file name to use with black when formatting.""" if document.uri.startswith("vscode-notebook-cell") and document.path.endswith( ".ipynb" ): # Treat the cell like a python file return document.path...
Returns line endings used in the text.
def _get_line_endings(lines: list[str]) -> str: """Returns line endings used in the text.""" try: if lines[0][-2:] == "\r\n": return "\r\n" return "\n" except Exception: # pylint: disable=broad-except return None
Ensures that the edited text line endings matches the document line endings.
def _match_line_endings(document: workspace.Document, text: str) -> str: """Ensures that the edited text line endings matches the document line endings.""" expected = _get_line_endings(document.source.splitlines(keepends=True)) actual = _get_line_endings(text.splitlines(keepends=True)) if actual == expe...
Returns arguments used by black based on file extensions.
def _get_args_by_file_extension(document: workspace.Document) -> List[str]: """Returns arguments used by black based on file extensions.""" if document.uri.startswith("vscode-notebook-cell"): return [] p = document.path.lower() if p.endswith(".py"): return [] elif p.endswith(".pyi")...
LSP handler for initialize request.
def initialize(params: lsp.InitializeParams) -> None: """LSP handler for initialize request.""" log_to_output(f"CWD Server: {os.getcwd()}") GLOBAL_SETTINGS.update(**params.initialization_options.get("globalSettings", {})) settings = params.initialization_options["settings"] _update_workspace_setti...
Handle clean up on exit.
def on_exit(_params: Optional[Any] = None) -> None: """Handle clean up on exit.""" jsonrpc.shutdown_json_rpc()
Handle clean up on shutdown.
def on_shutdown(_params: Optional[Any] = None) -> None: """Handle clean up on shutdown.""" jsonrpc.shutdown_json_rpc()
Returns cwd for the given settings and document.
def get_cwd(settings: Dict[str, Any], document: Optional[workspace.Document]) -> str: """Returns cwd for the given settings and document.""" if settings["cwd"] == "${workspaceFolder}": return settings["workspaceFS"] if settings["cwd"] == "${fileDirname}": if document is not None: ...
Runs tool on the given document. if use_stdin is true then contents of the document is passed to the tool via stdin.
def _run_tool_on_document( document: workspace.Document, use_stdin: bool = False, extra_args: Sequence[str] = [], ) -> utils.RunResult | None: """Runs tool on the given document. if use_stdin is true then contents of the document is passed to the tool via stdin. """ if utils.is_stdlib_...
Runs tool.
def _run_tool(extra_args: Sequence[str], settings: Dict[str, Any]) -> utils.RunResult: """Runs tool.""" code_workspace = settings["workspaceFS"] cwd = get_cwd(settings, None) use_path = False use_rpc = False if len(settings["path"]) > 0: # 'path' setting takes priority over everything. ...
Logs messages to Output > Black Formatter channel only.
def log_to_output( message: str, msg_type: lsp.MessageType = lsp.MessageType.Log ) -> None: """Logs messages to Output > Black Formatter channel only.""" LSP_SERVER.show_message_log(message, msg_type)
Logs messages with notification on error.
def log_error(message: str) -> None: """Logs messages with notification on error.""" LSP_SERVER.show_message_log(message, lsp.MessageType.Error) if os.getenv("LS_SHOW_NOTIFICATION", "off") in ["onError", "onWarning", "always"]: LSP_SERVER.show_message(message, lsp.MessageType.Error)
Logs messages with notification on warning.
def log_warning(message: str) -> None: """Logs messages with notification on warning.""" LSP_SERVER.show_message_log(message, lsp.MessageType.Warning) if os.getenv("LS_SHOW_NOTIFICATION", "off") in ["onWarning", "always"]: LSP_SERVER.show_message(message, lsp.MessageType.Warning)
Logs messages with notification.
def log_always(message: str) -> None: """Logs messages with notification.""" LSP_SERVER.show_message_log(message, lsp.MessageType.Info) if os.getenv("LS_SHOW_NOTIFICATION", "off") in ["always"]: LSP_SERVER.show_message(message, lsp.MessageType.Info)
Ensures we always get a list
def as_list(content: Union[Any, List[Any], Tuple[Any]]) -> List[Any]: """Ensures we always get a list""" if isinstance(content, (list, tuple)): return list(content) return [content]
Returns paths from sysconfig.get_paths().
def _get_sys_config_paths() -> List[str]: """Returns paths from sysconfig.get_paths().""" return [ path for group, path in sysconfig.get_paths().items() if group not in ["data", "platdata", "scripts"] ]
This is the extensions folder under ~/.vscode or ~/.vscode-server.
def _get_extensions_dir() -> List[str]: """This is the extensions folder under ~/.vscode or ~/.vscode-server.""" # The path here is calculated relative to the tool # this is because users can launch VS Code with custom # extensions folder using the --extensions-dir argument path = pathlib.Path(__fi...
Returns true if two paths are the same.
def is_same_path(file_path1: str, file_path2: str) -> bool: """Returns true if two paths are the same.""" return pathlib.Path(file_path1) == pathlib.Path(file_path2)
Returns normalized path.
def normalize_path(file_path: str) -> str: """Returns normalized path.""" return str(pathlib.Path(file_path).resolve())
Returns true if the executable path is same as the current interpreter.
def is_current_interpreter(executable) -> bool: """Returns true if the executable path is same as the current interpreter.""" return is_same_path(executable, sys.executable)
Return True if the file belongs to the standard library.
def is_stdlib_file(file_path: str) -> bool: """Return True if the file belongs to the standard library.""" normalized_path = str(pathlib.Path(file_path).resolve()) return any(normalized_path.startswith(path) for path in _stdlib_paths)
Manage object attributes context when using runpy.run_module().
def substitute_attr(obj: Any, attribute: str, new_value: Any): """Manage object attributes context when using runpy.run_module().""" old_value = getattr(obj, attribute) setattr(obj, attribute, new_value) yield setattr(obj, attribute, old_value)
Redirect stdio streams to a custom stream.
def redirect_io(stream: str, new_stream): """Redirect stdio streams to a custom stream.""" old_stream = getattr(sys, stream) setattr(sys, stream, new_stream) yield setattr(sys, stream, old_stream)
Change working directory before running code.
def change_cwd(new_cwd): """Change working directory before running code.""" os.chdir(new_cwd) yield os.chdir(SERVER_CWD)
Runs as a module.
def _run_module( module: str, argv: Sequence[str], use_stdin: bool, source: str = None ) -> RunResult: """Runs as a module.""" str_output = CustomIO("<stdout>", encoding="utf-8") str_error = CustomIO("<stderr>", encoding="utf-8") try: with substitute_attr(sys, "argv", argv): wit...
Runs as a module.
def run_module( module: str, argv: Sequence[str], use_stdin: bool, cwd: str, source: str = None ) -> RunResult: """Runs as a module.""" with CWD_LOCK: if is_same_path(os.getcwd(), cwd): return _run_module(module, argv, use_stdin, source) with change_cwd(cwd): return _...
Runs as an executable.
def run_path( argv: Sequence[str], use_stdin: bool, cwd: str, source: str = None ) -> RunResult: """Runs as an executable.""" if use_stdin: with subprocess.Popen( argv, encoding="utf-8", stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin...
Run a API.
def run_api( callback: Callable[[Sequence[str], CustomIO, CustomIO, CustomIO | None], None], argv: Sequence[str], use_stdin: bool, cwd: str, source: str = None, ) -> RunResult: """Run a API.""" with CWD_LOCK: if is_same_path(os.getcwd(), cwd): return _run_api(callback, ar...
Add given path to `sys.path`.
def update_sys_path(path_to_add: str) -> None: """Add given path to `sys.path`.""" if path_to_add not in sys.path and os.path.isdir(path_to_add): sys.path.append(path_to_add)
Test formatting a python file.
def test_formatting(sample: str): """Test formatting a python file.""" FORMATTED_TEST_FILE_PATH = constants.TEST_DATA / sample / "sample.py" UNFORMATTED_TEST_FILE_PATH = constants.TEST_DATA / sample / "sample.unformatted" contents = UNFORMATTED_TEST_FILE_PATH.read_text(encoding="utf-8") actual = [...
Test formating a python file.
def test_formatting_cell(): """Test formating a python file.""" FORMATTED_TEST_FILE_PATH = constants.TEST_DATA / "sample2" / "sample.formatted" UNFORMATTED_TEST_FILE_PATH = constants.TEST_DATA / "sample2" / "sample.unformatted" contents = UNFORMATTED_TEST_FILE_PATH.read_text(encoding="utf-8") actu...
Test skipping formatting when the file is in site-packages
def test_skipping_site_packages_files(): """Test skipping formatting when the file is in site-packages""" UNFORMATTED_TEST_FILE_PATH = constants.TEST_DATA / "sample1" / "sample.unformatted" with session.LspSession() as ls_session: # Use any stdlib path here uri = utils.as_uri(pathlib.__file...
Test formatting a python file.
def test_range_formatting(sample: str, ranges: str): """Test formatting a python file.""" FORMATTED_TEST_FILE_PATH = constants.TEST_DATA / sample / "sample.py" UNFORMATTED_TEST_FILE_PATH = constants.TEST_DATA / sample / "sample.unformatted" contents = UNFORMATTED_TEST_FILE_PATH.read_text(encoding="utf-...
Test linting using pylint bin path set.
def test_path(): """Test linting using pylint bin path set.""" init_params = copy.deepcopy(defaults.VSCODE_DEFAULT_INITIALIZE) init_params["initializationOptions"]["settings"][0]["path"] = [ sys.executable, os.fspath(UTILS_PATH), ] argv_callback_object = CallbackObject() conten...
Test linting using specific python path.
def test_interpreter(): """Test linting using specific python path.""" init_params = copy.deepcopy(defaults.VSCODE_DEFAULT_INITIALIZE) init_params["initializationOptions"]["settings"][0]["interpreter"] = ["python"] argv_callback_object = CallbackObject() contents = TEST_FILE.read_text() actual...
Fixes 'file' uri or path case for easier testing in windows.
def normalizecase(path: str) -> str: """Fixes 'file' uri or path case for easier testing in windows.""" if platform.system() == "Windows": return path.lower() return path
Return 'file' uri as string.
def as_uri(path: str) -> str: """Return 'file' uri as string.""" return normalizecase(pathlib.Path(path).as_uri())
Returns server info from package.json
def get_server_info_defaults(): """Returns server info from package.json""" package_json_path = PROJECT_ROOT / "package.json" package_json = json.loads(package_json_path.read_text()) return package_json["serverInfo"]
Returns initialization options from package.json
def get_initialization_options(): """Returns initialization options from package.json""" package_json_path = PROJECT_ROOT / "package.json" package_json = json.loads(package_json_path.read_text()) server_info = package_json["serverInfo"] server_id = f"{server_info['module']}-formatter" properti...
Converts text edits from the language server to the format used by the test client.
def destructure_text_edits(text_edits: List[Any]) -> List[lsp.TextEdit]: """Converts text edits from the language server to the format used by the test client.""" converter = cv.get_converter() return [converter.structure(text_edit, lsp.TextEdit) for text_edit in text_edits]
Returns true if the class has a property that may be python keyword.
def is_keyword_class(cls: type) -> bool: """Returns true if the class has a property that may be python keyword.""" return any(cls is c for c in _KEYWORD_CLASSES)
Returns true if the class or its properties require special handling.
def is_special_class(cls: type) -> bool: """Returns true if the class or its properties require special handling.""" return any(cls is c for c in _SPECIAL_CLASSES)
Returns true if the class or its properties require special handling. Example: Consider RenameRegistrationOptions * document_selector property: When you set `document_selector` to None in python it has to be preserved when serializing it. Since the serialized JSON value `{"document_selector": null...
def is_special_property(cls: type, property_name: str) -> bool: """Returns true if the class or its properties require special handling. Example: Consider RenameRegistrationOptions * document_selector property: When you set `document_selector` to None in python it has to be preserved w...
Returns message direction clientToServer, serverToClient or both.
def message_direction(method: str) -> str: """Returns message direction clientToServer, serverToClient or both.""" return _MESSAGE_DIRECTION[method]
Convert a string to ascii.
def string_to_ascii(value): """ Convert a string to ascii. """ return str(anyascii(value))
Returns a string that can be used to identify the specified model. The format is: `app_label.ModelName` This an be reversed with the `resolve_model_string` function
def get_model_string(model): """ Returns a string that can be used to identify the specified model. The format is: `app_label.ModelName` This an be reversed with the `resolve_model_string` function """ return model._meta.app_label + "." + model.__name__
Resolve an 'app_label.model_name' string into an actual model class. If a model class is passed in, just return that. Raises a LookupError if a model can not be found, or ValueError if passed something that is neither a model or a string.
def resolve_model_string(model_string, default_app=None): """ Resolve an 'app_label.model_name' string into an actual model class. If a model class is passed in, just return that. Raises a LookupError if a model can not be found, or ValueError if passed something that is neither a model or a string...
Escape `</script>` tags in 'text' so that it can be placed within a `<script>` block without accidentally closing it. A '-' character will be inserted for each time it is escaped: `<-/script>`, `<--/script>` etc.
def escape_script(text): """ Escape `</script>` tags in 'text' so that it can be placed within a `<script>` block without accidentally closing it. A '-' character will be inserted for each time it is escaped: `<-/script>`, `<--/script>` etc. """ warn( "The `escape_script` hook is depreca...
Convert a string to ASCII exactly as Django's slugify does, with the exception that any non-ASCII alphanumeric characters (that cannot be ASCIIfied under Unicode normalisation) are escaped into codes like 'u0421' instead of being deleted entirely. This ensures that the result of slugifying (for example - Cyrillic) tex...
def cautious_slugify(value): """ Convert a string to ASCII exactly as Django's slugify does, with the exception that any non-ASCII alphanumeric characters (that cannot be ASCIIfied under Unicode normalisation) are escaped into codes like 'u0421' instead of being deleted entirely. This ensures that ...
Convert a string to ASCII similar to Django's slugify, with cautious handling of non-ASCII alphanumeric characters. See `cautious_slugify`. Any inner whitespace, hyphens or dashes will be converted to underscores and will be safe for Django template or filename usage.
def safe_snake_case(value): """ Convert a string to ASCII similar to Django's slugify, with cautious handling of non-ASCII alphanumeric characters. See `cautious_slugify`. Any inner whitespace, hyphens or dashes will be converted to underscores and will be safe for Django template or filename usage...
Return a human-readable label for a content type object, suitable for display in the admin in place of the default 'wagtailcore | page' representation
def get_content_type_label(content_type): """ Return a human-readable label for a content type object, suitable for display in the admin in place of the default 'wagtailcore | page' representation """ if content_type is None: return _("Unknown content type") model = content_type.model_c...
Determine whether the callable `func` has a signature that accepts the keyword argument `kwarg`
def accepts_kwarg(func, kwarg): """ Determine whether the callable `func` has a signature that accepts the keyword argument `kwarg` """ signature = inspect.signature(func) try: signature.bind_partial(**{kwarg: None}) return True except TypeError: return False
Finds an available slug within the specified parent. If the requested slug is not available, this adds a number on the end, for example: - 'requested-slug' - 'requested-slug-1' - 'requested-slug-2' And so on, until an available slug is found. The `ignore_page_id` keyword argument is useful for when you are updat...
def find_available_slug(parent, requested_slug, ignore_page_id=None): """ Finds an available slug within the specified parent. If the requested slug is not available, this adds a number on the end, for example: - 'requested-slug' - 'requested-slug-1' - 'requested-slug-2' And so on, unt...
Cache of settings.WAGTAIL_CONTENT_LANGUAGES in a dictionary for easy lookups by key.
def get_content_languages(): """ Cache of settings.WAGTAIL_CONTENT_LANGUAGES in a dictionary for easy lookups by key. """ content_languages = getattr(settings, "WAGTAIL_CONTENT_LANGUAGES", None) languages = dict(settings.LANGUAGES) if content_languages is None: # Default to a single lan...
Return the language code that's listed in supported languages, possibly selecting a more generic variant. Raise LookupError if nothing is found. If `strict` is False (the default), look for a country-specific variant when neither the language code nor its generic variant is found. lru_cache should have a maxsize to pre...
def get_supported_content_language_variant(lang_code, strict=False): """ Return the language code that's listed in supported languages, possibly selecting a more generic variant. Raise LookupError if nothing is found. If `strict` is False (the default), look for a country-specific variant when neith...
Cache of the locale id -> locale display name mapping
def get_locales_display_names() -> dict: """ Cache of the locale id -> locale display name mapping """ from wagtail.models import Locale # inlined to avoid circular imports cached_map = cache.get("wagtail_locales_display_name") if cached_map is None: cached_map = { locale....
Clear cache when global WAGTAIL_CONTENT_LANGUAGES/LANGUAGES/LANGUAGE_CODE settings are changed
def reset_cache(**kwargs): """ Clear cache when global WAGTAIL_CONTENT_LANGUAGES/LANGUAGES/LANGUAGE_CODE settings are changed """ if kwargs["setting"] in ("WAGTAIL_CONTENT_LANGUAGES", "LANGUAGES", "LANGUAGE_CODE"): get_content_languages.cache_clear() get_supported_content_language_varian...
Like getattr, but accepts a dotted path as the accessor to be followed to any depth. At each step, the lookup on the object can be a dictionary lookup (foo['bar']) or an attribute lookup (foo.bar), and if it results in a callable, will be called (provided we can do so with no arguments, and it does not have an 'alters_...
def multigetattr(item, accessor): """ Like getattr, but accepts a dotted path as the accessor to be followed to any depth. At each step, the lookup on the object can be a dictionary lookup (foo['bar']) or an attribute lookup (foo.bar), and if it results in a callable, will be called (provided we can do ...
Return a simple ``HttpRequest`` instance that can be passed to ``Page.get_url()`` and other methods to benefit from improved performance when no real ``HttpRequest`` instance is available. If ``site`` is provided, the ``HttpRequest`` is made to look like it came from that Wagtail ``Site``.
def get_dummy_request(*, path: str = "/", site: "Site" = None) -> HttpRequest: """ Return a simple ``HttpRequest`` instance that can be passed to ``Page.get_url()`` and other methods to benefit from improved performance when no real ``HttpRequest`` instance is available. If ``site`` is provided, th...
Safely use the MD5 hash algorithm with the given ``data`` and a flag indicating if the purpose of the digest is for security or not. On security-restricted systems (such as FIPS systems), insecure hashes like MD5 are disabled by default. But passing ``usedforsecurity`` as ``False`` tells the underlying security implem...
def safe_md5(data=b"", usedforsecurity=True): """ Safely use the MD5 hash algorithm with the given ``data`` and a flag indicating if the purpose of the digest is for security or not. On security-restricted systems (such as FIPS systems), insecure hashes like MD5 are disabled by default. But passing...
A modified version of `make_template_fragment_key` which varies on page and site for use with `{% wagtailpagecache %}`.
def make_wagtail_template_fragment_key(fragment_name, page, site, vary_on=None): """ A modified version of `make_template_fragment_key` which varies on page and site for use with `{% wagtailpagecache %}`. """ if vary_on is None: vary_on = [] vary_on.extend([page.cache_key, site.id]) ...
Register hook for ``hook_name``. Can be used as a decorator:: @register('hook_name') def my_hook(...): pass or as a function call:: def my_hook(...): pass register('hook_name', my_hook)
def register(hook_name, fn=None, order=0): """ Register hook for ``hook_name``. Can be used as a decorator:: @register('hook_name') def my_hook(...): pass or as a function call:: def my_hook(...): pass register('hook_name', my_hook) """ # P...
Register hook for ``hook_name`` temporarily. This is useful for testing hooks. Can be used as a decorator:: def my_hook(...): pass class TestMyHook(Testcase): @hooks.register_temporarily('hook_name', my_hook) def test_my_hook(self): pass or as a context manager:: def...
def register_temporarily(hook_name_or_hooks, fn=None, *, order=0): """ Register hook for ``hook_name`` temporarily. This is useful for testing hooks. Can be used as a decorator:: def my_hook(...): pass class TestMyHook(Testcase): @hooks.register_temporarily('hook_n...
Return the hooks function sorted by their order.
def get_hooks(hook_name): """Return the hooks function sorted by their order.""" search_for_hooks() hooks = _hooks.get(hook_name, []) hooks = sorted(hooks, key=itemgetter(1)) return [hook[0] for hook in hooks]
A context manager that can be used to temporarily disable the reference index auto-update signal handlers. For example: with disable_reference_index_auto_update(): my_instance.save() # Reference index will not be updated by this save
def disable_reference_index_auto_update(): """ A context manager that can be used to temporarily disable the reference index auto-update signal handlers. For example: with disable_reference_index_auto_update(): my_instance.save() # Reference index will not be updated by this save """ ...
Allows a class to implement its adapting logic with a `js_args()` method on the class itself. This just helps reduce the amount of code you have to write. For example: @adapter('wagtail.mywidget') class MyWidget(): ... def js_args(self): return [ self.foo, ...
def adapter(js_constructor, base=Adapter): """ Allows a class to implement its adapting logic with a `js_args()` method on the class itself. This just helps reduce the amount of code you have to write. For example: @adapter('wagtail.mywidget') class MyWidget(): ... ...
Handle a submission of PasswordViewRestrictionForm to grant view access over a subtree that is protected by a PageViewRestriction
def authenticate_with_password(request, page_view_restriction_id, page_id): """ Handle a submission of PasswordViewRestrictionForm to grant view access over a subtree that is protected by a PageViewRestriction """ restriction = get_object_or_404(PageViewRestriction, id=page_view_restriction_id) ...
Check whether there are any view restrictions on this page which are not fulfilled by the given request object. If there are, return an HttpResponse that will notify the user of that restriction (and possibly include a password / login form that will allow them to proceed). If there are no such restrictions, return Non...
def check_view_restrictions(page, request, serve_args, serve_kwargs): """ Check whether there are any view restrictions on this page which are not fulfilled by the given request object. If there are, return an HttpResponse that will notify the user of that restriction (and possibly include a passwor...
Generator for functions that can be used as entries in Whitelister.element_rules. These functions accept a tag, and modify its attributes by looking each attribute up in the 'allowed_attrs' dict defined here: * if the lookup fails, drop the attribute * if the lookup returns a callable, replace the attribute with the re...
def attribute_rule(allowed_attrs): """ Generator for functions that can be used as entries in Whitelister.element_rules. These functions accept a tag, and modify its attributes by looking each attribute up in the 'allowed_attrs' dict defined here: * if the lookup fails, drop the attribute * if t...
Retrieves non-abstract descendants of the given model class. If `inclusive` is set to True, includes model_class
def get_concrete_descendants(model_class, inclusive=True): """Retrieves non-abstract descendants of the given model class. If `inclusive` is set to True, includes model_class""" subclasses = model_class.__subclasses__() if subclasses: for subclass in subclasses: yield from get_concr...
Retrieve the global list of menu items for the page action menu, which may then be customised on a per-request basis
def _get_base_page_action_menu_items(): """ Retrieve the global list of menu items for the page action menu, which may then be customised on a per-request basis """ global BASE_PAGE_ACTION_MENU_ITEMS if BASE_PAGE_ACTION_MENU_ITEMS is None: BASE_PAGE_ACTION_MENU_ITEMS = [ Sav...
Return a standard 'permission denied' response
def permission_denied(request): """Return a standard 'permission denied' response""" if request.headers.get("x-requested-with") == "XMLHttpRequest": raise PermissionDenied from wagtail.admin import messages messages.error(request, _("Sorry, you do not have permission to access this area.")) ...
Given a test function that takes a user object and returns a boolean, return a view decorator that denies access to the user if the test returns false.
def user_passes_test(test): """ Given a test function that takes a user object and returns a boolean, return a view decorator that denies access to the user if the test returns false. """ def decorator(view_func): # decorator takes the view function, and returns the view wrapped in ...
Replacement for django.contrib.auth.decorators.permission_required which returns a more meaningful 'permission denied' response than just redirecting to the login page. (The latter doesn't work anyway because Wagtail doesn't define LOGIN_URL...)
def permission_required(permission_name): """ Replacement for django.contrib.auth.decorators.permission_required which returns a more meaningful 'permission denied' response than just redirecting to the login page. (The latter doesn't work anyway because Wagtail doesn't define LOGIN_URL...) """ ...
Decorator that accepts a list of permission names, and allows the user to pass if they have *any* of the permissions in the list
def any_permission_required(*perms): """ Decorator that accepts a list of permission names, and allows the user to pass if they have *any* of the permissions in the list """ def test(user): for perm in perms: if user.has_perm(perm): return True return F...
Check if a user has any permission to add, edit, or otherwise manage any page.
def user_has_any_page_permission(user): """ Check if a user has any permission to add, edit, or otherwise manage any page. """ return page_permission_policy.user_has_any_permission( user, {"add", "change", "publish", "bulk_delete", "lock", "unlock"} )
Check panels configuration uses `panels` when `edit_handler` not in use.
def check_panels_in_model(cls, context="model"): """Check panels configuration uses `panels` when `edit_handler` not in use.""" from wagtail.admin.panels import InlinePanel, PanelGroup from wagtail.models import Page errors = [] if hasattr(cls, "get_edit_handler"): # must check the InlineP...
If L10N is enabled, check if WAGTAIL_* formats are compatible with Django input formats. See https://docs.djangoproject.com/en/stable/topics/i18n/formatting/#creating-custom-format-files See https://docs.wagtail.org/en/stable/reference/settings.html#wagtail-date-format-wagtail-datetime-format-wagtail-time-format
def datetime_format_check(app_configs, **kwargs): """ If L10N is enabled, check if WAGTAIL_* formats are compatible with Django input formats. See https://docs.djangoproject.com/en/stable/topics/i18n/formatting/#creating-custom-format-files See https://docs.wagtail.org/en/stable/reference/settings.html#...
Define parameters for form fields to be used by WagtailAdminModelForm for a given database field.
def register_comparison_class( field_class, to=None, comparison_class=None, exact_class=False ): """ Define parameters for form fields to be used by WagtailAdminModelForm for a given database field. """ if comparison_class is None: raise ImproperlyConfigured( "register_compa...
Performs a diffing algorithm on two pieces of text. Returns a string of HTML containing the content of both texts with <span> tags inserted indicating where the differences are.
def diff_text(a, b): """ Performs a diffing algorithm on two pieces of text. Returns a string of HTML containing the content of both texts with <span> tags inserted indicating where the differences are. """ def tokenise(text): """ Tokenises a string by splitting it into individu...
Given a python datetime format string, attempts to convert it to the nearest PHP datetime format string possible.
def to_datetimepicker_format(python_format_string): """ Given a python datetime format string, attempts to convert it to the nearest PHP datetime format string possible. """ python2PHP = { "%a": "D", "%A": "l", "%b": "M", "%B": "F", "%c": "", "%d": "d"...
Wrapper around Django's EmailMultiAlternatives as done in send_mail(). Custom from_email handling and special Auto-Submitted header.
def send_mail(subject, message, recipient_list, from_email=None, **kwargs): """ Wrapper around Django's EmailMultiAlternatives as done in send_mail(). Custom from_email handling and special Auto-Submitted header. """ if not from_email: if hasattr(settings, "WAGTAILADMIN_NOTIFICATION_FROM_EM...
" Render a response consisting of an HTML chunk and a JS onload chunk in the format required by the modal-workflow framework.
def render_modal_workflow( request, html_template, js_template=None, template_vars=None, json_data=None ): """ " Render a response consisting of an HTML chunk and a JS onload chunk in the format required by the modal-workflow framework. """ if js_template: raise TypeError( "P...
Returns a queryset of pages that link to a particular object
def get_object_usage(obj): """Returns a queryset of pages that link to a particular object""" pages = Page.objects.none() # get all the relation objects for obj relations = [ f for f in type(obj)._meta.get_fields(include_hidden=True) if (f.one_to_many or f.one_to_one) and f.au...
Return a queryset of the most frequently used tags used on this model class
def popular_tags_for_model(model, count=10): """Return a queryset of the most frequently used tags used on this model class""" content_type = ContentType.objects.get_for_model(model) return ( Tag.objects.filter(taggit_taggeditem_items__content_type=content_type) .annotate(item_count=Count("t...
Gets the base URL for the wagtail admin site. This is set in `settings.WAGTAILADMIN_BASE_URL`.
def get_admin_base_url(): """ Gets the base URL for the wagtail admin site. This is set in `settings.WAGTAILADMIN_BASE_URL`. """ return getattr(settings, "WAGTAILADMIN_BASE_URL", None)
Helper function to get the latest string representation of an object. Draft changes are saved as revisions instead of immediately reflected to the instance, so this function utilises the latest revision's object_str attribute if available.
def get_latest_str(obj): """ Helper function to get the latest string representation of an object. Draft changes are saved as revisions instead of immediately reflected to the instance, so this function utilises the latest revision's object_str attribute if available. """ from wagtail.models...