Skip to content

Commit

Permalink
Update
Browse files Browse the repository at this point in the history
- Update typing
- Update forms
- Generate stubs for wtforms, flask_wtf (incomplete)
  • Loading branch information
Virashu committed Jul 25, 2024
1 parent 841f331 commit f0aacf3
Show file tree
Hide file tree
Showing 31 changed files with 1,623 additions and 36 deletions.
14 changes: 14 additions & 0 deletions typings/flask_wtf/__init__.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
__all__ = (
"FlaskForm",
"Form",
"CSRFProtect",
"Recaptcha",
"RecaptchaField",
"RecaptchaWidget",
)

from .csrf import CSRFProtect
from .form import FlaskForm, Form
from .recaptcha import Recaptcha, RecaptchaField, RecaptchaWidget

__version__: str = ...
5 changes: 5 additions & 0 deletions typings/flask_wtf/_compat.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""
This type stub file was generated by pyright.
"""

class FlaskWTFDeprecationWarning(DeprecationWarning): ...
92 changes: 92 additions & 0 deletions typings/flask_wtf/csrf.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
from werkzeug.exceptions import BadRequest
from wtforms.csrf.core import CSRF

__all__ = ("generate_csrf", "validate_csrf", "CSRFProtect")
logger = ...

def generate_csrf(secret_key=..., token_key=...) -> Any:
"""Generate a CSRF token. The token is cached for a request, so multiple
calls to this function will generate the same token.
During testing, it might be useful to access the signed token in
``g.csrf_token`` and the raw token in ``session['csrf_token']``.
:param secret_key: Used to securely sign the token. Default is
``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``.
:param token_key: Key where token is stored in session for comparison.
Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``.
"""
...

def validate_csrf(data, secret_key=..., time_limit=..., token_key=...) -> None:
"""Check if the given data is a valid CSRF token. This compares the given
signed token to the one stored in the session.
:param data: The signed CSRF token to be checked.
:param secret_key: Used to securely sign the token. Default is
``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``.
:param time_limit: Number of seconds that the token is valid. Default is
``WTF_CSRF_TIME_LIMIT`` or 3600 seconds (60 minutes).
:param token_key: Key where token is stored in session for comparison.
Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``.
:raises ValidationError: Contains the reason that validation failed.
.. versionchanged:: 0.14
Raises ``ValidationError`` with a specific error message rather than
returning ``True`` or ``False``.
"""
...

class _FlaskFormCSRF(CSRF):
def setup_form(self, form) -> list[tuple[str, UnboundField[Any]]]: ...
def generate_csrf_token(self, csrf_token_field) -> Any: ...
def validate_csrf_token(self, form, field) -> None: ...

class CSRFProtect:
"""Enable CSRF protection globally for a Flask app.
::
app = Flask(__name__)
csrf = CSRFProtect(app)
Checks the ``csrf_token`` field sent with forms, or the ``X-CSRFToken``
header sent with JavaScript requests. Render the token in templates using
``{{ csrf_token() }}``.
See the :ref:`csrf` documentation.
"""

def __init__(self, app=...) -> None: ...
def init_app(self, app) -> None: ...
def protect(self) -> None: ...
def exempt(self, view) -> Blueprint | str:
"""Mark a view or blueprint to be excluded from CSRF protection.
::
@app.route('/some-view', methods=['POST'])
@csrf.exempt
def some_view():
...
::
bp = Blueprint(...)
csrf.exempt(bp)
"""
...

class CSRFError(BadRequest):
"""Raise if the client sends invalid CSRF data with the request.
Generates a 400 Bad Request response with the failure reason by default.
Customize the response by registering a handler with
:meth:`flask.Flask.errorhandler`.
"""

description = ...

def same_origin(current_uri, compare_uri): ...
69 changes: 69 additions & 0 deletions typings/flask_wtf/file.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""
This type stub file was generated by pyright.
"""

from wtforms import FileField as _FileField, MultipleFileField as _MultipleFileField
from wtforms.validators import DataRequired

class FileField(_FileField):
"""Werkzeug-aware subclass of :class:`wtforms.fields.FileField`."""

def process_formdata(self, valuelist): # -> None:
...

class MultipleFileField(_MultipleFileField):
"""Werkzeug-aware subclass of :class:`wtforms.fields.MultipleFileField`.
.. versionadded:: 1.2.0
"""

def process_formdata(self, valuelist): # -> None:
...

class FileRequired(DataRequired):
"""Validates that the uploaded files(s) is a Werkzeug
:class:`~werkzeug.datastructures.FileStorage` object.
:param message: error message
You can also use the synonym ``file_required``.
"""

def __call__(self, form, field): # -> None:
...

file_required = FileRequired

class FileAllowed:
"""Validates that the uploaded file(s) is allowed by a given list of
extensions or a Flask-Uploads :class:`~flaskext.uploads.UploadSet`.
:param upload_set: A list of extensions or an
:class:`~flaskext.uploads.UploadSet`
:param message: error message
You can also use the synonym ``file_allowed``.
"""

def __init__(self, upload_set, message=...) -> None: ...
def __call__(self, form, field): # -> None:
...

file_allowed = FileAllowed

class FileSize:
"""Validates that the uploaded file(s) is within a minimum and maximum
file size (set in bytes).
:param min_size: minimum allowed file size (in bytes). Defaults to 0 bytes.
:param max_size: maximum allowed file size (in bytes).
:param message: error message
You can also use the synonym ``file_size``.
"""

