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
7,726
pydal.objects
upper
null
def upper(self): return Expression( self.db, self._dialect.upper, self, None, self.type)
(self)
7,727
pydal.objects
validate
null
def validate(self, value): if not self.requires or self.requires == DEFAULT: return ((value if value != self.map_none else None), None) requires = self.requires if not isinstance(requires, (list, tuple)): requires = [requires] for validator in requires: (value, error) = validator(value) if error: return (value, error) return ((value if value != self.map_none else None), None)
(self, value)
7,728
pydal.objects
with_alias
null
def with_alias(self, alias): return Expression(self.db, self._dialect._as, self, alias, self.type)
(self, alias)
7,729
pydal.objects
year
null
def year(self): return Expression( self.db, self._dialect.extract, self, 'year', 'integer')
(self)
7,730
emmett.forms
Form
null
class Form(BaseForm): def __init__( self, fields: Optional[Dict[str, Field]] = None, csrf: Union[str, bool] = "auto", id_prefix: str = "", formstyle: Optional[Type[FormStyle]] = None, keepvalues: bool = False, onvalidation: Optional[Callable[[Form], None]] = None, submit: str = "Submit", upload: Optional[str] = None, _action: str = "", _enctype: str = "multipart/form-data", _method: str = "POST", **kwargs: Any ): fields = fields or {} #: get fields from kwargs for name, parameter in kwargs.items(): if isinstance(parameter, Field): fields[name] = parameter for name in fields.keys(): if name in kwargs: del kwargs[name] #: order fields correctly sorted_fields = [] for name, field in fields.items(): sorted_fields.append((name, field)) sorted_fields.sort(key=lambda tup: tup[1]._inst_count_) #: init fields fields_list_all = [] fields_list_writable = [] for name, obj in sorted_fields: field_obj = obj._make_field(name) fields_list_all.append(field_obj) if field_obj.writable: fields_list_writable.append(field_obj) super().__init__( fields=fields_list_all, writable_fields=fields_list_writable, csrf=csrf, id_prefix=id_prefix, formstyle=formstyle, keepvalues=keepvalues, onvalidation=onvalidation, submit=submit, upload=upload, _action=_action, _enctype=_enctype, _method=_method )
(fields: 'Optional[Dict[str, Field]]' = None, csrf: 'Union[str, bool]' = 'auto', id_prefix: 'str' = '', formstyle: 'Optional[Type[FormStyle]]' = None, keepvalues: 'bool' = False, onvalidation: 'Optional[Callable[[Form], None]]' = None, submit: 'str' = 'Submit', upload: 'Optional[str]' = None, _action: 'str' = '', _enctype: 'str' = 'multipart/form-data', _method: 'str' = 'POST', **kwargs: 'Any')
7,731
emmett.html
__add__
null
def __add__(self, other): return cat(self, other)
(self, other)
7,732
emmett.forms
__await__
null
def __await__(self): if self._awaited: return self._awaited_wrap().__await__() self._awaited = True return self._process().__await__()
(self)
7,733
emmett.html
__call__
null
def __call__(self, *components, **attributes): rules = self.rules.get(self.name, []) self.components = [self.wrap(comp, rules) for comp in components] self.attributes = attributes for component in self.components: if isinstance(component, HtmlTag): component.parent = self return self
(self, *components, **attributes)
7,734
emmett.html
__enter__
null
def __enter__(self): _stack.append(self) return self
(self)
7,735
emmett.html
__exit__
null
def __exit__(self, type, value, traceback): _stack.pop(-1)
(self, type, value, traceback)
7,736
emmett.html
__getitem__
null
def __getitem__(self, key): if isinstance(key, int): return self.components[key] else: return self.attributes.get(key)
(self, key)
7,737
emmett.forms
__html__
null
def __html__(self): return self._render().__html__()
(self)
7,738
emmett.forms
__init__
null
def __init__( self, fields: Optional[Dict[str, Field]] = None, csrf: Union[str, bool] = "auto", id_prefix: str = "", formstyle: Optional[Type[FormStyle]] = None, keepvalues: bool = False, onvalidation: Optional[Callable[[Form], None]] = None, submit: str = "Submit", upload: Optional[str] = None, _action: str = "", _enctype: str = "multipart/form-data", _method: str = "POST", **kwargs: Any ): fields = fields or {} #: get fields from kwargs for name, parameter in kwargs.items(): if isinstance(parameter, Field): fields[name] = parameter for name in fields.keys(): if name in kwargs: del kwargs[name] #: order fields correctly sorted_fields = [] for name, field in fields.items(): sorted_fields.append((name, field)) sorted_fields.sort(key=lambda tup: tup[1]._inst_count_) #: init fields fields_list_all = [] fields_list_writable = [] for name, obj in sorted_fields: field_obj = obj._make_field(name) fields_list_all.append(field_obj) if field_obj.writable: fields_list_writable.append(field_obj) super().__init__( fields=fields_list_all, writable_fields=fields_list_writable, csrf=csrf, id_prefix=id_prefix, formstyle=formstyle, keepvalues=keepvalues, onvalidation=onvalidation, submit=submit, upload=upload, _action=_action, _enctype=_enctype, _method=_method )
(self, fields: Optional[Dict[str, emmett.orm.objects.Field]] = None, csrf: Union[str, bool] = 'auto', id_prefix: str = '', formstyle: Optional[Type[emmett.forms.FormStyle]] = None, keepvalues: bool = False, onvalidation: Optional[Callable[[emmett.forms.Form], NoneType]] = None, submit: str = 'Submit', upload: Optional[str] = None, _action: str = '', _enctype: str = 'multipart/form-data', _method: str = 'POST', **kwargs: Any)
7,739
emmett.html
__iter__
null
def __iter__(self): for item in self.components: yield item
(self)
7,740
emmett.html
__json__
null
def __json__(self): return str(self)
(self)
7,741
emmett.html
__setitem__
null
def __setitem__(self, key, value): if isinstance(key, int): self.components.insert(key, value) else: self.attributes[key] = value
(self, key, value)
7,742
emmett.html
__str__
null
def __str__(self): return self.__html__()
(self)
7,743
emmett.forms
_awaited_wrap
null
def _validate_value(self, field, value): value, error = field.validate(value) if error: self.errors[field.name] = error elif field.type == "upload": self.files[field.name] = value else: self.params[field.name] = value
(self)
7,744
emmett.html
_build_html_attributes
null
def _build_html_attributes(self): return ' '.join( '%s="%s"' % (k[1:], k[1:] if v is True else htmlescape(v)) for (k, v) in sorted(self.attributes.items()) if k.startswith('_') and v is not None)
(self)
7,745
emmett.forms
_get_default_style
null
@staticmethod def _get_default_style(): return current.app.config.ui.forms_style or FormStyle
()
7,746
emmett.forms
_get_input_val
null
def _get_input_val(self, field): if field.type == "boolean": v = self.input_params.get(field.name, False) if v is not False: v = True elif field.type == "upload": v = self.input_files.get(field.name) else: v = self.input_params.get(field.name) return v
(self, field)
7,747
emmett.forms
_load_csrf
null
def _load_csrf(self): if not self.csrf: return if not hasattr(current, "session"): raise RuntimeError("You need sessions to use csrf in forms.") current.session._csrf = current.session._csrf or CSRFStorage()
(self)
7,750
emmett.forms
_preprocess
null
def _preprocess(self, **kwargs): #: process attributes self.attributes = { "_action": self._action, "_enctype": self._enctype, "_method": self._submit_method, "id_prefix": self._id_prefix, "hidden": {}, "submit": self._submit_text, "upload": self._upload } self.attributes.update(kwargs) #: init the form self._awaited = False self.input_params: sdict[str, Any] = sdict() self.errors: sdict[str, str] = sdict() self.params: sdict[str, Any] = sdict() self.files: sdict[str, FileStorage] = sdict() self.processed = False self.accepted = False self.formkey = "undef"
(self, **kwargs)
7,751
emmett.forms
_process
null
def _validate_input(self): for field in self.writable_fields: value = self._get_input_val(field) self._validate_value(field, value)
(self, write_defaults=True)
7,752
emmett.forms
_render
null
def _render(self): styler = self._formstyle(self.attributes) styler.on_start() for field in self.fields: value = self.input_params.get(field.name) error = self.errors.get(field.name) styler._proc_element(field, value, error) styler.add_buttons() styler._add_formkey(self.formkey) for key, value in self.attributes["hidden"].items(): styler._add_hidden(key, value) return styler.render()
(self)
7,755
emmett.html
add_class
add a class to _class attribute
def add_class(self, name): """ add a class to _class attribute """ c = self['_class'] classes = (set(c.split()) if c else set()) | set(name.split()) self['_class'] = ' '.join(classes) if classes else None return self
(self, name)
7,756
emmett.html
append
null
def append(self, component): self.components.append(component)
(self, component)
7,757
emmett.html
find
null
def find(self, expr): union = lambda a, b: a.union(b) if ',' in expr: tags = reduce( union, [self.find(x.strip()) for x in expr.split(',')], set()) elif ' ' in expr: tags = [self] for k, item in enumerate(expr.split()): if k > 0: children = [ set([c for c in tag if isinstance(c, HtmlTag)]) for tag in tags] tags = reduce(union, children) tags = reduce(union, [tag.find(item) for tag in tags], set()) else: tags = reduce( union, [c.find(expr) for c in self if isinstance(c, HtmlTag)], set()) tag = HtmlTag.regex_tag.match(expr) id = HtmlTag.regex_id.match(expr) _class = HtmlTag.regex_class.match(expr) attr = HtmlTag.regex_attr.match(expr) if ( (tag is None or self.name == tag.group(1)) and (id is None or self['_id'] == id.group(1)) and (_class is None or _class.group(1) in (self['_class'] or '').split()) and (attr is None or self['_' + attr.group(1)] == attr.group(2)) ): tags.add(self) return tags
(self, expr)
7,758
emmett.html
insert
null
def insert(self, i, component): self.components.insert(i, component)
(self, i, component)
7,759
emmett.html
remove
null
def remove(self, component): self.components.remove(component)
(self, component)
7,760
emmett.html
remove_class
remove a class from _class attribute
def remove_class(self, name): """ remove a class from _class attribute """ c = self['_class'] classes = (set(c.split()) if c else set()) - set(name.split()) self['_class'] = ' '.join(classes) if classes else None return self
(self, name)
7,761
emmett.html
wrap
null
@staticmethod def wrap(component, rules): if rules and ( not isinstance(component, HtmlTag) or component.name not in rules ): return HtmlTag(rules[0])(component) return component
(component, rules)
7,762
emmett.pipeline
Injector
null
class Injector(Pipe): namespace: str = '__global__' def __init__(self): self._injections_ = {} if self.namespace != '__global__': self._inject = self._inject_local return self._inject = self._inject_global for attr_name in ( set(dir(self)) - self.__class__._pipeline_methods_ - {'output', 'namespace'} ): if attr_name.startswith('_'): continue attr = getattr(self, attr_name) if isinstance(attr, types.MethodType): self._injections_[attr_name] = self._wrapped_method(attr) continue self._injections_[attr_name] = attr @staticmethod def _wrapped_method(method): def wrap(*args, **kwargs): return method(*args, **kwargs) return wrap def _inject_local(self, ctx): ctx[self.namespace] = self def _inject_global(self, ctx): ctx.update(self._injections_) async def pipe_request(self, next_pipe, **kwargs): ctx = await next_pipe(**kwargs) if isinstance(ctx, dict): self._inject(ctx) return ctx
()
7,763
emmett.pipeline
__init__
null
def __init__(self): self._injections_ = {} if self.namespace != '__global__': self._inject = self._inject_local return self._inject = self._inject_global for attr_name in ( set(dir(self)) - self.__class__._pipeline_methods_ - {'output', 'namespace'} ): if attr_name.startswith('_'): continue attr = getattr(self, attr_name) if isinstance(attr, types.MethodType): self._injections_[attr_name] = self._wrapped_method(attr) continue self._injections_[attr_name] = attr
(self)
7,764
emmett.pipeline
_inject_global
null
def _inject_global(self, ctx): ctx.update(self._injections_)
(self, ctx)
7,765
emmett.pipeline
_inject_local
null
def _inject_local(self, ctx): ctx[self.namespace] = self
(self, ctx)
7,766
emmett.pipeline
_wrapped_method
null
@staticmethod def _wrapped_method(method): def wrap(*args, **kwargs): return method(*args, **kwargs) return wrap
(method)
7,767
emmett.pipeline
close
null
def __new__(cls, name, bases, attrs): new_class = type.__new__(cls, name, bases, attrs) if not bases: return new_class declared_methods = cls._pipeline_methods_ & set(attrs.keys()) new_class._pipeline_declared_methods_ = declared_methods all_methods = set() for base in reversed(new_class.__mro__[:-2]): if hasattr(base, '_pipeline_declared_methods_'): all_methods = all_methods | base._pipeline_declared_methods_ all_methods = all_methods | declared_methods new_class._pipeline_all_methods_ = all_methods new_class._is_flow_request_responsible = bool( all_methods & { 'pipe', 'pipe_request', 'on_pipe_success', 'on_pipe_failure' } ) new_class._is_flow_ws_responsible = bool( all_methods & { 'pipe', 'pipe_ws', 'on_pipe_success', 'on_pipe_failure' } ) if all_methods.issuperset({'pipe', 'pipe_request'}): raise RuntimeError( f'{name} has double pipe methods. ' 'Use `pipe` or `pipe_request`, not both.' ) if all_methods.issuperset({'pipe', 'pipe_ws'}): raise RuntimeError( f'{name} has double pipe methods. ' 'Use `pipe` or `pipe_ws`, not both.' ) return new_class
(self)
7,772
emmett.pipeline
on_receive
null
def on_receive(self, data): return data
(self, data)
7,773
emmett.pipeline
on_send
null
def on_send(self, data): return data
(self, data)
7,780
emmett.pipeline
Pipe
null
class Pipe(metaclass=MetaPipe): output: Optional[str] = None async def open(self): pass async def open_request(self): pass async def open_ws(self): pass async def close(self): pass async def close_request(self): pass async def close_ws(self): pass async def pipe(self, next_pipe, **kwargs): return await next_pipe(**kwargs) async def pipe_request(self, next_pipe, **kwargs): return await next_pipe(**kwargs) async def pipe_ws(self, next_pipe, **kwargs): return await next_pipe(**kwargs) async def on_pipe_success(self): pass async def on_pipe_failure(self): pass def on_receive(self, data): return data def on_send(self, data): return data
()
7,796
emmett.helpers
abort
null
def abort(code: int, body: str = ''): response = current.response response.status = code raise HTTP( code, body=body, cookies=response.cookies )
(code: int, body: str = '')
7,799
emmett.html
asis
null
class asis(HtmlTag): def __init__(self, text): self.text = text def __html__(self): return _to_str(self.text)
(text)
7,805
emmett.html
__html__
null
def __html__(self): return _to_str(self.text)
(self)
7,806
emmett.html
__init__
null
def __init__(self, text): self.text = text
(self, text)
7,831
emmett.locals
now
null
def now() -> DateTime: return current.now
() -> pendulum.datetime.DateTime
7,835
emmett.http
redirect
null
def redirect(location: str, status_code: int = 303): response = current.response response.status = status_code raise HTTPRedirect(status_code, location, response.cookies)
(location: str, status_code: int = 303)
7,838
emmett.datastructures
sdict
null
class sdict(Dict[KT, VT]): #: like a dictionary except `obj.foo` can be used in addition to # `obj['foo']`, and setting obj.foo = None deletes item foo. __slots__ = () __setattr__ = dict.__setitem__ # type: ignore __delattr__ = dict.__delitem__ # type: ignore __getitem__ = dict.get # type: ignore # see http://stackoverflow.com/questions/10364332/how-to-pickle-python-object-derived-from-dict def __getattr__(self, key: str) -> Optional[VT]: if key.startswith('__'): raise AttributeError return self.get(key, None) # type: ignore __repr__ = lambda self: '<sdict %s>' % dict.__repr__(self) __getstate__ = lambda self: None __copy__ = lambda self: sdict(self) __deepcopy__ = lambda self, memo: sdict(copy.deepcopy(dict(self)))
null
7,839
emmett.datastructures
<lambda>
null
__copy__ = lambda self: sdict(self)
(self)
7,840
emmett.datastructures
<lambda>
null
__deepcopy__ = lambda self, memo: sdict(copy.deepcopy(dict(self)))
(self, memo)
7,841
emmett.datastructures
__getattr__
null
def __getattr__(self, key: str) -> Optional[VT]: if key.startswith('__'): raise AttributeError return self.get(key, None) # type: ignore
(self, key: str) -> Optional[~VT]
7,842
emmett.datastructures
<lambda>
null
__getstate__ = lambda self: None
(self)
7,843
emmett.datastructures
<lambda>
null
__repr__ = lambda self: '<sdict %s>' % dict.__repr__(self)
(self)
7,846
emmett.helpers
stream_file
null
def stream_file(path: str): full_path = os.path.join(current.app.root_path, path) raise HTTPFile( full_path, headers=current.response.headers, cookies=current.response.cookies )
(path: str)
7,859
ndcsv.read
read_csv
Parse an NDCSV file into a :class:`xarray.DataArray`. This function is conceptually similar to :func:`pandas.read_csv`, except that it only works for files that are strictly formatted according to :doc:`format` and, by design, does not offer any of the many config switches available in :func:`pandas.read_csv`. :param path_or_buf: One of: - .csv file path - .csv.gz / .csv.bz2 / .csv.xz file path (the compression algorithm is inferred automatically) - file-like object open for reading. It must support rewinding through ``seek(0)``. :param bool unstack: Set to True (the default) to automatically unstack any and all stacked dimensions in the output xarray, using first-seen order. Note that this differs from :meth:`xarray.DataArray.unstack`, which may occasionally use alphabetical order instead. All indices must be unique for the unstack to succeed. Non-index coords can be duplicated. Set to False to return the stacked dimensions as they appear in the CSV file. :returns: :class:`xarray.DataArray`
def read_csv(path_or_buf: str | TextIO, unstack: bool = True) -> DataArray: """Parse an NDCSV file into a :class:`xarray.DataArray`. This function is conceptually similar to :func:`pandas.read_csv`, except that it only works for files that are strictly formatted according to :doc:`format` and, by design, does not offer any of the many config switches available in :func:`pandas.read_csv`. :param path_or_buf: One of: - .csv file path - .csv.gz / .csv.bz2 / .csv.xz file path (the compression algorithm is inferred automatically) - file-like object open for reading. It must support rewinding through ``seek(0)``. :param bool unstack: Set to True (the default) to automatically unstack any and all stacked dimensions in the output xarray, using first-seen order. Note that this differs from :meth:`xarray.DataArray.unstack`, which may occasionally use alphabetical order instead. All indices must be unique for the unstack to succeed. Non-index coords can be duplicated. Set to False to return the stacked dimensions as they appear in the CSV file. :returns: :class:`xarray.DataArray` """ if isinstance(path_or_buf, str): with sh.open(path_or_buf) as fh: return read_csv(cast(TextIO, fh), unstack=unstack) xa = _buf_to_xarray(path_or_buf) assert xa.ndim in (0, 1, 2) # print(f"==== _buf_to_array:\n{xa}") xa = _coords_format_conversion(xa) assert xa.ndim in (0, 1, 2) # print(f"==== _coords_format_conversion:\n{xa}") if xa.ndim == 1: xa = _unpack(xa, xa.dims[0], unstack) # print(f"==== _unpack(dim_0):\n{xa}") elif xa.ndim == 2: dims = xa.dims xa = _unpack(xa, dims[0], unstack) # print(f"==== _unpack(dim_0):\n{xa}") xa = _unpack(xa, dims[1], unstack) # print(f"==== _unpack(dim_1):\n{xa}") return xa
(path_or_buf: str | typing.TextIO, unstack: bool = True) -> xarray.core.dataarray.DataArray
7,861
ndcsv.write
write_csv
Write an n-dimensional array to an NDCSV file. Any number of dimensions are supported. If the array has more than two dimensions, all dimensions beyond the first are automatically stacked together on the columns of the CSV file; if you want to stack dimensions on the rows you'll need to manually invoke :meth:`xarray.DataArray.stack` beforehand. This function is conceptually similar to :meth:`pandas.DataFrame.to_csv`, except that none of the many configuration settings is made available to the end user, in order to ensure consistency in the output file. :param array: One of: - :class:`xarray.DataArray` - :class:`pandas.Series` - :class:`pandas.DataFrame` :param path_or_buf: One of: - .csv file path - .csv.gz / .csv.bz2 / .csv.xz file path (the compression algorithm is inferred automatically) - file-like object open for writing - None (the result is returned as a string)
def write_csv( array: xarray.DataArray | pandas.Series | pandas.DataFrame, path_or_buf: str | IO | None = None, ) -> str | None: """Write an n-dimensional array to an NDCSV file. Any number of dimensions are supported. If the array has more than two dimensions, all dimensions beyond the first are automatically stacked together on the columns of the CSV file; if you want to stack dimensions on the rows you'll need to manually invoke :meth:`xarray.DataArray.stack` beforehand. This function is conceptually similar to :meth:`pandas.DataFrame.to_csv`, except that none of the many configuration settings is made available to the end user, in order to ensure consistency in the output file. :param array: One of: - :class:`xarray.DataArray` - :class:`pandas.Series` - :class:`pandas.DataFrame` :param path_or_buf: One of: - .csv file path - .csv.gz / .csv.bz2 / .csv.xz file path (the compression algorithm is inferred automatically) - file-like object open for writing - None (the result is returned as a string) """ if path_or_buf is None: buf = io.StringIO() write_csv(array, buf) return buf.getvalue() if isinstance(path_or_buf, str): # Automatically detect .csv or .csv.gz extension with sh.open(path_or_buf, "w") as fh: write_csv(array, fh) elif isinstance(array, xarray.DataArray): _write_csv_dataarray(array, path_or_buf) elif isinstance(array, (pandas.Series, pandas.DataFrame)): _write_csv_pandas(array, path_or_buf) else: raise TypeError( "Input data is not a xarray.DataArray, pandas.Series or pandas.DataFrame" ) return None
(array: xarray.core.dataarray.DataArray | pandas.core.series.Series | pandas.core.frame.DataFrame, path_or_buf: Union[str, IO, NoneType] = None) -> str | None
7,862
authclient.client
AuthClient
null
class AuthClient: def __init__(self, host, port): self.host = host self.port = port async def authenticate(self, service, username, password, ssl=True): if ssl: http_mode = "https" else: http_mode = "http" url = f"{http_mode}://{self.host}:{self.port}/{service}/authenticate/" payload = {"username": username, "password": password} async with aiohttp.ClientSession() as session: async with session.post(url, json=payload) as response: if response.status == 200: return True return False
(host, port)
7,863
authclient.client
__init__
null
def __init__(self, host, port): self.host = host self.port = port
(self, host, port)
7,866
webtest.app
AppError
null
class AppError(Exception): def __init__(self, message, *args): if isinstance(message, bytes): message = message.decode('utf8') str_args = () for arg in args: if isinstance(arg, webob.Response): body = arg.body if isinstance(body, bytes): if arg.charset: arg = body.decode(arg.charset) else: arg = repr(body) elif isinstance(arg, bytes): try: arg = arg.decode('utf8') except UnicodeDecodeError: arg = repr(arg) str_args += (arg,) message = message % str_args Exception.__init__(self, message)
(message, *args)
7,867
webtest.app
__init__
null
def __init__(self, message, *args): if isinstance(message, bytes): message = message.decode('utf8') str_args = () for arg in args: if isinstance(arg, webob.Response): body = arg.body if isinstance(body, bytes): if arg.charset: arg = body.decode(arg.charset) else: arg = repr(body) elif isinstance(arg, bytes): try: arg = arg.decode('utf8') except UnicodeDecodeError: arg = repr(arg) str_args += (arg,) message = message % str_args Exception.__init__(self, message)
(self, message, *args)
7,868
webtest.forms
Checkbox
Field representing ``<input type="checkbox">`` .. attribute:: checked Returns True if checkbox is checked.
class Checkbox(Field): """Field representing ``<input type="checkbox">`` .. attribute:: checked Returns True if checkbox is checked. """ def __init__(self, *args, **attrs): super().__init__(*args, **attrs) self._checked = 'checked' in attrs def value__set(self, value): self._checked = not not value def value__get(self): if self._checked: if self._value is None: return 'on' else: return self._value else: return None value = property(value__get, value__set) def checked__get(self): return bool(self._checked) def checked__set(self, value): self._checked = not not value checked = property(checked__get, checked__set)
(*args, **attrs)
7,869
webtest.forms
__init__
null
def __init__(self, *args, **attrs): super().__init__(*args, **attrs) self._checked = 'checked' in attrs
(self, *args, **attrs)
7,870
webtest.forms
__repr__
null
def __repr__(self): value = '<%s name="%s"' % (self.__class__.__name__, self.name) if self.id: value += ' id="%s"' % self.id return value + '>'
(self)
7,871
webtest.forms
checked__get
null
def checked__get(self): return bool(self._checked)
(self)
7,872
webtest.forms
checked__set
null
def checked__set(self, value): self._checked = not not value
(self, value)
7,873
webtest.forms
force_value
Like setting a value, except forces it (even for, say, hidden fields).
def force_value(self, value): """Like setting a value, except forces it (even for, say, hidden fields). """ self._value = value
(self, value)
7,874
webtest.forms
value__get
null
def value__get(self): if self._checked: if self._value is None: return 'on' else: return self._value else: return None
(self)
7,875
webtest.forms
value__set
null
def value__set(self, value): self._checked = not not value
(self, value)
7,876
webtest.forms
Field
Base class for all Field objects. .. attribute:: classes Dictionary of field types (select, radio, etc) .. attribute:: value Set/get value of the field.
class Field: """Base class for all Field objects. .. attribute:: classes Dictionary of field types (select, radio, etc) .. attribute:: value Set/get value of the field. """ classes = {} def __init__(self, form, tag, name, pos, value=None, id=None, **attrs): self.form = form self.tag = tag self.name = name self.pos = pos self._value = value self.id = id self.attrs = attrs def value__get(self): if self._value is None: return '' else: return self._value def value__set(self, value): self._value = value value = property(value__get, value__set) def force_value(self, value): """Like setting a value, except forces it (even for, say, hidden fields). """ self._value = value def __repr__(self): value = '<%s name="%s"' % (self.__class__.__name__, self.name) if self.id: value += ' id="%s"' % self.id return value + '>'
(form, tag, name, pos, value=None, id=None, **attrs)
7,877
webtest.forms
__init__
null
def __init__(self, form, tag, name, pos, value=None, id=None, **attrs): self.form = form self.tag = tag self.name = name self.pos = pos self._value = value self.id = id self.attrs = attrs
(self, form, tag, name, pos, value=None, id=None, **attrs)
7,880
webtest.forms
value__get
null
def value__get(self): if self._value is None: return '' else: return self._value
(self)
7,881
webtest.forms
value__set
null
def value__set(self, value): self._value = value
(self, value)
7,882
webtest.forms
Form
This object represents a form that has been found in a page. :param response: `webob.response.TestResponse` instance :param text: Unparsed html of the form .. attribute:: text the full HTML of the form. .. attribute:: action the relative URI of the action. .. attribute:: method the HTTP method (e.g., ``'GET'``). .. attribute:: id the id, or None if not given. .. attribute:: enctype encoding of the form submission .. attribute:: fields a dictionary of fields, each value is a list of fields by that name. ``<input type="radio">`` and ``<select>`` are both represented as single fields with multiple options. .. attribute:: field_order Ordered list of field names as found in the html.
class Form: """This object represents a form that has been found in a page. :param response: `webob.response.TestResponse` instance :param text: Unparsed html of the form .. attribute:: text the full HTML of the form. .. attribute:: action the relative URI of the action. .. attribute:: method the HTTP method (e.g., ``'GET'``). .. attribute:: id the id, or None if not given. .. attribute:: enctype encoding of the form submission .. attribute:: fields a dictionary of fields, each value is a list of fields by that name. ``<input type=\"radio\">`` and ``<select>`` are both represented as single fields with multiple options. .. attribute:: field_order Ordered list of field names as found in the html. """ # TODO: use BeautifulSoup4 for this _tag_re = re.compile(r'<(/?)([a-z0-9_\-]*)([^>]*?)>', re.I) _label_re = re.compile( r'''<label\s+(?:[^>]*)for=(?:"|')([a-z0-9_\-]+)(?:"|')(?:[^>]*)>''', re.I) FieldClass = Field def __init__(self, response, text, parser_features='html.parser'): self.response = response self.text = text self.html = BeautifulSoup(self.text, parser_features) attrs = self.html('form')[0].attrs self.action = attrs.get('action', '') self.method = attrs.get('method', 'GET') self.id = attrs.get('id') self.enctype = attrs.get('enctype', 'application/x-www-form-urlencoded') self._parse_fields() def _parse_fields(self): fields = OrderedDict() field_order = [] tags = ('input', 'select', 'textarea', 'button') for pos, node in enumerate(self.html.findAll(tags)): attrs = dict(node.attrs) tag = node.name name = None if 'name' in attrs: name = attrs.pop('name') if tag == 'textarea': if node.text.startswith('\r\n'): # pragma: no cover text = node.text[2:] elif node.text.startswith('\n'): text = node.text[1:] else: text = node.text attrs['value'] = text tag_type = attrs.get('type', 'text').lower() if tag == 'select': tag_type = 'select' if tag_type == "select" and "multiple" in attrs: tag_type = "multiple_select" if tag == 'button': tag_type = 'submit' FieldClass = self.FieldClass.classes.get(tag_type, self.FieldClass) # https://github.com/Pylons/webtest/issues/73 if sys.version_info[:2] <= (2, 6): attrs = {k.encode('utf-8') if isinstance(k, unicode) else k: v for k, v in attrs.items()} # https://github.com/Pylons/webtest/issues/131 reserved_attributes = ('form', 'tag', 'pos') for attr in reserved_attributes: if attr in attrs: del attrs[attr] if tag == 'input': if tag_type == 'radio': field = fields.get(name) if not field: field = FieldClass(self, tag, name, pos, **attrs) fields.setdefault(name, []).append(field) field_order.append((name, field)) else: field = field[0] assert isinstance(field, self.FieldClass.classes['radio']) field.options.append((attrs.get('value'), 'checked' in attrs, None)) field.optionPositions.append(pos) if 'checked' in attrs: field.selectedIndex = len(field.options) - 1 continue elif tag_type == 'file': if 'value' in attrs: del attrs['value'] field = FieldClass(self, tag, name, pos, **attrs) fields.setdefault(name, []).append(field) field_order.append((name, field)) if tag == 'select': for option in node('option'): field.options.append( (option.attrs.get('value', option.text), 'selected' in option.attrs, option.text)) self.field_order = field_order self.fields = fields def __setitem__(self, name, value): """Set the value of the named field. If there is 0 or multiple fields by that name, it is an error. Multiple checkboxes of the same name are special-cased; a list may be assigned to them to check the checkboxes whose value is present in the list (and uncheck all others). Setting the value of a ``<select>`` selects the given option (and confirms it is an option). Setting radio fields does the same. Checkboxes get boolean values. You cannot set hidden fields or buttons. Use ``.set()`` if there is any ambiguity and you must provide an index. """ fields = self.fields.get(name) assert fields is not None, ( "No field by the name %r found (fields: %s)" % (name, ', '.join(map(repr, self.fields.keys())))) all_checkboxes = all(isinstance(f, Checkbox) for f in fields) if all_checkboxes and isinstance(value, list): values = {utils.stringify(v) for v in value} for f in fields: f.checked = f._value in values else: assert len(fields) == 1, ( "Multiple fields match %r: %s" % (name, ', '.join(map(repr, fields)))) fields[0].value = value def __getitem__(self, name): """Get the named field object (ambiguity is an error).""" fields = self.fields.get(name) assert fields is not None, ( "No field by the name %r found" % name) assert len(fields) == 1, ( "Multiple fields match %r: %s" % (name, ', '.join(map(repr, fields)))) return fields[0] def lint(self): """ Check that the html is valid: - each field must have an id - each field must have a label """ labels = self._label_re.findall(self.text) for name, fields in self.fields.items(): for field in fields: if not isinstance(field, (Submit, Hidden)): if not field.id: raise AttributeError("%r as no id attribute" % field) elif field.id not in labels: raise AttributeError( "%r as no associated label" % field) def set(self, name, value, index=None): """Set the given name, using ``index`` to disambiguate.""" if index is None: self[name] = value else: fields = self.fields.get(name) assert fields is not None, ( "No fields found matching %r" % name) field = fields[index] field.value = value def get(self, name, index=None, default=utils.NoDefault): """ Get the named/indexed field object, or ``default`` if no field is found. Throws an AssertionError if no field is found and no ``default`` was given. """ fields = self.fields.get(name) if fields is None: if default is utils.NoDefault: raise AssertionError( "No fields found matching %r (and no default given)" % name) return default if index is None: return self[name] return fields[index] def select(self, name, value=None, text=None, index=None): """Like ``.set()``, except also confirms the target is a ``<select>`` and allows selecting options by text. """ field = self.get(name, index=index) assert isinstance(field, Select) field.select(value, text) def select_multiple(self, name, value=None, texts=None, index=None): """Like ``.set()``, except also confirms the target is a ``<select multiple>`` and allows selecting options by text. """ field = self.get(name, index=index) assert isinstance(field, MultipleSelect) field.select_multiple(value, texts) def submit(self, name=None, index=None, value=None, **args): """Submits the form. If ``name`` is given, then also select that button (using ``index`` or ``value`` to disambiguate)``. Any extra keyword arguments are passed to the :meth:`webtest.TestResponse.get` or :meth:`webtest.TestResponse.post` method. Returns a :class:`webtest.TestResponse` object. """ fields = self.submit_fields(name, index=index, submit_value=value) if self.method.upper() != "GET": args.setdefault("content_type", self.enctype) extra_environ = args.setdefault('extra_environ', {}) extra_environ.setdefault('HTTP_REFERER', str(self.response.request.url)) return self.response.goto(self.action, method=self.method, params=fields, **args) def upload_fields(self): """Return a list of file field tuples of the form:: (field name, file name) or:: (field name, file name, file contents). """ uploads = [] for name, fields in self.fields.items(): for field in fields: if isinstance(field, File) and field.value: uploads.append([name] + list(field.value)) return uploads def submit_fields(self, name=None, index=None, submit_value=None): """Return a list of ``[(name, value), ...]`` for the current state of the form. :param name: Same as for :meth:`submit` :param index: Same as for :meth:`submit` """ submit = [] # Use another name here so we can keep function param the same for BWC. submit_name = name if index is not None and submit_value is not None: raise ValueError("Can't specify both submit_value and index.") # If no particular button was selected, use the first one if index is None and submit_value is None: index = 0 # This counts all fields with the submit name not just submit fields. current_index = 0 for name, field in self.field_order: if name is None: # pragma: no cover continue if submit_name is not None and name == submit_name: if index is not None and current_index == index: submit.append((field.pos, name, field.value_if_submitted())) if submit_value is not None and \ field.value_if_submitted() == submit_value: submit.append((field.pos, name, field.value_if_submitted())) current_index += 1 else: value = field.value if value is None: continue if isinstance(field, File): submit.append((field.pos, name, field)) continue if isinstance(field, Radio): if field.selectedIndex is not None: submit.append((field.optionPositions[field.selectedIndex], name, value)) continue if isinstance(value, list): for item in value: submit.append((field.pos, name, item)) else: submit.append((field.pos, name, value)) submit.sort(key=operator.itemgetter(0)) return [x[1:] for x in submit] def __repr__(self): value = '<Form' if self.id: value += ' id=%r' % str(self.id) return value + ' />'
(response, text, parser_features='html.parser')
7,883
webtest.forms
__getitem__
Get the named field object (ambiguity is an error).
def __getitem__(self, name): """Get the named field object (ambiguity is an error).""" fields = self.fields.get(name) assert fields is not None, ( "No field by the name %r found" % name) assert len(fields) == 1, ( "Multiple fields match %r: %s" % (name, ', '.join(map(repr, fields)))) return fields[0]
(self, name)
7,884
webtest.forms
__init__
null
def __init__(self, response, text, parser_features='html.parser'): self.response = response self.text = text self.html = BeautifulSoup(self.text, parser_features) attrs = self.html('form')[0].attrs self.action = attrs.get('action', '') self.method = attrs.get('method', 'GET') self.id = attrs.get('id') self.enctype = attrs.get('enctype', 'application/x-www-form-urlencoded') self._parse_fields()
(self, response, text, parser_features='html.parser')
7,885
webtest.forms
__repr__
null
def __repr__(self): value = '<Form' if self.id: value += ' id=%r' % str(self.id) return value + ' />'
(self)
7,886
webtest.forms
__setitem__
Set the value of the named field. If there is 0 or multiple fields by that name, it is an error. Multiple checkboxes of the same name are special-cased; a list may be assigned to them to check the checkboxes whose value is present in the list (and uncheck all others). Setting the value of a ``<select>`` selects the given option (and confirms it is an option). Setting radio fields does the same. Checkboxes get boolean values. You cannot set hidden fields or buttons. Use ``.set()`` if there is any ambiguity and you must provide an index.
def __setitem__(self, name, value): """Set the value of the named field. If there is 0 or multiple fields by that name, it is an error. Multiple checkboxes of the same name are special-cased; a list may be assigned to them to check the checkboxes whose value is present in the list (and uncheck all others). Setting the value of a ``<select>`` selects the given option (and confirms it is an option). Setting radio fields does the same. Checkboxes get boolean values. You cannot set hidden fields or buttons. Use ``.set()`` if there is any ambiguity and you must provide an index. """ fields = self.fields.get(name) assert fields is not None, ( "No field by the name %r found (fields: %s)" % (name, ', '.join(map(repr, self.fields.keys())))) all_checkboxes = all(isinstance(f, Checkbox) for f in fields) if all_checkboxes and isinstance(value, list): values = {utils.stringify(v) for v in value} for f in fields: f.checked = f._value in values else: assert len(fields) == 1, ( "Multiple fields match %r: %s" % (name, ', '.join(map(repr, fields)))) fields[0].value = value
(self, name, value)
7,887
webtest.forms
_parse_fields
null
def _parse_fields(self): fields = OrderedDict() field_order = [] tags = ('input', 'select', 'textarea', 'button') for pos, node in enumerate(self.html.findAll(tags)): attrs = dict(node.attrs) tag = node.name name = None if 'name' in attrs: name = attrs.pop('name') if tag == 'textarea': if node.text.startswith('\r\n'): # pragma: no cover text = node.text[2:] elif node.text.startswith('\n'): text = node.text[1:] else: text = node.text attrs['value'] = text tag_type = attrs.get('type', 'text').lower() if tag == 'select': tag_type = 'select' if tag_type == "select" and "multiple" in attrs: tag_type = "multiple_select" if tag == 'button': tag_type = 'submit' FieldClass = self.FieldClass.classes.get(tag_type, self.FieldClass) # https://github.com/Pylons/webtest/issues/73 if sys.version_info[:2] <= (2, 6): attrs = {k.encode('utf-8') if isinstance(k, unicode) else k: v for k, v in attrs.items()} # https://github.com/Pylons/webtest/issues/131 reserved_attributes = ('form', 'tag', 'pos') for attr in reserved_attributes: if attr in attrs: del attrs[attr] if tag == 'input': if tag_type == 'radio': field = fields.get(name) if not field: field = FieldClass(self, tag, name, pos, **attrs) fields.setdefault(name, []).append(field) field_order.append((name, field)) else: field = field[0] assert isinstance(field, self.FieldClass.classes['radio']) field.options.append((attrs.get('value'), 'checked' in attrs, None)) field.optionPositions.append(pos) if 'checked' in attrs: field.selectedIndex = len(field.options) - 1 continue elif tag_type == 'file': if 'value' in attrs: del attrs['value'] field = FieldClass(self, tag, name, pos, **attrs) fields.setdefault(name, []).append(field) field_order.append((name, field)) if tag == 'select': for option in node('option'): field.options.append( (option.attrs.get('value', option.text), 'selected' in option.attrs, option.text)) self.field_order = field_order self.fields = fields
(self)
7,888
webtest.forms
get
Get the named/indexed field object, or ``default`` if no field is found. Throws an AssertionError if no field is found and no ``default`` was given.
def get(self, name, index=None, default=utils.NoDefault): """ Get the named/indexed field object, or ``default`` if no field is found. Throws an AssertionError if no field is found and no ``default`` was given. """ fields = self.fields.get(name) if fields is None: if default is utils.NoDefault: raise AssertionError( "No fields found matching %r (and no default given)" % name) return default if index is None: return self[name] return fields[index]
(self, name, index=None, default=<NoDefault>)
7,889
webtest.forms
lint
Check that the html is valid: - each field must have an id - each field must have a label
def lint(self): """ Check that the html is valid: - each field must have an id - each field must have a label """ labels = self._label_re.findall(self.text) for name, fields in self.fields.items(): for field in fields: if not isinstance(field, (Submit, Hidden)): if not field.id: raise AttributeError("%r as no id attribute" % field) elif field.id not in labels: raise AttributeError( "%r as no associated label" % field)
(self)
7,890
webtest.forms
select
Like ``.set()``, except also confirms the target is a ``<select>`` and allows selecting options by text.
def select(self, name, value=None, text=None, index=None): """Like ``.set()``, except also confirms the target is a ``<select>`` and allows selecting options by text. """ field = self.get(name, index=index) assert isinstance(field, Select) field.select(value, text)
(self, name, value=None, text=None, index=None)
7,891
webtest.forms
select_multiple
Like ``.set()``, except also confirms the target is a ``<select multiple>`` and allows selecting options by text.
def select_multiple(self, name, value=None, texts=None, index=None): """Like ``.set()``, except also confirms the target is a ``<select multiple>`` and allows selecting options by text. """ field = self.get(name, index=index) assert isinstance(field, MultipleSelect) field.select_multiple(value, texts)
(self, name, value=None, texts=None, index=None)
7,892
webtest.forms
set
Set the given name, using ``index`` to disambiguate.
def set(self, name, value, index=None): """Set the given name, using ``index`` to disambiguate.""" if index is None: self[name] = value else: fields = self.fields.get(name) assert fields is not None, ( "No fields found matching %r" % name) field = fields[index] field.value = value
(self, name, value, index=None)
7,893
webtest.forms
submit
Submits the form. If ``name`` is given, then also select that button (using ``index`` or ``value`` to disambiguate)``. Any extra keyword arguments are passed to the :meth:`webtest.TestResponse.get` or :meth:`webtest.TestResponse.post` method. Returns a :class:`webtest.TestResponse` object.
def submit(self, name=None, index=None, value=None, **args): """Submits the form. If ``name`` is given, then also select that button (using ``index`` or ``value`` to disambiguate)``. Any extra keyword arguments are passed to the :meth:`webtest.TestResponse.get` or :meth:`webtest.TestResponse.post` method. Returns a :class:`webtest.TestResponse` object. """ fields = self.submit_fields(name, index=index, submit_value=value) if self.method.upper() != "GET": args.setdefault("content_type", self.enctype) extra_environ = args.setdefault('extra_environ', {}) extra_environ.setdefault('HTTP_REFERER', str(self.response.request.url)) return self.response.goto(self.action, method=self.method, params=fields, **args)
(self, name=None, index=None, value=None, **args)
7,894
webtest.forms
submit_fields
Return a list of ``[(name, value), ...]`` for the current state of the form. :param name: Same as for :meth:`submit` :param index: Same as for :meth:`submit`
def submit_fields(self, name=None, index=None, submit_value=None): """Return a list of ``[(name, value), ...]`` for the current state of the form. :param name: Same as for :meth:`submit` :param index: Same as for :meth:`submit` """ submit = [] # Use another name here so we can keep function param the same for BWC. submit_name = name if index is not None and submit_value is not None: raise ValueError("Can't specify both submit_value and index.") # If no particular button was selected, use the first one if index is None and submit_value is None: index = 0 # This counts all fields with the submit name not just submit fields. current_index = 0 for name, field in self.field_order: if name is None: # pragma: no cover continue if submit_name is not None and name == submit_name: if index is not None and current_index == index: submit.append((field.pos, name, field.value_if_submitted())) if submit_value is not None and \ field.value_if_submitted() == submit_value: submit.append((field.pos, name, field.value_if_submitted())) current_index += 1 else: value = field.value if value is None: continue if isinstance(field, File): submit.append((field.pos, name, field)) continue if isinstance(field, Radio): if field.selectedIndex is not None: submit.append((field.optionPositions[field.selectedIndex], name, value)) continue if isinstance(value, list): for item in value: submit.append((field.pos, name, item)) else: submit.append((field.pos, name, value)) submit.sort(key=operator.itemgetter(0)) return [x[1:] for x in submit]
(self, name=None, index=None, submit_value=None)
7,895
webtest.forms
upload_fields
Return a list of file field tuples of the form:: (field name, file name) or:: (field name, file name, file contents).
def upload_fields(self): """Return a list of file field tuples of the form:: (field name, file name) or:: (field name, file name, file contents). """ uploads = [] for name, fields in self.fields.items(): for field in fields: if isinstance(field, File) and field.value: uploads.append([name] + list(field.value)) return uploads
(self)
7,896
webtest.forms
Hidden
Field representing ``<input type="hidden">``
class Hidden(Text): """Field representing ``<input type="hidden">``"""
(form, tag, name, pos, value=None, id=None, **attrs)
7,902
webtest.forms
Radio
Field representing ``<input type="radio">``
class Radio(Select): """Field representing ``<input type="radio">``""" def value__get(self): if self._forced_value is not NoValue: return self._forced_value elif self.selectedIndex is not None: return self.options[self.selectedIndex][0] else: for option, checked, text in self.options: if checked: return option else: return None value = property(value__get, Select.value__set)
(*args, **attrs)
7,903
webtest.forms
__init__
null
def __init__(self, *args, **attrs): super().__init__(*args, **attrs) self.options = [] self.optionPositions = [] # Undetermined yet: self.selectedIndex = None # we have no forced value self._forced_value = NoValue
(self, *args, **attrs)
7,905
webtest.forms
_get_value_for_text
null
def _get_value_for_text(self, text): for i, (option_value, checked, option_text) in enumerate(self.options): if option_text == utils.stringify(text): return option_value raise ValueError("Option with text %r not found (from %s)" % (text, ', '.join( [repr(t) for o, c, t in self.options])))
(self, text)
7,906
webtest.forms
force_value
Like setting a value, except forces it (even for, say, hidden fields).
def force_value(self, value): """Like setting a value, except forces it (even for, say, hidden fields). """ try: self.value = value self._forced_value = NoValue except ValueError: self.selectedIndex = None self._forced_value = value
(self, value)
7,907
webtest.forms
select
null
def select(self, value=None, text=None): if value is not None and text is not None: raise ValueError("Specify only one of value and text.") if text is not None: value = self._get_value_for_text(text) self.value = value
(self, value=None, text=None)
7,908
webtest.forms
value__get
null
def value__get(self): if self._forced_value is not NoValue: return self._forced_value elif self.selectedIndex is not None: return self.options[self.selectedIndex][0] else: for option, checked, text in self.options: if checked: return option else: return None
(self)
7,909
webtest.forms
value__set
null
def value__set(self, value): if self._forced_value is not NoValue: self._forced_value = NoValue for i, (option, checked, text) in enumerate(self.options): if option == utils.stringify(value): self.selectedIndex = i break else: raise ValueError( "Option %r not found (from %s)" % (value, ', '.join([repr(o) for o, c, t in self.options])))
(self, value)
7,910
webtest.forms
Select
Field representing ``<select />`` form element.
class Select(Field): """Field representing ``<select />`` form element.""" def __init__(self, *args, **attrs): super().__init__(*args, **attrs) self.options = [] self.optionPositions = [] # Undetermined yet: self.selectedIndex = None # we have no forced value self._forced_value = NoValue def force_value(self, value): """Like setting a value, except forces it (even for, say, hidden fields). """ try: self.value = value self._forced_value = NoValue except ValueError: self.selectedIndex = None self._forced_value = value def select(self, value=None, text=None): if value is not None and text is not None: raise ValueError("Specify only one of value and text.") if text is not None: value = self._get_value_for_text(text) self.value = value def _get_value_for_text(self, text): for i, (option_value, checked, option_text) in enumerate(self.options): if option_text == utils.stringify(text): return option_value raise ValueError("Option with text %r not found (from %s)" % (text, ', '.join( [repr(t) for o, c, t in self.options]))) def value__set(self, value): if self._forced_value is not NoValue: self._forced_value = NoValue for i, (option, checked, text) in enumerate(self.options): if option == utils.stringify(value): self.selectedIndex = i break else: raise ValueError( "Option %r not found (from %s)" % (value, ', '.join([repr(o) for o, c, t in self.options]))) def value__get(self): if self._forced_value is not NoValue: return self._forced_value elif self.selectedIndex is not None: return self.options[self.selectedIndex][0] else: for option, checked, text in self.options: if checked: return option else: if self.options: return self.options[0][0] value = property(value__get, value__set)
(*args, **attrs)
7,916
webtest.forms
value__get
null
def value__get(self): if self._forced_value is not NoValue: return self._forced_value elif self.selectedIndex is not None: return self.options[self.selectedIndex][0] else: for option, checked, text in self.options: if checked: return option else: if self.options: return self.options[0][0]
(self)
7,918
webtest.forms
Submit
Field representing ``<input type="submit">`` and ``<button>``
class Submit(Field): """Field representing ``<input type="submit">`` and ``<button>``""" def value__get(self): return None def value__set(self, value): raise AttributeError( "You cannot set the value of the <%s> field %r" % (self.tag, self.name)) value = property(value__get, value__set) def value_if_submitted(self): # parsed value of the empty string return self._value or ''
(form, tag, name, pos, value=None, id=None, **attrs)
7,922
webtest.forms
value__get
null
def value__get(self): return None
(self)
7,923
webtest.forms
value__set
null
def value__set(self, value): raise AttributeError( "You cannot set the value of the <%s> field %r" % (self.tag, self.name))
(self, value)
7,924
webtest.forms
value_if_submitted
null
def value_if_submitted(self): # parsed value of the empty string return self._value or ''
(self)