timApp.util.flask package#

Submodules#

timApp.util.flask.cache module#

timApp.util.flask.filters module#

timApp.util.flask.filters.humanize_datetime(value: datetime.datetime)[source]#
timApp.util.flask.filters.humanize_timedelta(value: datetime.timedelta)[source]#
timApp.util.flask.filters.map_format(value, pattern)[source]#

Applies Python string formatting on an object:

{{ "%s - %s"|format("Hello?", "Foo!") }}

gives:

Hello? - Foo!
timApp.util.flask.filters.timdate(value: datetime.datetime)[source]#

timApp.util.flask.requesthelper module#

class timApp.util.flask.requesthelper.EmptyWarning[source]#

Bases: object

warn(a: Any, b: Any) None[source]#
exception timApp.util.flask.requesthelper.JSONException(description: str, code: int = 400)[source]#

Bases: Exception

code: int = 400#
description: str#
exception timApp.util.flask.requesthelper.NotExist(description: Optional[str] = None, response: Optional[Response] = None)[source]#

Bases: werkzeug.exceptions.HTTPException

code: t.Optional[int] = 404#
exception timApp.util.flask.requesthelper.RouteException(description: Optional[str] = None, response: Optional[Response] = None)[source]#

Bases: werkzeug.exceptions.HTTPException

code: t.Optional[int] = 400#
timApp.util.flask.requesthelper.get_from_url(url: str) str[source]#
timApp.util.flask.requesthelper.get_option(req: flask.wrappers.Request | timApp.document.viewcontext.ViewContext, name: str, default: Any, cast: Optional[type] = None) Any[source]#
timApp.util.flask.requesthelper.get_request_message(status_code: Optional[int] = None, include_body: bool = False, include_time: bool = True, is_before: bool = False) str[source]#
timApp.util.flask.requesthelper.get_request_time() str | None[source]#
timApp.util.flask.requesthelper.get_urlmacros_from_request() tuple[tuple[str, str], ...][source]#
timApp.util.flask.requesthelper.is_localhost() bool[source]#
timApp.util.flask.requesthelper.is_testing() bool[source]#
timApp.util.flask.requesthelper.load_data_from_req(schema: type[marshmallow.schema.Schema]) Any[source]#
timApp.util.flask.requesthelper.use_model(m: type[ModelType]) Callable[[Callable[[timApp.util.flask.requesthelper.ModelType], flask.wrappers.Response]], Callable[[timApp.util.flask.requesthelper.ModelType], flask.wrappers.Response]][source]#
timApp.util.flask.requesthelper.verify_json_params(*args: str, require: bool = True, default: Optional[Any] = None, error_msgs: Optional[list[str]] = None) list[Any][source]#

Gets the specified JSON parameters from the request.

Parameters
  • default – The default value for the parameter if it is not found from the request.

  • require – If True and the parameter is not found, the request is aborted.

timApp.util.flask.requesthelper.view_ctx_with_urlmacros(route: timApp.document.viewcontext.ViewRoute, hide_names_requested: bool = False) timApp.document.viewcontext.ViewContext[source]#

timApp.util.flask.responsehelper module#