def __init__(self, max_size, min_size=..., message=...) -> None: ...
def __call__(self, form, field): # -> None:
...

file_size = FileSize
82 changes: 82 additions & 0 deletions typings/flask_wtf/form.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""
This type stub file was generated by pyright.
"""

from typing import Callable, Sequence, Any
from markupsafe import Markup
from werkzeug.datastructures import CombinedMultiDict, ImmutableMultiDict
from werkzeug.utils import cached_property
from wtforms import Form
from wtforms.meta import DefaultMeta
from .csrf import _FlaskFormCSRF

SUBMIT_METHODS = ...
_Auto = ...

class FlaskForm(Form):
"""Flask-specific subclass of WTForms :class:`~wtforms.form.Form`.
If ``formdata`` is not specified, this will use :attr:`flask.request.form`
and :attr:`flask.request.files`. Explicitly pass ``formdata=None`` to
prevent this.
"""

class Meta(DefaultMeta):
csrf_class = _FlaskFormCSRF
csrf_context = ...
@cached_property
def csrf(self): ...
@cached_property
def csrf_secret(self): ...
@cached_property
def csrf_field_name(self): ...
@cached_property
def csrf_time_limit(self): ...
def wrap_formdata(
self, form, formdata
) -> (
CombinedMultiDict[Any, Any]
| ImmutableMultiDict[str, str]
| ImmutableMultiDict[Any, Any]
| None
): ...
def get_translations(
self, form
) -> _SupportsGettextAndNgettext | Translations | None: ...

def __init__(self, formdata=..., **kwargs) -> None: ...
def is_submitted(self) -> bool:
"""Consider the form submitted if there is an active request and
the method is ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
"""
...

def validate_on_submit(
self, extra_validators: dict[str, Sequence[Callable[..., bool]]] = ...
) -> bool:
"""Call :meth:`validate` only if the form is submitted.
This is a shortcut for ``form.is_submitted() and form.validate()``.
"""
...

def hidden_tag(self, *fields: str) -> Markup:
"""Render the form's hidden fields in one call.
A field is considered hidden if it uses the
:class:`~wtforms.widgets.HiddenInput` widget.
If ``fields`` are given, only render the given fields that
are hidden. If a string is passed, render the field with that
name if it exists.
.. versionchanged:: 0.13
No longer wraps inputs in hidden div.
This is valid HTML 5.
.. versionchanged:: 0.13
Skip passed fields that aren't hidden.
Skip passed names that don't exist.
"""
...
13 changes: 13 additions & 0 deletions typings/flask_wtf/i18n.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""
This type stub file was generated by pyright.
"""

__all__ = ("Translations", "translations")

class Translations:
def gettext(self, string): # -> Any:
...
def ngettext(self, singular, plural, n): # -> Any:
...

translations = ...
7 changes: 7 additions & 0 deletions typings/flask_wtf/recaptcha/__init__.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"""
This type stub file was generated by pyright.
"""

from .fields import RecaptchaField
from .validators import Recaptcha
from .widgets import RecaptchaWidget
12 changes: 12 additions & 0 deletions typings/flask_wtf/recaptcha/fields.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"""
This type stub file was generated by pyright.
"""

from wtforms.fields import Field

__all__ = ["RecaptchaField"]

class RecaptchaField(Field):
widget = ...
recaptcha_error = ...
def __init__(self, label=..., validators=..., **kwargs) -> None: ...
14 changes: 14 additions & 0 deletions typings/flask_wtf/recaptcha/validators.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""
This type stub file was generated by pyright.
"""

RECAPTCHA_VERIFY_SERVER_DEFAULT = ...
RECAPTCHA_ERROR_CODES = ...
__all__ = ["Recaptcha"]

class Recaptcha:
"""Validates a ReCaptcha."""

def __init__(self, message=...) -> None: ...
def __call__(self, form, field): # -> Literal[True] | None:
...
15 changes: 15 additions & 0 deletions typings/flask_wtf/recaptcha/widgets.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""
This type stub file was generated by pyright.
"""

RECAPTCHA_SCRIPT_DEFAULT = ...
RECAPTCHA_DIV_CLASS_DEFAULT = ...
RECAPTCHA_TEMPLATE = ...
__all__ = ["RecaptchaWidget"]

class RecaptchaWidget:
def recaptcha_html(self, public_key): # -> Markup:
...
def __call__(self, field, error=..., **kwargs): # -> Markup:
"""Returns the recaptcha input HTML."""
...
8 changes: 8 additions & 0 deletions typings/wtforms/__init__.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
"""
This type stub file was generated by pyright.
"""

from wtforms import validators as validators, widgets as widgets
from wtforms.fields import *
from wtforms.form import Form as Form
from wtforms.validators import ValidationError as ValidationError
3 changes: 3 additions & 0 deletions typings/wtforms/csrf/__init__.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""
This type stub file was generated by pyright.
"""
12 changes: 12 additions & 0 deletions typings/wtforms/fields/__init__.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"""
This type stub file was generated by pyright.
"""

from wtforms.fields.choices import *
from wtforms.fields.choices import SelectFieldBase as SelectFieldBase
from wtforms.fields.core import Field as Field, Flags as Flags, Label as Label
from wtforms.fields.datetime import *
from wtforms.fields.form import *
from wtforms.fields.list import *
from wtforms.fields.numeric import *
from wtforms.fields.simple import *
Loading

0 comments on commit f0aacf3

Please sign in to comment.