index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
71,356 |
evaluate.utils.logging
|
disable_progress_bar
|
Enable tqdm progress bar.
|
def disable_progress_bar():
"""Enable tqdm progress bar."""
global _tqdm_active
_tqdm_active = False
|
()
|
71,357 |
evaluate.utils.logging
|
enable_progress_bar
|
Enable tqdm progress bar.
|
def enable_progress_bar():
"""Enable tqdm progress bar."""
global _tqdm_active
_tqdm_active = True
|
()
|
71,359 |
evaluate.evaluator
|
evaluator
|
Utility factory method to build an [`Evaluator`].
Evaluators encapsulate a task and a default metric name. They leverage `pipeline` functionality from `transformers`
to simplify the evaluation of multiple combinations of models, datasets and metrics for a given task.
Args:
task (`str`):
The task defining which evaluator will be returned. Currently accepted tasks are:
- `"image-classification"`: will return a [`ImageClassificationEvaluator`].
- `"question-answering"`: will return a [`QuestionAnsweringEvaluator`].
- `"text-classification"` (alias `"sentiment-analysis"` available): will return a [`TextClassificationEvaluator`].
- `"token-classification"`: will return a [`TokenClassificationEvaluator`].
Returns:
[`Evaluator`]: An evaluator suitable for the task.
Examples:
```python
>>> from evaluate import evaluator
>>> # Sentiment analysis evaluator
>>> evaluator("sentiment-analysis")
```
|
def evaluator(task: str = None) -> Evaluator:
"""
Utility factory method to build an [`Evaluator`].
Evaluators encapsulate a task and a default metric name. They leverage `pipeline` functionality from `transformers`
to simplify the evaluation of multiple combinations of models, datasets and metrics for a given task.
Args:
task (`str`):
The task defining which evaluator will be returned. Currently accepted tasks are:
- `"image-classification"`: will return a [`ImageClassificationEvaluator`].
- `"question-answering"`: will return a [`QuestionAnsweringEvaluator`].
- `"text-classification"` (alias `"sentiment-analysis"` available): will return a [`TextClassificationEvaluator`].
- `"token-classification"`: will return a [`TokenClassificationEvaluator`].
Returns:
[`Evaluator`]: An evaluator suitable for the task.
Examples:
```python
>>> from evaluate import evaluator
>>> # Sentiment analysis evaluator
>>> evaluator("sentiment-analysis")
```"""
if not TRANSFORMERS_AVAILABLE:
raise ImportError(
"If you want to use the `Evaluator` you need `transformers`. Run `pip install evaluate[transformers]`."
)
targeted_task = check_task(task)
evaluator_class = targeted_task["implementation"]
default_metric_name = targeted_task["default_metric_name"]
return evaluator_class(task=task, default_metric_name=default_metric_name)
|
(task: Optional[str] = None) -> evaluate.evaluator.base.Evaluator
|
71,362 |
evaluate.utils.gradio
|
infer_gradio_input_types
|
Maps metric feature types to input types for gradio Dataframes:
- float/int -> numbers
- string -> strings
- any other -> json
Note that json is not a native gradio type but will be treated as string that
is then parsed as a json.
|
def infer_gradio_input_types(feature_types):
"""
Maps metric feature types to input types for gradio Dataframes:
- float/int -> numbers
- string -> strings
- any other -> json
Note that json is not a native gradio type but will be treated as string that
is then parsed as a json.
"""
input_types = []
for feature_type in feature_types:
input_type = "json"
if isinstance(feature_type, Value):
if feature_type.dtype.startswith("int") or feature_type.dtype.startswith("float"):
input_type = "number"
elif feature_type.dtype == "string":
input_type = "str"
input_types.append(input_type)
return input_types
|
(feature_types)
|
71,365 |
evaluate.inspect
|
inspect_evaluation_module
|
Allow inspection/modification of a evaluation script by copying it on local drive at local_path.
Args:
path (``str``): path to the evaluation script. Can be either:
- a local path to script or the directory containing the script (if the script has the same name as the directory),
e.g. ``'./metrics/accuracy'`` or ``'./metrics/accuracy/accuracy.py'``
- a dataset identifier on the Hugging Face Hub (list all available datasets and ids with ``evaluate.list_evaluation_modules()``)
e.g. ``'accuracy'``, ``'bleu'`` or ``'word_length'``
local_path (``str``): path to the local folder to copy the datset script to.
download_config (Optional ``datasets.DownloadConfig``: specific download configuration parameters.
**download_kwargs: optional attributes for DownloadConfig() which will override the attributes in download_config if supplied.
|
def inspect_evaluation_module(
path: str, local_path: str, download_config: Optional[DownloadConfig] = None, **download_kwargs
):
r"""
Allow inspection/modification of a evaluation script by copying it on local drive at local_path.
Args:
path (``str``): path to the evaluation script. Can be either:
- a local path to script or the directory containing the script (if the script has the same name as the directory),
e.g. ``'./metrics/accuracy'`` or ``'./metrics/accuracy/accuracy.py'``
- a dataset identifier on the Hugging Face Hub (list all available datasets and ids with ``evaluate.list_evaluation_modules()``)
e.g. ``'accuracy'``, ``'bleu'`` or ``'word_length'``
local_path (``str``): path to the local folder to copy the datset script to.
download_config (Optional ``datasets.DownloadConfig``: specific download configuration parameters.
**download_kwargs: optional attributes for DownloadConfig() which will override the attributes in download_config if supplied.
"""
evaluation_module = evaluation_module_factory(
path, download_config=download_config, force_local_path=local_path, **download_kwargs
)
print(
f"The processing scripts for metric {path} can be inspected at {local_path}. "
f"The main class is in {evaluation_module.module_path}. "
f"You can modify this processing scripts and use it with `evaluate.load({local_path})`."
)
|
(path: str, local_path: str, download_config: Optional[datasets.download.download_config.DownloadConfig] = None, **download_kwargs)
|
71,366 |
evaluate.utils.logging
|
is_progress_bar_enabled
|
Return a boolean indicating whether tqdm progress bars are enabled.
|
def is_progress_bar_enabled() -> bool:
"""Return a boolean indicating whether tqdm progress bars are enabled."""
global _tqdm_active
return bool(_tqdm_active)
|
() -> bool
|
71,367 |
evaluate.utils.gradio
|
json_to_string_type
|
Maps json input type to str.
|
def json_to_string_type(input_types):
"""Maps json input type to str."""
return ["str" if i == "json" else i for i in input_types]
|
(input_types)
|
71,368 |
evaluate.utils.gradio
|
launch_gradio_widget
|
Launches `metric` widget with Gradio.
|
def launch_gradio_widget(metric):
"""Launches `metric` widget with Gradio."""
try:
import gradio as gr
except ImportError as error:
logger.error("To create a metric widget with Gradio make sure gradio is installed.")
raise error
local_path = Path(sys.path[0])
# if there are several input types, use first as default.
if isinstance(metric.features, list):
(feature_names, feature_types) = zip(*metric.features[0].items())
else:
(feature_names, feature_types) = zip(*metric.features.items())
gradio_input_types = infer_gradio_input_types(feature_types)
def compute(data):
return metric.compute(**parse_gradio_data(data, gradio_input_types))
iface = gr.Interface(
fn=compute,
inputs=gr.inputs.Dataframe(
headers=feature_names,
col_count=len(feature_names),
row_count=1,
datatype=json_to_string_type(gradio_input_types),
),
outputs=gr.outputs.Textbox(label=metric.name),
description=(
metric.info.description + "\nIf this is a text-based metric, make sure to wrap you input in double quotes."
" Alternatively you can use a JSON-formatted list as input."
),
title=f"Metric: {metric.name}",
article=parse_readme(local_path / "README.md"),
# TODO: load test cases and use them to populate examples
# examples=[parse_test_cases(test_cases, feature_names, gradio_input_types)]
)
iface.launch()
|
(metric)
|
71,369 |
evaluate.inspect
|
list_evaluation_modules
|
List all evaluation modules available on the Hugging Face Hub.
Args:
module_type (`str`, *optional*, defaults to `None`):
Type of evaluation modules to list. Has to be one of `'metric'`, `'comparison'`, or `'measurement'`. If `None`, all types are listed.
include_community (`bool`, *optional*, defaults to `True`):
Include community modules in the list.
with_details (`bool`, *optional*, defaults to `False`):
Return the full details on the metrics instead of only the ID.
Returns:
`List[Union[str, dict]]`
Example:
```py
>>> from evaluate import list_evaluation_modules
>>> list_evaluation_modules(module_type="metric")
```
|
def list_evaluation_modules(module_type=None, include_community=True, with_details=False):
"""List all evaluation modules available on the Hugging Face Hub.
Args:
module_type (`str`, *optional*, defaults to `None`):
Type of evaluation modules to list. Has to be one of `'metric'`, `'comparison'`, or `'measurement'`. If `None`, all types are listed.
include_community (`bool`, *optional*, defaults to `True`):
Include community modules in the list.
with_details (`bool`, *optional*, defaults to `False`):
Return the full details on the metrics instead of only the ID.
Returns:
`List[Union[str, dict]]`
Example:
```py
>>> from evaluate import list_evaluation_modules
>>> list_evaluation_modules(module_type="metric")
```
"""
if module_type is None:
evaluations_list = []
for module_type in EVALUATION_MODULE_TYPES:
evaluations_list.extend(
_list_evaluation_modules_type(
module_type, include_community=include_community, with_details=with_details
)
)
else:
if module_type not in EVALUATION_MODULE_TYPES:
raise ValueError(f"Invalid module type '{module_type}'. Has to be one of {EVALUATION_MODULE_TYPES}.")
evaluations_list = _list_evaluation_modules_type(
module_type, include_community=include_community, with_details=with_details
)
return evaluations_list
|
(module_type=None, include_community=True, with_details=False)
|
71,370 |
evaluate.loading
|
load
|
Load a [`~evaluate.EvaluationModule`].
Args:
path (`str`):
Path to the evaluation processing script with the evaluation builder. Can be either:
- a local path to processing script or the directory containing the script (if the script has the same name as the directory),
e.g. `'./metrics/rouge'` or `'./metrics/rouge/rouge.py'`
- a evaluation module identifier on the HuggingFace evaluate repo e.g. `'rouge'` or `'bleu'` that are in either `'metrics/'`,
`'comparisons/'`, or `'measurements/'` depending on the provided `module_type`
config_name (`str`, *optional*):
Selecting a configuration for the metric (e.g. the GLUE metric has a configuration for each subset).
module_type (`str`, default `'metric'`):
Type of evaluation module, can be one of `'metric'`, `'comparison'`, or `'measurement'`.
process_id (`int`, *optional*):
For distributed evaluation: id of the process.
num_process (`int`, *optional*):
For distributed evaluation: total number of processes.
cache_dir (`str`, *optional*):
Path to store the temporary predictions and references (default to `~/.cache/huggingface/evaluate/`).
experiment_id (`str`):
A specific experiment id. This is used if several distributed evaluations share the same file system.
This is useful to compute metrics in distributed setups (in particular non-additive metrics like F1).
keep_in_memory (`bool`):
Whether to store the temporary results in memory (defaults to `False`).
download_config ([`~evaluate.DownloadConfig`], *optional*):
Specific download configuration parameters.
download_mode ([`DownloadMode`], defaults to `REUSE_DATASET_IF_EXISTS`):
Download/generate mode.
revision (`Union[str, evaluate.Version]`, *optional*):
If specified, the module will be loaded from the datasets repository
at this version. By default it is set to the local version of the lib. Specifying a version that is different from
your local version of the lib might cause compatibility issues.
Returns:
[`evaluate.EvaluationModule`]
Example:
```py
>>> from evaluate import load
>>> accuracy = load("accuracy")
```
|
def load(
path: str,
config_name: Optional[str] = None,
module_type: Optional[str] = None,
process_id: int = 0,
num_process: int = 1,
cache_dir: Optional[str] = None,
experiment_id: Optional[str] = None,
keep_in_memory: bool = False,
download_config: Optional[DownloadConfig] = None,
download_mode: Optional[DownloadMode] = None,
revision: Optional[Union[str, Version]] = None,
**init_kwargs,
) -> EvaluationModule:
"""Load a [`~evaluate.EvaluationModule`].
Args:
path (`str`):
Path to the evaluation processing script with the evaluation builder. Can be either:
- a local path to processing script or the directory containing the script (if the script has the same name as the directory),
e.g. `'./metrics/rouge'` or `'./metrics/rouge/rouge.py'`
- a evaluation module identifier on the HuggingFace evaluate repo e.g. `'rouge'` or `'bleu'` that are in either `'metrics/'`,
`'comparisons/'`, or `'measurements/'` depending on the provided `module_type`
config_name (`str`, *optional*):
Selecting a configuration for the metric (e.g. the GLUE metric has a configuration for each subset).
module_type (`str`, default `'metric'`):
Type of evaluation module, can be one of `'metric'`, `'comparison'`, or `'measurement'`.
process_id (`int`, *optional*):
For distributed evaluation: id of the process.
num_process (`int`, *optional*):
For distributed evaluation: total number of processes.
cache_dir (`str`, *optional*):
Path to store the temporary predictions and references (default to `~/.cache/huggingface/evaluate/`).
experiment_id (`str`):
A specific experiment id. This is used if several distributed evaluations share the same file system.
This is useful to compute metrics in distributed setups (in particular non-additive metrics like F1).
keep_in_memory (`bool`):
Whether to store the temporary results in memory (defaults to `False`).
download_config ([`~evaluate.DownloadConfig`], *optional*):
Specific download configuration parameters.
download_mode ([`DownloadMode`], defaults to `REUSE_DATASET_IF_EXISTS`):
Download/generate mode.
revision (`Union[str, evaluate.Version]`, *optional*):
If specified, the module will be loaded from the datasets repository
at this version. By default it is set to the local version of the lib. Specifying a version that is different from
your local version of the lib might cause compatibility issues.
Returns:
[`evaluate.EvaluationModule`]
Example:
```py
>>> from evaluate import load
>>> accuracy = load("accuracy")
```
"""
download_mode = DownloadMode(download_mode or DownloadMode.REUSE_DATASET_IF_EXISTS)
evaluation_module = evaluation_module_factory(
path, module_type=module_type, revision=revision, download_config=download_config, download_mode=download_mode
)
evaluation_cls = import_main_class(evaluation_module.module_path)
evaluation_instance = evaluation_cls(
config_name=config_name,
process_id=process_id,
num_process=num_process,
cache_dir=cache_dir,
keep_in_memory=keep_in_memory,
experiment_id=experiment_id,
hash=evaluation_module.hash,
**init_kwargs,
)
if module_type and module_type != evaluation_instance.module_type:
raise TypeError(
f"No module of module type '{module_type}' not found for '{path}' locally, or on the Hugging Face Hub. Found module of module type '{evaluation_instance.module_type}' instead."
)
# Download and prepare resources for the metric
evaluation_instance.download_and_prepare(download_config=download_config)
return evaluation_instance
|
(path: str, config_name: Optional[str] = None, module_type: Optional[str] = None, process_id: int = 0, num_process: int = 1, cache_dir: Optional[str] = None, experiment_id: Optional[str] = None, keep_in_memory: bool = False, download_config: Optional[datasets.download.download_config.DownloadConfig] = None, download_mode: Optional[datasets.download.download_manager.DownloadMode] = None, revision: Union[str, datasets.utils.version.Version, NoneType] = None, **init_kwargs) -> evaluate.module.EvaluationModule
|
71,375 |
evaluate.utils.gradio
|
parse_gradio_data
|
Parses data from gradio Dataframe for use in metric.
|
def parse_gradio_data(data, input_types):
"""Parses data from gradio Dataframe for use in metric."""
metric_inputs = {}
data.replace("", np.nan, inplace=True)
data.dropna(inplace=True)
for feature_name, input_type in zip(data, input_types):
if input_type == "json":
metric_inputs[feature_name] = [json.loads(d) for d in data[feature_name].to_list()]
elif input_type == "str":
metric_inputs[feature_name] = [d.strip('"') for d in data[feature_name].to_list()]
else:
metric_inputs[feature_name] = data[feature_name]
return metric_inputs
|
(data, input_types)
|
71,376 |
evaluate.utils.gradio
|
parse_readme
|
Parses a repositories README and removes
|
def parse_readme(filepath):
"""Parses a repositories README and removes"""
if not os.path.exists(filepath):
return "No README.md found."
with open(filepath, "r") as f:
text = f.read()
match = REGEX_YAML_BLOCK.search(text)
if match:
text = text[match.end() :]
return text
|
(filepath)
|
71,377 |
evaluate.utils.gradio
|
parse_test_cases
|
Parses test cases to be used in gradio Dataframe. Note that an apostrophe is added
to strings to follow the format in json.
|
def parse_test_cases(test_cases, feature_names, input_types):
"""
Parses test cases to be used in gradio Dataframe. Note that an apostrophe is added
to strings to follow the format in json.
"""
if len(test_cases) == 0:
return None
examples = []
for test_case in test_cases:
parsed_cases = []
for feat, input_type in zip(feature_names, input_types):
if input_type == "json":
parsed_cases.append([str(element) for element in test_case[feat]])
elif input_type == "str":
parsed_cases.append(['"' + element + '"' for element in test_case[feat]])
else:
parsed_cases.append(test_case[feat])
examples.append([list(i) for i in zip(*parsed_cases)])
return examples
|
(test_cases, feature_names, input_types)
|
71,378 |
evaluate.hub
|
push_to_hub
|
Pushes the result of a metric to the metadata of a model repository in the Hub.
Args:
model_id (`str`):
Model id from https://hf.co/models.
task_type (`str`):
Task id, refer to the [Hub allowed tasks](https://github.com/huggingface/evaluate/blob/main/src/evaluate/config.py#L154) for allowed values.
dataset_type (`str`):
Dataset id from https://hf.co/datasets.
dataset_name (`str`):
Pretty name for the dataset.
metric_type (`str`):
Metric id from https://hf.co/metrics.
metric_name (`str`):
Pretty name for the metric.
metric_value (`float`):
Computed metric value.
task_name (`str`, *optional*):
Pretty name for the task.
dataset_config (`str`, *optional*):
Dataset configuration used in [`~datasets.load_dataset`].
See [`~datasets.load_dataset`] for more info.
dataset_split (`str`, *optional*):
Name of split used for metric computation.
dataset_revision (`str`, *optional*):
Git hash for the specific version of the dataset.
dataset_args (`dict[str, int]`, *optional*):
Additional arguments passed to [`~datasets.load_dataset`].
metric_config (`str`, *optional*):
Configuration for the metric (e.g. the GLUE metric has a configuration for each subset).
metric_args (`dict[str, int]`, *optional*):
Arguments passed during [`~evaluate.EvaluationModule.compute`].
overwrite (`bool`, *optional*, defaults to `False`):
If set to `True` an existing metric field can be overwritten, otherwise
attempting to overwrite any existing fields will cause an error.
Example:
```python
>>> push_to_hub(
... model_id="huggingface/gpt2-wikitext2",
... metric_value=0.5
... metric_type="bleu",
... metric_name="BLEU",
... dataset_name="WikiText",
... dataset_type="wikitext",
... dataset_split="test",
... task_type="text-generation",
... task_name="Text Generation"
... )
```
|
def push_to_hub(
model_id: str,
task_type: str,
dataset_type: str,
dataset_name: str,
metric_type: str,
metric_name: str,
metric_value: float,
task_name: str = None,
dataset_config: str = None,
dataset_split: str = None,
dataset_revision: str = None,
dataset_args: Dict[str, int] = None,
metric_config: str = None,
metric_args: Dict[str, int] = None,
overwrite: bool = False,
):
r"""
Pushes the result of a metric to the metadata of a model repository in the Hub.
Args:
model_id (`str`):
Model id from https://hf.co/models.
task_type (`str`):
Task id, refer to the [Hub allowed tasks](https://github.com/huggingface/evaluate/blob/main/src/evaluate/config.py#L154) for allowed values.
dataset_type (`str`):
Dataset id from https://hf.co/datasets.
dataset_name (`str`):
Pretty name for the dataset.
metric_type (`str`):
Metric id from https://hf.co/metrics.
metric_name (`str`):
Pretty name for the metric.
metric_value (`float`):
Computed metric value.
task_name (`str`, *optional*):
Pretty name for the task.
dataset_config (`str`, *optional*):
Dataset configuration used in [`~datasets.load_dataset`].
See [`~datasets.load_dataset`] for more info.
dataset_split (`str`, *optional*):
Name of split used for metric computation.
dataset_revision (`str`, *optional*):
Git hash for the specific version of the dataset.
dataset_args (`dict[str, int]`, *optional*):
Additional arguments passed to [`~datasets.load_dataset`].
metric_config (`str`, *optional*):
Configuration for the metric (e.g. the GLUE metric has a configuration for each subset).
metric_args (`dict[str, int]`, *optional*):
Arguments passed during [`~evaluate.EvaluationModule.compute`].
overwrite (`bool`, *optional*, defaults to `False`):
If set to `True` an existing metric field can be overwritten, otherwise
attempting to overwrite any existing fields will cause an error.
Example:
```python
>>> push_to_hub(
... model_id="huggingface/gpt2-wikitext2",
... metric_value=0.5
... metric_type="bleu",
... metric_name="BLEU",
... dataset_name="WikiText",
... dataset_type="wikitext",
... dataset_split="test",
... task_type="text-generation",
... task_name="Text Generation"
... )
```"""
if task_type not in HF_HUB_ALLOWED_TASKS:
raise ValueError(f"Task type not supported. Task has to be one of {HF_HUB_ALLOWED_TASKS}")
try:
dataset_info(dataset_type)
except requests.exceptions.HTTPError:
logger.warning(f"Dataset {dataset_type} not found on the Hub at hf.co/datasets/{dataset_type}")
try:
model_info(model_id)
except requests.exceptions.HTTPError:
raise ValueError(f"Model {model_id} not found on the Hub at hf.co/{model_id}")
result = {
"task": {
"type": task_type,
},
"dataset": {
"type": dataset_type,
"name": dataset_name,
},
"metrics": [
{
"type": metric_type,
"value": metric_value,
},
],
}
if dataset_config is not None:
result["dataset"]["config"] = dataset_config
if dataset_split is not None:
result["dataset"]["split"] = dataset_split
if dataset_revision is not None:
result["dataset"]["revision"] = dataset_revision
if dataset_args is not None:
result["dataset"]["args"] = dataset_args
if task_name is not None:
result["task"]["name"] = task_name
if metric_name is not None:
result["metrics"][0]["name"] = metric_name
if metric_config is not None:
result["metrics"][0]["config"] = metric_config
if metric_args is not None:
result["metrics"][0]["args"] = metric_args
metadata = {"model-index": [{"results": [result]}]}
return metadata_update(repo_id=model_id, metadata=metadata, overwrite=overwrite)
|
(model_id: str, task_type: str, dataset_type: str, dataset_name: str, metric_type: str, metric_name: str, metric_value: float, task_name: Optional[str] = None, dataset_config: Optional[str] = None, dataset_split: Optional[str] = None, dataset_revision: Optional[str] = None, dataset_args: Optional[Dict[str, int]] = None, metric_config: Optional[str] = None, metric_args: Optional[Dict[str, int]] = None, overwrite: bool = False)
|
71,379 |
evaluate.saving
|
save
|
Saves results to a JSON file. Also saves system information such as current time, current commit
hash if inside a repository, and Python system information.
Args:
path_or_file (`str`):
Path or file to store the file. If only a folder is provided
the results file will be saved in the format `"result-%Y_%m_%d-%H_%M_%S.json"`.
Example:
```py
>>> import evaluate
>>> result = {"bleu": 0.7}
>>> params = {"model": "gpt-2"}
>>> evaluate.save("./results/", **result, **params)
```
|
def save(path_or_file, **data):
"""
Saves results to a JSON file. Also saves system information such as current time, current commit
hash if inside a repository, and Python system information.
Args:
path_or_file (`str`):
Path or file to store the file. If only a folder is provided
the results file will be saved in the format `"result-%Y_%m_%d-%H_%M_%S.json"`.
Example:
```py
>>> import evaluate
>>> result = {"bleu": 0.7}
>>> params = {"model": "gpt-2"}
>>> evaluate.save("./results/", **result, **params)
```
"""
current_time = datetime.now()
file_path = _setup_path(path_or_file, current_time)
data["_timestamp"] = current_time.isoformat()
data["_git_commit_hash"] = _git_commit_hash()
data["_evaluate_version"] = __version__
data["_python_version"] = sys.version
data["_interpreter_path"] = sys.executable
with FileLock(str(file_path) + ".lock"):
with open(file_path, "w") as f:
json.dump(data, f)
# cleanup lock file
try:
os.remove(str(file_path) + ".lock")
except FileNotFoundError:
pass
return file_path
|
(path_or_file, **data)
|
71,382 |
wtforms_components.validators
|
Chain
|
Represents a chain of validators, useful when using multiple validators
with If control structure.
:param validators:
list of validator objects
:param message:
custom validation error message, if this message is set and some of the
child validators raise a ValidationError, an exception is being raised
again with this custom message.
|
class Chain(ControlStructure):
"""
Represents a chain of validators, useful when using multiple validators
with If control structure.
:param validators:
list of validator objects
:param message:
custom validation error message, if this message is set and some of the
child validators raise a ValidationError, an exception is being raised
again with this custom message.
"""
def __init__(self, validators, message=None):
self.validators = validators
if message:
self.message = message
def __call__(self, form, field):
for validator in self.validators:
try:
validator(form, field)
except ValidationError as exc:
self.reraise(exc)
except StopValidation as exc:
self.reraise(exc)
|
(validators, message=None)
|
71,383 |
wtforms_components.validators
|
__call__
| null |
def __call__(self, form, field):
for validator in self.validators:
try:
validator(form, field)
except ValidationError as exc:
self.reraise(exc)
except StopValidation as exc:
self.reraise(exc)
|
(self, form, field)
|
71,384 |
wtforms_components.validators
|
__init__
| null |
def __init__(self, validators, message=None):
self.validators = validators
if message:
self.message = message
|
(self, validators, message=None)
|
71,385 |
wtforms_components.validators
|
reraise
| null |
def reraise(self, exc):
if not self.message:
raise exc
else:
raise type(exc)(self.message)
|
(self, exc)
|
71,386 |
wtforms_components.fields.color
|
ColorField
|
A string field representing a Color object from python colour package.
.. _colours:
https://github.com/vaab/colour
Represents an ``<input type="color">``.
|
class ColorField(StringField):
"""
A string field representing a Color object from python colour package.
.. _colours:
https://github.com/vaab/colour
Represents an ``<input type="color">``.
"""
widget = ColorInput()
error_msg = u'Not a valid color.'
def _value(self):
if self.raw_data:
return self.raw_data[0]
if self.data:
return str(self.data)
else:
return u''
def process_formdata(self, valuelist):
from colour import Color
if valuelist:
if valuelist[0] == u'' or valuelist[0] == '':
self.data = None
else:
try:
self.data = Color(valuelist[0])
except AttributeError:
self.data = None
raise ValueError(self.gettext(self.error_msg))
|
(*args, **kwargs)
|
71,387 |
wtforms.fields.core
|
__call__
|
Render this field as HTML, using keyword args as additional attributes.
This delegates rendering to
:meth:`meta.render_field <wtforms.meta.DefaultMeta.render_field>`
whose default behavior is to call the field's widget, passing any
keyword arguments from this call along to the widget.
In all of the WTForms HTML widgets, keyword arguments are turned to
HTML attributes, though in theory a widget is free to do anything it
wants with the supplied keyword arguments, and widgets don't have to
even do anything related to HTML.
|
def __call__(self, **kwargs):
"""
Render this field as HTML, using keyword args as additional attributes.
This delegates rendering to
:meth:`meta.render_field <wtforms.meta.DefaultMeta.render_field>`
whose default behavior is to call the field's widget, passing any
keyword arguments from this call along to the widget.
In all of the WTForms HTML widgets, keyword arguments are turned to
HTML attributes, though in theory a widget is free to do anything it
wants with the supplied keyword arguments, and widgets don't have to
even do anything related to HTML.
"""
return self.meta.render_field(self, kwargs)
|
(self, **kwargs)
|
71,388 |
wtforms.fields.core
|
__html__
|
Returns a HTML representation of the field. For more powerful rendering,
see the :meth:`__call__` method.
|
def __html__(self):
"""
Returns a HTML representation of the field. For more powerful rendering,
see the :meth:`__call__` method.
"""
return self()
|
(self)
|
71,389 |
wtforms.fields.core
|
__init__
|
Construct a new field.
:param label:
The label of the field.
:param validators:
A sequence of validators to call when `validate` is called.
:param filters:
A sequence of callable which are run by :meth:`~Field.process`
to filter or transform the input data. For example
``StringForm(filters=[str.strip, str.upper])``.
Note that filters are applied after processing the default and
incoming data, but before validation.
:param description:
A description for the field, typically used for help text.
:param id:
An id to use for the field. A reasonable default is set by the form,
and you shouldn't need to set this manually.
:param default:
The default value to assign to the field, if no form or object
input is provided. May be a callable.
:param widget:
If provided, overrides the widget used to render the field.
:param dict render_kw:
If provided, a dictionary which provides default keywords that
will be given to the widget at render time.
:param name:
The HTML name of this field. The default value is the Python
attribute name.
:param _form:
The form holding this field. It is passed by the form itself during
construction. You should never pass this value yourself.
:param _prefix:
The prefix to prepend to the form name of this field, passed by
the enclosing form during construction.
:param _translations:
A translations object providing message translations. Usually
passed by the enclosing form during construction. See
:doc:`I18n docs <i18n>` for information on message translations.
:param _meta:
If provided, this is the 'meta' instance from the form. You usually
don't pass this yourself.
If `_form` isn't provided, an :class:`UnboundField` will be
returned instead. Call its :func:`bind` method with a form instance and
a name to construct the field.
|
def __init__(
self,
label=None,
validators=None,
filters=(),
description="",
id=None,
default=None,
widget=None,
render_kw=None,
name=None,
_form=None,
_prefix="",
_translations=None,
_meta=None,
):
"""
Construct a new field.
:param label:
The label of the field.
:param validators:
A sequence of validators to call when `validate` is called.
:param filters:
A sequence of callable which are run by :meth:`~Field.process`
to filter or transform the input data. For example
``StringForm(filters=[str.strip, str.upper])``.
Note that filters are applied after processing the default and
incoming data, but before validation.
:param description:
A description for the field, typically used for help text.
:param id:
An id to use for the field. A reasonable default is set by the form,
and you shouldn't need to set this manually.
:param default:
The default value to assign to the field, if no form or object
input is provided. May be a callable.
:param widget:
If provided, overrides the widget used to render the field.
:param dict render_kw:
If provided, a dictionary which provides default keywords that
will be given to the widget at render time.
:param name:
The HTML name of this field. The default value is the Python
attribute name.
:param _form:
The form holding this field. It is passed by the form itself during
construction. You should never pass this value yourself.
:param _prefix:
The prefix to prepend to the form name of this field, passed by
the enclosing form during construction.
:param _translations:
A translations object providing message translations. Usually
passed by the enclosing form during construction. See
:doc:`I18n docs <i18n>` for information on message translations.
:param _meta:
If provided, this is the 'meta' instance from the form. You usually
don't pass this yourself.
If `_form` isn't provided, an :class:`UnboundField` will be
returned instead. Call its :func:`bind` method with a form instance and
a name to construct the field.
"""
if _translations is not None:
self._translations = _translations
if _meta is not None:
self.meta = _meta
elif _form is not None:
self.meta = _form.meta
else:
raise TypeError("Must provide one of _form or _meta")
self.default = default
self.description = description
self.render_kw = render_kw
self.filters = filters
self.flags = Flags()
self.name = _prefix + name
self.short_name = name
self.type = type(self).__name__
self.check_validators(validators)
self.validators = validators or self.validators
self.id = id or self.name
self.label = Label(
self.id,
label
if label is not None
else self.gettext(name.replace("_", " ").title()),
)
if widget is not None:
self.widget = widget
for v in itertools.chain(self.validators, [self.widget]):
flags = getattr(v, "field_flags", {})
# check for legacy format, remove eventually
if isinstance(flags, tuple): # pragma: no cover
warnings.warn(
"Flags should be stored in dicts and not in tuples. "
"The next version of WTForms will abandon support "
"for flags in tuples.",
DeprecationWarning,
stacklevel=2,
)
flags = {flag_name: True for flag_name in flags}
for k, v in flags.items():
setattr(self.flags, k, v)
|
(self, label=None, validators=None, filters=(), description='', id=None, default=None, widget=None, render_kw=None, name=None, _form=None, _prefix='', _translations=None, _meta=None)
|
71,390 |
wtforms.fields.core
|
__new__
| null |
def __new__(cls, *args, **kwargs):
if "_form" in kwargs:
return super().__new__(cls)
else:
return UnboundField(cls, *args, **kwargs)
|
(cls, *args, **kwargs)
|
71,391 |
wtforms.fields.core
|
__str__
|
Returns a HTML representation of the field. For more powerful rendering,
see the `__call__` method.
|
def __str__(self):
"""
Returns a HTML representation of the field. For more powerful rendering,
see the `__call__` method.
"""
return self()
|
(self)
|
71,392 |
wtforms.fields.core
|
_run_validation_chain
|
Run a validation chain, stopping if any validator raises StopValidation.
:param form: The Form instance this field belongs to.
:param validators: a sequence or iterable of validator callables.
:return: True if validation was stopped, False otherwise.
|
def _run_validation_chain(self, form, validators):
"""
Run a validation chain, stopping if any validator raises StopValidation.
:param form: The Form instance this field belongs to.
:param validators: a sequence or iterable of validator callables.
:return: True if validation was stopped, False otherwise.
"""
for validator in validators:
try:
validator(form, self)
except StopValidation as e:
if e.args and e.args[0]:
self.errors.append(e.args[0])
return True
except ValidationError as e:
self.errors.append(e.args[0])
return False
|
(self, form, validators)
|
71,393 |
wtforms_components.fields.color
|
_value
| null |
def _value(self):
if self.raw_data:
return self.raw_data[0]
if self.data:
return str(self.data)
else:
return u''
|
(self)
|
71,394 |
wtforms.fields.core
|
gettext
|
Get a translation for the given message.
This proxies for the internal translations object.
:param string: A string to be translated.
:return: A string which is the translated output.
|
def gettext(self, string):
"""
Get a translation for the given message.
This proxies for the internal translations object.
:param string: A string to be translated.
:return: A string which is the translated output.
"""
return self._translations.gettext(string)
|
(self, string)
|
71,395 |
wtforms.fields.core
|
ngettext
|
Get a translation for a message which can be pluralized.
:param str singular: The singular form of the message.
:param str plural: The plural form of the message.
:param int n: The number of elements this message is referring to
|
def ngettext(self, singular, plural, n):
"""
Get a translation for a message which can be pluralized.
:param str singular: The singular form of the message.
:param str plural: The plural form of the message.
:param int n: The number of elements this message is referring to
"""
return self._translations.ngettext(singular, plural, n)
|
(self, singular, plural, n)
|
71,396 |
wtforms.fields.core
|
populate_obj
|
Populates `obj.<name>` with the field's data.
:note: This is a destructive operation. If `obj.<name>` already exists,
it will be overridden. Use with caution.
|
def populate_obj(self, obj, name):
"""
Populates `obj.<name>` with the field's data.
:note: This is a destructive operation. If `obj.<name>` already exists,
it will be overridden. Use with caution.
"""
setattr(obj, name, self.data)
|
(self, obj, name)
|
71,397 |
wtforms.fields.core
|
post_validate
|
Override if you need to run any field-level validation tasks after
normal validation. This shouldn't be needed in most cases.
:param form: The form the field belongs to.
:param validation_stopped:
`True` if any validator raised StopValidation.
|
def post_validate(self, form, validation_stopped):
"""
Override if you need to run any field-level validation tasks after
normal validation. This shouldn't be needed in most cases.
:param form: The form the field belongs to.
:param validation_stopped:
`True` if any validator raised StopValidation.
"""
pass
|
(self, form, validation_stopped)
|
71,398 |
wtforms.fields.core
|
pre_validate
|
Override if you need field-level validation. Runs before any other
validators.
:param form: The form the field belongs to.
|
def pre_validate(self, form):
"""
Override if you need field-level validation. Runs before any other
validators.
:param form: The form the field belongs to.
"""
pass
|
(self, form)
|
71,399 |
wtforms.fields.core
|
process
|
Process incoming data, calling process_data, process_formdata as needed,
and run filters.
If `data` is not provided, process_data will be called on the field's
default.
Field subclasses usually won't override this, instead overriding the
process_formdata and process_data methods. Only override this for
special advanced processing, such as when a field encapsulates many
inputs.
:param extra_filters: A sequence of extra filters to run.
|
def process(self, formdata, data=unset_value, extra_filters=None):
"""
Process incoming data, calling process_data, process_formdata as needed,
and run filters.
If `data` is not provided, process_data will be called on the field's
default.
Field subclasses usually won't override this, instead overriding the
process_formdata and process_data methods. Only override this for
special advanced processing, such as when a field encapsulates many
inputs.
:param extra_filters: A sequence of extra filters to run.
"""
self.process_errors = []
if data is unset_value:
try:
data = self.default()
except TypeError:
data = self.default
self.object_data = data
try:
self.process_data(data)
except ValueError as e:
self.process_errors.append(e.args[0])
if formdata is not None:
if self.name in formdata:
self.raw_data = formdata.getlist(self.name)
else:
self.raw_data = []
try:
self.process_formdata(self.raw_data)
except ValueError as e:
self.process_errors.append(e.args[0])
try:
for filter in itertools.chain(self.filters, extra_filters or []):
self.data = filter(self.data)
except ValueError as e:
self.process_errors.append(e.args[0])
|
(self, formdata, data=<unset value>, extra_filters=None)
|
71,400 |
wtforms.fields.core
|
process_data
|
Process the Python data applied to this field and store the result.
This will be called during form construction by the form's `kwargs` or
`obj` argument.
:param value: The python object containing the value to process.
|
def process_data(self, value):
"""
Process the Python data applied to this field and store the result.
This will be called during form construction by the form's `kwargs` or
`obj` argument.
:param value: The python object containing the value to process.
"""
self.data = value
|
(self, value)
|
71,401 |
wtforms_components.fields.color
|
process_formdata
| null |
def process_formdata(self, valuelist):
from colour import Color
if valuelist:
if valuelist[0] == u'' or valuelist[0] == '':
self.data = None
else:
try:
self.data = Color(valuelist[0])
except AttributeError:
self.data = None
raise ValueError(self.gettext(self.error_msg))
|
(self, valuelist)
|
71,402 |
wtforms.fields.core
|
validate
|
Validates the field and returns True or False. `self.errors` will
contain any errors raised during validation. This is usually only
called by `Form.validate`.
Subfields shouldn't override this, but rather override either
`pre_validate`, `post_validate` or both, depending on needs.
:param form: The form the field belongs to.
:param extra_validators: A sequence of extra validators to run.
|
def validate(self, form, extra_validators=()):
"""
Validates the field and returns True or False. `self.errors` will
contain any errors raised during validation. This is usually only
called by `Form.validate`.
Subfields shouldn't override this, but rather override either
`pre_validate`, `post_validate` or both, depending on needs.
:param form: The form the field belongs to.
:param extra_validators: A sequence of extra validators to run.
"""
self.errors = list(self.process_errors)
stop_validation = False
# Check the type of extra_validators
self.check_validators(extra_validators)
# Call pre_validate
try:
self.pre_validate(form)
except StopValidation as e:
if e.args and e.args[0]:
self.errors.append(e.args[0])
stop_validation = True
except ValidationError as e:
self.errors.append(e.args[0])
# Run validators
if not stop_validation:
chain = itertools.chain(self.validators, extra_validators)
stop_validation = self._run_validation_chain(form, chain)
# Call post_validate
try:
self.post_validate(form, stop_validation)
except ValidationError as e:
self.errors.append(e.args[0])
return len(self.errors) == 0
|
(self, form, extra_validators=())
|
71,403 |
wtforms_components.fields.html5
|
DateField
| null |
class DateField(DateField):
widget = DateInput()
|
(*args, **kwargs)
|
71,406 |
wtforms.fields.datetime
|
__init__
| null |
def __init__(self, label=None, validators=None, format="%Y-%m-%d", **kwargs):
super().__init__(label, validators, format, **kwargs)
|
(self, label=None, validators=None, format='%Y-%m-%d', **kwargs)
|
71,410 |
wtforms.fields.datetime
|
_value
| null |
def _value(self):
if self.raw_data:
return " ".join(self.raw_data)
return self.data and self.data.strftime(self.format[0]) or ""
|
(self)
|
71,418 |
wtforms.fields.datetime
|
process_formdata
| null |
def process_formdata(self, valuelist):
if not valuelist:
return
date_str = " ".join(valuelist)
for format in self.strptime_format:
try:
self.data = datetime.datetime.strptime(date_str, format).date()
return
except ValueError:
self.data = None
raise ValueError(self.gettext("Not a valid date value."))
|
(self, valuelist)
|
71,420 |
wtforms_components.fields.interval
|
DateIntervalField
| null |
class DateIntervalField(IntervalField):
error_msg = u'Not a valid date range value'
interval_class = DateInterval
|
(*args, **kwargs)
|
71,427 |
wtforms_components.fields.interval
|
_value
| null |
def _value(self):
if self.raw_data:
return self.raw_data[0]
if self.data:
return self.data.hyphenized
else:
return u''
|
(self)
|
71,435 |
wtforms_components.fields.interval
|
process_formdata
| null |
def process_formdata(self, valuelist):
if valuelist:
if valuelist[0] == u'' or valuelist[0] == '':
self.data = None
else:
try:
self.data = self.interval_class.from_string(valuelist[0])
except IntervalException:
self.data = None
raise ValueError(self.gettext(self.error_msg))
|
(self, valuelist)
|
71,437 |
wtforms_components.validators
|
DateRange
|
Same as wtforms.validators.NumberRange but validates date.
:param min:
The minimum required value of the date. If not provided, minimum
value will not be checked.
:param max:
The maximum value of the date. If not provided, maximum value
will not be checked.
:param message:
Error message to raise in case of a validation error. Can be
interpolated using `%(min)s` and `%(max)s` if desired. Useful defaults
are provided depending on the existence of min and max.
|
class DateRange(BaseDateTimeRange):
"""
Same as wtforms.validators.NumberRange but validates date.
:param min:
The minimum required value of the date. If not provided, minimum
value will not be checked.
:param max:
The maximum value of the date. If not provided, maximum value
will not be checked.
:param message:
Error message to raise in case of a validation error. Can be
interpolated using `%(min)s` and `%(max)s` if desired. Useful defaults
are provided depending on the existence of min and max.
"""
greater_than_msg = u'Date must be greater than %(min)s.'
less_than_msg = u'Date must be less than %(max)s.'
between_msg = u'Date must be between %(min)s and %(max)s.'
def __init__(self, min=None, max=None, format='%Y-%m-%d', message=None):
super(DateRange, self).__init__(
min=min, max=max, format=format, message=message
)
|
(min=None, max=None, format='%Y-%m-%d', message=None)
|
71,438 |
wtforms_components.validators
|
__call__
| null |
def __call__(self, form, field):
data = field.data
min_ = self.min() if callable(self.min) else self.min
max_ = self.max() if callable(self.max) else self.max
if (data is None or (min_ is not None and data < min_) or
(max_ is not None and data > max_)):
if self.message is None:
if max_ is None:
self.message = field.gettext(self.greater_than_msg)
elif min_ is None:
self.message = field.gettext(self.less_than_msg)
else:
self.message = field.gettext(self.between_msg)
raise ValidationError(
self.message % dict(
field_label=field.label,
min=min_.strftime(self.format) if min_ else '',
max=max_.strftime(self.format) if max_ else ''
)
)
|
(self, form, field)
|
71,439 |
wtforms_components.validators
|
__init__
| null |
def __init__(self, min=None, max=None, format='%Y-%m-%d', message=None):
super(DateRange, self).__init__(
min=min, max=max, format=format, message=message
)
|
(self, min=None, max=None, format='%Y-%m-%d', message=None)
|
71,440 |
wtforms_components.fields.html5
|
DateTimeField
| null |
class DateTimeField(DateTimeField):
widget = DateTimeInput()
|
(*args, **kwargs)
|
71,443 |
wtforms.fields.datetime
|
__init__
| null |
def __init__(
self, label=None, validators=None, format="%Y-%m-%d %H:%M:%S", **kwargs
):
super().__init__(label, validators, **kwargs)
self.format = format if isinstance(format, list) else [format]
self.strptime_format = clean_datetime_format_for_strptime(self.format)
|
(self, label=None, validators=None, format='%Y-%m-%d %H:%M:%S', **kwargs)
|
71,455 |
wtforms.fields.datetime
|
process_formdata
| null |
def process_formdata(self, valuelist):
if not valuelist:
return
date_str = " ".join(valuelist)
for format in self.strptime_format:
try:
self.data = datetime.datetime.strptime(date_str, format)
return
except ValueError:
self.data = None
raise ValueError(self.gettext("Not a valid datetime value."))
|
(self, valuelist)
|
71,457 |
wtforms_components.fields.interval
|
DateTimeIntervalField
| null |
class DateTimeIntervalField(IntervalField):
error_msg = u'Not a valid datetime range value'
interval_class = DateTimeInterval
|
(*args, **kwargs)
|
71,474 |
wtforms_components.fields.html5
|
DateTimeLocalField
| null |
class DateTimeLocalField(DateTimeField):
def __init__(
self,
label=None,
validators=None,
format='%Y-%m-%dT%H:%M:%S',
**kwargs
):
super(DateTimeLocalField, self).__init__(
label,
validators,
format,
**kwargs
)
widget = DateTimeLocalInput()
|
(label=None, validators=None, format='%Y-%m-%dT%H:%M:%S', **kwargs)
|
71,477 |
wtforms_components.fields.html5
|
__init__
| null |
def __init__(
self,
label=None,
validators=None,
format='%Y-%m-%dT%H:%M:%S',
**kwargs
):
super(DateTimeLocalField, self).__init__(
label,
validators,
format,
**kwargs
)
|
(self, label=None, validators=None, format='%Y-%m-%dT%H:%M:%S', **kwargs)
|
71,491 |
wtforms_components.fields.html5
|
DecimalField
| null |
class DecimalField(DecimalField):
widget = NumberInput(step='any')
|
(*args, **kwargs)
|
71,494 |
wtforms.fields.numeric
|
__init__
| null |
def __init__(
self, label=None, validators=None, places=unset_value, rounding=None, **kwargs
):
super().__init__(label, validators, **kwargs)
if self.use_locale and (places is not unset_value or rounding is not None):
raise TypeError(
"When using locale-aware numbers, 'places' and 'rounding' are ignored."
)
if places is unset_value:
places = 2
self.places = places
self.rounding = rounding
|
(self, label=None, validators=None, places=<unset value>, rounding=None, **kwargs)
|
71,497 |
wtforms.fields.numeric
|
_format_decimal
| null |
def _format_decimal(self, value):
return self.babel_numbers.format_decimal(value, self.number_format, self.locale)
|
(self, value)
|
71,498 |
wtforms.fields.numeric
|
_init_babel
| null |
def _init_babel(self):
try:
from babel import numbers
self.babel_numbers = numbers
except ImportError as exc:
raise ImportError(
"Using locale-aware decimals requires the babel library."
) from exc
|
(self)
|
71,499 |
wtforms.fields.numeric
|
_parse_decimal
| null |
def _parse_decimal(self, value):
return self.babel_numbers.parse_decimal(value, self.locale)
|
(self, value)
|
71,501 |
wtforms.fields.numeric
|
_value
| null |
def _value(self):
if self.raw_data:
return self.raw_data[0]
if self.data is None:
return ""
if self.use_locale:
return str(self._format_decimal(self.data))
if self.places is None:
return str(self.data)
if not hasattr(self.data, "quantize"):
# If for some reason, data is a float or int, then format
# as we would for floats using string formatting.
format = "%%0.%df" % self.places
return format % self.data
exp = decimal.Decimal(".1") ** self.places
if self.rounding is None:
quantized = self.data.quantize(exp)
else:
quantized = self.data.quantize(exp, rounding=self.rounding)
return str(quantized)
|
(self)
|
71,509 |
wtforms.fields.numeric
|
process_formdata
| null |
def process_formdata(self, valuelist):
if not valuelist:
return
try:
if self.use_locale:
self.data = self._parse_decimal(valuelist[0])
else:
self.data = decimal.Decimal(valuelist[0])
except (decimal.InvalidOperation, ValueError) as exc:
self.data = None
raise ValueError(self.gettext("Not a valid decimal value.")) from exc
|
(self, valuelist)
|
71,511 |
wtforms_components.fields.interval
|
DecimalIntervalField
| null |
class DecimalIntervalField(IntervalField):
error_msg = u'Not a valid decimal range value'
interval_class = DecimalInterval
|
(*args, **kwargs)
|
71,528 |
wtforms_components.fields.html5
|
DecimalSliderField
| null |
class DecimalSliderField(DecimalRangeField):
widget = RangeInput(step='any')
|
(*args, **kwargs)
|
71,548 |
wtforms_components.validators
|
Email
|
Validates an email address. This validator is based on `Django's
email validator`_ and is stricter than the standard email
validator included in WTForms.
.. _Django's email validator:
https://github.com/django/django/blob/master/django/core/validators.py
:param message:
Error message to raise in case of a validation error.
:copyright: (c) Django Software Foundation and individual contributors.
:license: BSD
|
class Email(object):
"""
Validates an email address. This validator is based on `Django's
email validator`_ and is stricter than the standard email
validator included in WTForms.
.. _Django's email validator:
https://github.com/django/django/blob/master/django/core/validators.py
:param message:
Error message to raise in case of a validation error.
:copyright: (c) Django Software Foundation and individual contributors.
:license: BSD
"""
domain_whitelist = ['localhost']
def __init__(self, message=None, whitelist=None):
self.message = message
if whitelist is not None:
self.domain_whitelist = whitelist
def __call__(self, form, field):
if not email(field.data, self.domain_whitelist):
if self.message is None:
self.message = field.gettext(u'Invalid email address.')
raise ValidationError(self.message)
|
(message=None, whitelist=None)
|
71,549 |
wtforms_components.validators
|
__call__
| null |
def __call__(self, form, field):
if not email(field.data, self.domain_whitelist):
if self.message is None:
self.message = field.gettext(u'Invalid email address.')
raise ValidationError(self.message)
|
(self, form, field)
|
71,550 |
wtforms_components.validators
|
__init__
| null |
def __init__(self, message=None, whitelist=None):
self.message = message
if whitelist is not None:
self.domain_whitelist = whitelist
|
(self, message=None, whitelist=None)
|
71,551 |
wtforms_components.fields.html5
|
EmailField
| null |
class EmailField(_StringField):
widget = EmailInput()
|
(*args, **kwargs)
|
71,558 |
wtforms.fields.simple
|
_value
| null |
def _value(self):
return str(self.data) if self.data is not None else ""
|
(self)
|
71,566 |
wtforms.fields.simple
|
process_formdata
| null |
def process_formdata(self, valuelist):
if valuelist:
self.data = valuelist[0]
|
(self, valuelist)
|
71,568 |
wtforms_components.fields.interval
|
FloatIntervalField
| null |
class FloatIntervalField(IntervalField):
error_msg = u'Not a valid float range value'
interval_class = FloatInterval
|
(*args, **kwargs)
|
71,585 |
wtforms.form
|
Form
|
Declarative Form base class. Extends BaseForm's core behaviour allowing
fields to be defined on Form subclasses as class attributes.
In addition, form and instance input data are taken at construction time
and passed to `process()`.
|
class Form(BaseForm, metaclass=FormMeta):
"""
Declarative Form base class. Extends BaseForm's core behaviour allowing
fields to be defined on Form subclasses as class attributes.
In addition, form and instance input data are taken at construction time
and passed to `process()`.
"""
Meta = DefaultMeta
def __init__(
self,
formdata=None,
obj=None,
prefix="",
data=None,
meta=None,
**kwargs,
):
"""
:param formdata: Input data coming from the client, usually
``request.form`` or equivalent. Should provide a "multi
dict" interface to get a list of values for a given key,
such as what Werkzeug, Django, and WebOb provide.
:param obj: Take existing data from attributes on this object
matching form field attributes. Only used if ``formdata`` is
not passed.
:param prefix: If provided, all fields will have their name
prefixed with the value. This is for distinguishing multiple
forms on a single page. This only affects the HTML name for
matching input data, not the Python name for matching
existing data.
:param data: Take existing data from keys in this dict matching
form field attributes. ``obj`` takes precedence if it also
has a matching attribute. Only used if ``formdata`` is not
passed.
:param meta: A dict of attributes to override on this form's
:attr:`meta` instance.
:param extra_filters: A dict mapping field attribute names to
lists of extra filter functions to run. Extra filters run
after filters passed when creating the field. If the form
has ``filter_<fieldname>``, it is the last extra filter.
:param kwargs: Merged with ``data`` to allow passing existing
data as parameters. Overwrites any duplicate keys in
``data``. Only used if ``formdata`` is not passed.
"""
meta_obj = self._wtforms_meta()
if meta is not None and isinstance(meta, dict):
meta_obj.update_values(meta)
super().__init__(self._unbound_fields, meta=meta_obj, prefix=prefix)
for name, field in self._fields.items():
# Set all the fields to attributes so that they obscure the class
# attributes with the same names.
setattr(self, name, field)
self.process(formdata, obj, data=data, **kwargs)
def __setitem__(self, name, value):
raise TypeError("Fields may not be added to Form instances, only classes.")
def __delitem__(self, name):
del self._fields[name]
setattr(self, name, None)
def __delattr__(self, name):
if name in self._fields:
self.__delitem__(name)
else:
# This is done for idempotency, if we have a name which is a field,
# we want to mask it by setting the value to None.
unbound_field = getattr(self.__class__, name, None)
if unbound_field is not None and hasattr(unbound_field, "_formfield"):
setattr(self, name, None)
else:
super().__delattr__(name)
def validate(self, extra_validators=None):
"""Validate the form by calling ``validate`` on each field.
Returns ``True`` if validation passes.
If the form defines a ``validate_<fieldname>`` method, it is
appended as an extra validator for the field's ``validate``.
:param extra_validators: A dict mapping field names to lists of
extra validator methods to run. Extra validators run after
validators passed when creating the field. If the form has
``validate_<fieldname>``, it is the last extra validator.
"""
if extra_validators is not None:
extra = extra_validators.copy()
else:
extra = {}
for name in self._fields:
inline = getattr(self.__class__, f"validate_{name}", None)
if inline is not None:
extra.setdefault(name, []).append(inline)
return super().validate(extra)
|
(*args, **kwargs)
|
71,586 |
wtforms.form
|
__contains__
|
Returns `True` if the named field is a member of this form.
|
def __contains__(self, name):
"""Returns `True` if the named field is a member of this form."""
return name in self._fields
|
(self, name)
|
71,587 |
wtforms.form
|
__delattr__
| null |
def __delattr__(self, name):
if name in self._fields:
self.__delitem__(name)
else:
# This is done for idempotency, if we have a name which is a field,
# we want to mask it by setting the value to None.
unbound_field = getattr(self.__class__, name, None)
if unbound_field is not None and hasattr(unbound_field, "_formfield"):
setattr(self, name, None)
else:
super().__delattr__(name)
|
(self, name)
|
71,588 |
wtforms.form
|
__delitem__
| null |
def __delitem__(self, name):
del self._fields[name]
setattr(self, name, None)
|
(self, name)
|
71,589 |
wtforms.form
|
__getitem__
|
Dict-style access to this form's fields.
|
def __getitem__(self, name):
"""Dict-style access to this form's fields."""
return self._fields[name]
|
(self, name)
|
71,590 |
wtforms.form
|
__init__
|
:param formdata: Input data coming from the client, usually
``request.form`` or equivalent. Should provide a "multi
dict" interface to get a list of values for a given key,
such as what Werkzeug, Django, and WebOb provide.
:param obj: Take existing data from attributes on this object
matching form field attributes. Only used if ``formdata`` is
not passed.
:param prefix: If provided, all fields will have their name
prefixed with the value. This is for distinguishing multiple
forms on a single page. This only affects the HTML name for
matching input data, not the Python name for matching
existing data.
:param data: Take existing data from keys in this dict matching
form field attributes. ``obj`` takes precedence if it also
has a matching attribute. Only used if ``formdata`` is not
passed.
:param meta: A dict of attributes to override on this form's
:attr:`meta` instance.
:param extra_filters: A dict mapping field attribute names to
lists of extra filter functions to run. Extra filters run
after filters passed when creating the field. If the form
has ``filter_<fieldname>``, it is the last extra filter.
:param kwargs: Merged with ``data`` to allow passing existing
data as parameters. Overwrites any duplicate keys in
``data``. Only used if ``formdata`` is not passed.
|
def __init__(
self,
formdata=None,
obj=None,
prefix="",
data=None,
meta=None,
**kwargs,
):
"""
:param formdata: Input data coming from the client, usually
``request.form`` or equivalent. Should provide a "multi
dict" interface to get a list of values for a given key,
such as what Werkzeug, Django, and WebOb provide.
:param obj: Take existing data from attributes on this object
matching form field attributes. Only used if ``formdata`` is
not passed.
:param prefix: If provided, all fields will have their name
prefixed with the value. This is for distinguishing multiple
forms on a single page. This only affects the HTML name for
matching input data, not the Python name for matching
existing data.
:param data: Take existing data from keys in this dict matching
form field attributes. ``obj`` takes precedence if it also
has a matching attribute. Only used if ``formdata`` is not
passed.
:param meta: A dict of attributes to override on this form's
:attr:`meta` instance.
:param extra_filters: A dict mapping field attribute names to
lists of extra filter functions to run. Extra filters run
after filters passed when creating the field. If the form
has ``filter_<fieldname>``, it is the last extra filter.
:param kwargs: Merged with ``data`` to allow passing existing
data as parameters. Overwrites any duplicate keys in
``data``. Only used if ``formdata`` is not passed.
"""
meta_obj = self._wtforms_meta()
if meta is not None and isinstance(meta, dict):
meta_obj.update_values(meta)
super().__init__(self._unbound_fields, meta=meta_obj, prefix=prefix)
for name, field in self._fields.items():
# Set all the fields to attributes so that they obscure the class
# attributes with the same names.
setattr(self, name, field)
self.process(formdata, obj, data=data, **kwargs)
|
(self, formdata=None, obj=None, prefix='', data=None, meta=None, **kwargs)
|
71,591 |
wtforms.form
|
__iter__
|
Iterate form fields in creation order.
|
def __iter__(self):
"""Iterate form fields in creation order."""
return iter(self._fields.values())
|
(self)
|
71,592 |
wtforms.form
|
__setitem__
| null |
def __setitem__(self, name, value):
raise TypeError("Fields may not be added to Form instances, only classes.")
|
(self, name, value)
|
71,593 |
wtforms.form
|
populate_obj
|
Populates the attributes of the passed `obj` with data from the form's
fields.
:note: This is a destructive operation; Any attribute with the same name
as a field will be overridden. Use with caution.
|
def populate_obj(self, obj):
"""
Populates the attributes of the passed `obj` with data from the form's
fields.
:note: This is a destructive operation; Any attribute with the same name
as a field will be overridden. Use with caution.
"""
for name, field in self._fields.items():
field.populate_obj(obj, name)
|
(self, obj)
|
71,594 |
wtforms.form
|
process
|
Process default and input data with each field.
:param formdata: Input data coming from the client, usually
``request.form`` or equivalent. Should provide a "multi
dict" interface to get a list of values for a given key,
such as what Werkzeug, Django, and WebOb provide.
:param obj: Take existing data from attributes on this object
matching form field attributes. Only used if ``formdata`` is
not passed.
:param data: Take existing data from keys in this dict matching
form field attributes. ``obj`` takes precedence if it also
has a matching attribute. Only used if ``formdata`` is not
passed.
:param extra_filters: A dict mapping field attribute names to
lists of extra filter functions to run. Extra filters run
after filters passed when creating the field. If the form
has ``filter_<fieldname>``, it is the last extra filter.
:param kwargs: Merged with ``data`` to allow passing existing
data as parameters. Overwrites any duplicate keys in
``data``. Only used if ``formdata`` is not passed.
|
def process(self, formdata=None, obj=None, data=None, extra_filters=None, **kwargs):
"""Process default and input data with each field.
:param formdata: Input data coming from the client, usually
``request.form`` or equivalent. Should provide a "multi
dict" interface to get a list of values for a given key,
such as what Werkzeug, Django, and WebOb provide.
:param obj: Take existing data from attributes on this object
matching form field attributes. Only used if ``formdata`` is
not passed.
:param data: Take existing data from keys in this dict matching
form field attributes. ``obj`` takes precedence if it also
has a matching attribute. Only used if ``formdata`` is not
passed.
:param extra_filters: A dict mapping field attribute names to
lists of extra filter functions to run. Extra filters run
after filters passed when creating the field. If the form
has ``filter_<fieldname>``, it is the last extra filter.
:param kwargs: Merged with ``data`` to allow passing existing
data as parameters. Overwrites any duplicate keys in
``data``. Only used if ``formdata`` is not passed.
"""
formdata = self.meta.wrap_formdata(self, formdata)
if data is not None:
kwargs = dict(data, **kwargs)
filters = extra_filters.copy() if extra_filters is not None else {}
for name, field in self._fields.items():
field_extra_filters = filters.get(name, [])
inline_filter = getattr(self, "filter_%s" % name, None)
if inline_filter is not None:
field_extra_filters.append(inline_filter)
if obj is not None and hasattr(obj, name):
data = getattr(obj, name)
elif name in kwargs:
data = kwargs[name]
else:
data = unset_value
field.process(formdata, data, extra_filters=field_extra_filters)
|
(self, formdata=None, obj=None, data=None, extra_filters=None, **kwargs)
|
71,595 |
wtforms.form
|
validate
|
Validate the form by calling ``validate`` on each field.
Returns ``True`` if validation passes.
If the form defines a ``validate_<fieldname>`` method, it is
appended as an extra validator for the field's ``validate``.
:param extra_validators: A dict mapping field names to lists of
extra validator methods to run. Extra validators run after
validators passed when creating the field. If the form has
``validate_<fieldname>``, it is the last extra validator.
|
def validate(self, extra_validators=None):
"""Validate the form by calling ``validate`` on each field.
Returns ``True`` if validation passes.
If the form defines a ``validate_<fieldname>`` method, it is
appended as an extra validator for the field's ``validate``.
:param extra_validators: A dict mapping field names to lists of
extra validator methods to run. Extra validators run after
validators passed when creating the field. If the form has
``validate_<fieldname>``, it is the last extra validator.
"""
if extra_validators is not None:
extra = extra_validators.copy()
else:
extra = {}
for name in self._fields:
inline = getattr(self.__class__, f"validate_{name}", None)
if inline is not None:
extra.setdefault(name, []).append(inline)
return super().validate(extra)
|
(self, extra_validators=None)
|
71,596 |
wtforms_components.validators
|
If
|
Conditional validator.
:param condition: callable which takes two arguments form and field
:param validator: encapsulated validator, this validator is validated
only if given condition returns true
:param message: custom message, which overrides child validator's
validation error message
|
class If(ControlStructure):
"""
Conditional validator.
:param condition: callable which takes two arguments form and field
:param validator: encapsulated validator, this validator is validated
only if given condition returns true
:param message: custom message, which overrides child validator's
validation error message
"""
def __init__(self, condition, validator, message=None):
self.condition = condition
self.validator = validator
if message:
self.message = message
def __call__(self, form, field):
if self.condition(form, field):
try:
self.validator(form, field)
except ValidationError as exc:
self.reraise(exc)
except StopValidation as exc:
self.reraise(exc)
|
(condition, validator, message=None)
|
71,597 |
wtforms_components.validators
|
__call__
| null |
def __call__(self, form, field):
if self.condition(form, field):
try:
self.validator(form, field)
except ValidationError as exc:
self.reraise(exc)
except StopValidation as exc:
self.reraise(exc)
|
(self, form, field)
|
71,598 |
wtforms_components.validators
|
__init__
| null |
def __init__(self, condition, validator, message=None):
self.condition = condition
self.validator = validator
if message:
self.message = message
|
(self, condition, validator, message=None)
|
71,600 |
wtforms_components.fields.interval
|
IntIntervalField
| null |
class IntIntervalField(IntervalField):
error_msg = u'Not a valid int range value'
interval_class = IntInterval
|
(*args, **kwargs)
|
71,617 |
wtforms_components.fields.html5
|
IntegerField
| null |
class IntegerField(IntegerField):
widget = NumberInput(step='1')
|
(*args, **kwargs)
|
71,620 |
wtforms.fields.numeric
|
__init__
| null |
def __init__(self, label=None, validators=None, **kwargs):
super().__init__(label, validators, **kwargs)
|
(self, label=None, validators=None, **kwargs)
|
71,624 |
wtforms.fields.numeric
|
_value
| null |
def _value(self):
if self.raw_data:
return self.raw_data[0]
if self.data is not None:
return str(self.data)
return ""
|
(self)
|
71,631 |
wtforms.fields.numeric
|
process_data
| null |
def process_data(self, value):
if value is None or value is unset_value:
self.data = None
return
try:
self.data = int(value)
except (ValueError, TypeError) as exc:
self.data = None
raise ValueError(self.gettext("Not a valid integer value.")) from exc
|
(self, value)
|
71,632 |
wtforms.fields.numeric
|
process_formdata
| null |
def process_formdata(self, valuelist):
if not valuelist:
return
try:
self.data = int(valuelist[0])
except ValueError as exc:
self.data = None
raise ValueError(self.gettext("Not a valid integer value.")) from exc
|
(self, valuelist)
|
71,634 |
wtforms_components.fields.html5
|
IntegerSliderField
| null |
class IntegerSliderField(IntegerRangeField):
widget = RangeInput(step='1')
|
(*args, **kwargs)
|
71,651 |
wtforms_components.fields.json_field
|
JSONField
|
A text field which stores a `json`.
|
class JSONField(fields.StringField):
"""
A text field which stores a `json`.
"""
widget = widgets.TextArea()
def _value(self):
return json.dumps(self.data) if self.data else ''
def process_formdata(self, valuelist):
if valuelist:
try:
self.data = json.loads(valuelist[0])
except ValueError:
self.data = None
raise ValueError('This field contains invalid JSON')
else:
self.data = None
def pre_validate(self, form):
if self.data:
try:
json.dumps(self.data)
except TypeError:
self.data = None
raise ValueError('This field contains invalid JSON')
|
(*args, **kwargs)
|
71,658 |
wtforms_components.fields.json_field
|
_value
| null |
def _value(self):
return json.dumps(self.data) if self.data else ''
|
(self)
|
71,663 |
wtforms_components.fields.json_field
|
pre_validate
| null |
def pre_validate(self, form):
if self.data:
try:
json.dumps(self.data)
except TypeError:
self.data = None
raise ValueError('This field contains invalid JSON')
|
(self, form)
|
71,666 |
wtforms_components.fields.json_field
|
process_formdata
| null |
def process_formdata(self, valuelist):
if valuelist:
try:
self.data = json.loads(valuelist[0])
except ValueError:
self.data = None
raise ValueError('This field contains invalid JSON')
else:
self.data = None
|
(self, valuelist)
|
71,668 |
wtforms_components
|
ModelForm
|
Simple ModelForm, use this if your form needs to use the Unique validator
|
class ModelForm(Form):
"""
Simple ModelForm, use this if your form needs to use the Unique validator
"""
def __init__(self, formdata=None, obj=None, prefix='', **kwargs):
Form.__init__(
self, formdata=formdata, obj=obj, prefix=prefix, **kwargs
)
self._obj = obj
|
(*args, **kwargs)
|
71,673 |
wtforms_components
|
__init__
| null |
def __init__(self, formdata=None, obj=None, prefix='', **kwargs):
Form.__init__(
self, formdata=formdata, obj=obj, prefix=prefix, **kwargs
)
self._obj = obj
|
(self, formdata=None, obj=None, prefix='', **kwargs)
|
71,679 |
wtforms_components.widgets
|
NumberInput
|
Renders an input with type "number".
Adds min and max html5 field parameters based on field's NumberRange
validator.
|
class NumberInput(HTML5Input):
"""
Renders an input with type "number".
Adds min and max html5 field parameters based on field's NumberRange
validator.
"""
input_type = 'number'
range_validator_class = NumberRange
def range_validators(self, field):
return min_max(field, self.range_validator_class)
|
(**kwargs)
|
71,680 |
wtforms_components.widgets
|
__call__
| null |
def __call__(self, field, **kwargs):
if has_validator(field, DataRequired):
kwargs.setdefault('required', True)
for key, value in self.range_validators(field).items():
kwargs.setdefault(key, value)
if hasattr(field, 'widget_options'):
for key, value in self.field.widget_options:
kwargs.setdefault(key, value)
options_copy = copy(self.options)
options_copy.update(kwargs)
return super(HTML5Input, self).__call__(field, **options_copy)
|
(self, field, **kwargs)
|
71,681 |
wtforms_components.widgets
|
__init__
| null |
def __init__(self, **kwargs):
self.options = kwargs
|
(self, **kwargs)
|
71,682 |
wtforms.widgets.core
|
html_params
|
Generate HTML attribute syntax from inputted keyword arguments.
The output value is sorted by the passed keys, to provide consistent output
each time this function is called with the same parameters. Because of the
frequent use of the normally reserved keywords `class` and `for`, suffixing
these with an underscore will allow them to be used.
In order to facilitate the use of ``data-`` and ``aria-`` attributes, if the
name of the attribute begins with ``data_`` or ``aria_``, then every
underscore will be replaced with a hyphen in the generated attribute.
>>> html_params(data_attr='user.name', aria_labeledby='name')
'data-attr="user.name" aria-labeledby="name"'
In addition, the values ``True`` and ``False`` are special:
* ``attr=True`` generates the HTML compact output of a boolean attribute,
e.g. ``checked=True`` will generate simply ``checked``
* ``attr=False`` will be ignored and generate no output.
>>> html_params(name='text1', id='f', class_='text')
'class="text" id="f" name="text1"'
>>> html_params(checked=True, readonly=False, name="text1", abc="hello")
'abc="hello" checked name="text1"'
.. versionchanged:: 3.0
``aria_`` args convert underscores to hyphens like ``data_``
args.
.. versionchanged:: 2.2
``data_`` args convert all underscores to hyphens, instead of
only the first one.
|
def html_params(**kwargs):
"""
Generate HTML attribute syntax from inputted keyword arguments.
The output value is sorted by the passed keys, to provide consistent output
each time this function is called with the same parameters. Because of the
frequent use of the normally reserved keywords `class` and `for`, suffixing
these with an underscore will allow them to be used.
In order to facilitate the use of ``data-`` and ``aria-`` attributes, if the
name of the attribute begins with ``data_`` or ``aria_``, then every
underscore will be replaced with a hyphen in the generated attribute.
>>> html_params(data_attr='user.name', aria_labeledby='name')
'data-attr="user.name" aria-labeledby="name"'
In addition, the values ``True`` and ``False`` are special:
* ``attr=True`` generates the HTML compact output of a boolean attribute,
e.g. ``checked=True`` will generate simply ``checked``
* ``attr=False`` will be ignored and generate no output.
>>> html_params(name='text1', id='f', class_='text')
'class="text" id="f" name="text1"'
>>> html_params(checked=True, readonly=False, name="text1", abc="hello")
'abc="hello" checked name="text1"'
.. versionchanged:: 3.0
``aria_`` args convert underscores to hyphens like ``data_``
args.
.. versionchanged:: 2.2
``data_`` args convert all underscores to hyphens, instead of
only the first one.
"""
params = []
for k, v in sorted(kwargs.items()):
k = clean_key(k)
if v is True:
params.append(k)
elif v is False:
pass
else:
params.append(f'{str(k)}="{escape(v)}"') # noqa: B907
return " ".join(params)
|
(**kwargs)
|
71,683 |
wtforms_components.widgets
|
range_validators
| null |
def range_validators(self, field):
return min_max(field, self.range_validator_class)
|
(self, field)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.