timApp.util.flask.responsehelper.add_csp_header(response: flask.wrappers.Response, value: str = 'sandbox')[source]#
timApp.util.flask.responsehelper.add_no_cache_headers(response: flask.wrappers.Response)[source]#
timApp.util.flask.responsehelper.csv_response(data, dialect='excel', delimiter=',', quoting: int = 0, pad_spaces: bool = False)[source]#
timApp.util.flask.responsehelper.csv_string(data: list[list[Any]], dialect: str, delimiter: str = ',', quoting: int = 0, pad_spaces: bool = False) str[source]#
timApp.util.flask.responsehelper.empty_response()[source]#
timApp.util.flask.responsehelper.error_generic(error: str, code: int, template='error.jinja2', status: Optional[str] = None)[source]#
timApp.util.flask.responsehelper.flash_if_visible(message: str, view_ctx: timApp.document.viewcontext.ViewContext) None[source]#
timApp.util.flask.responsehelper.get_grid_modules()[source]#
timApp.util.flask.responsehelper.html_error(error: str, code: int, title=None, description='', auto_refresh=True, template='generic_html_error_standalone.jinja2')[source]#
timApp.util.flask.responsehelper.is_safe_url(url)[source]#
timApp.util.flask.responsehelper.iter_csv(data: list[list[Any]], dialect: str, delimiter: str = ',', quoting: int = 0, pad_spaces: bool = False)[source]#
timApp.util.flask.responsehelper.json_response(jsondata: Any, status_code: int = 200, headers: Optional[dict[str, str]] = None, date_conversion: bool = False) flask.wrappers.Response[source]#
timApp.util.flask.responsehelper.json_response_and_commit(jsondata, status_code=200)[source]#
timApp.util.flask.responsehelper.no_cache_json_response(data: Any, date_conversion: bool = False) flask.wrappers.Response[source]#

Returns a JSON response that prevents any caching of the result.

timApp.util.flask.responsehelper.ok_response() flask.wrappers.Response[source]#
timApp.util.flask.responsehelper.pad_csv_data(data: list[list[Any]]) list[list[str]][source]#

Pad each column with spaces to the maximum length of the column. :param data: :return:

timApp.util.flask.responsehelper.safe_redirect(url: str, **values) flask.wrappers.Response[source]#
timApp.util.flask.responsehelper.text_response(data: str, status_code: int = 200) flask.wrappers.Response[source]#
timApp.util.flask.responsehelper.to_dict(jsondata: Any) dict[source]#
timApp.util.flask.responsehelper.to_json_str(jsondata) str[source]#

timApp.util.flask.search module#

Routes for searching.

class timApp.util.flask.search.DocResult(doc_info: timApp.document.docinfo.DocInfo, par_results=None, title_results=None, incomplete=False)[source]#

Bases: object

Contains one document’s title and word search information.

add_par_result(result: timApp.util.flask.search.ParResult) None[source]#

Add new paragraph search result to the list.

Parameters

result – New paragraph result.

Returns

None.

add_title_result(result: timApp.util.flask.search.TitleResult) None[source]#

Add new title search result to the list.

Parameters

result – New title result.

Returns

None.

get_par_match_count() int[source]#
Returns

Total document count for paragraph word matches.

get_title_match_count() int[source]#
Returns

Total document count for title matches.

has_results() bool[source]#
Returns

Whether the document has any results in it.

to_json()[source]#
Returns

A dictionary of the object, suitable for JSON-conversion.

class timApp.util.flask.search.GetFoldersModel(folder: str)[source]#

Bases: object

folder: str#
class timApp.util.flask.search.ParResult(par_id: str = '', preview: str = '', word_results=None, alt_num_results=0)[source]#

Bases: object

Paragraph search results.

add_result(result: timApp.util.flask.search.WordResult) None[source]#

Add new word result.

Parameters

result – New word result from paragraph markdown.

Returns

None.

get_match_count() int[source]#
Returns

How many matches there are in this paragraph.

has_results() bool[source]#
Returns

True if the object contains results.

to_json()[source]#
Returns

A dictionary of attributes and derived attributes.

class timApp.util.flask.search.TitleResult(word_results=None, alt_num_results: int = 0)[source]#

Bases: object

Title search result containing a list of match data.

add_result(result: timApp.util.flask.search.WordResult) None[source]#

Add new result to the list.

Parameters

result – New word result.

Returns

None.

get_match_count() int[source]#
Returns

How many match words the title has.

has_results() bool[source]#
Returns

Whether the object contains any results.

to_json()[source]#
Returns

A dictionary of attributes and derived attributes, suitable for JSON-conversion.

class timApp.util.flask.search.WordResult(match_word: str, match_start: int, match_end: int)[source]#

Bases: object

One match word with location and match word.

to_json()[source]#
Returns

A dictionary containing object data, suitable for JSON-conversion.

