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,626 |
emmett.app
|
config_from_yaml
| null |
def config_from_yaml(self, filename: str, namespace: Optional[str] = None):
#: import configuration from yaml files
rc = read_file(os.path.join(self.config_path, filename))
rc = ymlload(rc, Loader=ymlLoader)
c = self.config if namespace is None else self.config[namespace]
for key, val in rc.items():
c[key] = dict_to_sdict(val)
|
(self, filename: str, namespace: Optional[str] = None)
|
7,627 |
emmett.app
|
make_shell_context
| null |
def make_shell_context(self, context: Dict[str, Any] = {}) -> Dict[str, Any]:
context['app'] = self
return context
|
(self, context: Dict[str, Any] = {}) -> Dict[str, Any]
|
7,628 |
emmett.app
|
module
| null |
def module(
self,
import_name: str,
name: str,
template_folder: Optional[str] = None,
template_path: Optional[str] = None,
static_folder: Optional[str] = None,
static_path: Optional[str] = None,
url_prefix: Optional[str] = None,
hostname: Optional[str] = None,
cache: Optional[RouteCacheRule] = None,
root_path: Optional[str] = None,
pipeline: Optional[List[Pipe]] = None,
injectors: Optional[List[Injector]] = None,
module_class: Optional[Type[AppModule]] = None,
**kwargs: Any
) -> AppModule:
module_class = module_class or self.config.modules_class
return module_class.from_app(
self,
import_name,
name,
template_folder=template_folder,
template_path=template_path,
static_folder=static_folder,
static_path=static_path,
url_prefix=url_prefix,
hostname=hostname,
cache=cache,
root_path=root_path,
pipeline=pipeline or [],
injectors=injectors or [],
opts=kwargs
)
|
(self, import_name: str, name: str, template_folder: Optional[str] = None, template_path: Optional[str] = None, static_folder: Optional[str] = None, static_path: Optional[str] = None, url_prefix: Optional[str] = None, hostname: Optional[str] = None, cache: Optional[emmett.cache.RouteCacheRule] = None, root_path: Optional[str] = None, pipeline: Optional[List[emmett.pipeline.Pipe]] = None, injectors: Optional[List[emmett.pipeline.Injector]] = None, module_class: Optional[Type[emmett.app.AppModule]] = None, **kwargs: Any) -> emmett.app.AppModule
|
7,629 |
emmett.app
|
module_group
| null |
def module_group(self, *modules: AppModule) -> AppModuleGroup:
return AppModuleGroup(*modules)
|
(self, *modules: emmett.app.AppModule) -> emmett.app.AppModuleGroup
|
7,630 |
emmett.app
|
on_error
| null |
def on_error(self, code: int) -> Callable[[ErrorHandlerType], ErrorHandlerType]:
def decorator(f: ErrorHandlerType) -> ErrorHandlerType:
self.error_handlers[code] = f
return f
return decorator
|
(self, code: int) -> Callable[[~ErrorHandlerType], ~ErrorHandlerType]
|
7,631 |
emmett.app
|
render_template
| null |
def render_template(self, filename: str) -> str:
ctx = {
'current': current, 'url': url, 'asis': asis,
'load_component': load_component
}
return self.templater.render(filename, ctx)
|
(self, filename: str) -> str
|
7,632 |
emmett.app
|
route
| null |
def route(
self,
paths: Optional[Union[str, List[str]]] = None,
name: Optional[str] = None,
template: Optional[str] = None,
pipeline: Optional[List[Pipe]] = None,
injectors: Optional[List[Injector]] = None,
schemes: Optional[Union[str, List[str]]] = None,
hostname: Optional[str] = None,
methods: Optional[Union[str, List[str]]] = None,
prefix: Optional[str] = None,
template_folder: Optional[str] = None,
template_path: Optional[str] = None,
cache: Optional[RouteCacheRule] = None,
output: str = 'auto'
) -> RoutingCtx:
if callable(paths):
raise SyntaxError('Use @route(), not @route.')
return self._router_http(
paths=paths,
name=name,
template=template,
pipeline=pipeline,
injectors=injectors,
schemes=schemes,
hostname=hostname,
methods=methods,
prefix=prefix,
template_folder=template_folder,
template_path=template_path,
cache=cache,
output=output
)
|
(self, paths: Union[str, List[str], NoneType] = None, name: Optional[str] = None, template: Optional[str] = None, pipeline: Optional[List[emmett.pipeline.Pipe]] = None, injectors: Optional[List[emmett.pipeline.Injector]] = None, schemes: Union[str, List[str], NoneType] = None, hostname: Optional[str] = None, methods: Union[str, List[str], NoneType] = None, prefix: Optional[str] = None, template_folder: Optional[str] = None, template_path: Optional[str] = None, cache: Optional[emmett.cache.RouteCacheRule] = None, output: str = 'auto') -> emmett.routing.router.RoutingCtx
|
7,633 |
emmett.app
|
send_signal
| null |
def send_signal(self, signal: Union[str, Signals], *args, **kwargs):
if not isinstance(signal, Signals):
warn_of_deprecation(
"App.send_signal str argument",
"extensions.Signals as argument",
stack=3
)
try:
signal = Signals[signal]
except KeyError:
raise SyntaxError(f"{signal} is not a valid signal")
for listener in self._extensions_listeners[signal]:
listener(*args, **kwargs)
|
(self, signal: Union[str, emmett.extensions.Signals], *args, **kwargs)
|
7,634 |
emmett.app
|
test_client
| null |
def test_client(self, use_cookies: bool = True, **kwargs) -> EmmettTestClient:
tclass = self.test_client_class or EmmettTestClient
return tclass(self, use_cookies=use_cookies, **kwargs)
|
(self, use_cookies: bool = True, **kwargs) -> emmett.testing.client.EmmettTestClient
|
7,635 |
emmett.app
|
use_extension
| null |
def use_extension(self, ext_cls: Type[ExtensionType]) -> ExtensionType:
if not issubclass(ext_cls, Extension):
raise RuntimeError(
f'{ext_cls.__name__} is an invalid Emmett extension'
)
ext_env, ext_config = self.__init_extension(ext_cls)
ext = self.ext[ext_cls.__name__] = ext_cls(self, ext_env, ext_config)
self.__register_extension_listeners(ext)
ext.on_load()
return ext
|
(self, ext_cls: Type[~ExtensionType]) -> ~ExtensionType
|
7,636 |
emmett.app
|
use_template_extension
| null |
def use_template_extension(self, ext_cls, **config):
return self.templater.use_extension(ext_cls, **config)
|
(self, ext_cls, **config)
|
7,637 |
emmett.app
|
websocket
| null |
def websocket(
self,
paths: Optional[Union[str, List[str]]] = None,
name: Optional[str] = None,
pipeline: Optional[List[Pipe]] = None,
schemes: Optional[Union[str, List[str]]] = None,
hostname: Optional[str] = None,
prefix: Optional[str] = None
) -> RoutingCtx:
if callable(paths):
raise SyntaxError('Use @websocket(), not @websocket.')
return self._router_ws(
paths=paths,
name=name,
pipeline=pipeline,
schemes=schemes,
hostname=hostname,
prefix=prefix
)
|
(self, paths: Union[str, List[str], NoneType] = None, name: Optional[str] = None, pipeline: Optional[List[emmett.pipeline.Pipe]] = None, schemes: Union[str, List[str], NoneType] = None, hostname: Optional[str] = None, prefix: Optional[str] = None) -> emmett.routing.router.RoutingCtx
|
7,638 |
emmett.app
|
AppModule
| null |
class AppModule:
@classmethod
def from_app(
cls,
app: App,
import_name: str,
name: str,
template_folder: Optional[str],
template_path: Optional[str],
static_folder: Optional[str],
static_path: Optional[str],
url_prefix: Optional[str],
hostname: Optional[str],
cache: Optional[RouteCacheRule],
root_path: Optional[str],
pipeline: List[Pipe],
injectors: List[Injector],
opts: Dict[str, Any] = {}
):
return cls(
app,
name,
import_name,
template_folder=template_folder,
template_path=template_path,
static_folder=static_folder,
static_path=static_path,
url_prefix=url_prefix,
hostname=hostname,
cache=cache,
root_path=root_path,
pipeline=pipeline,
injectors=injectors,
**opts
)
@classmethod
def from_module(
cls,
appmod: AppModule,
import_name: str,
name: str,
template_folder: Optional[str],
template_path: Optional[str],
static_folder: Optional[str],
static_path: Optional[str],
url_prefix: Optional[str],
hostname: Optional[str],
cache: Optional[RouteCacheRule],
root_path: Optional[str],
opts: Dict[str, Any] = {}
):
if '.' in name:
raise RuntimeError(
"Nested app modules' names should not contains dots"
)
name = appmod.name + '.' + name
if url_prefix and not url_prefix.startswith('/'):
url_prefix = '/' + url_prefix
module_url_prefix = (appmod.url_prefix + (url_prefix or '')) \
if appmod.url_prefix else url_prefix
hostname = hostname or appmod.hostname
cache = cache or appmod.cache
return cls(
appmod.app,
name,
import_name,
template_folder=template_folder,
template_path=template_path,
static_folder=static_folder,
static_path=static_path,
url_prefix=module_url_prefix,
hostname=hostname,
cache=cache,
root_path=root_path,
pipeline=appmod.pipeline,
injectors=appmod.injectors,
**opts
)
@classmethod
def from_module_group(
cls,
appmodgroup: AppModuleGroup,
import_name: str,
name: str,
template_folder: Optional[str],
template_path: Optional[str],
static_folder: Optional[str],
static_path: Optional[str],
url_prefix: Optional[str],
hostname: Optional[str],
cache: Optional[RouteCacheRule],
root_path: Optional[str],
opts: Dict[str, Any] = {}
) -> AppModulesGrouped:
mods = []
for module in appmodgroup.modules:
mod = cls.from_module(
module,
import_name,
name,
template_folder=template_folder,
template_path=template_path,
static_folder=static_folder,
static_path=static_path,
url_prefix=url_prefix,
hostname=hostname,
cache=cache,
root_path=root_path,
opts=opts
)
mods.append(mod)
return AppModulesGrouped(*mods)
def module(
self,
import_name: str,
name: str,
template_folder: Optional[str] = None,
template_path: Optional[str] = None,
static_folder: Optional[str] = None,
static_path: Optional[str] = None,
url_prefix: Optional[str] = None,
hostname: Optional[str] = None,
cache: Optional[RouteCacheRule] = None,
root_path: Optional[str] = None,
module_class: Optional[Type[AppModule]] = None,
**kwargs: Any
) -> AppModule:
module_class = module_class or self.__class__
return module_class.from_module(
self,
import_name,
name,
template_folder=template_folder,
template_path=template_path,
static_folder=static_folder,
static_path=static_path,
url_prefix=url_prefix,
hostname=hostname,
cache=cache,
root_path=root_path,
opts=kwargs
)
def __init__(
self,
app: App,
name: str,
import_name: str,
template_folder: Optional[str] = None,
template_path: Optional[str] = None,
static_folder: Optional[str] = None,
static_path: Optional[str] = None,
url_prefix: Optional[str] = None,
hostname: Optional[str] = None,
cache: Optional[RouteCacheRule] = None,
root_path: Optional[str] = None,
pipeline: Optional[List[Pipe]] = None,
injectors: Optional[List[Injector]] = None,
**kwargs: Any
):
self.app = app
self.name = name
self.import_name = import_name
if root_path is None:
root_path = get_root_path(self.import_name)
self.root_path = root_path
#: - `template_folder` is referred to application `template_path`
# - `template_path` is referred to module root_directory unless absolute
self.template_folder = template_folder
if template_path and not template_path.startswith("/"):
template_path = os.path.join(self.root_path, template_path)
self.template_path = template_path
#: - `static_folder` is referred to application `static_path`
# - `static_path` is referred to module root_directory unless absolute
if static_path and not static_path.startswith("/"):
static_path = os.path.join(self.root_path, static_path)
self._static_path = (
os.path.join(self.app.static_path, static_folder) if static_folder else
(static_path or self.app.static_path)
)
self.url_prefix = url_prefix
self.hostname = hostname
self.cache = cache
self._super_pipeline = pipeline or []
self._super_injectors = injectors or []
self.pipeline = []
self.injectors = []
self.app._register_module(self)
@property
def pipeline(self) -> List[Pipe]:
return self._pipeline
@pipeline.setter
def pipeline(self, pipeline: List[Pipe]):
self._pipeline = self._super_pipeline + pipeline
@property
def injectors(self) -> List[Injector]:
return self._injectors
@injectors.setter
def injectors(self, injectors: List[Injector]):
self._injectors = self._super_injectors + injectors
def route(
self,
paths: Optional[Union[str, List[str]]] = None,
name: Optional[str] = None,
template: Optional[str] = None,
**kwargs
) -> RoutingCtx:
if name is not None and "." in name:
raise RuntimeError(
"App modules' route names should not contains dots"
)
name = self.name + "." + (name or "")
pipeline = kwargs.get('pipeline', [])
injectors = kwargs.get('injectors', [])
if self.pipeline:
pipeline = self.pipeline + pipeline
kwargs['pipeline'] = pipeline
if self.injectors:
injectors = self.injectors + injectors
kwargs['injectors'] = injectors
kwargs['cache'] = kwargs.get('cache', self.cache)
return self.app.route(
paths=paths,
name=name,
template=template,
prefix=self.url_prefix,
template_folder=self.template_folder,
template_path=self.template_path,
hostname=self.hostname,
**kwargs
)
def websocket(
self,
paths: Optional[Union[str, List[str]]] = None,
name: Optional[str] = None,
**kwargs
) -> RoutingCtx:
if name is not None and "." in name:
raise RuntimeError(
"App modules' websocket names should not contains dots"
)
name = self.name + "." + (name or "")
pipeline = kwargs.get('pipeline', [])
if self.pipeline:
pipeline = self.pipeline + pipeline
kwargs['pipeline'] = pipeline
return self.app.websocket(
paths=paths,
name=name,
prefix=self.url_prefix,
hostname=self.hostname,
**kwargs
)
|
(app: 'App', name: 'str', import_name: 'str', template_folder: 'Optional[str]' = None, template_path: 'Optional[str]' = None, static_folder: 'Optional[str]' = None, static_path: 'Optional[str]' = None, url_prefix: 'Optional[str]' = None, hostname: 'Optional[str]' = None, cache: 'Optional[RouteCacheRule]' = None, root_path: 'Optional[str]' = None, pipeline: 'Optional[List[Pipe]]' = None, injectors: 'Optional[List[Injector]]' = None, **kwargs: 'Any')
|
7,639 |
emmett.app
|
__init__
| null |
def __init__(
self,
app: App,
name: str,
import_name: str,
template_folder: Optional[str] = None,
template_path: Optional[str] = None,
static_folder: Optional[str] = None,
static_path: Optional[str] = None,
url_prefix: Optional[str] = None,
hostname: Optional[str] = None,
cache: Optional[RouteCacheRule] = None,
root_path: Optional[str] = None,
pipeline: Optional[List[Pipe]] = None,
injectors: Optional[List[Injector]] = None,
**kwargs: Any
):
self.app = app
self.name = name
self.import_name = import_name
if root_path is None:
root_path = get_root_path(self.import_name)
self.root_path = root_path
#: - `template_folder` is referred to application `template_path`
# - `template_path` is referred to module root_directory unless absolute
self.template_folder = template_folder
if template_path and not template_path.startswith("/"):
template_path = os.path.join(self.root_path, template_path)
self.template_path = template_path
#: - `static_folder` is referred to application `static_path`
# - `static_path` is referred to module root_directory unless absolute
if static_path and not static_path.startswith("/"):
static_path = os.path.join(self.root_path, static_path)
self._static_path = (
os.path.join(self.app.static_path, static_folder) if static_folder else
(static_path or self.app.static_path)
)
self.url_prefix = url_prefix
self.hostname = hostname
self.cache = cache
self._super_pipeline = pipeline or []
self._super_injectors = injectors or []
self.pipeline = []
self.injectors = []
self.app._register_module(self)
|
(self, app: emmett.app.App, name: str, import_name: str, template_folder: Optional[str] = None, template_path: Optional[str] = None, static_folder: Optional[str] = None, static_path: Optional[str] = None, url_prefix: Optional[str] = None, hostname: Optional[str] = None, cache: Optional[emmett.cache.RouteCacheRule] = None, root_path: Optional[str] = None, pipeline: Optional[List[emmett.pipeline.Pipe]] = None, injectors: Optional[List[emmett.pipeline.Injector]] = None, **kwargs: Any)
|
7,640 |
emmett.app
|
module
| null |
def module(
self,
import_name: str,
name: str,
template_folder: Optional[str] = None,
template_path: Optional[str] = None,
static_folder: Optional[str] = None,
static_path: Optional[str] = None,
url_prefix: Optional[str] = None,
hostname: Optional[str] = None,
cache: Optional[RouteCacheRule] = None,
root_path: Optional[str] = None,
module_class: Optional[Type[AppModule]] = None,
**kwargs: Any
) -> AppModule:
module_class = module_class or self.__class__
return module_class.from_module(
self,
import_name,
name,
template_folder=template_folder,
template_path=template_path,
static_folder=static_folder,
static_path=static_path,
url_prefix=url_prefix,
hostname=hostname,
cache=cache,
root_path=root_path,
opts=kwargs
)
|
(self, import_name: str, name: str, template_folder: Optional[str] = None, template_path: Optional[str] = None, static_folder: Optional[str] = None, static_path: Optional[str] = None, url_prefix: Optional[str] = None, hostname: Optional[str] = None, cache: Optional[emmett.cache.RouteCacheRule] = None, root_path: Optional[str] = None, module_class: Optional[Type[emmett.app.AppModule]] = None, **kwargs: Any) -> emmett.app.AppModule
|
7,641 |
emmett.app
|
route
| null |
def route(
self,
paths: Optional[Union[str, List[str]]] = None,
name: Optional[str] = None,
template: Optional[str] = None,
**kwargs
) -> RoutingCtx:
if name is not None and "." in name:
raise RuntimeError(
"App modules' route names should not contains dots"
)
name = self.name + "." + (name or "")
pipeline = kwargs.get('pipeline', [])
injectors = kwargs.get('injectors', [])
if self.pipeline:
pipeline = self.pipeline + pipeline
kwargs['pipeline'] = pipeline
if self.injectors:
injectors = self.injectors + injectors
kwargs['injectors'] = injectors
kwargs['cache'] = kwargs.get('cache', self.cache)
return self.app.route(
paths=paths,
name=name,
template=template,
prefix=self.url_prefix,
template_folder=self.template_folder,
template_path=self.template_path,
hostname=self.hostname,
**kwargs
)
|
(self, paths: Union[str, List[str], NoneType] = None, name: Optional[str] = None, template: Optional[str] = None, **kwargs) -> emmett.routing.router.RoutingCtx
|
7,642 |
emmett.app
|
websocket
| null |
def websocket(
self,
paths: Optional[Union[str, List[str]]] = None,
name: Optional[str] = None,
**kwargs
) -> RoutingCtx:
if name is not None and "." in name:
raise RuntimeError(
"App modules' websocket names should not contains dots"
)
name = self.name + "." + (name or "")
pipeline = kwargs.get('pipeline', [])
if self.pipeline:
pipeline = self.pipeline + pipeline
kwargs['pipeline'] = pipeline
return self.app.websocket(
paths=paths,
name=name,
prefix=self.url_prefix,
hostname=self.hostname,
**kwargs
)
|
(self, paths: Union[str, List[str], NoneType] = None, name: Optional[str] = None, **kwargs) -> emmett.routing.router.RoutingCtx
|
7,643 |
emmett.cache
|
Cache
| null |
class Cache:
def __init__(self, **kwargs):
#: load handlers
handlers = []
for key, val in kwargs.items():
if key == "default":
continue
handlers.append((key, val))
if not handlers:
handlers.append(('ram', RamCache()))
#: set handlers
for name, handler in handlers:
setattr(self, name, handler)
_default_handler_name = kwargs.get('default', handlers[0][0])
self._default_handler = getattr(self, _default_handler_name)
@overload
def __call__(
self,
key: Optional[str] = None,
function: None = None,
duration: Union[int, str, None] = 'default'
) -> CacheDecorator:
...
@overload
def __call__(
self,
key: str,
function: Optional[Callable[..., T]],
duration: Union[int, str, None] = 'default'
) -> T:
...
def __call__(
self,
key: Optional[str] = None,
function: Optional[Callable[..., T]] = None,
duration: Union[int, str, None] = 'default'
) -> Union[CacheDecorator, T]:
return self._default_handler(key, function, duration)
def get(self, key: str) -> Any:
return self._default_handler.get(key)
def set(
self,
key: str,
value: Any,
duration: Union[int, str, None] = 'default'
):
self._default_handler.set(key, value, duration)
def get_or_set(
self,
key: str,
function: Callable[..., T],
duration: Union[int, str, None] = 'default'
) -> T:
return self._default_handler.get_or_set(key, function, duration)
def clear(self, key: Optional[str] = None):
self._default_handler.clear(key)
def response(
self,
duration: Union[int, str, None] = 'default',
query_params: bool = True,
language: bool = True,
hostname: bool = False,
headers: List[str] = []
) -> RouteCacheRule:
return self._default_handler.response(
duration, query_params, language, hostname, headers
)
|
(**kwargs)
|
7,644 |
emmett.cache
|
__call__
| null |
def __call__(
self,
key: Optional[str] = None,
function: Optional[Callable[..., T]] = None,
duration: Union[int, str, None] = 'default'
) -> Union[CacheDecorator, T]:
return self._default_handler(key, function, duration)
|
(self, key: Optional[str] = None, function: Optional[Callable[..., ~T]] = None, duration: Union[int, str, NoneType] = 'default') -> Union[emmett.cache.CacheDecorator, ~T]
|
7,645 |
emmett.cache
|
__init__
| null |
def __init__(self, **kwargs):
#: load handlers
handlers = []
for key, val in kwargs.items():
if key == "default":
continue
handlers.append((key, val))
if not handlers:
handlers.append(('ram', RamCache()))
#: set handlers
for name, handler in handlers:
setattr(self, name, handler)
_default_handler_name = kwargs.get('default', handlers[0][0])
self._default_handler = getattr(self, _default_handler_name)
|
(self, **kwargs)
|
7,646 |
emmett.cache
|
clear
| null |
def clear(self, key: Optional[str] = None):
self._default_handler.clear(key)
|
(self, key: Optional[str] = None)
|
7,647 |
emmett.cache
|
get
| null |
def get(self, key: str) -> Any:
return self._default_handler.get(key)
|
(self, key: str) -> Any
|
7,648 |
emmett.cache
|
get_or_set
| null |
def get_or_set(
self,
key: str,
function: Callable[..., T],
duration: Union[int, str, None] = 'default'
) -> T:
return self._default_handler.get_or_set(key, function, duration)
|
(self, key: str, function: Callable[..., ~T], duration: Union[int, str, NoneType] = 'default') -> ~T
|
7,649 |
emmett.cache
|
response
| null |
def response(
self,
duration: Union[int, str, None] = 'default',
query_params: bool = True,
language: bool = True,
hostname: bool = False,
headers: List[str] = []
) -> RouteCacheRule:
return self._default_handler.response(
duration, query_params, language, hostname, headers
)
|
(self, duration: Union[int, str, NoneType] = 'default', query_params: bool = True, language: bool = True, hostname: bool = False, headers: List[str] = []) -> emmett.cache.RouteCacheRule
|
7,650 |
emmett.cache
|
set
| null |
def set(
self,
key: str,
value: Any,
duration: Union[int, str, None] = 'default'
):
self._default_handler.set(key, value, duration)
|
(self, key: str, value: Any, duration: Union[int, str, NoneType] = 'default')
|
7,651 |
emmett.orm.objects
|
Field
| null |
class Field(_Field):
_internal_types = {
'integer': 'int',
'double': 'float',
'boolean': 'bool',
'list:integer': 'list:int'
}
_pydal_types = {
'int': 'integer',
'bool': 'boolean',
'list:int': 'list:integer',
}
_internal_delete = {
'cascade': 'CASCADE', 'nullify': 'SET NULL', 'nothing': 'NO ACTION'
}
_inst_count_ = 0
_obj_created_ = False
def __init__(self, type='string', *args, **kwargs):
self.modelname = None
#: convert type
self._type = self._internal_types.get(type, type)
#: convert 'rw' -> 'readable', 'writeable'
if 'rw' in kwargs:
_rw = kwargs.pop('rw')
if isinstance(_rw, (tuple, list)):
read, write = _rw
else:
read = write = _rw
kwargs['readable'] = read
kwargs['writable'] = write
#: convert 'info' -> 'comment'
_info = kwargs.pop('info', None)
if _info:
kwargs['comment'] = _info
#: convert ondelete parameter
_ondelete = kwargs.get('ondelete')
if _ondelete:
if _ondelete not in list(self._internal_delete):
raise SyntaxError(
'Field ondelete should be set on %s, %s or %s' %
list(self._internal_delete)
)
kwargs['ondelete'] = self._internal_delete[_ondelete]
#: process 'refers_to' fields
self._isrefers = kwargs.pop('_isrefers', None)
#: get auto validation preferences
self._auto_validation = kwargs.pop('auto_validation', True)
#: intercept validation (will be processed by `_make_field`)
self._requires = {}
self._custom_requires = []
if 'validation' in kwargs:
_validation = kwargs.pop('validation')
if isinstance(_validation, dict):
self._requires = _validation
else:
self._custom_requires = _validation
if not isinstance(self._custom_requires, list):
self._custom_requires = [self._custom_requires]
self._validation = {}
self._vparser = ValidateFromDict()
#: ensure 'length' is an integer
if 'length' in kwargs:
kwargs['length'] = int(kwargs['length'])
#: store args and kwargs for `_make_field`
self._ormkw = kwargs.pop('_kw', {})
self._args = args
self._kwargs = kwargs
#: increase creation counter (used to keep order of fields)
self._inst_count_ = Field._inst_count_
Field._inst_count_ += 1
def _default_validation(self):
rv = {}
auto_types = [
'int', 'float', 'date', 'time', 'datetime', 'json'
]
if self._type in auto_types:
rv['is'] = self._type
elif self._type.startswith('decimal'):
rv['is'] = 'decimal'
elif self._type == 'jsonb':
rv['is'] = 'json'
if self._type == 'bigint':
rv['is'] = 'int'
if self._type == 'bool':
rv['in'] = (False, True)
if self._type in ['string', 'text', 'password']:
rv['len'] = {'lte': self.length}
if self._type == 'password':
rv['len']['gte'] = 6
rv['crypt'] = True
if self._type == 'list:int':
rv['is'] = 'list:int'
if (
self.notnull or self._type.startswith('reference') or
self._type.startswith('list:reference')
):
rv['presence'] = True
if not self.notnull and self._isrefers is True:
rv['allow'] = 'empty'
if self.unique:
rv['unique'] = True
return rv
def _parse_validation(self):
for key in list(self._requires):
self._validation[key] = self._requires[key]
self.requires = self._vparser(self, self._validation) + \
self._custom_requires
#: `_make_field` will be called by `Model` class or `Form` class
# it will make internal Field class compatible with the pyDAL's one
def _make_field(self, name, model=None):
if self._obj_created_:
return self
if model is not None:
self.modelname = model.__class__.__name__
#: convert field type to pyDAL ones if needed
ftype = self._pydal_types.get(self._type, self._type)
if ftype.startswith("geo") and model:
geometry_type = self._ormkw["geometry_type"]
srid = self._ormkw["srid"] or getattr(model.db._adapter, "srid", 4326)
dimension = self._ormkw["dimension"] or 2
ftype = f"{ftype}({geometry_type},{srid},{dimension})"
#: create pyDAL's Field instance
super(Field, self).__init__(name, ftype, *self._args, **self._kwargs)
#: add automatic validation (if requested)
if self._auto_validation:
auto = True
if self.modelname:
auto = model.auto_validation
if auto:
self._validation = self._default_validation()
#: validators
if not self.modelname:
self._parse_validation()
self._obj_created_ = True
return self
def __str__(self):
if self._obj_created_:
return super(Field, self).__str__()
return object.__str__(self)
def __repr__(self):
if self.modelname and hasattr(self, 'name'):
return "<%s.%s (%s) field>" % (self.modelname, self.name,
self._type)
return super(Field, self).__repr__()
@classmethod
def string(cls, *args, **kwargs):
return cls('string', *args, **kwargs)
@classmethod
def int(cls, *args, **kwargs):
return cls('int', *args, **kwargs)
@classmethod
def bigint(cls, *args, **kwargs):
return cls('bigint', *args, **kwargs)
@classmethod
def float(cls, *args, **kwargs):
return cls('float', *args, **kwargs)
@classmethod
def text(cls, *args, **kwargs):
return cls('text', *args, **kwargs)
@classmethod
def bool(cls, *args, **kwargs):
return cls('bool', *args, **kwargs)
@classmethod
def blob(cls, *args, **kwargs):
return cls('blob', *args, **kwargs)
@classmethod
def date(cls, *args, **kwargs):
return cls('date', *args, **kwargs)
@classmethod
def time(cls, *args, **kwargs):
return cls('time', *args, **kwargs)
@classmethod
def datetime(cls, *args, **kwargs):
return cls('datetime', *args, **kwargs)
@classmethod
def decimal(cls, precision, scale, *args, **kwargs):
return cls('decimal({},{})'.format(precision, scale), *args, **kwargs)
@classmethod
def json(cls, *args, **kwargs):
return cls('json', *args, **kwargs)
@classmethod
def jsonb(cls, *args, **kwargs):
return cls('jsonb', *args, **kwargs)
@classmethod
def password(cls, *args, **kwargs):
return cls('password', *args, **kwargs)
@classmethod
def upload(cls, *args, **kwargs):
return cls('upload', *args, **kwargs)
@classmethod
def int_list(cls, *args, **kwargs):
return cls('list:int', *args, **kwargs)
@classmethod
def string_list(cls, *args, **kwargs):
return cls('list:string', *args, **kwargs)
@classmethod
def geography(
cls,
geometry_type: str = 'GEOMETRY',
srid: Optional[type_int] = None,
dimension: Optional[type_int] = None,
**kwargs
):
kwargs['_kw'] = {
"geometry_type": geometry_type,
"srid": srid,
"dimension": dimension
}
return cls("geography", **kwargs)
@classmethod
def geometry(
cls,
geometry_type: str = 'GEOMETRY',
srid: Optional[type_int] = None,
dimension: Optional[type_int] = None,
**kwargs
):
kwargs['_kw'] = {
"geometry_type": geometry_type,
"srid": srid,
"dimension": dimension
}
return cls("geometry", **kwargs)
def cast(self, value, **kwargs):
return Expression(
self.db, self._dialect.cast, self,
self._dialect.types[value] % kwargs, value)
|
(type='string', *args, **kwargs)
|
7,652 |
pydal.objects
|
__add__
| null |
def __add__(self, other):
return Expression(self.db, self._dialect.add, self, other, self.type)
|
(self, other)
|
7,653 |
pydal.objects
|
__bool__
| null |
def __bool__(self):
return True
|
(self)
|
7,654 |
pydal.objects
|
__div__
| null |
def __div__(self, other):
return Expression(self.db, self._dialect.div, self, other, self.type)
|
(self, other)
|
7,655 |
pydal.objects
|
__eq__
| null |
def __eq__(self, value):
return Query(self.db, self._dialect.eq, self, value)
|
(self, value)
|
7,656 |
pydal.objects
|
__ge__
| null |
def __ge__(self, value):
return Query(self.db, self._dialect.gte, self, value)
|
(self, value)
|
7,657 |
pydal.objects
|
__getitem__
| null |
def __getitem__(self, i):
if isinstance(i, slice):
start = i.start or 0
stop = i.stop
db = self.db
if start < 0:
pos0 = '(%s - %d)' % (self.len(), abs(start) - 1)
else:
pos0 = start + 1
maxint = sys.maxint if PY2 else sys.maxsize
if stop is None or stop == maxint:
length = self.len()
elif stop < 0:
length = '(%s - %d - %s)' % (self.len(), abs(stop) - 1, pos0)
else:
length = '(%s - %s)' % (stop + 1, pos0)
return Expression(db, self._dialect.substring,
self, (pos0, length), self.type)
else:
return self[i:i + 1]
|
(self, i)
|
7,658 |
pydal.objects
|
__gt__
| null |
def __gt__(self, value):
return Query(self.db, self._dialect.gt, self, value)
|
(self, value)
|
7,659 |
pydal.objects
|
__hash__
| null |
def __hash__(self):
return id(self)
|
(self)
|
7,660 |
emmett.orm.objects
|
__init__
| null |
def __init__(self, type='string', *args, **kwargs):
self.modelname = None
#: convert type
self._type = self._internal_types.get(type, type)
#: convert 'rw' -> 'readable', 'writeable'
if 'rw' in kwargs:
_rw = kwargs.pop('rw')
if isinstance(_rw, (tuple, list)):
read, write = _rw
else:
read = write = _rw
kwargs['readable'] = read
kwargs['writable'] = write
#: convert 'info' -> 'comment'
_info = kwargs.pop('info', None)
if _info:
kwargs['comment'] = _info
#: convert ondelete parameter
_ondelete = kwargs.get('ondelete')
if _ondelete:
if _ondelete not in list(self._internal_delete):
raise SyntaxError(
'Field ondelete should be set on %s, %s or %s' %
list(self._internal_delete)
)
kwargs['ondelete'] = self._internal_delete[_ondelete]
#: process 'refers_to' fields
self._isrefers = kwargs.pop('_isrefers', None)
#: get auto validation preferences
self._auto_validation = kwargs.pop('auto_validation', True)
#: intercept validation (will be processed by `_make_field`)
self._requires = {}
self._custom_requires = []
if 'validation' in kwargs:
_validation = kwargs.pop('validation')
if isinstance(_validation, dict):
self._requires = _validation
else:
self._custom_requires = _validation
if not isinstance(self._custom_requires, list):
self._custom_requires = [self._custom_requires]
self._validation = {}
self._vparser = ValidateFromDict()
#: ensure 'length' is an integer
if 'length' in kwargs:
kwargs['length'] = int(kwargs['length'])
#: store args and kwargs for `_make_field`
self._ormkw = kwargs.pop('_kw', {})
self._args = args
self._kwargs = kwargs
#: increase creation counter (used to keep order of fields)
self._inst_count_ = Field._inst_count_
Field._inst_count_ += 1
|
(self, type='string', *args, **kwargs)
|
7,661 |
pydal.objects
|
__invert__
| null |
def __invert__(self):
if hasattr(self, '_op') and self.op == self._dialect.invert:
return self.first
return Expression(self.db, self._dialect.invert, self, type=self.type)
|
(self)
|
7,662 |
pydal.objects
|
__le__
| null |
def __le__(self, value):
return Query(self.db, self._dialect.lte, self, value)
|
(self, value)
|
7,663 |
pydal.objects
|
__lt__
| null |
def __lt__(self, value):
return Query(self.db, self._dialect.lt, self, value)
|
(self, value)
|
7,664 |
pydal.objects
|
__mod__
| null |
def __mod__(self, other):
return Expression(self.db, self._dialect.mod, self, other, self.type)
|
(self, other)
|
7,665 |
pydal.objects
|
__mul__
| null |
def __mul__(self, other):
return Expression(self.db, self._dialect.mul, self, other, self.type)
|
(self, other)
|
7,666 |
pydal.objects
|
__ne__
| null |
def __ne__(self, value):
return Query(self.db, self._dialect.ne, self, value)
|
(self, value)
|
7,667 |
pydal.objects
|
__new__
| null |
def __new__(cls, *args, **kwargs):
for name, wrapper in iteritems(cls._dialect_expressions_):
setattr(cls, name, _expression_wrap(wrapper))
new_cls = super(Expression, cls).__new__(cls)
return new_cls
|
(cls, *args, **kwargs)
|
7,668 |
pydal.objects
|
__or__
| null |
def __or__(self, other): # for use in sortby
return Expression(self.db, self._dialect.comma, self, other, self.type)
|
(self, other)
|
7,669 |
emmett.orm.objects
|
__repr__
| null |
def __repr__(self):
if self.modelname and hasattr(self, 'name'):
return "<%s.%s (%s) field>" % (self.modelname, self.name,
self._type)
return super(Field, self).__repr__()
|
(self)
|
7,670 |
emmett.orm.objects
|
__str__
| null |
def __str__(self):
if self._obj_created_:
return super(Field, self).__str__()
return object.__str__(self)
|
(self)
|
7,671 |
pydal.objects
|
__sub__
| null |
def __sub__(self, other):
if self.type in ('integer', 'bigint'):
result_type = 'integer'
elif self.type in ['date', 'time', 'datetime', 'double', 'float']:
result_type = 'double'
elif self.type.startswith('decimal('):
result_type = self.type
else:
raise SyntaxError("subtraction operation not supported for type")
return Expression(self.db, self._dialect.sub, self, other, result_type)
|
(self, other)
|
7,672 |
pydal.objects
|
__truediv__
| null |
def __truediv__(self, other):
return self.__div__(other)
|
(self, other)
|
7,673 |
emmett.orm.objects
|
_default_validation
| null |
def _default_validation(self):
rv = {}
auto_types = [
'int', 'float', 'date', 'time', 'datetime', 'json'
]
if self._type in auto_types:
rv['is'] = self._type
elif self._type.startswith('decimal'):
rv['is'] = 'decimal'
elif self._type == 'jsonb':
rv['is'] = 'json'
if self._type == 'bigint':
rv['is'] = 'int'
if self._type == 'bool':
rv['in'] = (False, True)
if self._type in ['string', 'text', 'password']:
rv['len'] = {'lte': self.length}
if self._type == 'password':
rv['len']['gte'] = 6
rv['crypt'] = True
if self._type == 'list:int':
rv['is'] = 'list:int'
if (
self.notnull or self._type.startswith('reference') or
self._type.startswith('list:reference')
):
rv['presence'] = True
if not self.notnull and self._isrefers is True:
rv['allow'] = 'empty'
if self.unique:
rv['unique'] = True
return rv
|
(self)
|
7,674 |
emmett.orm.objects
|
_make_field
| null |
def _make_field(self, name, model=None):
if self._obj_created_:
return self
if model is not None:
self.modelname = model.__class__.__name__
#: convert field type to pyDAL ones if needed
ftype = self._pydal_types.get(self._type, self._type)
if ftype.startswith("geo") and model:
geometry_type = self._ormkw["geometry_type"]
srid = self._ormkw["srid"] or getattr(model.db._adapter, "srid", 4326)
dimension = self._ormkw["dimension"] or 2
ftype = f"{ftype}({geometry_type},{srid},{dimension})"
#: create pyDAL's Field instance
super(Field, self).__init__(name, ftype, *self._args, **self._kwargs)
#: add automatic validation (if requested)
if self._auto_validation:
auto = True
if self.modelname:
auto = model.auto_validation
if auto:
self._validation = self._default_validation()
#: validators
if not self.modelname:
self._parse_validation()
self._obj_created_ = True
return self
|
(self, name, model=None)
|
7,675 |
emmett.orm.objects
|
_parse_validation
| null |
def _parse_validation(self):
for key in list(self._requires):
self._validation[key] = self._requires[key]
self.requires = self._vparser(self, self._validation) + \
self._custom_requires
|
(self)
|
7,676 |
pydal.objects
|
abs
| null |
def abs(self):
return Expression(
self.db, self._dialect.aggregate, self, 'ABS', self.type)
|
(self)
|
7,677 |
pydal.objects
|
as_dict
| null |
def as_dict(self, flat=False, sanitize=True):
attrs = (
'name', 'authorize', 'represent', 'ondelete',
'custom_store', 'autodelete', 'custom_retrieve',
'filter_out', 'uploadseparate', 'widget', 'uploadfs',
'update', 'custom_delete', 'uploadfield', 'uploadfolder',
'custom_qualifier', 'unique', 'writable', 'compute',
'map_none', 'default', 'type', 'required', 'readable',
'requires', 'comment', 'label', 'length', 'notnull',
'custom_retrieve_file_properties', 'filter_in')
serializable = (int, long, basestring, float, tuple,
bool, type(None))
def flatten(obj):
if isinstance(obj, dict):
return dict((flatten(k), flatten(v)) for k, v in obj.items())
elif isinstance(obj, (tuple, list, set)):
return [flatten(v) for v in obj]
elif isinstance(obj, serializable):
return obj
elif isinstance(obj, (datetime.datetime,
datetime.date, datetime.time)):
return str(obj)
else:
return None
d = dict()
if not (sanitize and not (self.readable or self.writable)):
for attr in attrs:
if flat:
d.update({attr: flatten(getattr(self, attr))})
else:
d.update({attr: getattr(self, attr)})
d["fieldname"] = d.pop("name")
return d
|
(self, flat=False, sanitize=True)
|
7,678 |
pydal.helpers.classes
|
as_json
| null |
def as_json(self, sanitize=True):
return serializers.json(self.as_dict(flat=True, sanitize=sanitize))
|
(self, sanitize=True)
|
7,679 |
pydal.helpers.classes
|
as_xml
| null |
def as_xml(self, sanitize=True):
return serializers.xml(self.as_dict(flat=True, sanitize=sanitize))
|
(self, sanitize=True)
|
7,680 |
pydal.helpers.classes
|
as_yaml
| null |
def as_yaml(self, sanitize=True):
return serializers.yaml(self.as_dict(flat=True, sanitize=sanitize))
|
(self, sanitize=True)
|
7,681 |
pydal.objects
|
avg
| null |
def avg(self):
return Expression(
self.db, self._dialect.aggregate, self, 'AVG', self.type)
|
(self)
|
7,682 |
pydal.objects
|
belongs
|
Accepts the following inputs::
field.belongs(1, 2)
field.belongs((1, 2))
field.belongs(query)
Does NOT accept:
field.belongs(1)
If the set you want back includes `None` values, you can do::
field.belongs((1, None), null=True)
|
def belongs(self, *value, **kwattr):
"""
Accepts the following inputs::
field.belongs(1, 2)
field.belongs((1, 2))
field.belongs(query)
Does NOT accept:
field.belongs(1)
If the set you want back includes `None` values, you can do::
field.belongs((1, None), null=True)
"""
db = self.db
if len(value) == 1:
value = value[0]
if isinstance(value, Query):
value = db(value)._select(value.first._table._id)
elif not isinstance(value, (Select, basestring)):
value = set(value)
if kwattr.get('null') and None in value:
value.remove(None)
return (self == None) | Query(
self.db, self._dialect.belongs, self, value)
return Query(self.db, self._dialect.belongs, self, value)
|
(self, *value, **kwattr)
|
7,683 |
pydal.objects
|
bind
| null |
def bind(self, table):
if self._table is not None:
raise ValueError(
'Field %s is already bound to a table' % self.longname)
self.db = self._db = table._db
self.table = self._table = table
self.tablename = self._tablename = table._tablename
if self._db and self._rname is None:
self._rname = self._db._adapter.sqlsafe_field(self.name)
self._raw_rname = self.name
|
(self, table)
|
7,684 |
emmett.orm.objects
|
cast
| null |
def cast(self, value, **kwargs):
return Expression(
self.db, self._dialect.cast, self,
self._dialect.types[value] % kwargs, value)
|
(self, value, **kwargs)
|
7,685 |
pydal.objects
|
clone
| null |
def clone(self, point_self_references_to=False, **args):
field = copy.copy(self)
if point_self_references_to and \
self.type == 'reference %s' % self._tablename:
field.type = 'reference %s' % point_self_references_to
field.__dict__.update(args)
field.db = field._db = None
field.table = field._table = None
field.tablename = field._tablename = None
if self._db and \
self._rname == self._db._adapter.sqlsafe_field(self.name):
# Reset the name because it may need to be requoted by bind()
field._rname = field._raw_rname = None
return field
|
(self, point_self_references_to=False, **args)
|
7,686 |
pydal.objects
|
coalesce
| null |
def coalesce(self, *others):
return Expression(
self.db, self._dialect.coalesce, self, others, self.type)
|
(self, *others)
|
7,687 |
pydal.objects
|
coalesce_zero
| null |
def coalesce_zero(self):
return Expression(
self.db, self._dialect.coalesce_zero, self, None, self.type)
|
(self)
|
7,688 |
pydal.objects
|
contains
|
For GAE contains() is always case sensitive
|
def contains(self, value, all=False, case_sensitive=False):
"""
For GAE contains() is always case sensitive
"""
if isinstance(value, (list, tuple)):
subqueries = [self.contains(str(v), case_sensitive=case_sensitive)
for v in value if str(v)]
if not subqueries:
return self.contains('')
else:
return reduce(all and AND or OR, subqueries)
if self.type not in ('string', 'text', 'json', 'upload') and not \
self.type.startswith('list:'):
raise SyntaxError("contains used with incompatible field type")
return Query(
self.db, self._dialect.contains, self, value,
case_sensitive=case_sensitive)
|
(self, value, all=False, case_sensitive=False)
|
7,689 |
pydal.objects
|
count
| null |
def count(self, distinct=None):
return Expression(
self.db, self._dialect.count, self, distinct, 'integer')
|
(self, distinct=None)
|
7,690 |
pydal.objects
|
day
| null |
def day(self):
return Expression(
self.db, self._dialect.extract, self, 'day', 'integer')
|
(self)
|
7,691 |
pydal.objects
|
endswith
| null |
def endswith(self, value):
if self.type not in ('string', 'text', 'json', 'upload'):
raise SyntaxError("endswith used with incompatible field type")
return Query(self.db, self._dialect.endswith, self, value)
|
(self, value)
|
7,692 |
pydal.objects
|
epoch
| null |
def epoch(self):
return Expression(
self.db, self._dialect.epoch, self, None, 'integer')
|
(self)
|
7,693 |
pydal.objects
|
formatter
| null |
def formatter(self, value):
requires = self.requires
if value is None:
return self.map_none
if not requires:
return value
if not isinstance(requires, (list, tuple)):
requires = [requires]
elif isinstance(requires, tuple):
requires = list(requires)
else:
requires = copy.copy(requires)
requires.reverse()
for item in requires:
if hasattr(item, 'formatter'):
value = item.formatter(value)
return value
|
(self, value)
|
7,694 |
pydal.objects
|
hour
| null |
def hour(self):
return Expression(
self.db, self._dialect.extract, self, 'hour', 'integer')
|
(self)
|
7,695 |
pydal.objects
|
ilike
| null |
def ilike(self, value, escape=None):
return self.like(value, case_sensitive=False, escape=escape)
|
(self, value, escape=None)
|
7,696 |
pydal.objects
|
len
| null |
def len(self):
return Expression(
self.db, self._dialect.length, self, None, 'integer')
|
(self)
|
7,697 |
pydal.objects
|
like
| null |
def like(self, value, case_sensitive=True, escape=None):
op = case_sensitive and self._dialect.like or self._dialect.ilike
return Query(self.db, op, self, value, escape=escape)
|
(self, value, case_sensitive=True, escape=None)
|
7,698 |
pydal.objects
|
lower
| null |
def lower(self):
return Expression(
self.db, self._dialect.lower, self, None, self.type)
|
(self)
|
7,699 |
pydal.objects
|
max
| null |
def max(self):
return Expression(
self.db, self._dialect.aggregate, self, 'MAX', self.type)
|
(self)
|
7,700 |
pydal.objects
|
min
| null |
def min(self):
return Expression(
self.db, self._dialect.aggregate, self, 'MIN', self.type)
|
(self)
|
7,701 |
pydal.objects
|
minutes
| null |
def minutes(self):
return Expression(
self.db, self._dialect.extract, self, 'minute', 'integer')
|
(self)
|
7,702 |
pydal.objects
|
month
| null |
def month(self):
return Expression(
self.db, self._dialect.extract, self, 'month', 'integer')
|
(self)
|
7,703 |
pydal.objects
|
regexp
| null |
def regexp(self, value):
return Query(self.db, self._dialect.regexp, self, value)
|
(self, value)
|
7,704 |
pydal.objects
|
replace
| null |
def replace(self, a, b):
return Expression(
self.db, self._dialect.replace, self, (a, b), self.type)
|
(self, a, b)
|
7,705 |
pydal.objects
|
retrieve
|
If `nameonly==True` return (filename, fullfilename) instead of
(filename, stream)
|
def retrieve(self, name, path=None, nameonly=False):
"""
If `nameonly==True` return (filename, fullfilename) instead of
(filename, stream)
"""
self_uploadfield = self.uploadfield
if self.custom_retrieve:
return self.custom_retrieve(name, path)
if self.authorize or isinstance(self_uploadfield, str):
row = self.db(self == name).select().first()
if not row:
raise NotFoundException
if self.authorize and not self.authorize(row):
raise NotAuthorizedException
file_properties = self.retrieve_file_properties(name, path)
filename = file_properties['filename']
if isinstance(self_uploadfield, str): # ## if file is in DB
stream = BytesIO(to_bytes(row[self_uploadfield] or ''))
elif isinstance(self_uploadfield, Field):
blob_uploadfield_name = self_uploadfield.uploadfield
query = self_uploadfield == name
data = self_uploadfield.table(query)[blob_uploadfield_name]
stream = BytesIO(to_bytes(data))
elif self.uploadfs:
# ## if file is on pyfilesystem
stream = self.uploadfs.open(name, 'rb')
else:
# ## if file is on regular filesystem
# this is intentially a sting with filename and not a stream
# this propagates and allows stream_file_or_304_or_206 to be called
fullname = pjoin(file_properties['path'], name)
if nameonly:
return (filename, fullname)
stream = open(fullname, 'rb')
return (filename, stream)
|
(self, name, path=None, nameonly=False)
|
7,706 |
pydal.objects
|
retrieve_file_properties
| null |
def retrieve_file_properties(self, name, path=None):
m = REGEX_UPLOAD_PATTERN.match(name)
if not m or not self.isattachment:
raise TypeError('Can\'t retrieve %s file properties' % name)
self_uploadfield = self.uploadfield
if self.custom_retrieve_file_properties:
return self.custom_retrieve_file_properties(name, path)
if m.group('name'):
try:
filename = base64.b16decode(m.group('name'), True).decode('utf-8')
filename = REGEX_CLEANUP_FN.sub('_', filename)
except (TypeError, AttributeError):
filename = name
else:
filename = name
# ## if file is in DB
if isinstance(self_uploadfield, (str, Field)):
return dict(path=None, filename=filename)
# ## if file is on filesystem
if not path:
if self.uploadfolder:
path = self.uploadfolder
else:
path = pjoin(self.db._adapter.folder, '..', 'uploads')
if self.uploadseparate:
t = m.group('table')
f = m.group('field')
u = m.group('uuidkey')
path = pjoin(path, "%s.%s" % (t, f), u[:2])
return dict(path=path, filename=filename)
|
(self, name, path=None)
|
7,707 |
pydal.objects
|
seconds
| null |
def seconds(self):
return Expression(
self.db, self._dialect.extract, self, 'second', 'integer')
|
(self)
|
7,708 |
pydal.objects
|
set_attributes
| null |
def set_attributes(self, *args, **attributes):
self.__dict__.update(*args, **attributes)
|
(self, *args, **attributes)
|
7,709 |
pydal.objects
|
st_asgeojson
| null |
def st_asgeojson(self, precision=15, options=0, version=1):
return Expression(self.db, self.db._adapter.ST_ASGEOJSON, self,
dict(precision=precision, options=options,
version=version), 'string')
|
(self, precision=15, options=0, version=1)
|
7,710 |
pydal.objects
|
st_astext
| null |
def st_astext(self):
return Expression(
self.db, self._dialect.st_astext, self, type='string')
|
(self)
|
7,711 |
pydal.objects
|
st_contains
| null |
def st_contains(self, value):
return Query(self.db, self._dialect.st_contains, self, value)
|
(self, value)
|
7,712 |
pydal.objects
|
st_distance
| null |
def st_distance(self, other):
return Expression(
self.db, self._dialect.st_distance, self, other, 'double')
|
(self, other)
|
7,713 |
pydal.objects
|
st_dwithin
| null |
def st_dwithin(self, value, distance):
return Query(
self.db, self._dialect.st_dwithin, self, (value, distance))
|
(self, value, distance)
|
7,714 |
pydal.objects
|
st_equals
| null |
def st_equals(self, value):
return Query(self.db, self._dialect.st_equals, self, value)
|
(self, value)
|
7,715 |
pydal.objects
|
st_intersects
| null |
def st_intersects(self, value):
return Query(self.db, self._dialect.st_intersects, self, value)
|
(self, value)
|
7,716 |
pydal.objects
|
st_overlaps
| null |
def st_overlaps(self, value):
return Query(self.db, self._dialect.st_overlaps, self, value)
|
(self, value)
|
7,717 |
pydal.objects
|
st_simplify
| null |
def st_simplify(self, value):
return Expression(
self.db, self._dialect.st_simplify, self, value, self.type)
|
(self, value)
|
7,718 |
pydal.objects
|
st_simplifypreservetopology
| null |
def st_simplifypreservetopology(self, value):
return Expression(
self.db, self._dialect.st_simplifypreservetopology, self, value,
self.type)
|
(self, value)
|
7,719 |
pydal.objects
|
st_touches
| null |
def st_touches(self, value):
return Query(self.db, self._dialect.st_touches, self, value)
|
(self, value)
|
7,720 |
pydal.objects
|
st_within
| null |
def st_within(self, value):
return Query(self.db, self._dialect.st_within, self, value)
|
(self, value)
|
7,721 |
pydal.objects
|
st_x
| null |
def st_x(self):
return Expression(self.db, self._dialect.st_x, self, type='string')
|
(self)
|
7,722 |
pydal.objects
|
st_y
| null |
def st_y(self):
return Expression(self.db, self._dialect.st_y, self, type='string')
|
(self)
|
7,723 |
pydal.objects
|
startswith
| null |
def startswith(self, value):
if self.type not in ('string', 'text', 'json', 'upload'):
raise SyntaxError("startswith used with incompatible field type")
return Query(self.db, self._dialect.startswith, self, value)
|
(self, value)
|
7,724 |
pydal.objects
|
store
| null |
def store(self, file, filename=None, path=None):
# make sure filename is a str sequence
filename = "{}".format(filename)
if self.custom_store:
return self.custom_store(file, filename, path)
if isinstance(file, cgi.FieldStorage):
filename = filename or file.filename
file = file.file
elif not filename:
filename = file.name
filename = os.path.basename(
filename.replace('/', os.sep).replace('\\', os.sep))
m = REGEX_STORE_PATTERN.search(filename)
extension = m and m.group('e') or 'txt'
uuid_key = self._db.uuid().replace('-', '')[-16:]
encoded_filename = to_native(
base64.b16encode(to_bytes(filename)).lower())
newfilename = '%s.%s.%s.%s' % (
self._tablename, self.name, uuid_key, encoded_filename)
newfilename = newfilename[:(self.length - 1 - len(extension))] + \
'.' + extension
self_uploadfield = self.uploadfield
if isinstance(self_uploadfield, Field):
blob_uploadfield_name = self_uploadfield.uploadfield
keys = {self_uploadfield.name: newfilename,
blob_uploadfield_name: file.read()}
self_uploadfield.table.insert(**keys)
elif self_uploadfield is True:
if self.uploadfs:
dest_file = self.uploadfs.open(newfilename, 'wb')
else:
if path:
pass
elif self.uploadfolder:
path = self.uploadfolder
elif self.db._adapter.folder:
path = pjoin(self.db._adapter.folder, '..', 'uploads')
else:
raise RuntimeError(
"you must specify a Field(..., uploadfolder=...)")
if self.uploadseparate:
if self.uploadfs:
raise RuntimeError("not supported")
path = pjoin(path, "%s.%s" % (
self._tablename, self.name), uuid_key[:2]
)
if not exists(path):
os.makedirs(path)
pathfilename = pjoin(path, newfilename)
dest_file = open(pathfilename, 'wb')
try:
shutil.copyfileobj(file, dest_file)
except IOError:
raise IOError(
'Unable to store file "%s" because invalid permissions, '
'readonly file system, or filename too long' %
pathfilename)
dest_file.close()
return newfilename
|
(self, file, filename=None, path=None)
|
7,725 |
pydal.objects
|
sum
| null |
def sum(self):
return Expression(
self.db, self._dialect.aggregate, self, 'SUM', self.type)
|
(self)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.