timApp.util.flask.search.add_doc_info_content_line(doc_id: int, par_data, remove_deleted_pars: bool = True, add_title: bool = False) str | None[source]#

Forms a JSON-compatible string with doc_id and list of paragraph data with id and md attributes.

Parameters
  • doc_id – Document id.

  • par_data – List of paragraph dictionaries.

  • remove_deleted_pars – Check paragraph existence and leave deleted ones out.

:param add_title Add document title. :return: String with paragraph data grouped under a document.

timApp.util.flask.search.add_doc_info_title_line(doc_id: int) str | None[source]#

Forms a JSON-compatible string with doc id, title and path.

Parameters

doc_id – Document id.

Returns

String with doc data.

timApp.util.flask.search.compile_regex(query: str, regex: bool, case_sensitive: bool, search_whole_words: bool)[source]#

Set flags and compile regular expression. Abort if invalid or empty regex.

Parameters
  • query – Search word.

  • regex – Regex search.

  • case_sensitive – Distinguish between upper and lower case in search.

  • search_whole_words – Search words separated by spaces, commas etc.

Returns

Compiled regex.

timApp.util.flask.search.create_search_files(remove_deleted_pars=True)[source]#

Groups all TIM-paragraphs under documents and combines them into a single file. Creates also a similar file for title searches and a raw file without grouping.

Parameters

remove_deleted_pars – Check paragraph existence before adding.

Returns

Status code and a message confirming success of file creation.

timApp.util.flask.search.create_search_files_route()[source]#

Route for grouping all TIM-paragraphs under documents and combining them into a single file. Creates also a similar file for title searches and a raw file without grouping. Note: may take several minutes, so timeout settings need to be lenient.

Returns

A message confirming success of file creation.

timApp.util.flask.search.get_common_search_params(req) tuple[str, str, bool, bool, bool, bool][source]#

Picks parameters that are common in the search routes from a request.

Parameters

req – Request.

Returns

A tuple with six values.

timApp.util.flask.search.get_doc_par_id(line: str) tuple[int, str, str] | None[source]#

Takes doc id, par id and par data from one grep search result line.

Parameters

line – Tim pars grep search result line.

Returns

Triple containing ids and par data.

timApp.util.flask.search.get_subfolders(m: timApp.util.flask.search.GetFoldersModel)[source]#

Returns subfolders of the starting folder. :return: Response containing a list of subfolder paths.

timApp.util.flask.search.is_excluded(relevance: int, relevance_threshold: int) bool[source]#

Exclude if relevance is less than relevance threshold.

Parameters
  • relevance – Document relevance value.

  • relevance_threshold – Min included relevance.

Returns

True if document relevance is less than relevance threshold.

timApp.util.flask.search.is_timeouted(start_time: float, timeout: float) bool[source]#

Compares elapsed time and timeout limit.

Parameters
  • start_time – The time comparison starts from.

  • timeout – Maximum allowed elapsed time.

Returns

True if timeout has been passed, false if not.

timApp.util.flask.search.log_search_error(error: str, query: str, doc: str, tag: str = '', par: str = '', title: bool = False, path: bool = False) None[source]#

Forms an error report and sends it to timLog.

Parameters
  • error – The error’s message

  • query – Search word.

  • doc – Document identifier.

  • tag – Tag name.

  • par – Par id.

  • title – If error was in title search.

  • path – If error was in path search.

Returns

None.

Document path search. Path results are treated as title results and use TitleResult objects and content & title search interface.

Returns

Path results.

timApp.util.flask.search.preview_result(md: str, query, m: Match[str], snippet_length: int = 40, max_length: int = 160) str[source]#

Forms preview of the match paragraph.

Parameters
  • md – Paragraph markdown to preview.

  • query – Search word.

  • m – Match object.

  • snippet_length – The length of preview before and after search word.

  • max_length – The maximum allowed length of the preview.

Returns

Preview with set amount of characters around search word.

timApp.util.flask.search.result_response(results, title_result_count: int = 0, word_result_count: int = 0, incomplete_search_reason='')[source]#

Formats result data for JSON-response. :param results: List of result dictionaries. :param title_result_count: Number of title results. :param word_result_count: Number of paragraph word results. :param incomplete_search_reason: Whether search was cut short. :return: Dictionary containing search results.

timApp.util.flask.search.search()[source]#

Perform document word search on a combined and grouped par file using grep.

Returns

Document paragraph search results with total result count.

A route for document tag search. :return: Tag search results response.

Performs search on document titles. :return: Title search results.

timApp.util.flask.search.validate_query(query: str, search_whole_words: bool) None[source]#

Abort if query is too short.

Parameters
  • query – Search word(s).

  • search_whole_words – Whole words search has different limits.

Returns

None.

timApp.util.flask.typedblueprint module#

class timApp.util.flask.typedblueprint.TypedBlueprint(name: str, import_name: str, static_folder: typing.Optional[typing.Union[str, os.PathLike]] = None, static_url_path: typing.Optional[str] = None, template_folder: typing.Optional[str] = None, url_prefix: typing.Optional[str] = None, subdomain: typing.Optional[str] = None, url_defaults: typing.Optional[dict] = None, root_path: typing.Optional[str] = None, cli_group: typing.Optional[str] = <object object>)[source]#

Bases: flask.blueprints.Blueprint

A special blueprint that allows to generate an query argument parsing model automatically based on route parameters.

delete(rule: str, model: Optional[type[ModelType]] = None, **kwargs: Any) Callable[source]#

Define a DELETE route.

Parameters
  • rule – Flask route rule.

  • model – Custom model to use for request parsing.

  • kwargs – Additional arguments passed to Flask.

Returns

Wrapped function.

get(rule: str, model: Optional[type[ModelType]] = None, **kwargs: Any) Callable[source]#

Define a GET route.

Parameters
  • rule – Flask route rule.

  • model – Custom model to use for request parsing.

  • kwargs – Additional arguments passed to Flask.

Returns

Wrapped function.

patch(rule: str, model: Optional[type[ModelType]] = None, **kwargs: Any) Callable[source]#

Define a PATCH route.

Parameters
  • rule – Flask route rule.

  • model – Custom model to use for request parsing.

  • kwargs – Additional arguments passed to Flask.

Returns

Wrapped function.

post(rule: str, model: Optional[type[ModelType]] = None, **kwargs: Any) Callable[source]#

Define a POST route.

Parameters
  • rule – Flask route rule.

  • model – Custom model to use for request parsing.

  • kwargs – Additional arguments passed to Flask.

Returns

Wrapped function.

put(rule: str, model: Optional[type[ModelType]] = None, **kwargs: Any) Callable[source]#

Define a PUT route.

Parameters
  • rule – Flask route rule.

  • model – Custom model to use for request parsing.

  • kwargs – Additional arguments passed to Flask.

Returns

Wrapped function.

route(rule: str, model: Optional[type[ModelType]] = None, **options: Any) Callable[source]#

Define a generic Flask route.

Parameters
  • rule – Flask route rule.

  • model – Custom model to use for request parsing.

  • kwargs – Additional arguments passed to Flask.

Returns

Wrapped function.

timApp.util.flask.typedblueprint.use_typed_params(num_path_params: int = 0, model: Optional[type[ModelType]] = None) Callable[source]#

timApp.util.flask.user_agent module#

class timApp.util.flask.user_agent.SimpleUserAgent(string: str)[source]#

Bases: werkzeug.user_agent.UserAgent

class timApp.util.flask.user_agent.UserAgentDevice[source]#

Bases: TypedDict

name: str#
version: str#
class timApp.util.flask.user_agent.UserAgentResult[source]#

Bases: TypedDict

bot: bool#
browser: timApp.util.flask.user_agent.UserAgentDevice#
dist: timApp.util.flask.user_agent.UserAgentDevice#
flavor: timApp.util.flask.user_agent.UserAgentDevice#
os: timApp.util.flask.user_agent.UserAgentDevice#
platform: timApp.util.flask.user_agent.UserAgentDevice#

Module contents#