repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
limodou/uliweb
uliweb/utils/process.py
wait_pid
def wait_pid(pid, timeout=None, callback=None): """Wait for process with pid 'pid' to terminate and return its exit status code as an integer. If pid is not a children of os.getpid() (current process) just waits until the process disappears and return None. If pid does not exist at all return None immediately. Raise TimeoutExpired on timeout expired (if specified). """ def check_timeout(delay): if timeout is not None: if time.time() >= stop_at: if callback: callback(pid) else: raise TimeoutExpired time.sleep(delay) return min(delay * 2, 0.04) if timeout is not None: waitcall = lambda: os.waitpid(pid, os.WNOHANG) stop_at = time.time() + timeout else: waitcall = lambda: os.waitpid(pid, 0) delay = 0.0001 while 1: try: retpid, status = waitcall() except OSError as err: if err.errno == errno.EINTR: delay = check_timeout(delay) continue elif err.errno == errno.ECHILD: # This has two meanings: # - pid is not a child of os.getpid() in which case # we keep polling until it's gone # - pid never existed in the first place # In both cases we'll eventually return None as we # can't determine its exit status code. while 1: if pid_exists(pid): delay = check_timeout(delay) else: return else: raise else: if retpid == 0: # WNOHANG was used, pid is still running delay = check_timeout(delay) continue # process exited due to a signal; return the integer of # that signal if os.WIFSIGNALED(status): return os.WTERMSIG(status) # process exited using exit(2) system call; return the # integer exit(2) system call has been called with elif os.WIFEXITED(status): return os.WEXITSTATUS(status) else: # should never happen raise RuntimeError("unknown process exit status")
python
def wait_pid(pid, timeout=None, callback=None): """Wait for process with pid 'pid' to terminate and return its exit status code as an integer. If pid is not a children of os.getpid() (current process) just waits until the process disappears and return None. If pid does not exist at all return None immediately. Raise TimeoutExpired on timeout expired (if specified). """ def check_timeout(delay): if timeout is not None: if time.time() >= stop_at: if callback: callback(pid) else: raise TimeoutExpired time.sleep(delay) return min(delay * 2, 0.04) if timeout is not None: waitcall = lambda: os.waitpid(pid, os.WNOHANG) stop_at = time.time() + timeout else: waitcall = lambda: os.waitpid(pid, 0) delay = 0.0001 while 1: try: retpid, status = waitcall() except OSError as err: if err.errno == errno.EINTR: delay = check_timeout(delay) continue elif err.errno == errno.ECHILD: # This has two meanings: # - pid is not a child of os.getpid() in which case # we keep polling until it's gone # - pid never existed in the first place # In both cases we'll eventually return None as we # can't determine its exit status code. while 1: if pid_exists(pid): delay = check_timeout(delay) else: return else: raise else: if retpid == 0: # WNOHANG was used, pid is still running delay = check_timeout(delay) continue # process exited due to a signal; return the integer of # that signal if os.WIFSIGNALED(status): return os.WTERMSIG(status) # process exited using exit(2) system call; return the # integer exit(2) system call has been called with elif os.WIFEXITED(status): return os.WEXITSTATUS(status) else: # should never happen raise RuntimeError("unknown process exit status")
[ "def", "wait_pid", "(", "pid", ",", "timeout", "=", "None", ",", "callback", "=", "None", ")", ":", "def", "check_timeout", "(", "delay", ")", ":", "if", "timeout", "is", "not", "None", ":", "if", "time", ".", "time", "(", ")", ">=", "stop_at", ":", "if", "callback", ":", "callback", "(", "pid", ")", "else", ":", "raise", "TimeoutExpired", "time", ".", "sleep", "(", "delay", ")", "return", "min", "(", "delay", "*", "2", ",", "0.04", ")", "if", "timeout", "is", "not", "None", ":", "waitcall", "=", "lambda", ":", "os", ".", "waitpid", "(", "pid", ",", "os", ".", "WNOHANG", ")", "stop_at", "=", "time", ".", "time", "(", ")", "+", "timeout", "else", ":", "waitcall", "=", "lambda", ":", "os", ".", "waitpid", "(", "pid", ",", "0", ")", "delay", "=", "0.0001", "while", "1", ":", "try", ":", "retpid", ",", "status", "=", "waitcall", "(", ")", "except", "OSError", "as", "err", ":", "if", "err", ".", "errno", "==", "errno", ".", "EINTR", ":", "delay", "=", "check_timeout", "(", "delay", ")", "continue", "elif", "err", ".", "errno", "==", "errno", ".", "ECHILD", ":", "# This has two meanings:", "# - pid is not a child of os.getpid() in which case", "# we keep polling until it's gone", "# - pid never existed in the first place", "# In both cases we'll eventually return None as we", "# can't determine its exit status code.", "while", "1", ":", "if", "pid_exists", "(", "pid", ")", ":", "delay", "=", "check_timeout", "(", "delay", ")", "else", ":", "return", "else", ":", "raise", "else", ":", "if", "retpid", "==", "0", ":", "# WNOHANG was used, pid is still running", "delay", "=", "check_timeout", "(", "delay", ")", "continue", "# process exited due to a signal; return the integer of", "# that signal", "if", "os", ".", "WIFSIGNALED", "(", "status", ")", ":", "return", "os", ".", "WTERMSIG", "(", "status", ")", "# process exited using exit(2) system call; return the", "# integer exit(2) system call has been called with", "elif", "os", ".", "WIFEXITED", "(", "status", ")", ":", "return", "os", ".", "WEXITSTATUS", "(", "status", ")", "else", ":", "# should never happen", "raise", "RuntimeError", "(", "\"unknown process exit status\"", ")" ]
Wait for process with pid 'pid' to terminate and return its exit status code as an integer. If pid is not a children of os.getpid() (current process) just waits until the process disappears and return None. If pid does not exist at all return None immediately. Raise TimeoutExpired on timeout expired (if specified).
[ "Wait", "for", "process", "with", "pid", "pid", "to", "terminate", "and", "return", "its", "exit", "status", "code", "as", "an", "integer", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/process.py#L30-L94
train
limodou/uliweb
uliweb/contrib/upload/__init__.py
FileServing.get_filename
def get_filename(self, filename, filesystem=False, convert=False, subpath=''): """ Get the filename according to self.to_path, and if filesystem is False then return unicode filename, otherwise return filesystem encoded filename @param filename: relative filename, it'll be combine with self.to_path @param filesystem: if True, then encoding the filename to filesystem @param convert: if True, then convert filename with FilenameConverter class @param subpath: sub folder in to_path """ from uliweb.utils.common import safe_unicode #make sure the filename is unicode s = settings.GLOBAL if convert: _p, _f = os.path.split(filename) _filename = os.path.join(_p, self.filename_convert(_f)) else: _filename = filename nfile = safe_unicode(_filename, s.HTMLPAGE_ENCODING) if subpath: paths = [application_path(self.to_path), subpath, nfile] else: paths = [application_path(self.to_path), nfile] f = os.path.normpath(os.path.join(*paths)).replace('\\', '/') if filesystem: return files.encode_filename(f, to_encoding=s.FILESYSTEM_ENCODING) return f
python
def get_filename(self, filename, filesystem=False, convert=False, subpath=''): """ Get the filename according to self.to_path, and if filesystem is False then return unicode filename, otherwise return filesystem encoded filename @param filename: relative filename, it'll be combine with self.to_path @param filesystem: if True, then encoding the filename to filesystem @param convert: if True, then convert filename with FilenameConverter class @param subpath: sub folder in to_path """ from uliweb.utils.common import safe_unicode #make sure the filename is unicode s = settings.GLOBAL if convert: _p, _f = os.path.split(filename) _filename = os.path.join(_p, self.filename_convert(_f)) else: _filename = filename nfile = safe_unicode(_filename, s.HTMLPAGE_ENCODING) if subpath: paths = [application_path(self.to_path), subpath, nfile] else: paths = [application_path(self.to_path), nfile] f = os.path.normpath(os.path.join(*paths)).replace('\\', '/') if filesystem: return files.encode_filename(f, to_encoding=s.FILESYSTEM_ENCODING) return f
[ "def", "get_filename", "(", "self", ",", "filename", ",", "filesystem", "=", "False", ",", "convert", "=", "False", ",", "subpath", "=", "''", ")", ":", "from", "uliweb", ".", "utils", ".", "common", "import", "safe_unicode", "#make sure the filename is unicode\r", "s", "=", "settings", ".", "GLOBAL", "if", "convert", ":", "_p", ",", "_f", "=", "os", ".", "path", ".", "split", "(", "filename", ")", "_filename", "=", "os", ".", "path", ".", "join", "(", "_p", ",", "self", ".", "filename_convert", "(", "_f", ")", ")", "else", ":", "_filename", "=", "filename", "nfile", "=", "safe_unicode", "(", "_filename", ",", "s", ".", "HTMLPAGE_ENCODING", ")", "if", "subpath", ":", "paths", "=", "[", "application_path", "(", "self", ".", "to_path", ")", ",", "subpath", ",", "nfile", "]", "else", ":", "paths", "=", "[", "application_path", "(", "self", ".", "to_path", ")", ",", "nfile", "]", "f", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "*", "paths", ")", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "if", "filesystem", ":", "return", "files", ".", "encode_filename", "(", "f", ",", "to_encoding", "=", "s", ".", "FILESYSTEM_ENCODING", ")", "return", "f" ]
Get the filename according to self.to_path, and if filesystem is False then return unicode filename, otherwise return filesystem encoded filename @param filename: relative filename, it'll be combine with self.to_path @param filesystem: if True, then encoding the filename to filesystem @param convert: if True, then convert filename with FilenameConverter class @param subpath: sub folder in to_path
[ "Get", "the", "filename", "according", "to", "self", ".", "to_path", "and", "if", "filesystem", "is", "False", "then", "return", "unicode", "filename", "otherwise", "return", "filesystem", "encoded", "filename" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/upload/__init__.py#L82-L111
train
limodou/uliweb
uliweb/contrib/upload/__init__.py
FileServing.download
def download(self, filename, action='download', x_filename='', x_sendfile=None, real_filename=''): """ action will be "download", "inline" and if the request.GET has 'action', then the action will be replaced by it. """ from uliweb import request from uliweb.utils.common import safe_str from uliweb.utils.filedown import filedown s = settings.GLOBAL action = request.GET.get('action', action) if not real_filename: real_filename = self.get_filename(filename, True, convert=False) else: real_filename = files.encode_filename(real_filename, to_encoding=s.FILESYSTEM_ENCODING) if not x_filename: x_filename = safe_str(filename, s.FILESYSTEM_ENCODING) if self.x_file_prefix: x_filename = os.path.normpath(os.path.join(self.x_file_prefix, x_filename)).replace('\\', '/') xsend_flag = bool(self.x_sendfile) if x_sendfile is None else x_sendfile return filedown(request.environ, filename, action=action, x_sendfile=xsend_flag, x_header_name=self.x_header_name, x_filename=x_filename, real_filename=real_filename)
python
def download(self, filename, action='download', x_filename='', x_sendfile=None, real_filename=''): """ action will be "download", "inline" and if the request.GET has 'action', then the action will be replaced by it. """ from uliweb import request from uliweb.utils.common import safe_str from uliweb.utils.filedown import filedown s = settings.GLOBAL action = request.GET.get('action', action) if not real_filename: real_filename = self.get_filename(filename, True, convert=False) else: real_filename = files.encode_filename(real_filename, to_encoding=s.FILESYSTEM_ENCODING) if not x_filename: x_filename = safe_str(filename, s.FILESYSTEM_ENCODING) if self.x_file_prefix: x_filename = os.path.normpath(os.path.join(self.x_file_prefix, x_filename)).replace('\\', '/') xsend_flag = bool(self.x_sendfile) if x_sendfile is None else x_sendfile return filedown(request.environ, filename, action=action, x_sendfile=xsend_flag, x_header_name=self.x_header_name, x_filename=x_filename, real_filename=real_filename)
[ "def", "download", "(", "self", ",", "filename", ",", "action", "=", "'download'", ",", "x_filename", "=", "''", ",", "x_sendfile", "=", "None", ",", "real_filename", "=", "''", ")", ":", "from", "uliweb", "import", "request", "from", "uliweb", ".", "utils", ".", "common", "import", "safe_str", "from", "uliweb", ".", "utils", ".", "filedown", "import", "filedown", "s", "=", "settings", ".", "GLOBAL", "action", "=", "request", ".", "GET", ".", "get", "(", "'action'", ",", "action", ")", "if", "not", "real_filename", ":", "real_filename", "=", "self", ".", "get_filename", "(", "filename", ",", "True", ",", "convert", "=", "False", ")", "else", ":", "real_filename", "=", "files", ".", "encode_filename", "(", "real_filename", ",", "to_encoding", "=", "s", ".", "FILESYSTEM_ENCODING", ")", "if", "not", "x_filename", ":", "x_filename", "=", "safe_str", "(", "filename", ",", "s", ".", "FILESYSTEM_ENCODING", ")", "if", "self", ".", "x_file_prefix", ":", "x_filename", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "x_file_prefix", ",", "x_filename", ")", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "xsend_flag", "=", "bool", "(", "self", ".", "x_sendfile", ")", "if", "x_sendfile", "is", "None", "else", "x_sendfile", "return", "filedown", "(", "request", ".", "environ", ",", "filename", ",", "action", "=", "action", ",", "x_sendfile", "=", "xsend_flag", ",", "x_header_name", "=", "self", ".", "x_header_name", ",", "x_filename", "=", "x_filename", ",", "real_filename", "=", "real_filename", ")" ]
action will be "download", "inline" and if the request.GET has 'action', then the action will be replaced by it.
[ "action", "will", "be", "download", "inline", "and", "if", "the", "request", ".", "GET", "has", "action", "then", "the", "action", "will", "be", "replaced", "by", "it", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/upload/__init__.py#L113-L139
train
limodou/uliweb
uliweb/contrib/auth/__init__.py
logout
def logout(): """ Remove the authenticated user's ID from the request. """ from uliweb import request delete_user_session() request.session.delete() request.user = None return True
python
def logout(): """ Remove the authenticated user's ID from the request. """ from uliweb import request delete_user_session() request.session.delete() request.user = None return True
[ "def", "logout", "(", ")", ":", "from", "uliweb", "import", "request", "delete_user_session", "(", ")", "request", ".", "session", ".", "delete", "(", ")", "request", ".", "user", "=", "None", "return", "True" ]
Remove the authenticated user's ID from the request.
[ "Remove", "the", "authenticated", "user", "s", "ID", "from", "the", "request", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/auth/__init__.py#L241-L250
train
limodou/uliweb
uliweb/lib/weto/backends/memcache_storage.py
Storage.get
def get(self, key): """ because memcached does not provide a function to check if a key is existed so here is a heck way, if the value is None, then raise Exception """ if isinstance(key, unicode): key = key.encode('utf-8') v = self.client.get(key) if v is None: raise KeyError("Cache key [%s] not found" % key) else: return v
python
def get(self, key): """ because memcached does not provide a function to check if a key is existed so here is a heck way, if the value is None, then raise Exception """ if isinstance(key, unicode): key = key.encode('utf-8') v = self.client.get(key) if v is None: raise KeyError("Cache key [%s] not found" % key) else: return v
[ "def", "get", "(", "self", ",", "key", ")", ":", "if", "isinstance", "(", "key", ",", "unicode", ")", ":", "key", "=", "key", ".", "encode", "(", "'utf-8'", ")", "v", "=", "self", ".", "client", ".", "get", "(", "key", ")", "if", "v", "is", "None", ":", "raise", "KeyError", "(", "\"Cache key [%s] not found\"", "%", "key", ")", "else", ":", "return", "v" ]
because memcached does not provide a function to check if a key is existed so here is a heck way, if the value is None, then raise Exception
[ "because", "memcached", "does", "not", "provide", "a", "function", "to", "check", "if", "a", "key", "is", "existed", "so", "here", "is", "a", "heck", "way", "if", "the", "value", "is", "None", "then", "raise", "Exception" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/weto/backends/memcache_storage.py#L20-L31
train
limodou/uliweb
uliweb/core/commands.py
get_commands
def get_commands(mod): """ Find commands from a module """ import inspect import types commands = {} def check(c): return (inspect.isclass(c) and issubclass(c, Command) and c is not Command and not issubclass(c, CommandManager)) for name in dir(mod): c = getattr(mod, name) if check(c): commands[c.name] = c return commands
python
def get_commands(mod): """ Find commands from a module """ import inspect import types commands = {} def check(c): return (inspect.isclass(c) and issubclass(c, Command) and c is not Command and not issubclass(c, CommandManager)) for name in dir(mod): c = getattr(mod, name) if check(c): commands[c.name] = c return commands
[ "def", "get_commands", "(", "mod", ")", ":", "import", "inspect", "import", "types", "commands", "=", "{", "}", "def", "check", "(", "c", ")", ":", "return", "(", "inspect", ".", "isclass", "(", "c", ")", "and", "issubclass", "(", "c", ",", "Command", ")", "and", "c", "is", "not", "Command", "and", "not", "issubclass", "(", "c", ",", "CommandManager", ")", ")", "for", "name", "in", "dir", "(", "mod", ")", ":", "c", "=", "getattr", "(", "mod", ",", "name", ")", "if", "check", "(", "c", ")", ":", "commands", "[", "c", ".", "name", "]", "=", "c", "return", "commands" ]
Find commands from a module
[ "Find", "commands", "from", "a", "module" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/commands.py#L53-L71
train
limodou/uliweb
uliweb/core/commands.py
Command.usage
def usage(self, subcommand): """ Return a brief description of how to use this command, by default from the attribute ``self.help``. """ if len(self.option_list) > 0: usage = '%%prog %s [options] %s' % (subcommand, self.args) else: usage = '%%prog %s %s' % (subcommand, self.args) if self.help: return '%s\n\n%s' % (usage, self.help) else: return usage
python
def usage(self, subcommand): """ Return a brief description of how to use this command, by default from the attribute ``self.help``. """ if len(self.option_list) > 0: usage = '%%prog %s [options] %s' % (subcommand, self.args) else: usage = '%%prog %s %s' % (subcommand, self.args) if self.help: return '%s\n\n%s' % (usage, self.help) else: return usage
[ "def", "usage", "(", "self", ",", "subcommand", ")", ":", "if", "len", "(", "self", ".", "option_list", ")", ">", "0", ":", "usage", "=", "'%%prog %s [options] %s'", "%", "(", "subcommand", ",", "self", ".", "args", ")", "else", ":", "usage", "=", "'%%prog %s %s'", "%", "(", "subcommand", ",", "self", ".", "args", ")", "if", "self", ".", "help", ":", "return", "'%s\\n\\n%s'", "%", "(", "usage", ",", "self", ".", "help", ")", "else", ":", "return", "usage" ]
Return a brief description of how to use this command, by default from the attribute ``self.help``.
[ "Return", "a", "brief", "description", "of", "how", "to", "use", "this", "command", "by", "default", "from", "the", "attribute", "self", ".", "help", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/commands.py#L128-L141
train
limodou/uliweb
uliweb/contrib/orm/commands.py
show_table
def show_table(name, table, i, total): """ Display table info, name is tablename table is table object i is current Index total is total of tables """ return '[%d/%d, %s] %s' % (i+1, total, table.__appname__, name)
python
def show_table(name, table, i, total): """ Display table info, name is tablename table is table object i is current Index total is total of tables """ return '[%d/%d, %s] %s' % (i+1, total, table.__appname__, name)
[ "def", "show_table", "(", "name", ",", "table", ",", "i", ",", "total", ")", ":", "return", "'[%d/%d, %s] %s'", "%", "(", "i", "+", "1", ",", "total", ",", "table", ".", "__appname__", ",", "name", ")" ]
Display table info, name is tablename table is table object i is current Index total is total of tables
[ "Display", "table", "info", "name", "is", "tablename", "table", "is", "table", "object", "i", "is", "current", "Index", "total", "is", "total", "of", "tables" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/orm/commands.py#L303-L311
train
limodou/uliweb
uliweb/lib/werkzeug/contrib/kickstart.py
TemplateLoader.get_template
def get_template(self, name): """Get a template from a given name.""" filename = path.join(self.search_path, *[p for p in name.split('/') if p and p[0] != '.']) if not path.exists(filename): raise TemplateNotFound(name) return Template.from_file(filename, self.encoding)
python
def get_template(self, name): """Get a template from a given name.""" filename = path.join(self.search_path, *[p for p in name.split('/') if p and p[0] != '.']) if not path.exists(filename): raise TemplateNotFound(name) return Template.from_file(filename, self.encoding)
[ "def", "get_template", "(", "self", ",", "name", ")", ":", "filename", "=", "path", ".", "join", "(", "self", ".", "search_path", ",", "*", "[", "p", "for", "p", "in", "name", ".", "split", "(", "'/'", ")", "if", "p", "and", "p", "[", "0", "]", "!=", "'.'", "]", ")", "if", "not", "path", ".", "exists", "(", "filename", ")", ":", "raise", "TemplateNotFound", "(", "name", ")", "return", "Template", ".", "from_file", "(", "filename", ",", "self", ".", "encoding", ")" ]
Get a template from a given name.
[ "Get", "a", "template", "from", "a", "given", "name", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/kickstart.py#L218-L224
train
limodou/uliweb
uliweb/lib/werkzeug/contrib/kickstart.py
TemplateLoader.render_to_string
def render_to_string(self, *args, **kwargs): """Load and render a template into a unicode string.""" try: template_name, args = args[0], args[1:] except IndexError: raise TypeError('name of template required') return self.get_template(template_name).render(*args, **kwargs)
python
def render_to_string(self, *args, **kwargs): """Load and render a template into a unicode string.""" try: template_name, args = args[0], args[1:] except IndexError: raise TypeError('name of template required') return self.get_template(template_name).render(*args, **kwargs)
[ "def", "render_to_string", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "template_name", ",", "args", "=", "args", "[", "0", "]", ",", "args", "[", "1", ":", "]", "except", "IndexError", ":", "raise", "TypeError", "(", "'name of template required'", ")", "return", "self", ".", "get_template", "(", "template_name", ")", ".", "render", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Load and render a template into a unicode string.
[ "Load", "and", "render", "a", "template", "into", "a", "unicode", "string", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/kickstart.py#L230-L236
train
limodou/uliweb
uliweb/lib/werkzeug/contrib/kickstart.py
GenshiTemplateLoader.get_template
def get_template(self, template_name): """Get the template which is at the given name""" try: return self.loader.load(template_name, encoding=self.encoding) except self.not_found_exception, e: # catch the exception raised by Genshi, convert it into a werkzeug # exception (for the sake of consistency) raise TemplateNotFound(template_name)
python
def get_template(self, template_name): """Get the template which is at the given name""" try: return self.loader.load(template_name, encoding=self.encoding) except self.not_found_exception, e: # catch the exception raised by Genshi, convert it into a werkzeug # exception (for the sake of consistency) raise TemplateNotFound(template_name)
[ "def", "get_template", "(", "self", ",", "template_name", ")", ":", "try", ":", "return", "self", ".", "loader", ".", "load", "(", "template_name", ",", "encoding", "=", "self", ".", "encoding", ")", "except", "self", ".", "not_found_exception", ",", "e", ":", "# catch the exception raised by Genshi, convert it into a werkzeug", "# exception (for the sake of consistency)", "raise", "TemplateNotFound", "(", "template_name", ")" ]
Get the template which is at the given name
[ "Get", "the", "template", "which", "is", "at", "the", "given", "name" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/kickstart.py#L271-L278
train
limodou/uliweb
uliweb/lib/werkzeug/contrib/kickstart.py
GenshiTemplateLoader.render_to_string
def render_to_string(self, template_name, context=None): """Load and render a template into an unicode string""" # create an empty context if no context was specified context = context or {} tmpl = self.get_template(template_name) # render the template into a unicode string (None means unicode) return tmpl. \ generate(**context). \ render(self.output_type, encoding=None)
python
def render_to_string(self, template_name, context=None): """Load and render a template into an unicode string""" # create an empty context if no context was specified context = context or {} tmpl = self.get_template(template_name) # render the template into a unicode string (None means unicode) return tmpl. \ generate(**context). \ render(self.output_type, encoding=None)
[ "def", "render_to_string", "(", "self", ",", "template_name", ",", "context", "=", "None", ")", ":", "# create an empty context if no context was specified", "context", "=", "context", "or", "{", "}", "tmpl", "=", "self", ".", "get_template", "(", "template_name", ")", "# render the template into a unicode string (None means unicode)", "return", "tmpl", ".", "generate", "(", "*", "*", "context", ")", ".", "render", "(", "self", ".", "output_type", ",", "encoding", "=", "None", ")" ]
Load and render a template into an unicode string
[ "Load", "and", "render", "a", "template", "into", "an", "unicode", "string" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/kickstart.py#L280-L288
train
limodou/uliweb
uliweb/contrib/rbac/dbinit.py
process_permission_roles
def process_permission_roles(perm, v): """ v is roles """ if isinstance(v, (tuple, list)): roles = v else: roles = [v] for r in roles: if isinstance(r, (tuple, list)): role_name, role_props = r else: role_name, role_props = r, '' role = Role.get(Role.c.name == role_name) if not role: raise Exception, 'Role [%s] not found.' % r rel = Rel.get((Rel.c.role==role.id) & (Rel.c.permission==perm.id)) if not rel: rel = Rel(role=role, permission=perm, props=role_props) msg = 'Add Relation(Permision=%s, Role=%s)...' % (name, role_name) else: rel.update(props=role_props) msg = 'Update Relation(Permision=%s, Role=%s)...' % (name, role_name) flag = rel.save() if flag: print msg
python
def process_permission_roles(perm, v): """ v is roles """ if isinstance(v, (tuple, list)): roles = v else: roles = [v] for r in roles: if isinstance(r, (tuple, list)): role_name, role_props = r else: role_name, role_props = r, '' role = Role.get(Role.c.name == role_name) if not role: raise Exception, 'Role [%s] not found.' % r rel = Rel.get((Rel.c.role==role.id) & (Rel.c.permission==perm.id)) if not rel: rel = Rel(role=role, permission=perm, props=role_props) msg = 'Add Relation(Permision=%s, Role=%s)...' % (name, role_name) else: rel.update(props=role_props) msg = 'Update Relation(Permision=%s, Role=%s)...' % (name, role_name) flag = rel.save() if flag: print msg
[ "def", "process_permission_roles", "(", "perm", ",", "v", ")", ":", "if", "isinstance", "(", "v", ",", "(", "tuple", ",", "list", ")", ")", ":", "roles", "=", "v", "else", ":", "roles", "=", "[", "v", "]", "for", "r", "in", "roles", ":", "if", "isinstance", "(", "r", ",", "(", "tuple", ",", "list", ")", ")", ":", "role_name", ",", "role_props", "=", "r", "else", ":", "role_name", ",", "role_props", "=", "r", ",", "''", "role", "=", "Role", ".", "get", "(", "Role", ".", "c", ".", "name", "==", "role_name", ")", "if", "not", "role", ":", "raise", "Exception", ",", "'Role [%s] not found.'", "%", "r", "rel", "=", "Rel", ".", "get", "(", "(", "Rel", ".", "c", ".", "role", "==", "role", ".", "id", ")", "&", "(", "Rel", ".", "c", ".", "permission", "==", "perm", ".", "id", ")", ")", "if", "not", "rel", ":", "rel", "=", "Rel", "(", "role", "=", "role", ",", "permission", "=", "perm", ",", "props", "=", "role_props", ")", "msg", "=", "'Add Relation(Permision=%s, Role=%s)...'", "%", "(", "name", ",", "role_name", ")", "else", ":", "rel", ".", "update", "(", "props", "=", "role_props", ")", "msg", "=", "'Update Relation(Permision=%s, Role=%s)...'", "%", "(", "name", ",", "role_name", ")", "flag", "=", "rel", ".", "save", "(", ")", "if", "flag", ":", "print", "msg" ]
v is roles
[ "v", "is", "roles" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/rbac/dbinit.py#L32-L58
train
limodou/uliweb
uliweb/lib/werkzeug/contrib/jsrouting.py
generate_adapter
def generate_adapter(adapter, name='url_for', map_name='url_map'): """Generates the url building function for a map.""" values = { u'server_name': dumps(adapter.server_name), u'script_name': dumps(adapter.script_name), u'subdomain': dumps(adapter.subdomain), u'url_scheme': dumps(adapter.url_scheme), u'name': name, u'map_name': map_name } return u'''\ var %(name)s = %(map_name)s( %(server_name)s, %(script_name)s, %(subdomain)s, %(url_scheme)s );''' % values
python
def generate_adapter(adapter, name='url_for', map_name='url_map'): """Generates the url building function for a map.""" values = { u'server_name': dumps(adapter.server_name), u'script_name': dumps(adapter.script_name), u'subdomain': dumps(adapter.subdomain), u'url_scheme': dumps(adapter.url_scheme), u'name': name, u'map_name': map_name } return u'''\ var %(name)s = %(map_name)s( %(server_name)s, %(script_name)s, %(subdomain)s, %(url_scheme)s );''' % values
[ "def", "generate_adapter", "(", "adapter", ",", "name", "=", "'url_for'", ",", "map_name", "=", "'url_map'", ")", ":", "values", "=", "{", "u'server_name'", ":", "dumps", "(", "adapter", ".", "server_name", ")", ",", "u'script_name'", ":", "dumps", "(", "adapter", ".", "script_name", ")", ",", "u'subdomain'", ":", "dumps", "(", "adapter", ".", "subdomain", ")", ",", "u'url_scheme'", ":", "dumps", "(", "adapter", ".", "url_scheme", ")", ",", "u'name'", ":", "name", ",", "u'map_name'", ":", "map_name", "}", "return", "u'''\\\nvar %(name)s = %(map_name)s(\n %(server_name)s,\n %(script_name)s,\n %(subdomain)s,\n %(url_scheme)s\n);'''", "%", "values" ]
Generates the url building function for a map.
[ "Generates", "the", "url", "building", "function", "for", "a", "map", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/jsrouting.py#L217-L233
train
limodou/uliweb
uliweb/lib/werkzeug/contrib/jsrouting.py
js_to_url_function
def js_to_url_function(converter): """Get the JavaScript converter function from a rule.""" if hasattr(converter, 'js_to_url_function'): data = converter.js_to_url_function() else: for cls in getmro(type(converter)): if cls in js_to_url_functions: data = js_to_url_functions[cls](converter) break else: return 'encodeURIComponent' return '(function(value) { %s })' % data
python
def js_to_url_function(converter): """Get the JavaScript converter function from a rule.""" if hasattr(converter, 'js_to_url_function'): data = converter.js_to_url_function() else: for cls in getmro(type(converter)): if cls in js_to_url_functions: data = js_to_url_functions[cls](converter) break else: return 'encodeURIComponent' return '(function(value) { %s })' % data
[ "def", "js_to_url_function", "(", "converter", ")", ":", "if", "hasattr", "(", "converter", ",", "'js_to_url_function'", ")", ":", "data", "=", "converter", ".", "js_to_url_function", "(", ")", "else", ":", "for", "cls", "in", "getmro", "(", "type", "(", "converter", ")", ")", ":", "if", "cls", "in", "js_to_url_functions", ":", "data", "=", "js_to_url_functions", "[", "cls", "]", "(", "converter", ")", "break", "else", ":", "return", "'encodeURIComponent'", "return", "'(function(value) { %s })'", "%", "data" ]
Get the JavaScript converter function from a rule.
[ "Get", "the", "JavaScript", "converter", "function", "from", "a", "rule", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/jsrouting.py#L236-L247
train
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
_warn_if_string
def _warn_if_string(iterable): """Helper for the response objects to check if the iterable returned to the WSGI server is not a string. """ if isinstance(iterable, string_types): from warnings import warn warn(Warning('response iterable was set to a string. This appears ' 'to work but means that the server will send the ' 'data to the client char, by char. This is almost ' 'never intended behavior, use response.data to assign ' 'strings to the response object.'), stacklevel=2)
python
def _warn_if_string(iterable): """Helper for the response objects to check if the iterable returned to the WSGI server is not a string. """ if isinstance(iterable, string_types): from warnings import warn warn(Warning('response iterable was set to a string. This appears ' 'to work but means that the server will send the ' 'data to the client char, by char. This is almost ' 'never intended behavior, use response.data to assign ' 'strings to the response object.'), stacklevel=2)
[ "def", "_warn_if_string", "(", "iterable", ")", ":", "if", "isinstance", "(", "iterable", ",", "string_types", ")", ":", "from", "warnings", "import", "warn", "warn", "(", "Warning", "(", "'response iterable was set to a string. This appears '", "'to work but means that the server will send the '", "'data to the client char, by char. This is almost '", "'never intended behavior, use response.data to assign '", "'strings to the response object.'", ")", ",", "stacklevel", "=", "2", ")" ]
Helper for the response objects to check if the iterable returned to the WSGI server is not a string.
[ "Helper", "for", "the", "response", "objects", "to", "check", "if", "the", "iterable", "returned", "to", "the", "WSGI", "server", "is", "not", "a", "string", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L60-L70
train
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
BaseRequest._get_file_stream
def _get_file_stream(self, total_content_length, content_type, filename=None, content_length=None): """Called to get a stream for the file upload. This must provide a file-like class with `read()`, `readline()` and `seek()` methods that is both writeable and readable. The default implementation returns a temporary file if the total content length is higher than 500KB. Because many browsers do not provide a content length for the files only the total content length matters. :param total_content_length: the total content length of all the data in the request combined. This value is guaranteed to be there. :param content_type: the mimetype of the uploaded file. :param filename: the filename of the uploaded file. May be `None`. :param content_length: the length of this file. This value is usually not provided because webbrowsers do not provide this value. """ return default_stream_factory(total_content_length, content_type, filename, content_length)
python
def _get_file_stream(self, total_content_length, content_type, filename=None, content_length=None): """Called to get a stream for the file upload. This must provide a file-like class with `read()`, `readline()` and `seek()` methods that is both writeable and readable. The default implementation returns a temporary file if the total content length is higher than 500KB. Because many browsers do not provide a content length for the files only the total content length matters. :param total_content_length: the total content length of all the data in the request combined. This value is guaranteed to be there. :param content_type: the mimetype of the uploaded file. :param filename: the filename of the uploaded file. May be `None`. :param content_length: the length of this file. This value is usually not provided because webbrowsers do not provide this value. """ return default_stream_factory(total_content_length, content_type, filename, content_length)
[ "def", "_get_file_stream", "(", "self", ",", "total_content_length", ",", "content_type", ",", "filename", "=", "None", ",", "content_length", "=", "None", ")", ":", "return", "default_stream_factory", "(", "total_content_length", ",", "content_type", ",", "filename", ",", "content_length", ")" ]
Called to get a stream for the file upload. This must provide a file-like class with `read()`, `readline()` and `seek()` methods that is both writeable and readable. The default implementation returns a temporary file if the total content length is higher than 500KB. Because many browsers do not provide a content length for the files only the total content length matters. :param total_content_length: the total content length of all the data in the request combined. This value is guaranteed to be there. :param content_type: the mimetype of the uploaded file. :param filename: the filename of the uploaded file. May be `None`. :param content_length: the length of this file. This value is usually not provided because webbrowsers do not provide this value.
[ "Called", "to", "get", "a", "stream", "for", "the", "file", "upload", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L288-L310
train
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
BaseRequest.close
def close(self): """Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement with will automatically close it. .. versionadded:: 0.9 """ files = self.__dict__.get('files') for key, value in iter_multi_items(files or ()): value.close()
python
def close(self): """Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement with will automatically close it. .. versionadded:: 0.9 """ files = self.__dict__.get('files') for key, value in iter_multi_items(files or ()): value.close()
[ "def", "close", "(", "self", ")", ":", "files", "=", "self", ".", "__dict__", ".", "get", "(", "'files'", ")", "for", "key", ",", "value", "in", "iter_multi_items", "(", "files", "or", "(", ")", ")", ":", "value", ".", "close", "(", ")" ]
Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement with will automatically close it. .. versionadded:: 0.9
[ "Closes", "associated", "resources", "of", "this", "request", "object", ".", "This", "closes", "all", "file", "handles", "explicitly", ".", "You", "can", "also", "use", "the", "request", "object", "in", "a", "with", "statement", "with", "will", "automatically", "close", "it", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L364-L373
train
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
BaseResponse.get_data
def get_data(self, as_text=False): """The string representation of the request body. Whenever you call this property the request iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data. This behavior can be disabled by setting :attr:`implicit_sequence_conversion` to `False`. If `as_text` is set to `True` the return value will be a decoded unicode string. .. versionadded:: 0.9 """ self._ensure_sequence() rv = b''.join(self.iter_encoded()) if as_text: rv = rv.decode(self.charset) return rv
python
def get_data(self, as_text=False): """The string representation of the request body. Whenever you call this property the request iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data. This behavior can be disabled by setting :attr:`implicit_sequence_conversion` to `False`. If `as_text` is set to `True` the return value will be a decoded unicode string. .. versionadded:: 0.9 """ self._ensure_sequence() rv = b''.join(self.iter_encoded()) if as_text: rv = rv.decode(self.charset) return rv
[ "def", "get_data", "(", "self", ",", "as_text", "=", "False", ")", ":", "self", ".", "_ensure_sequence", "(", ")", "rv", "=", "b''", ".", "join", "(", "self", ".", "iter_encoded", "(", ")", ")", "if", "as_text", ":", "rv", "=", "rv", ".", "decode", "(", "self", ".", "charset", ")", "return", "rv" ]
The string representation of the request body. Whenever you call this property the request iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data. This behavior can be disabled by setting :attr:`implicit_sequence_conversion` to `False`. If `as_text` is set to `True` the return value will be a decoded unicode string. .. versionadded:: 0.9
[ "The", "string", "representation", "of", "the", "request", "body", ".", "Whenever", "you", "call", "this", "property", "the", "request", "iterable", "is", "encoded", "and", "flattened", ".", "This", "can", "lead", "to", "unwanted", "behavior", "if", "you", "stream", "big", "data", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L836-L853
train
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
BaseResponse._ensure_sequence
def _ensure_sequence(self, mutable=False): """This method can be called by methods that need a sequence. If `mutable` is true, it will also ensure that the response sequence is a standard Python list. .. versionadded:: 0.6 """ if self.is_sequence: # if we need a mutable object, we ensure it's a list. if mutable and not isinstance(self.response, list): self.response = list(self.response) return if self.direct_passthrough: raise RuntimeError('Attempted implicit sequence conversion ' 'but the response object is in direct ' 'passthrough mode.') if not self.implicit_sequence_conversion: raise RuntimeError('The response object required the iterable ' 'to be a sequence, but the implicit ' 'conversion was disabled. Call ' 'make_sequence() yourself.') self.make_sequence()
python
def _ensure_sequence(self, mutable=False): """This method can be called by methods that need a sequence. If `mutable` is true, it will also ensure that the response sequence is a standard Python list. .. versionadded:: 0.6 """ if self.is_sequence: # if we need a mutable object, we ensure it's a list. if mutable and not isinstance(self.response, list): self.response = list(self.response) return if self.direct_passthrough: raise RuntimeError('Attempted implicit sequence conversion ' 'but the response object is in direct ' 'passthrough mode.') if not self.implicit_sequence_conversion: raise RuntimeError('The response object required the iterable ' 'to be a sequence, but the implicit ' 'conversion was disabled. Call ' 'make_sequence() yourself.') self.make_sequence()
[ "def", "_ensure_sequence", "(", "self", ",", "mutable", "=", "False", ")", ":", "if", "self", ".", "is_sequence", ":", "# if we need a mutable object, we ensure it's a list.", "if", "mutable", "and", "not", "isinstance", "(", "self", ".", "response", ",", "list", ")", ":", "self", ".", "response", "=", "list", "(", "self", ".", "response", ")", "return", "if", "self", ".", "direct_passthrough", ":", "raise", "RuntimeError", "(", "'Attempted implicit sequence conversion '", "'but the response object is in direct '", "'passthrough mode.'", ")", "if", "not", "self", ".", "implicit_sequence_conversion", ":", "raise", "RuntimeError", "(", "'The response object required the iterable '", "'to be a sequence, but the implicit '", "'conversion was disabled. Call '", "'make_sequence() yourself.'", ")", "self", ".", "make_sequence", "(", ")" ]
This method can be called by methods that need a sequence. If `mutable` is true, it will also ensure that the response sequence is a standard Python list. .. versionadded:: 0.6
[ "This", "method", "can", "be", "called", "by", "methods", "that", "need", "a", "sequence", ".", "If", "mutable", "is", "true", "it", "will", "also", "ensure", "that", "the", "response", "sequence", "is", "a", "standard", "Python", "list", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L885-L906
train
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
BaseResponse.delete_cookie
def delete_cookie(self, key, path='/', domain=None): """Delete a cookie. Fails silently if key doesn't exist. :param key: the key (name) of the cookie to be deleted. :param path: if the cookie that should be deleted was limited to a path, the path has to be defined here. :param domain: if the cookie that should be deleted was limited to a domain, that domain has to be defined here. """ self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)
python
def delete_cookie(self, key, path='/', domain=None): """Delete a cookie. Fails silently if key doesn't exist. :param key: the key (name) of the cookie to be deleted. :param path: if the cookie that should be deleted was limited to a path, the path has to be defined here. :param domain: if the cookie that should be deleted was limited to a domain, that domain has to be defined here. """ self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)
[ "def", "delete_cookie", "(", "self", ",", "key", ",", "path", "=", "'/'", ",", "domain", "=", "None", ")", ":", "self", ".", "set_cookie", "(", "key", ",", "expires", "=", "0", ",", "max_age", "=", "0", ",", "path", "=", "path", ",", "domain", "=", "domain", ")" ]
Delete a cookie. Fails silently if key doesn't exist. :param key: the key (name) of the cookie to be deleted. :param path: if the cookie that should be deleted was limited to a path, the path has to be defined here. :param domain: if the cookie that should be deleted was limited to a domain, that domain has to be defined here.
[ "Delete", "a", "cookie", ".", "Fails", "silently", "if", "key", "doesn", "t", "exist", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L962-L971
train
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
BaseResponse.freeze
def freeze(self): """Call this method if you want to make your response object ready for being pickled. This buffers the generator if there is one. It will also set the `Content-Length` header to the length of the body. .. versionchanged:: 0.6 The `Content-Length` header is now set. """ # we explicitly set the length to a list of the *encoded* response # iterator. Even if the implicit sequence conversion is disabled. self.response = list(self.iter_encoded()) self.headers['Content-Length'] = str(sum(map(len, self.response)))
python
def freeze(self): """Call this method if you want to make your response object ready for being pickled. This buffers the generator if there is one. It will also set the `Content-Length` header to the length of the body. .. versionchanged:: 0.6 The `Content-Length` header is now set. """ # we explicitly set the length to a list of the *encoded* response # iterator. Even if the implicit sequence conversion is disabled. self.response = list(self.iter_encoded()) self.headers['Content-Length'] = str(sum(map(len, self.response)))
[ "def", "freeze", "(", "self", ")", ":", "# we explicitly set the length to a list of the *encoded* response", "# iterator. Even if the implicit sequence conversion is disabled.", "self", ".", "response", "=", "list", "(", "self", ".", "iter_encoded", "(", ")", ")", "self", ".", "headers", "[", "'Content-Length'", "]", "=", "str", "(", "sum", "(", "map", "(", "len", ",", "self", ".", "response", ")", ")", ")" ]
Call this method if you want to make your response object ready for being pickled. This buffers the generator if there is one. It will also set the `Content-Length` header to the length of the body. .. versionchanged:: 0.6 The `Content-Length` header is now set.
[ "Call", "this", "method", "if", "you", "want", "to", "make", "your", "response", "object", "ready", "for", "being", "pickled", ".", "This", "buffers", "the", "generator", "if", "there", "is", "one", ".", "It", "will", "also", "set", "the", "Content", "-", "Length", "header", "to", "the", "length", "of", "the", "body", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L1017-L1028
train
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
BaseResponse.get_app_iter
def get_app_iter(self, environ): """Returns the application iterator for the given environ. Depending on the request method and the current status code the return value might be an empty response rather than the one from the response. If the request method is `HEAD` or the status code is in a range where the HTTP specification requires an empty response, an empty iterable is returned. .. versionadded:: 0.6 :param environ: the WSGI environment of the request. :return: a response iterable. """ status = self.status_code if environ['REQUEST_METHOD'] == 'HEAD' or \ 100 <= status < 200 or status in (204, 304): iterable = () elif self.direct_passthrough: if __debug__: _warn_if_string(self.response) return self.response else: iterable = self.iter_encoded() return ClosingIterator(iterable, self.close)
python
def get_app_iter(self, environ): """Returns the application iterator for the given environ. Depending on the request method and the current status code the return value might be an empty response rather than the one from the response. If the request method is `HEAD` or the status code is in a range where the HTTP specification requires an empty response, an empty iterable is returned. .. versionadded:: 0.6 :param environ: the WSGI environment of the request. :return: a response iterable. """ status = self.status_code if environ['REQUEST_METHOD'] == 'HEAD' or \ 100 <= status < 200 or status in (204, 304): iterable = () elif self.direct_passthrough: if __debug__: _warn_if_string(self.response) return self.response else: iterable = self.iter_encoded() return ClosingIterator(iterable, self.close)
[ "def", "get_app_iter", "(", "self", ",", "environ", ")", ":", "status", "=", "self", ".", "status_code", "if", "environ", "[", "'REQUEST_METHOD'", "]", "==", "'HEAD'", "or", "100", "<=", "status", "<", "200", "or", "status", "in", "(", "204", ",", "304", ")", ":", "iterable", "=", "(", ")", "elif", "self", ".", "direct_passthrough", ":", "if", "__debug__", ":", "_warn_if_string", "(", "self", ".", "response", ")", "return", "self", ".", "response", "else", ":", "iterable", "=", "self", ".", "iter_encoded", "(", ")", "return", "ClosingIterator", "(", "iterable", ",", "self", ".", "close", ")" ]
Returns the application iterator for the given environ. Depending on the request method and the current status code the return value might be an empty response rather than the one from the response. If the request method is `HEAD` or the status code is in a range where the HTTP specification requires an empty response, an empty iterable is returned. .. versionadded:: 0.6 :param environ: the WSGI environment of the request. :return: a response iterable.
[ "Returns", "the", "application", "iterator", "for", "the", "given", "environ", ".", "Depending", "on", "the", "request", "method", "and", "the", "current", "status", "code", "the", "return", "value", "might", "be", "an", "empty", "response", "rather", "than", "the", "one", "from", "the", "response", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L1117-L1141
train
limodou/uliweb
uliweb/lib/werkzeug/wrappers.py
WWWAuthenticateMixin.www_authenticate
def www_authenticate(self): """The `WWW-Authenticate` header in a parsed form.""" def on_update(www_auth): if not www_auth and 'www-authenticate' in self.headers: del self.headers['www-authenticate'] elif www_auth: self.headers['WWW-Authenticate'] = www_auth.to_header() header = self.headers.get('www-authenticate') return parse_www_authenticate_header(header, on_update)
python
def www_authenticate(self): """The `WWW-Authenticate` header in a parsed form.""" def on_update(www_auth): if not www_auth and 'www-authenticate' in self.headers: del self.headers['www-authenticate'] elif www_auth: self.headers['WWW-Authenticate'] = www_auth.to_header() header = self.headers.get('www-authenticate') return parse_www_authenticate_header(header, on_update)
[ "def", "www_authenticate", "(", "self", ")", ":", "def", "on_update", "(", "www_auth", ")", ":", "if", "not", "www_auth", "and", "'www-authenticate'", "in", "self", ".", "headers", ":", "del", "self", ".", "headers", "[", "'www-authenticate'", "]", "elif", "www_auth", ":", "self", ".", "headers", "[", "'WWW-Authenticate'", "]", "=", "www_auth", ".", "to_header", "(", ")", "header", "=", "self", ".", "headers", ".", "get", "(", "'www-authenticate'", ")", "return", "parse_www_authenticate_header", "(", "header", ",", "on_update", ")" ]
The `WWW-Authenticate` header in a parsed form.
[ "The", "WWW", "-", "Authenticate", "header", "in", "a", "parsed", "form", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/wrappers.py#L1730-L1738
train
limodou/uliweb
uliweb/lib/werkzeug/routing.py
MapAdapter.make_alias_redirect_url
def make_alias_redirect_url(self, path, endpoint, values, method, query_args): """Internally called to make an alias redirect URL.""" url = self.build(endpoint, values, method, append_unknown=False, force_external=True) if query_args: url += '?' + self.encode_query_args(query_args) assert url != path, 'detected invalid alias setting. No canonical ' \ 'URL found' return url
python
def make_alias_redirect_url(self, path, endpoint, values, method, query_args): """Internally called to make an alias redirect URL.""" url = self.build(endpoint, values, method, append_unknown=False, force_external=True) if query_args: url += '?' + self.encode_query_args(query_args) assert url != path, 'detected invalid alias setting. No canonical ' \ 'URL found' return url
[ "def", "make_alias_redirect_url", "(", "self", ",", "path", ",", "endpoint", ",", "values", ",", "method", ",", "query_args", ")", ":", "url", "=", "self", ".", "build", "(", "endpoint", ",", "values", ",", "method", ",", "append_unknown", "=", "False", ",", "force_external", "=", "True", ")", "if", "query_args", ":", "url", "+=", "'?'", "+", "self", ".", "encode_query_args", "(", "query_args", ")", "assert", "url", "!=", "path", ",", "'detected invalid alias setting. No canonical '", "'URL found'", "return", "url" ]
Internally called to make an alias redirect URL.
[ "Internally", "called", "to", "make", "an", "alias", "redirect", "URL", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/routing.py#L1523-L1531
train
limodou/uliweb
uliweb/lib/werkzeug/templates.py
Template.from_file
def from_file(cls, file, charset='utf-8', errors='strict', unicode_mode=True): """Load a template from a file. .. versionchanged:: 0.5 The encoding parameter was renamed to charset. :param file: a filename or file object to load the template from. :param charset: the charset of the template to load. :param errors: the error behavior of the charset decoding. :param unicode_mode: set to `False` to disable unicode mode. :return: a template """ close = False f = file if isinstance(file, basestring): f = open(file, 'r') close = True try: data = _decode_unicode(f.read(), charset, errors) finally: if close: f.close() return cls(data, getattr(f, 'name', '<template>'), charset, errors, unicode_mode)
python
def from_file(cls, file, charset='utf-8', errors='strict', unicode_mode=True): """Load a template from a file. .. versionchanged:: 0.5 The encoding parameter was renamed to charset. :param file: a filename or file object to load the template from. :param charset: the charset of the template to load. :param errors: the error behavior of the charset decoding. :param unicode_mode: set to `False` to disable unicode mode. :return: a template """ close = False f = file if isinstance(file, basestring): f = open(file, 'r') close = True try: data = _decode_unicode(f.read(), charset, errors) finally: if close: f.close() return cls(data, getattr(f, 'name', '<template>'), charset, errors, unicode_mode)
[ "def", "from_file", "(", "cls", ",", "file", ",", "charset", "=", "'utf-8'", ",", "errors", "=", "'strict'", ",", "unicode_mode", "=", "True", ")", ":", "close", "=", "False", "f", "=", "file", "if", "isinstance", "(", "file", ",", "basestring", ")", ":", "f", "=", "open", "(", "file", ",", "'r'", ")", "close", "=", "True", "try", ":", "data", "=", "_decode_unicode", "(", "f", ".", "read", "(", ")", ",", "charset", ",", "errors", ")", "finally", ":", "if", "close", ":", "f", ".", "close", "(", ")", "return", "cls", "(", "data", ",", "getattr", "(", "f", ",", "'name'", ",", "'<template>'", ")", ",", "charset", ",", "errors", ",", "unicode_mode", ")" ]
Load a template from a file. .. versionchanged:: 0.5 The encoding parameter was renamed to charset. :param file: a filename or file object to load the template from. :param charset: the charset of the template to load. :param errors: the error behavior of the charset decoding. :param unicode_mode: set to `False` to disable unicode mode. :return: a template
[ "Load", "a", "template", "from", "a", "file", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/templates.py#L351-L375
train
limodou/uliweb
uliweb/lib/werkzeug/security.py
safe_str_cmp
def safe_str_cmp(a, b): """This function compares strings in somewhat constant time. This requires that the length of at least one string is known in advance. Returns `True` if the two strings are equal or `False` if they are not. .. versionadded:: 0.7 """ if _builtin_safe_str_cmp is not None: return _builtin_safe_str_cmp(a, b) if len(a) != len(b): return False rv = 0 if isinstance(a, bytes) and isinstance(b, bytes) and not PY2: for x, y in izip(a, b): rv |= x ^ y else: for x, y in izip(a, b): rv |= ord(x) ^ ord(y) return rv == 0
python
def safe_str_cmp(a, b): """This function compares strings in somewhat constant time. This requires that the length of at least one string is known in advance. Returns `True` if the two strings are equal or `False` if they are not. .. versionadded:: 0.7 """ if _builtin_safe_str_cmp is not None: return _builtin_safe_str_cmp(a, b) if len(a) != len(b): return False rv = 0 if isinstance(a, bytes) and isinstance(b, bytes) and not PY2: for x, y in izip(a, b): rv |= x ^ y else: for x, y in izip(a, b): rv |= ord(x) ^ ord(y) return rv == 0
[ "def", "safe_str_cmp", "(", "a", ",", "b", ")", ":", "if", "_builtin_safe_str_cmp", "is", "not", "None", ":", "return", "_builtin_safe_str_cmp", "(", "a", ",", "b", ")", "if", "len", "(", "a", ")", "!=", "len", "(", "b", ")", ":", "return", "False", "rv", "=", "0", "if", "isinstance", "(", "a", ",", "bytes", ")", "and", "isinstance", "(", "b", ",", "bytes", ")", "and", "not", "PY2", ":", "for", "x", ",", "y", "in", "izip", "(", "a", ",", "b", ")", ":", "rv", "|=", "x", "^", "y", "else", ":", "for", "x", ",", "y", "in", "izip", "(", "a", ",", "b", ")", ":", "rv", "|=", "ord", "(", "x", ")", "^", "ord", "(", "y", ")", "return", "rv", "==", "0" ]
This function compares strings in somewhat constant time. This requires that the length of at least one string is known in advance. Returns `True` if the two strings are equal or `False` if they are not. .. versionadded:: 0.7
[ "This", "function", "compares", "strings", "in", "somewhat", "constant", "time", ".", "This", "requires", "that", "the", "length", "of", "at", "least", "one", "string", "is", "known", "in", "advance", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/security.py#L108-L127
train
limodou/uliweb
uliweb/lib/werkzeug/security.py
gen_salt
def gen_salt(length): """Generate a random string of SALT_CHARS with specified ``length``.""" if length <= 0: raise ValueError('requested salt of length <= 0') return ''.join(_sys_rng.choice(SALT_CHARS) for _ in range_type(length))
python
def gen_salt(length): """Generate a random string of SALT_CHARS with specified ``length``.""" if length <= 0: raise ValueError('requested salt of length <= 0') return ''.join(_sys_rng.choice(SALT_CHARS) for _ in range_type(length))
[ "def", "gen_salt", "(", "length", ")", ":", "if", "length", "<=", "0", ":", "raise", "ValueError", "(", "'requested salt of length <= 0'", ")", "return", "''", ".", "join", "(", "_sys_rng", ".", "choice", "(", "SALT_CHARS", ")", "for", "_", "in", "range_type", "(", "length", ")", ")" ]
Generate a random string of SALT_CHARS with specified ``length``.
[ "Generate", "a", "random", "string", "of", "SALT_CHARS", "with", "specified", "length", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/security.py#L130-L134
train
limodou/uliweb
uliweb/form/uliform.py
BaseField.html
def html(self, data='', py=True): """ Convert data to html value format. """ if py: value = self.to_html(data) else: value = data if self.static: return str('<span class="value">%s</span>' % safe_str(value)) else: if self.hidden: build = Hidden else: build = self.build self._get_http_attrs() return str(build(name=self.name, value=value, id=self.id, **self.html_attrs))
python
def html(self, data='', py=True): """ Convert data to html value format. """ if py: value = self.to_html(data) else: value = data if self.static: return str('<span class="value">%s</span>' % safe_str(value)) else: if self.hidden: build = Hidden else: build = self.build self._get_http_attrs() return str(build(name=self.name, value=value, id=self.id, **self.html_attrs))
[ "def", "html", "(", "self", ",", "data", "=", "''", ",", "py", "=", "True", ")", ":", "if", "py", ":", "value", "=", "self", ".", "to_html", "(", "data", ")", "else", ":", "value", "=", "data", "if", "self", ".", "static", ":", "return", "str", "(", "'<span class=\"value\">%s</span>'", "%", "safe_str", "(", "value", ")", ")", "else", ":", "if", "self", ".", "hidden", ":", "build", "=", "Hidden", "else", ":", "build", "=", "self", ".", "build", "self", ".", "_get_http_attrs", "(", ")", "return", "str", "(", "build", "(", "name", "=", "self", ".", "name", ",", "value", "=", "value", ",", "id", "=", "self", ".", "id", ",", "*", "*", "self", ".", "html_attrs", ")", ")" ]
Convert data to html value format.
[ "Convert", "data", "to", "html", "value", "format", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/form/uliform.py#L176-L193
train
limodou/uliweb
uliweb/form/uliform.py
BaseField.validate
def validate(self, data, all_data=None): """ if 'rule' in kwargs, then validate extra rules e.g.: rule= {'required':True, 'minlength':6} """ all_data = all_data or {} if hasattr(data, 'stream'): data.file = data.stream if hasattr(data, 'file'): if data.file: v = data.filename else: raise Exception, 'Unsupport type %s' % type(data) else: v = data # if v is None: msg = TEST_NOT_EMPTY()(v) if self.required: if msg: return False, msg else: if msg: return True, self.default try: if isinstance(data, list): v = [] for i in data: v.append(self.to_python(i)) data = v else: data = self.to_python(data) except: return False, unicode(ERR_CONVERT) % (data, self.__class__.__name__) for v in self.get_validators(): msg = v(data, all_data) if msg: return False, msg return True, data
python
def validate(self, data, all_data=None): """ if 'rule' in kwargs, then validate extra rules e.g.: rule= {'required':True, 'minlength':6} """ all_data = all_data or {} if hasattr(data, 'stream'): data.file = data.stream if hasattr(data, 'file'): if data.file: v = data.filename else: raise Exception, 'Unsupport type %s' % type(data) else: v = data # if v is None: msg = TEST_NOT_EMPTY()(v) if self.required: if msg: return False, msg else: if msg: return True, self.default try: if isinstance(data, list): v = [] for i in data: v.append(self.to_python(i)) data = v else: data = self.to_python(data) except: return False, unicode(ERR_CONVERT) % (data, self.__class__.__name__) for v in self.get_validators(): msg = v(data, all_data) if msg: return False, msg return True, data
[ "def", "validate", "(", "self", ",", "data", ",", "all_data", "=", "None", ")", ":", "all_data", "=", "all_data", "or", "{", "}", "if", "hasattr", "(", "data", ",", "'stream'", ")", ":", "data", ".", "file", "=", "data", ".", "stream", "if", "hasattr", "(", "data", ",", "'file'", ")", ":", "if", "data", ".", "file", ":", "v", "=", "data", ".", "filename", "else", ":", "raise", "Exception", ",", "'Unsupport type %s'", "%", "type", "(", "data", ")", "else", ":", "v", "=", "data", "# if v is None:", "msg", "=", "TEST_NOT_EMPTY", "(", ")", "(", "v", ")", "if", "self", ".", "required", ":", "if", "msg", ":", "return", "False", ",", "msg", "else", ":", "if", "msg", ":", "return", "True", ",", "self", ".", "default", "try", ":", "if", "isinstance", "(", "data", ",", "list", ")", ":", "v", "=", "[", "]", "for", "i", "in", "data", ":", "v", ".", "append", "(", "self", ".", "to_python", "(", "i", ")", ")", "data", "=", "v", "else", ":", "data", "=", "self", ".", "to_python", "(", "data", ")", "except", ":", "return", "False", ",", "unicode", "(", "ERR_CONVERT", ")", "%", "(", "data", ",", "self", ".", "__class__", ".", "__name__", ")", "for", "v", "in", "self", ".", "get_validators", "(", ")", ":", "msg", "=", "v", "(", "data", ",", "all_data", ")", "if", "msg", ":", "return", "False", ",", "msg", "return", "True", ",", "data" ]
if 'rule' in kwargs, then validate extra rules e.g.: rule= {'required':True, 'minlength':6}
[ "if", "rule", "in", "kwargs", "then", "validate", "extra", "rules" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/form/uliform.py#L277-L321
train
limodou/uliweb
uliweb/lib/werkzeug/datastructures.py
cache_property
def cache_property(key, empty, type): """Return a new property object for a cache header. Useful if you want to add support for a cache extension in a subclass.""" return property(lambda x: x._get_cache_value(key, empty, type), lambda x, v: x._set_cache_value(key, v, type), lambda x: x._del_cache_value(key), 'accessor for %r' % key)
python
def cache_property(key, empty, type): """Return a new property object for a cache header. Useful if you want to add support for a cache extension in a subclass.""" return property(lambda x: x._get_cache_value(key, empty, type), lambda x, v: x._set_cache_value(key, v, type), lambda x: x._del_cache_value(key), 'accessor for %r' % key)
[ "def", "cache_property", "(", "key", ",", "empty", ",", "type", ")", ":", "return", "property", "(", "lambda", "x", ":", "x", ".", "_get_cache_value", "(", "key", ",", "empty", ",", "type", ")", ",", "lambda", "x", ",", "v", ":", "x", ".", "_set_cache_value", "(", "key", ",", "v", ",", "type", ")", ",", "lambda", "x", ":", "x", ".", "_del_cache_value", "(", "key", ")", ",", "'accessor for %r'", "%", "key", ")" ]
Return a new property object for a cache header. Useful if you want to add support for a cache extension in a subclass.
[ "Return", "a", "new", "property", "object", "for", "a", "cache", "header", ".", "Useful", "if", "you", "want", "to", "add", "support", "for", "a", "cache", "extension", "in", "a", "subclass", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/datastructures.py#L1731-L1737
train
limodou/uliweb
uliweb/lib/werkzeug/datastructures.py
ContentRange.set
def set(self, start, stop, length=None, units='bytes'): """Simple method to update the ranges.""" assert is_byte_range_valid(start, stop, length), \ 'Bad range provided' self._units = units self._start = start self._stop = stop self._length = length if self.on_update is not None: self.on_update(self)
python
def set(self, start, stop, length=None, units='bytes'): """Simple method to update the ranges.""" assert is_byte_range_valid(start, stop, length), \ 'Bad range provided' self._units = units self._start = start self._stop = stop self._length = length if self.on_update is not None: self.on_update(self)
[ "def", "set", "(", "self", ",", "start", ",", "stop", ",", "length", "=", "None", ",", "units", "=", "'bytes'", ")", ":", "assert", "is_byte_range_valid", "(", "start", ",", "stop", ",", "length", ")", ",", "'Bad range provided'", "self", ".", "_units", "=", "units", "self", ".", "_start", "=", "start", "self", ".", "_stop", "=", "stop", "self", ".", "_length", "=", "length", "if", "self", ".", "on_update", "is", "not", "None", ":", "self", ".", "on_update", "(", "self", ")" ]
Simple method to update the ranges.
[ "Simple", "method", "to", "update", "the", "ranges", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/datastructures.py#L2242-L2251
train
limodou/uliweb
uliweb/lib/werkzeug/datastructures.py
Authorization.qop
def qop(self): """Indicates what "quality of protection" the client has applied to the message for HTTP digest auth.""" def on_update(header_set): if not header_set and 'qop' in self: del self['qop'] elif header_set: self['qop'] = header_set.to_header() return parse_set_header(self.get('qop'), on_update)
python
def qop(self): """Indicates what "quality of protection" the client has applied to the message for HTTP digest auth.""" def on_update(header_set): if not header_set and 'qop' in self: del self['qop'] elif header_set: self['qop'] = header_set.to_header() return parse_set_header(self.get('qop'), on_update)
[ "def", "qop", "(", "self", ")", ":", "def", "on_update", "(", "header_set", ")", ":", "if", "not", "header_set", "and", "'qop'", "in", "self", ":", "del", "self", "[", "'qop'", "]", "elif", "header_set", ":", "self", "[", "'qop'", "]", "=", "header_set", ".", "to_header", "(", ")", "return", "parse_set_header", "(", "self", ".", "get", "(", "'qop'", ")", ",", "on_update", ")" ]
Indicates what "quality of protection" the client has applied to the message for HTTP digest auth.
[ "Indicates", "what", "quality", "of", "protection", "the", "client", "has", "applied", "to", "the", "message", "for", "HTTP", "digest", "auth", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/datastructures.py#L2336-L2344
train
limodou/uliweb
uliweb/lib/werkzeug/datastructures.py
WWWAuthenticate.set_basic
def set_basic(self, realm='authentication required'): """Clear the auth info and enable basic auth.""" dict.clear(self) dict.update(self, {'__auth_type__': 'basic', 'realm': realm}) if self.on_update: self.on_update(self)
python
def set_basic(self, realm='authentication required'): """Clear the auth info and enable basic auth.""" dict.clear(self) dict.update(self, {'__auth_type__': 'basic', 'realm': realm}) if self.on_update: self.on_update(self)
[ "def", "set_basic", "(", "self", ",", "realm", "=", "'authentication required'", ")", ":", "dict", ".", "clear", "(", "self", ")", "dict", ".", "update", "(", "self", ",", "{", "'__auth_type__'", ":", "'basic'", ",", "'realm'", ":", "realm", "}", ")", "if", "self", ".", "on_update", ":", "self", ".", "on_update", "(", "self", ")" ]
Clear the auth info and enable basic auth.
[ "Clear", "the", "auth", "info", "and", "enable", "basic", "auth", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/datastructures.py#L2359-L2364
train
limodou/uliweb
uliweb/orm/__init__.py
get_connection
def get_connection(connection='', engine_name=None, connection_type='long', **args): """ Creating an NamedEngine or just return existed engine instance if '://' include in connection parameter, it'll create new engine object otherwise return existed engine isntance """ engine_name = engine_name or __default_engine__ if '://' in connection: d = { 'connection_string':connection, 'connection_args':args, 'connection_type':connection_type, } return engine_manager.add(engine_name, d).engine else: connection = connection or __default_engine__ if connection in engine_manager: return engine_manager[connection].engine else: raise Error("Can't find engine %s" % connection)
python
def get_connection(connection='', engine_name=None, connection_type='long', **args): """ Creating an NamedEngine or just return existed engine instance if '://' include in connection parameter, it'll create new engine object otherwise return existed engine isntance """ engine_name = engine_name or __default_engine__ if '://' in connection: d = { 'connection_string':connection, 'connection_args':args, 'connection_type':connection_type, } return engine_manager.add(engine_name, d).engine else: connection = connection or __default_engine__ if connection in engine_manager: return engine_manager[connection].engine else: raise Error("Can't find engine %s" % connection)
[ "def", "get_connection", "(", "connection", "=", "''", ",", "engine_name", "=", "None", ",", "connection_type", "=", "'long'", ",", "*", "*", "args", ")", ":", "engine_name", "=", "engine_name", "or", "__default_engine__", "if", "'://'", "in", "connection", ":", "d", "=", "{", "'connection_string'", ":", "connection", ",", "'connection_args'", ":", "args", ",", "'connection_type'", ":", "connection_type", ",", "}", "return", "engine_manager", ".", "add", "(", "engine_name", ",", "d", ")", ".", "engine", "else", ":", "connection", "=", "connection", "or", "__default_engine__", "if", "connection", "in", "engine_manager", ":", "return", "engine_manager", "[", "connection", "]", ".", "engine", "else", ":", "raise", "Error", "(", "\"Can't find engine %s\"", "%", "connection", ")" ]
Creating an NamedEngine or just return existed engine instance if '://' include in connection parameter, it'll create new engine object otherwise return existed engine isntance
[ "Creating", "an", "NamedEngine", "or", "just", "return", "existed", "engine", "instance" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L453-L474
train
limodou/uliweb
uliweb/orm/__init__.py
get_metadata
def get_metadata(engine_name=None): """ get metadata according used for alembic It'll import all tables """ dispatch.get(None, 'load_models') engine = engine_manager[engine_name] for tablename, m in engine.models.items(): get_model(tablename, engine_name, signal=False) if hasattr(m, '__dynamic__') and getattr(m, '__dynamic__'): m.table.__mapping_only__ = True return engine.metadata
python
def get_metadata(engine_name=None): """ get metadata according used for alembic It'll import all tables """ dispatch.get(None, 'load_models') engine = engine_manager[engine_name] for tablename, m in engine.models.items(): get_model(tablename, engine_name, signal=False) if hasattr(m, '__dynamic__') and getattr(m, '__dynamic__'): m.table.__mapping_only__ = True return engine.metadata
[ "def", "get_metadata", "(", "engine_name", "=", "None", ")", ":", "dispatch", ".", "get", "(", "None", ",", "'load_models'", ")", "engine", "=", "engine_manager", "[", "engine_name", "]", "for", "tablename", ",", "m", "in", "engine", ".", "models", ".", "items", "(", ")", ":", "get_model", "(", "tablename", ",", "engine_name", ",", "signal", "=", "False", ")", "if", "hasattr", "(", "m", ",", "'__dynamic__'", ")", "and", "getattr", "(", "m", ",", "'__dynamic__'", ")", ":", "m", ".", "table", ".", "__mapping_only__", "=", "True", "return", "engine", ".", "metadata" ]
get metadata according used for alembic It'll import all tables
[ "get", "metadata", "according", "used", "for", "alembic", "It", "ll", "import", "all", "tables" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L476-L489
train
limodou/uliweb
uliweb/orm/__init__.py
get_session
def get_session(ec=None, create=True): """ ec - engine_name or connection """ ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): session = engine_manager[ec].session(create=True) elif isinstance(ec, Session): session = ec else: raise Error("Connection %r should be existed engine name or Session object" % ec) return session
python
def get_session(ec=None, create=True): """ ec - engine_name or connection """ ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): session = engine_manager[ec].session(create=True) elif isinstance(ec, Session): session = ec else: raise Error("Connection %r should be existed engine name or Session object" % ec) return session
[ "def", "get_session", "(", "ec", "=", "None", ",", "create", "=", "True", ")", ":", "ec", "=", "ec", "or", "__default_engine__", "if", "isinstance", "(", "ec", ",", "(", "str", ",", "unicode", ")", ")", ":", "session", "=", "engine_manager", "[", "ec", "]", ".", "session", "(", "create", "=", "True", ")", "elif", "isinstance", "(", "ec", ",", "Session", ")", ":", "session", "=", "ec", "else", ":", "raise", "Error", "(", "\"Connection %r should be existed engine name or Session object\"", "%", "ec", ")", "return", "session" ]
ec - engine_name or connection
[ "ec", "-", "engine_name", "or", "connection" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L491-L503
train
limodou/uliweb
uliweb/orm/__init__.py
rawsql
def rawsql(query, ec=None): """ ec could be engine name or engine instance """ if isinstance(query, Result): query = query.get_query() ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): engine = engine_manager[ec] dialect = engine.engine.dialect else: dialect = ec.dialect if isinstance(query, (str, unicode)): return query # comp = query.compile(dialect=dialect) compiler = query._compiler(dialect) class LiteralCompiler(compiler.__class__): def visit_bindparam( self, bindparam, within_columns_clause=False, literal_binds=False, **kwargs ): return super(LiteralCompiler, self).render_literal_bindparam( bindparam, within_columns_clause=within_columns_clause, literal_binds=literal_binds, **kwargs ) def render_literal_value(self, value, type_): """Render the value of a bind parameter as a quoted literal. This is used for statement sections that do not accept bind paramters on the target driver/database. This should be implemented by subclasses using the quoting services of the DBAPI. """ return repr_value(value) compiler = LiteralCompiler(dialect, query) return str(compiler.process(query)).replace('\n', '')
python
def rawsql(query, ec=None): """ ec could be engine name or engine instance """ if isinstance(query, Result): query = query.get_query() ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): engine = engine_manager[ec] dialect = engine.engine.dialect else: dialect = ec.dialect if isinstance(query, (str, unicode)): return query # comp = query.compile(dialect=dialect) compiler = query._compiler(dialect) class LiteralCompiler(compiler.__class__): def visit_bindparam( self, bindparam, within_columns_clause=False, literal_binds=False, **kwargs ): return super(LiteralCompiler, self).render_literal_bindparam( bindparam, within_columns_clause=within_columns_clause, literal_binds=literal_binds, **kwargs ) def render_literal_value(self, value, type_): """Render the value of a bind parameter as a quoted literal. This is used for statement sections that do not accept bind paramters on the target driver/database. This should be implemented by subclasses using the quoting services of the DBAPI. """ return repr_value(value) compiler = LiteralCompiler(dialect, query) return str(compiler.process(query)).replace('\n', '')
[ "def", "rawsql", "(", "query", ",", "ec", "=", "None", ")", ":", "if", "isinstance", "(", "query", ",", "Result", ")", ":", "query", "=", "query", ".", "get_query", "(", ")", "ec", "=", "ec", "or", "__default_engine__", "if", "isinstance", "(", "ec", ",", "(", "str", ",", "unicode", ")", ")", ":", "engine", "=", "engine_manager", "[", "ec", "]", "dialect", "=", "engine", ".", "engine", ".", "dialect", "else", ":", "dialect", "=", "ec", ".", "dialect", "if", "isinstance", "(", "query", ",", "(", "str", ",", "unicode", ")", ")", ":", "return", "query", "# comp = query.compile(dialect=dialect)", "compiler", "=", "query", ".", "_compiler", "(", "dialect", ")", "class", "LiteralCompiler", "(", "compiler", ".", "__class__", ")", ":", "def", "visit_bindparam", "(", "self", ",", "bindparam", ",", "within_columns_clause", "=", "False", ",", "literal_binds", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "LiteralCompiler", ",", "self", ")", ".", "render_literal_bindparam", "(", "bindparam", ",", "within_columns_clause", "=", "within_columns_clause", ",", "literal_binds", "=", "literal_binds", ",", "*", "*", "kwargs", ")", "def", "render_literal_value", "(", "self", ",", "value", ",", "type_", ")", ":", "\"\"\"Render the value of a bind parameter as a quoted literal.\n\n This is used for statement sections that do not accept bind paramters\n on the target driver/database.\n\n This should be implemented by subclasses using the quoting services\n of the DBAPI.\n\n \"\"\"", "return", "repr_value", "(", "value", ")", "compiler", "=", "LiteralCompiler", "(", "dialect", ",", "query", ")", "return", "str", "(", "compiler", ".", "process", "(", "query", ")", ")", ".", "replace", "(", "'\\n'", ",", "''", ")" ]
ec could be engine name or engine instance
[ "ec", "could", "be", "engine", "name", "or", "engine", "instance" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L555-L595
train
limodou/uliweb
uliweb/orm/__init__.py
get_engine_name
def get_engine_name(ec=None): """ Get the name of a engine or session """ ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): return ec elif isinstance(ec, Session): return ec.engine_name else: raise Error("Parameter ec should be an engine_name or Session object, but %r found" % ec)
python
def get_engine_name(ec=None): """ Get the name of a engine or session """ ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): return ec elif isinstance(ec, Session): return ec.engine_name else: raise Error("Parameter ec should be an engine_name or Session object, but %r found" % ec)
[ "def", "get_engine_name", "(", "ec", "=", "None", ")", ":", "ec", "=", "ec", "or", "__default_engine__", "if", "isinstance", "(", "ec", ",", "(", "str", ",", "unicode", ")", ")", ":", "return", "ec", "elif", "isinstance", "(", "ec", ",", "Session", ")", ":", "return", "ec", ".", "engine_name", "else", ":", "raise", "Error", "(", "\"Parameter ec should be an engine_name or Session object, but %r found\"", "%", "ec", ")" ]
Get the name of a engine or session
[ "Get", "the", "name", "of", "a", "engine", "or", "session" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L597-L607
train
limodou/uliweb
uliweb/orm/__init__.py
CommitAll
def CommitAll(close=None): """ Commit all transactions according Local.conn """ if close: warnings.simplefilter('default') warnings.warn("close parameter will not need at all.", DeprecationWarning) for k, v in engine_manager.items(): session = v.session(create=False) if session: session.commit()
python
def CommitAll(close=None): """ Commit all transactions according Local.conn """ if close: warnings.simplefilter('default') warnings.warn("close parameter will not need at all.", DeprecationWarning) for k, v in engine_manager.items(): session = v.session(create=False) if session: session.commit()
[ "def", "CommitAll", "(", "close", "=", "None", ")", ":", "if", "close", ":", "warnings", ".", "simplefilter", "(", "'default'", ")", "warnings", ".", "warn", "(", "\"close parameter will not need at all.\"", ",", "DeprecationWarning", ")", "for", "k", ",", "v", "in", "engine_manager", ".", "items", "(", ")", ":", "session", "=", "v", ".", "session", "(", "create", "=", "False", ")", "if", "session", ":", "session", ".", "commit", "(", ")" ]
Commit all transactions according Local.conn
[ "Commit", "all", "transactions", "according", "Local", ".", "conn" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L814-L825
train
limodou/uliweb
uliweb/orm/__init__.py
RollbackAll
def RollbackAll(close=None): """ Rollback all transactions, according Local.conn """ if close: warnings.simplefilter('default') warnings.warn("close parameter will not need at all.", DeprecationWarning) for k, v in engine_manager.items(): session = v.session(create=False) if session: session.rollback()
python
def RollbackAll(close=None): """ Rollback all transactions, according Local.conn """ if close: warnings.simplefilter('default') warnings.warn("close parameter will not need at all.", DeprecationWarning) for k, v in engine_manager.items(): session = v.session(create=False) if session: session.rollback()
[ "def", "RollbackAll", "(", "close", "=", "None", ")", ":", "if", "close", ":", "warnings", ".", "simplefilter", "(", "'default'", ")", "warnings", ".", "warn", "(", "\"close parameter will not need at all.\"", ",", "DeprecationWarning", ")", "for", "k", ",", "v", "in", "engine_manager", ".", "items", "(", ")", ":", "session", "=", "v", ".", "session", "(", "create", "=", "False", ")", "if", "session", ":", "session", ".", "rollback", "(", ")" ]
Rollback all transactions, according Local.conn
[ "Rollback", "all", "transactions", "according", "Local", ".", "conn" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L836-L847
train
limodou/uliweb
uliweb/orm/__init__.py
set_model
def set_model(model, tablename=None, created=None, appname=None, model_path=None): """ Register an model and tablename to a global variable. model could be a string format, i.e., 'uliweb.contrib.auth.models.User' :param appname: if no appname, then archive according to model item structure created model model_path appname For dynamic model you should pass model_path with '' value """ if isinstance(model, type) and issubclass(model, Model): #use alias first tablename = model._alias or model.tablename tablename = tablename.lower() #set global __models__ d = __models__.setdefault(tablename, {}) engines = d.get('config', {}).pop('engines', ['default']) if isinstance(engines, (str, unicode)): engines = [engines] d['engines'] = engines item = {} if created is not None: item['created'] = created else: item['created'] = None if isinstance(model, (str, unicode)): if model_path is None: model_path = model else: model_path = model_path if not appname: appname = model.rsplit('.', 2)[0] #for example 'uliweb.contrib.auth.models.User' model = None else: appname = model.__module__.rsplit('.', 1)[0] if model_path is None: model_path = model.__module__ + '.' + model.__name__ else: model_path = '' #for example 'uliweb.contrib.auth.models' model.__engines__ = engines item['model'] = model item['model_path'] = model_path item['appname'] = appname d['model_path'] = model_path d['appname'] = appname for name in engines: if not isinstance(name, (str, unicode)): raise BadValueError('Engine name should be string type, but %r found' % name) engine_manager[name].models[tablename] = item.copy()
python
def set_model(model, tablename=None, created=None, appname=None, model_path=None): """ Register an model and tablename to a global variable. model could be a string format, i.e., 'uliweb.contrib.auth.models.User' :param appname: if no appname, then archive according to model item structure created model model_path appname For dynamic model you should pass model_path with '' value """ if isinstance(model, type) and issubclass(model, Model): #use alias first tablename = model._alias or model.tablename tablename = tablename.lower() #set global __models__ d = __models__.setdefault(tablename, {}) engines = d.get('config', {}).pop('engines', ['default']) if isinstance(engines, (str, unicode)): engines = [engines] d['engines'] = engines item = {} if created is not None: item['created'] = created else: item['created'] = None if isinstance(model, (str, unicode)): if model_path is None: model_path = model else: model_path = model_path if not appname: appname = model.rsplit('.', 2)[0] #for example 'uliweb.contrib.auth.models.User' model = None else: appname = model.__module__.rsplit('.', 1)[0] if model_path is None: model_path = model.__module__ + '.' + model.__name__ else: model_path = '' #for example 'uliweb.contrib.auth.models' model.__engines__ = engines item['model'] = model item['model_path'] = model_path item['appname'] = appname d['model_path'] = model_path d['appname'] = appname for name in engines: if not isinstance(name, (str, unicode)): raise BadValueError('Engine name should be string type, but %r found' % name) engine_manager[name].models[tablename] = item.copy()
[ "def", "set_model", "(", "model", ",", "tablename", "=", "None", ",", "created", "=", "None", ",", "appname", "=", "None", ",", "model_path", "=", "None", ")", ":", "if", "isinstance", "(", "model", ",", "type", ")", "and", "issubclass", "(", "model", ",", "Model", ")", ":", "#use alias first", "tablename", "=", "model", ".", "_alias", "or", "model", ".", "tablename", "tablename", "=", "tablename", ".", "lower", "(", ")", "#set global __models__", "d", "=", "__models__", ".", "setdefault", "(", "tablename", ",", "{", "}", ")", "engines", "=", "d", ".", "get", "(", "'config'", ",", "{", "}", ")", ".", "pop", "(", "'engines'", ",", "[", "'default'", "]", ")", "if", "isinstance", "(", "engines", ",", "(", "str", ",", "unicode", ")", ")", ":", "engines", "=", "[", "engines", "]", "d", "[", "'engines'", "]", "=", "engines", "item", "=", "{", "}", "if", "created", "is", "not", "None", ":", "item", "[", "'created'", "]", "=", "created", "else", ":", "item", "[", "'created'", "]", "=", "None", "if", "isinstance", "(", "model", ",", "(", "str", ",", "unicode", ")", ")", ":", "if", "model_path", "is", "None", ":", "model_path", "=", "model", "else", ":", "model_path", "=", "model_path", "if", "not", "appname", ":", "appname", "=", "model", ".", "rsplit", "(", "'.'", ",", "2", ")", "[", "0", "]", "#for example 'uliweb.contrib.auth.models.User'", "model", "=", "None", "else", ":", "appname", "=", "model", ".", "__module__", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", "if", "model_path", "is", "None", ":", "model_path", "=", "model", ".", "__module__", "+", "'.'", "+", "model", ".", "__name__", "else", ":", "model_path", "=", "''", "#for example 'uliweb.contrib.auth.models'", "model", ".", "__engines__", "=", "engines", "item", "[", "'model'", "]", "=", "model", "item", "[", "'model_path'", "]", "=", "model_path", "item", "[", "'appname'", "]", "=", "appname", "d", "[", "'model_path'", "]", "=", "model_path", "d", "[", "'appname'", "]", "=", "appname", "for", "name", "in", "engines", ":", "if", "not", "isinstance", "(", "name", ",", "(", "str", ",", "unicode", ")", ")", ":", "raise", "BadValueError", "(", "'Engine name should be string type, but %r found'", "%", "name", ")", "engine_manager", "[", "name", "]", ".", "models", "[", "tablename", "]", "=", "item", ".", "copy", "(", ")" ]
Register an model and tablename to a global variable. model could be a string format, i.e., 'uliweb.contrib.auth.models.User' :param appname: if no appname, then archive according to model item structure created model model_path appname For dynamic model you should pass model_path with '' value
[ "Register", "an", "model", "and", "tablename", "to", "a", "global", "variable", ".", "model", "could", "be", "a", "string", "format", "i", ".", "e", ".", "uliweb", ".", "contrib", ".", "auth", ".", "models", ".", "User" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L855-L914
train
limodou/uliweb
uliweb/orm/__init__.py
create_model
def create_model(modelname, fields, indexes=None, basemodel=None, **props): """ Create model dynamically :param fields: Just format like [ {'name':name, 'type':type, ...}, ... ] type should be a string, eg. 'str', 'int', etc kwargs will be passed to Property.__init__() according field type, it'll be a dict :param props: Model attributes, such as '__mapping_only__', '__replace__' :param indexes: Multiple fields index, single index can be set directly using `index=True` to a field, the value format should be: [ {'name':name, 'fields':[...], ...}, ] e.g. [ {'name':'audit_idx', 'fields':['table_id', 'obj_id']} ] for kwargs can be ommited. :param basemodel: Will be the new Model base class, so new Model can inherited parent methods, it can be a string or a real class object """ assert not props or isinstance(props, dict) assert not indexes or isinstance(indexes, list) props = SortedDict(props or {}) props['__dynamic__'] = True props['__config__'] = False for p in fields: kwargs = p.copy() name = kwargs.pop('name') _type = kwargs.pop('type') #if the key is start with '_', then remove it for k in kwargs.keys(): if k.startswith('_'): kwargs.pop(k, None) field_type = get_field_type(_type) prop = field_type(**kwargs) props[name] = prop if basemodel: model = import_attr(basemodel) # model.clear_relation() else: model = Model # try: # old = get_model(modelname, signal=False) # old.clear_relation() # except ModelNotFound as e: # pass cls = type(str(modelname.title()), (model,), props) tablename = props.get('__tablename__', modelname) set_model(cls, tablename, appname=__name__, model_path='') get_model(modelname, signal=False, reload=True) indexes = indexes or [] for x in indexes: kwargs = x.copy() name = kwargs.pop('name') fields = kwargs.pop('fields') #if the key is start with '_', then remove it for k in kwargs.keys(): if k.startswith('_'): kwargs.pop(k, None) if not isinstance(fields, (list, tuple)): raise ValueError("Index value format is not right, the value is %r" % indexes) props = [] for y in fields: props.append(cls.c[y]) Index(name, *props, **kwargs) return cls
python
def create_model(modelname, fields, indexes=None, basemodel=None, **props): """ Create model dynamically :param fields: Just format like [ {'name':name, 'type':type, ...}, ... ] type should be a string, eg. 'str', 'int', etc kwargs will be passed to Property.__init__() according field type, it'll be a dict :param props: Model attributes, such as '__mapping_only__', '__replace__' :param indexes: Multiple fields index, single index can be set directly using `index=True` to a field, the value format should be: [ {'name':name, 'fields':[...], ...}, ] e.g. [ {'name':'audit_idx', 'fields':['table_id', 'obj_id']} ] for kwargs can be ommited. :param basemodel: Will be the new Model base class, so new Model can inherited parent methods, it can be a string or a real class object """ assert not props or isinstance(props, dict) assert not indexes or isinstance(indexes, list) props = SortedDict(props or {}) props['__dynamic__'] = True props['__config__'] = False for p in fields: kwargs = p.copy() name = kwargs.pop('name') _type = kwargs.pop('type') #if the key is start with '_', then remove it for k in kwargs.keys(): if k.startswith('_'): kwargs.pop(k, None) field_type = get_field_type(_type) prop = field_type(**kwargs) props[name] = prop if basemodel: model = import_attr(basemodel) # model.clear_relation() else: model = Model # try: # old = get_model(modelname, signal=False) # old.clear_relation() # except ModelNotFound as e: # pass cls = type(str(modelname.title()), (model,), props) tablename = props.get('__tablename__', modelname) set_model(cls, tablename, appname=__name__, model_path='') get_model(modelname, signal=False, reload=True) indexes = indexes or [] for x in indexes: kwargs = x.copy() name = kwargs.pop('name') fields = kwargs.pop('fields') #if the key is start with '_', then remove it for k in kwargs.keys(): if k.startswith('_'): kwargs.pop(k, None) if not isinstance(fields, (list, tuple)): raise ValueError("Index value format is not right, the value is %r" % indexes) props = [] for y in fields: props.append(cls.c[y]) Index(name, *props, **kwargs) return cls
[ "def", "create_model", "(", "modelname", ",", "fields", ",", "indexes", "=", "None", ",", "basemodel", "=", "None", ",", "*", "*", "props", ")", ":", "assert", "not", "props", "or", "isinstance", "(", "props", ",", "dict", ")", "assert", "not", "indexes", "or", "isinstance", "(", "indexes", ",", "list", ")", "props", "=", "SortedDict", "(", "props", "or", "{", "}", ")", "props", "[", "'__dynamic__'", "]", "=", "True", "props", "[", "'__config__'", "]", "=", "False", "for", "p", "in", "fields", ":", "kwargs", "=", "p", ".", "copy", "(", ")", "name", "=", "kwargs", ".", "pop", "(", "'name'", ")", "_type", "=", "kwargs", ".", "pop", "(", "'type'", ")", "#if the key is start with '_', then remove it", "for", "k", "in", "kwargs", ".", "keys", "(", ")", ":", "if", "k", ".", "startswith", "(", "'_'", ")", ":", "kwargs", ".", "pop", "(", "k", ",", "None", ")", "field_type", "=", "get_field_type", "(", "_type", ")", "prop", "=", "field_type", "(", "*", "*", "kwargs", ")", "props", "[", "name", "]", "=", "prop", "if", "basemodel", ":", "model", "=", "import_attr", "(", "basemodel", ")", "# model.clear_relation()", "else", ":", "model", "=", "Model", "# try:", "# old = get_model(modelname, signal=False)", "# old.clear_relation()", "# except ModelNotFound as e:", "# pass", "cls", "=", "type", "(", "str", "(", "modelname", ".", "title", "(", ")", ")", ",", "(", "model", ",", ")", ",", "props", ")", "tablename", "=", "props", ".", "get", "(", "'__tablename__'", ",", "modelname", ")", "set_model", "(", "cls", ",", "tablename", ",", "appname", "=", "__name__", ",", "model_path", "=", "''", ")", "get_model", "(", "modelname", ",", "signal", "=", "False", ",", "reload", "=", "True", ")", "indexes", "=", "indexes", "or", "[", "]", "for", "x", "in", "indexes", ":", "kwargs", "=", "x", ".", "copy", "(", ")", "name", "=", "kwargs", ".", "pop", "(", "'name'", ")", "fields", "=", "kwargs", ".", "pop", "(", "'fields'", ")", "#if the key is start with '_', then remove it", "for", "k", "in", "kwargs", ".", "keys", "(", ")", ":", "if", "k", ".", "startswith", "(", "'_'", ")", ":", "kwargs", ".", "pop", "(", "k", ",", "None", ")", "if", "not", "isinstance", "(", "fields", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "ValueError", "(", "\"Index value format is not right, the value is %r\"", "%", "indexes", ")", "props", "=", "[", "]", "for", "y", "in", "fields", ":", "props", ".", "append", "(", "cls", ".", "c", "[", "y", "]", ")", "Index", "(", "name", ",", "*", "props", ",", "*", "*", "kwargs", ")", "return", "cls" ]
Create model dynamically :param fields: Just format like [ {'name':name, 'type':type, ...}, ... ] type should be a string, eg. 'str', 'int', etc kwargs will be passed to Property.__init__() according field type, it'll be a dict :param props: Model attributes, such as '__mapping_only__', '__replace__' :param indexes: Multiple fields index, single index can be set directly using `index=True` to a field, the value format should be: [ {'name':name, 'fields':[...], ...}, ] e.g. [ {'name':'audit_idx', 'fields':['table_id', 'obj_id']} ] for kwargs can be ommited. :param basemodel: Will be the new Model base class, so new Model can inherited parent methods, it can be a string or a real class object
[ "Create", "model", "dynamically" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L934-L1020
train
limodou/uliweb
uliweb/orm/__init__.py
reflect_table_model
def reflect_table_model(table, mapping=None, without_id=False, engine_name='default'): """ Write table to Model class """ table = reflect_table(table, engine_name) mapping = mapping or {} meta = reflect_table_data(table) code = ['class {}(Model):'.format(table.name.title())] code.append(''' """ Description: """ __tablename__ = '{}\''''.format(table.name)) if sa_version >= '1.2' and table.comment: code.append(' __verbose_name__ = {}\n'.format(dumps(table.comment, bool_int=False))) #process id if 'id' not in meta['columns'] and without_id: code.append(' __without_id__ = True\n') # if _primary_key: # code.append(' _primary_field = {}'.format(_primary_key)) #output columns text for k, v in meta['columns'].items(): kw = v[1].items() x_v = mapping.get(v[0]) kwargs = ', '.join([v[0]] + ['{0}={1}'.format(x, dumps(y, bool_int=False)) for x, y in kw]) if x_v: type_class = ' ,type_class={}'.format(x_v) else: type_class = '' txt = " "*4 + "{0} = Field({1}{2})".format(k, kwargs, type_class) code.append(txt) #output index text if meta['indexes']: code.append(""" @classmethod def OnInit(cls):""") for index in meta['indexes']: buf = [] buf.append(index['name']) for c in index['columns']: buf.append('cls.c.{}'.format(c)) if index['unique']: buf.append('unique=True') code.append(' '*8 + 'Index({})'.format(', '.join(buf))) return '\n'.join(code)
python
def reflect_table_model(table, mapping=None, without_id=False, engine_name='default'): """ Write table to Model class """ table = reflect_table(table, engine_name) mapping = mapping or {} meta = reflect_table_data(table) code = ['class {}(Model):'.format(table.name.title())] code.append(''' """ Description: """ __tablename__ = '{}\''''.format(table.name)) if sa_version >= '1.2' and table.comment: code.append(' __verbose_name__ = {}\n'.format(dumps(table.comment, bool_int=False))) #process id if 'id' not in meta['columns'] and without_id: code.append(' __without_id__ = True\n') # if _primary_key: # code.append(' _primary_field = {}'.format(_primary_key)) #output columns text for k, v in meta['columns'].items(): kw = v[1].items() x_v = mapping.get(v[0]) kwargs = ', '.join([v[0]] + ['{0}={1}'.format(x, dumps(y, bool_int=False)) for x, y in kw]) if x_v: type_class = ' ,type_class={}'.format(x_v) else: type_class = '' txt = " "*4 + "{0} = Field({1}{2})".format(k, kwargs, type_class) code.append(txt) #output index text if meta['indexes']: code.append(""" @classmethod def OnInit(cls):""") for index in meta['indexes']: buf = [] buf.append(index['name']) for c in index['columns']: buf.append('cls.c.{}'.format(c)) if index['unique']: buf.append('unique=True') code.append(' '*8 + 'Index({})'.format(', '.join(buf))) return '\n'.join(code)
[ "def", "reflect_table_model", "(", "table", ",", "mapping", "=", "None", ",", "without_id", "=", "False", ",", "engine_name", "=", "'default'", ")", ":", "table", "=", "reflect_table", "(", "table", ",", "engine_name", ")", "mapping", "=", "mapping", "or", "{", "}", "meta", "=", "reflect_table_data", "(", "table", ")", "code", "=", "[", "'class {}(Model):'", ".", "format", "(", "table", ".", "name", ".", "title", "(", ")", ")", "]", "code", ".", "append", "(", "''' \"\"\"\n Description:\n \"\"\"\n\n __tablename__ = '{}\\''''", ".", "format", "(", "table", ".", "name", ")", ")", "if", "sa_version", ">=", "'1.2'", "and", "table", ".", "comment", ":", "code", ".", "append", "(", "' __verbose_name__ = {}\\n'", ".", "format", "(", "dumps", "(", "table", ".", "comment", ",", "bool_int", "=", "False", ")", ")", ")", "#process id", "if", "'id'", "not", "in", "meta", "[", "'columns'", "]", "and", "without_id", ":", "code", ".", "append", "(", "' __without_id__ = True\\n'", ")", "# if _primary_key:", "# code.append(' _primary_field = {}'.format(_primary_key))", "#output columns text", "for", "k", ",", "v", "in", "meta", "[", "'columns'", "]", ".", "items", "(", ")", ":", "kw", "=", "v", "[", "1", "]", ".", "items", "(", ")", "x_v", "=", "mapping", ".", "get", "(", "v", "[", "0", "]", ")", "kwargs", "=", "', '", ".", "join", "(", "[", "v", "[", "0", "]", "]", "+", "[", "'{0}={1}'", ".", "format", "(", "x", ",", "dumps", "(", "y", ",", "bool_int", "=", "False", ")", ")", "for", "x", ",", "y", "in", "kw", "]", ")", "if", "x_v", ":", "type_class", "=", "' ,type_class={}'", ".", "format", "(", "x_v", ")", "else", ":", "type_class", "=", "''", "txt", "=", "\" \"", "*", "4", "+", "\"{0} = Field({1}{2})\"", ".", "format", "(", "k", ",", "kwargs", ",", "type_class", ")", "code", ".", "append", "(", "txt", ")", "#output index text", "if", "meta", "[", "'indexes'", "]", ":", "code", ".", "append", "(", "\"\"\"\n @classmethod\n def OnInit(cls):\"\"\"", ")", "for", "index", "in", "meta", "[", "'indexes'", "]", ":", "buf", "=", "[", "]", "buf", ".", "append", "(", "index", "[", "'name'", "]", ")", "for", "c", "in", "index", "[", "'columns'", "]", ":", "buf", ".", "append", "(", "'cls.c.{}'", ".", "format", "(", "c", ")", ")", "if", "index", "[", "'unique'", "]", ":", "buf", ".", "append", "(", "'unique=True'", ")", "code", ".", "append", "(", "' '", "*", "8", "+", "'Index({})'", ".", "format", "(", "', '", ".", "join", "(", "buf", ")", ")", ")", "return", "'\\n'", ".", "join", "(", "code", ")" ]
Write table to Model class
[ "Write", "table", "to", "Model", "class" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L1372-L1422
train
limodou/uliweb
uliweb/orm/__init__.py
SelfReferenceProperty
def SelfReferenceProperty(label=None, collection_name=None, **attrs): """Create a self reference. """ if 'reference_class' in attrs: raise ConfigurationError( 'Do not provide reference_class to self-reference.') return ReferenceProperty(_SELF_REFERENCE, label, collection_name, **attrs)
python
def SelfReferenceProperty(label=None, collection_name=None, **attrs): """Create a self reference. """ if 'reference_class' in attrs: raise ConfigurationError( 'Do not provide reference_class to self-reference.') return ReferenceProperty(_SELF_REFERENCE, label, collection_name, **attrs)
[ "def", "SelfReferenceProperty", "(", "label", "=", "None", ",", "collection_name", "=", "None", ",", "*", "*", "attrs", ")", ":", "if", "'reference_class'", "in", "attrs", ":", "raise", "ConfigurationError", "(", "'Do not provide reference_class to self-reference.'", ")", "return", "ReferenceProperty", "(", "_SELF_REFERENCE", ",", "label", ",", "collection_name", ",", "*", "*", "attrs", ")" ]
Create a self reference.
[ "Create", "a", "self", "reference", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3595-L3601
train
limodou/uliweb
uliweb/orm/__init__.py
NamedEngine.session
def session(self, create=True): """ Used to created default session """ if hasattr(self.local, 'session'): return self.local.session else: if create: s = Session(self.name) self.local.session = s return s
python
def session(self, create=True): """ Used to created default session """ if hasattr(self.local, 'session'): return self.local.session else: if create: s = Session(self.name) self.local.session = s return s
[ "def", "session", "(", "self", ",", "create", "=", "True", ")", ":", "if", "hasattr", "(", "self", ".", "local", ",", "'session'", ")", ":", "return", "self", ".", "local", ".", "session", "else", ":", "if", "create", ":", "s", "=", "Session", "(", "self", ".", "name", ")", "self", ".", "local", ".", "session", "=", "s", "return", "s" ]
Used to created default session
[ "Used", "to", "created", "default", "session" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L263-L273
train
limodou/uliweb
uliweb/orm/__init__.py
Property.get_parameters
def get_parameters(self): """ Get common attributes and it'll used for Model.relationship clone process """ d = {} for k in ['label', 'verbose_name', 'required', 'hint', 'placeholder', 'choices', 'default', 'validators', 'max_length']: d[k] = getattr(self, k) return d
python
def get_parameters(self): """ Get common attributes and it'll used for Model.relationship clone process """ d = {} for k in ['label', 'verbose_name', 'required', 'hint', 'placeholder', 'choices', 'default', 'validators', 'max_length']: d[k] = getattr(self, k) return d
[ "def", "get_parameters", "(", "self", ")", ":", "d", "=", "{", "}", "for", "k", "in", "[", "'label'", ",", "'verbose_name'", ",", "'required'", ",", "'hint'", ",", "'placeholder'", ",", "'choices'", ",", "'default'", ",", "'validators'", ",", "'max_length'", "]", ":", "d", "[", "k", "]", "=", "getattr", "(", "self", ",", "k", ")", "return", "d" ]
Get common attributes and it'll used for Model.relationship clone process
[ "Get", "common", "attributes", "and", "it", "ll", "used", "for", "Model", ".", "relationship", "clone", "process" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L1628-L1636
train
limodou/uliweb
uliweb/orm/__init__.py
ReferenceProperty.validate
def validate(self, value): """Validate reference. Returns: A valid value. Raises: BadValueError for the following reasons: - Value is not saved. - Object not of correct model type for reference. """ if value == '': if self.kwargs.get('nullable', __nullable__): value = None else: value = 0 if not isinstance(value, Model): return super(ReferenceProperty, self).validate(value) if not value.is_saved(): raise BadValueError( '%s instance must be saved before it can be stored as a ' 'reference' % self.reference_class.__class__.__name__) if not isinstance(value, self.reference_class): raise KindError('Property %s must be an instance of %s' % (self.name, self.reference_class.__class__.__name__)) return value
python
def validate(self, value): """Validate reference. Returns: A valid value. Raises: BadValueError for the following reasons: - Value is not saved. - Object not of correct model type for reference. """ if value == '': if self.kwargs.get('nullable', __nullable__): value = None else: value = 0 if not isinstance(value, Model): return super(ReferenceProperty, self).validate(value) if not value.is_saved(): raise BadValueError( '%s instance must be saved before it can be stored as a ' 'reference' % self.reference_class.__class__.__name__) if not isinstance(value, self.reference_class): raise KindError('Property %s must be an instance of %s' % (self.name, self.reference_class.__class__.__name__)) return value
[ "def", "validate", "(", "self", ",", "value", ")", ":", "if", "value", "==", "''", ":", "if", "self", ".", "kwargs", ".", "get", "(", "'nullable'", ",", "__nullable__", ")", ":", "value", "=", "None", "else", ":", "value", "=", "0", "if", "not", "isinstance", "(", "value", ",", "Model", ")", ":", "return", "super", "(", "ReferenceProperty", ",", "self", ")", ".", "validate", "(", "value", ")", "if", "not", "value", ".", "is_saved", "(", ")", ":", "raise", "BadValueError", "(", "'%s instance must be saved before it can be stored as a '", "'reference'", "%", "self", ".", "reference_class", ".", "__class__", ".", "__name__", ")", "if", "not", "isinstance", "(", "value", ",", "self", ".", "reference_class", ")", ":", "raise", "KindError", "(", "'Property %s must be an instance of %s'", "%", "(", "self", ".", "name", ",", "self", ".", "reference_class", ".", "__class__", ".", "__name__", ")", ")", "return", "value" ]
Validate reference. Returns: A valid value. Raises: BadValueError for the following reasons: - Value is not saved. - Object not of correct model type for reference.
[ "Validate", "reference", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L2394-L2422
train
limodou/uliweb
uliweb/orm/__init__.py
Result.get_fields
def get_fields(self): """ get property instance according self.columns """ columns = self.columns model = self.model fields = [] for col in columns: if isinstance(col, (str, unicode)): v = col.split('.') if len(v) > 1: field = get_model(v[0], engine_name=self.model.get_engine_name(), signal=False).properties(v[1]) else: field = model.properties[col] elif isinstance(col, Column): field = get_model(col.table.name, engine_name=self.model.get_engine_name(), signal=False).properties[col.name] else: field = col fields.append(field) return fields
python
def get_fields(self): """ get property instance according self.columns """ columns = self.columns model = self.model fields = [] for col in columns: if isinstance(col, (str, unicode)): v = col.split('.') if len(v) > 1: field = get_model(v[0], engine_name=self.model.get_engine_name(), signal=False).properties(v[1]) else: field = model.properties[col] elif isinstance(col, Column): field = get_model(col.table.name, engine_name=self.model.get_engine_name(), signal=False).properties[col.name] else: field = col fields.append(field) return fields
[ "def", "get_fields", "(", "self", ")", ":", "columns", "=", "self", ".", "columns", "model", "=", "self", ".", "model", "fields", "=", "[", "]", "for", "col", "in", "columns", ":", "if", "isinstance", "(", "col", ",", "(", "str", ",", "unicode", ")", ")", ":", "v", "=", "col", ".", "split", "(", "'.'", ")", "if", "len", "(", "v", ")", ">", "1", ":", "field", "=", "get_model", "(", "v", "[", "0", "]", ",", "engine_name", "=", "self", ".", "model", ".", "get_engine_name", "(", ")", ",", "signal", "=", "False", ")", ".", "properties", "(", "v", "[", "1", "]", ")", "else", ":", "field", "=", "model", ".", "properties", "[", "col", "]", "elif", "isinstance", "(", "col", ",", "Column", ")", ":", "field", "=", "get_model", "(", "col", ".", "table", ".", "name", ",", "engine_name", "=", "self", ".", "model", ".", "get_engine_name", "(", ")", ",", "signal", "=", "False", ")", ".", "properties", "[", "col", ".", "name", "]", "else", ":", "field", "=", "col", "fields", ".", "append", "(", "field", ")", "return", "fields" ]
get property instance according self.columns
[ "get", "property", "instance", "according", "self", ".", "columns" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L2596-L2619
train
limodou/uliweb
uliweb/orm/__init__.py
Result.count
def count(self): """ If result is True, then the count will process result set , if result if False, then only use condition to count """ if self._group_by or self._join or self.distinct_field: return self.do_(self.get_query().limit(None).order_by(None).offset(None).alias().count()).scalar() else: return self.do_(self.get_query().with_only_columns([func.count()]).limit(None).order_by(None).offset(None)).scalar()
python
def count(self): """ If result is True, then the count will process result set , if result if False, then only use condition to count """ if self._group_by or self._join or self.distinct_field: return self.do_(self.get_query().limit(None).order_by(None).offset(None).alias().count()).scalar() else: return self.do_(self.get_query().with_only_columns([func.count()]).limit(None).order_by(None).offset(None)).scalar()
[ "def", "count", "(", "self", ")", ":", "if", "self", ".", "_group_by", "or", "self", ".", "_join", "or", "self", ".", "distinct_field", ":", "return", "self", ".", "do_", "(", "self", ".", "get_query", "(", ")", ".", "limit", "(", "None", ")", ".", "order_by", "(", "None", ")", ".", "offset", "(", "None", ")", ".", "alias", "(", ")", ".", "count", "(", ")", ")", ".", "scalar", "(", ")", "else", ":", "return", "self", ".", "do_", "(", "self", ".", "get_query", "(", ")", ".", "with_only_columns", "(", "[", "func", ".", "count", "(", ")", "]", ")", ".", "limit", "(", "None", ")", ".", "order_by", "(", "None", ")", ".", "offset", "(", "None", ")", ")", ".", "scalar", "(", ")" ]
If result is True, then the count will process result set , if result if False, then only use condition to count
[ "If", "result", "is", "True", "then", "the", "count", "will", "process", "result", "set", "if", "result", "if", "False", "then", "only", "use", "condition", "to", "count" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L2661-L2669
train
limodou/uliweb
uliweb/orm/__init__.py
Result.update
def update(self, **kwargs): """ Execute update table set field = field+1 like statement """ if self.condition is not None: self.result = self.do_(self.model.table.update().where(self.condition).values(**kwargs)) else: self.result = self.do_(self.model.table.update().values(**kwargs)) return self.result
python
def update(self, **kwargs): """ Execute update table set field = field+1 like statement """ if self.condition is not None: self.result = self.do_(self.model.table.update().where(self.condition).values(**kwargs)) else: self.result = self.do_(self.model.table.update().values(**kwargs)) return self.result
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "condition", "is", "not", "None", ":", "self", ".", "result", "=", "self", ".", "do_", "(", "self", ".", "model", ".", "table", ".", "update", "(", ")", ".", "where", "(", "self", ".", "condition", ")", ".", "values", "(", "*", "*", "kwargs", ")", ")", "else", ":", "self", ".", "result", "=", "self", ".", "do_", "(", "self", ".", "model", ".", "table", ".", "update", "(", ")", ".", "values", "(", "*", "*", "kwargs", ")", ")", "return", "self", ".", "result" ]
Execute update table set field = field+1 like statement
[ "Execute", "update", "table", "set", "field", "=", "field", "+", "1", "like", "statement" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L2754-L2762
train
limodou/uliweb
uliweb/orm/__init__.py
Result.save_file
def save_file(self, filename, encoding='utf8', headers=None, convertors=None, display=True, **kwargs): """ save result to a csv file. display = True will convert value according choices value """ global save_file convertors = convertors or {} headers = headers or [] fields = self.get_fields() _header = [] for i, column in enumerate(fields): if column.name not in convertors: if display: def f(value, data): return column.get_display_value(value) convertors[column.name] = f flag = False for j in headers: if not isinstance(j, dict): raise ValueError("Header should be a list of dict, but {} type found".format(type(j))) if j['name'] == column.name: _header.append(j) flag = True break if not flag: d = {'name':column.name} if display: d['title'] = column.verbose_name or column.name else: d['title'] = column.name _header.append(d) return save_file(self.run(), filename, encoding=encoding, headers=_header, convertors=convertors, **kwargs)
python
def save_file(self, filename, encoding='utf8', headers=None, convertors=None, display=True, **kwargs): """ save result to a csv file. display = True will convert value according choices value """ global save_file convertors = convertors or {} headers = headers or [] fields = self.get_fields() _header = [] for i, column in enumerate(fields): if column.name not in convertors: if display: def f(value, data): return column.get_display_value(value) convertors[column.name] = f flag = False for j in headers: if not isinstance(j, dict): raise ValueError("Header should be a list of dict, but {} type found".format(type(j))) if j['name'] == column.name: _header.append(j) flag = True break if not flag: d = {'name':column.name} if display: d['title'] = column.verbose_name or column.name else: d['title'] = column.name _header.append(d) return save_file(self.run(), filename, encoding=encoding, headers=_header, convertors=convertors, **kwargs)
[ "def", "save_file", "(", "self", ",", "filename", ",", "encoding", "=", "'utf8'", ",", "headers", "=", "None", ",", "convertors", "=", "None", ",", "display", "=", "True", ",", "*", "*", "kwargs", ")", ":", "global", "save_file", "convertors", "=", "convertors", "or", "{", "}", "headers", "=", "headers", "or", "[", "]", "fields", "=", "self", ".", "get_fields", "(", ")", "_header", "=", "[", "]", "for", "i", ",", "column", "in", "enumerate", "(", "fields", ")", ":", "if", "column", ".", "name", "not", "in", "convertors", ":", "if", "display", ":", "def", "f", "(", "value", ",", "data", ")", ":", "return", "column", ".", "get_display_value", "(", "value", ")", "convertors", "[", "column", ".", "name", "]", "=", "f", "flag", "=", "False", "for", "j", "in", "headers", ":", "if", "not", "isinstance", "(", "j", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"Header should be a list of dict, but {} type found\"", ".", "format", "(", "type", "(", "j", ")", ")", ")", "if", "j", "[", "'name'", "]", "==", "column", ".", "name", ":", "_header", ".", "append", "(", "j", ")", "flag", "=", "True", "break", "if", "not", "flag", ":", "d", "=", "{", "'name'", ":", "column", ".", "name", "}", "if", "display", ":", "d", "[", "'title'", "]", "=", "column", ".", "verbose_name", "or", "column", ".", "name", "else", ":", "d", "[", "'title'", "]", "=", "column", ".", "name", "_header", ".", "append", "(", "d", ")", "return", "save_file", "(", "self", ".", "run", "(", ")", ",", "filename", ",", "encoding", "=", "encoding", ",", "headers", "=", "_header", ",", "convertors", "=", "convertors", ",", "*", "*", "kwargs", ")" ]
save result to a csv file. display = True will convert value according choices value
[ "save", "result", "to", "a", "csv", "file", ".", "display", "=", "True", "will", "convert", "value", "according", "choices", "value" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L2777-L2814
train
limodou/uliweb
uliweb/orm/__init__.py
ManyResult.all
def all(self, cache=False): """ can use cache to return objects """ if cache: return [get_object(self.modelb, obj_id, cache=True, use_local=True) for obj_id in self.keys(True)] else: return self
python
def all(self, cache=False): """ can use cache to return objects """ if cache: return [get_object(self.modelb, obj_id, cache=True, use_local=True) for obj_id in self.keys(True)] else: return self
[ "def", "all", "(", "self", ",", "cache", "=", "False", ")", ":", "if", "cache", ":", "return", "[", "get_object", "(", "self", ".", "modelb", ",", "obj_id", ",", "cache", "=", "True", ",", "use_local", "=", "True", ")", "for", "obj_id", "in", "self", ".", "keys", "(", "True", ")", "]", "else", ":", "return", "self" ]
can use cache to return objects
[ "can", "use", "cache", "to", "return", "objects" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3010-L3017
train
limodou/uliweb
uliweb/orm/__init__.py
ManyResult.update
def update(self, *objs): """ Update the third relationship table, but not the ModelA or ModelB """ keys = self.keys() new_keys = get_objs_columns(objs, self.realfieldb) modified = False for v in new_keys: if v in keys: #the id has been existed, so don't insert new record keys.remove(v) else: d = {self.fielda:self.valuea, self.fieldb:v} if self.before_save: self.before_save(d) if self.through_model: obj = self.through_model(**d) obj.save() else: self.do_(self.table.insert().values(**d)) modified = True if keys: #if there are still keys, so delete them self.clear(*keys) modified = True #cache [] to _STORED_attr_name setattr(self.instance, self.store_key, new_keys) return modified
python
def update(self, *objs): """ Update the third relationship table, but not the ModelA or ModelB """ keys = self.keys() new_keys = get_objs_columns(objs, self.realfieldb) modified = False for v in new_keys: if v in keys: #the id has been existed, so don't insert new record keys.remove(v) else: d = {self.fielda:self.valuea, self.fieldb:v} if self.before_save: self.before_save(d) if self.through_model: obj = self.through_model(**d) obj.save() else: self.do_(self.table.insert().values(**d)) modified = True if keys: #if there are still keys, so delete them self.clear(*keys) modified = True #cache [] to _STORED_attr_name setattr(self.instance, self.store_key, new_keys) return modified
[ "def", "update", "(", "self", ",", "*", "objs", ")", ":", "keys", "=", "self", ".", "keys", "(", ")", "new_keys", "=", "get_objs_columns", "(", "objs", ",", "self", ".", "realfieldb", ")", "modified", "=", "False", "for", "v", "in", "new_keys", ":", "if", "v", "in", "keys", ":", "#the id has been existed, so don't insert new record", "keys", ".", "remove", "(", "v", ")", "else", ":", "d", "=", "{", "self", ".", "fielda", ":", "self", ".", "valuea", ",", "self", ".", "fieldb", ":", "v", "}", "if", "self", ".", "before_save", ":", "self", ".", "before_save", "(", "d", ")", "if", "self", ".", "through_model", ":", "obj", "=", "self", ".", "through_model", "(", "*", "*", "d", ")", "obj", ".", "save", "(", ")", "else", ":", "self", ".", "do_", "(", "self", ".", "table", ".", "insert", "(", ")", ".", "values", "(", "*", "*", "d", ")", ")", "modified", "=", "True", "if", "keys", ":", "#if there are still keys, so delete them", "self", ".", "clear", "(", "*", "keys", ")", "modified", "=", "True", "#cache [] to _STORED_attr_name", "setattr", "(", "self", ".", "instance", ",", "self", ".", "store_key", ",", "new_keys", ")", "return", "modified" ]
Update the third relationship table, but not the ModelA or ModelB
[ "Update", "the", "third", "relationship", "table", "but", "not", "the", "ModelA", "or", "ModelB" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3099-L3128
train
limodou/uliweb
uliweb/orm/__init__.py
ManyResult.with_relation
def with_relation(self, relation_name=None): """ if relation is not None, when fetch manytomany result, also fetch relation record and saved them to manytomany object, and named them as relation. If relation_name is not given, then default value is 'relation' """ if not relation_name: relation_name = 'relation' if hasattr(self.modelb, relation_name): raise Error("The attribute name %s has already existed in Model %s!" % (relation_name, self.modelb.__name__)) if not self.through_model: raise Error("Only with through style in ManyToMany supports with_relation function of Model %s!" % self.modelb.__name__) self.with_relation_name = relation_name return self
python
def with_relation(self, relation_name=None): """ if relation is not None, when fetch manytomany result, also fetch relation record and saved them to manytomany object, and named them as relation. If relation_name is not given, then default value is 'relation' """ if not relation_name: relation_name = 'relation' if hasattr(self.modelb, relation_name): raise Error("The attribute name %s has already existed in Model %s!" % (relation_name, self.modelb.__name__)) if not self.through_model: raise Error("Only with through style in ManyToMany supports with_relation function of Model %s!" % self.modelb.__name__) self.with_relation_name = relation_name return self
[ "def", "with_relation", "(", "self", ",", "relation_name", "=", "None", ")", ":", "if", "not", "relation_name", ":", "relation_name", "=", "'relation'", "if", "hasattr", "(", "self", ".", "modelb", ",", "relation_name", ")", ":", "raise", "Error", "(", "\"The attribute name %s has already existed in Model %s!\"", "%", "(", "relation_name", ",", "self", ".", "modelb", ".", "__name__", ")", ")", "if", "not", "self", ".", "through_model", ":", "raise", "Error", "(", "\"Only with through style in ManyToMany supports with_relation function of Model %s!\"", "%", "self", ".", "modelb", ".", "__name__", ")", "self", ".", "with_relation_name", "=", "relation_name", "return", "self" ]
if relation is not None, when fetch manytomany result, also fetch relation record and saved them to manytomany object, and named them as relation. If relation_name is not given, then default value is 'relation'
[ "if", "relation", "is", "not", "None", "when", "fetch", "manytomany", "result", "also", "fetch", "relation", "record", "and", "saved", "them", "to", "manytomany", "object", "and", "named", "them", "as", "relation", ".", "If", "relation_name", "is", "not", "given", "then", "default", "value", "is", "relation" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3192-L3207
train
limodou/uliweb
uliweb/orm/__init__.py
ManyToMany.in_
def in_(self, *objs): """ Create a condition """ if not objs: return self.table.c[self.fielda]!=self.table.c[self.fielda] else: keys = get_objs_columns(objs, self.reference_fieldname) sub_query = select([self.table.c[self.fielda]], (self.table.c[self.fieldb] == self.reference_class.c[self.reference_fieldname]) & (self.table.c[self.fieldb].in_(keys))) condition = self.model_class.c[self.reversed_fieldname].in_(sub_query) return condition
python
def in_(self, *objs): """ Create a condition """ if not objs: return self.table.c[self.fielda]!=self.table.c[self.fielda] else: keys = get_objs_columns(objs, self.reference_fieldname) sub_query = select([self.table.c[self.fielda]], (self.table.c[self.fieldb] == self.reference_class.c[self.reference_fieldname]) & (self.table.c[self.fieldb].in_(keys))) condition = self.model_class.c[self.reversed_fieldname].in_(sub_query) return condition
[ "def", "in_", "(", "self", ",", "*", "objs", ")", ":", "if", "not", "objs", ":", "return", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "!=", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "else", ":", "keys", "=", "get_objs_columns", "(", "objs", ",", "self", ".", "reference_fieldname", ")", "sub_query", "=", "select", "(", "[", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "]", ",", "(", "self", ".", "table", ".", "c", "[", "self", ".", "fieldb", "]", "==", "self", ".", "reference_class", ".", "c", "[", "self", ".", "reference_fieldname", "]", ")", "&", "(", "self", ".", "table", ".", "c", "[", "self", ".", "fieldb", "]", ".", "in_", "(", "keys", ")", ")", ")", "condition", "=", "self", ".", "model_class", ".", "c", "[", "self", ".", "reversed_fieldname", "]", ".", "in_", "(", "sub_query", ")", "return", "condition" ]
Create a condition
[ "Create", "a", "condition" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3529-L3539
train
limodou/uliweb
uliweb/orm/__init__.py
ManyToMany.join_in
def join_in(self, *objs): """ Create a join condition, connect A and C """ if not objs: return self.table.c[self.fielda]!=self.table.c[self.fielda] else: keys = get_objs_columns(objs, self.reference_fieldname) return (self.table.c[self.fielda] == self.model_class.c[self.reversed_fieldname]) & (self.table.c[self.fieldb].in_(keys))
python
def join_in(self, *objs): """ Create a join condition, connect A and C """ if not objs: return self.table.c[self.fielda]!=self.table.c[self.fielda] else: keys = get_objs_columns(objs, self.reference_fieldname) return (self.table.c[self.fielda] == self.model_class.c[self.reversed_fieldname]) & (self.table.c[self.fieldb].in_(keys))
[ "def", "join_in", "(", "self", ",", "*", "objs", ")", ":", "if", "not", "objs", ":", "return", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "!=", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "else", ":", "keys", "=", "get_objs_columns", "(", "objs", ",", "self", ".", "reference_fieldname", ")", "return", "(", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "==", "self", ".", "model_class", ".", "c", "[", "self", ".", "reversed_fieldname", "]", ")", "&", "(", "self", ".", "table", ".", "c", "[", "self", ".", "fieldb", "]", ".", "in_", "(", "keys", ")", ")" ]
Create a join condition, connect A and C
[ "Create", "a", "join", "condition", "connect", "A", "and", "C" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3541-L3549
train
limodou/uliweb
uliweb/orm/__init__.py
ManyToMany.join_right_in
def join_right_in(self, *objs): """ Create a join condition, connect B and C """ if not objs: return self.table.c[self.fielda]!=self.table.c[self.fielda] else: keys = get_objs_columns(objs, self.reference_fieldname) return (self.table.c[self.fieldb] == self.reference_class.c[self.reference_fieldname]) & (self.table.c[self.fielda].in_(keys))
python
def join_right_in(self, *objs): """ Create a join condition, connect B and C """ if not objs: return self.table.c[self.fielda]!=self.table.c[self.fielda] else: keys = get_objs_columns(objs, self.reference_fieldname) return (self.table.c[self.fieldb] == self.reference_class.c[self.reference_fieldname]) & (self.table.c[self.fielda].in_(keys))
[ "def", "join_right_in", "(", "self", ",", "*", "objs", ")", ":", "if", "not", "objs", ":", "return", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "!=", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", "else", ":", "keys", "=", "get_objs_columns", "(", "objs", ",", "self", ".", "reference_fieldname", ")", "return", "(", "self", ".", "table", ".", "c", "[", "self", ".", "fieldb", "]", "==", "self", ".", "reference_class", ".", "c", "[", "self", ".", "reference_fieldname", "]", ")", "&", "(", "self", ".", "table", ".", "c", "[", "self", ".", "fielda", "]", ".", "in_", "(", "keys", ")", ")" ]
Create a join condition, connect B and C
[ "Create", "a", "join", "condition", "connect", "B", "and", "C" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3551-L3559
train
limodou/uliweb
uliweb/orm/__init__.py
Model._get_data
def _get_data(self, fields=None, compare=True): """ Get the changed property, it'll be used to save the object If compare is False, then it'll include all data not only changed property """ fields = fields or [] if self._key is None or self._key == '' or self._key == 0: d = {} for k, v in self.properties.items(): #test fields if fields and k not in fields: continue # if not isinstance(v, ManyToMany): if v.property_type == 'compound': continue if v.sequence: continue if not isinstance(v, ManyToMany): x = v.get_value_for_datastore(self) if isinstance(x, Model): x = x._key elif x is None or (k==self._primary_field and not x): if isinstance(v, DateTimeProperty) and v.auto_now_add: x = v.now() elif (v.auto_add or (not v.auto and not v.auto_add)): x = v.default_value() else: x = v.get_value_for_datastore(self, cached=True) if x is not None and not x is Lazy: d[k] = x else: d = {} d[self._primary_field] = self._key for k, v in self.properties.items(): if fields and k not in fields: continue if v.property_type == 'compound': continue t = self._old_values.get(k, None) if not isinstance(v, ManyToMany): x = v.get_value_for_datastore(self) if isinstance(x, Model): x = x._key else: x = v.get_value_for_datastore(self, cached=True) if not x is Lazy: if (compare and t != self.field_str(x)) or not compare: d[k] = x return d
python
def _get_data(self, fields=None, compare=True): """ Get the changed property, it'll be used to save the object If compare is False, then it'll include all data not only changed property """ fields = fields or [] if self._key is None or self._key == '' or self._key == 0: d = {} for k, v in self.properties.items(): #test fields if fields and k not in fields: continue # if not isinstance(v, ManyToMany): if v.property_type == 'compound': continue if v.sequence: continue if not isinstance(v, ManyToMany): x = v.get_value_for_datastore(self) if isinstance(x, Model): x = x._key elif x is None or (k==self._primary_field and not x): if isinstance(v, DateTimeProperty) and v.auto_now_add: x = v.now() elif (v.auto_add or (not v.auto and not v.auto_add)): x = v.default_value() else: x = v.get_value_for_datastore(self, cached=True) if x is not None and not x is Lazy: d[k] = x else: d = {} d[self._primary_field] = self._key for k, v in self.properties.items(): if fields and k not in fields: continue if v.property_type == 'compound': continue t = self._old_values.get(k, None) if not isinstance(v, ManyToMany): x = v.get_value_for_datastore(self) if isinstance(x, Model): x = x._key else: x = v.get_value_for_datastore(self, cached=True) if not x is Lazy: if (compare and t != self.field_str(x)) or not compare: d[k] = x return d
[ "def", "_get_data", "(", "self", ",", "fields", "=", "None", ",", "compare", "=", "True", ")", ":", "fields", "=", "fields", "or", "[", "]", "if", "self", ".", "_key", "is", "None", "or", "self", ".", "_key", "==", "''", "or", "self", ".", "_key", "==", "0", ":", "d", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "properties", ".", "items", "(", ")", ":", "#test fields", "if", "fields", "and", "k", "not", "in", "fields", ":", "continue", "# if not isinstance(v, ManyToMany):", "if", "v", ".", "property_type", "==", "'compound'", ":", "continue", "if", "v", ".", "sequence", ":", "continue", "if", "not", "isinstance", "(", "v", ",", "ManyToMany", ")", ":", "x", "=", "v", ".", "get_value_for_datastore", "(", "self", ")", "if", "isinstance", "(", "x", ",", "Model", ")", ":", "x", "=", "x", ".", "_key", "elif", "x", "is", "None", "or", "(", "k", "==", "self", ".", "_primary_field", "and", "not", "x", ")", ":", "if", "isinstance", "(", "v", ",", "DateTimeProperty", ")", "and", "v", ".", "auto_now_add", ":", "x", "=", "v", ".", "now", "(", ")", "elif", "(", "v", ".", "auto_add", "or", "(", "not", "v", ".", "auto", "and", "not", "v", ".", "auto_add", ")", ")", ":", "x", "=", "v", ".", "default_value", "(", ")", "else", ":", "x", "=", "v", ".", "get_value_for_datastore", "(", "self", ",", "cached", "=", "True", ")", "if", "x", "is", "not", "None", "and", "not", "x", "is", "Lazy", ":", "d", "[", "k", "]", "=", "x", "else", ":", "d", "=", "{", "}", "d", "[", "self", ".", "_primary_field", "]", "=", "self", ".", "_key", "for", "k", ",", "v", "in", "self", ".", "properties", ".", "items", "(", ")", ":", "if", "fields", "and", "k", "not", "in", "fields", ":", "continue", "if", "v", ".", "property_type", "==", "'compound'", ":", "continue", "t", "=", "self", ".", "_old_values", ".", "get", "(", "k", ",", "None", ")", "if", "not", "isinstance", "(", "v", ",", "ManyToMany", ")", ":", "x", "=", "v", ".", "get_value_for_datastore", "(", "self", ")", "if", "isinstance", "(", "x", ",", "Model", ")", ":", "x", "=", "x", ".", "_key", "else", ":", "x", "=", "v", ".", "get_value_for_datastore", "(", "self", ",", "cached", "=", "True", ")", "if", "not", "x", "is", "Lazy", ":", "if", "(", "compare", "and", "t", "!=", "self", ".", "field_str", "(", "x", ")", ")", "or", "not", "compare", ":", "d", "[", "k", "]", "=", "x", "return", "d" ]
Get the changed property, it'll be used to save the object If compare is False, then it'll include all data not only changed property
[ "Get", "the", "changed", "property", "it", "ll", "be", "used", "to", "save", "the", "object", "If", "compare", "is", "False", "then", "it", "ll", "include", "all", "data", "not", "only", "changed", "property" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L3967-L4016
train
limodou/uliweb
uliweb/orm/__init__.py
Model.create_sql
def create_sql(self, insert=False, version=False, version_fieldname=None, fields=None, ec=None, compare=False): """ Create sql statement, do not process manytomany """ version_fieldname = version_fieldname or 'version' #fix when d is empty, orm will not insert record bug 2013/04/07 if not self._key or insert: d = self._get_data(fields, compare=compare) if d: return rawsql(self.table.insert().values(**d), ec or self.get_engine_name()) + ';' else: d = self._get_data(fields, compare=compare) _key = d.pop(self._primary_field) if d: _cond = self.table.c[self._primary_field] == self._key if version: version_field = self.table.c.get(version_fieldname) if version_field is None: raise KindError("version_fieldname %s is not existed in Model %s" % (version_fieldname, self.__class__.__name__)) _version_value = getattr(self, version_fieldname, 0) # setattr(self, version_fieldname, _version_value+1) d[version_fieldname] = _version_value+1 _cond = (version_field == _version_value) & _cond return rawsql(self.table.update(_cond).values(**d), ec or self.get_engine_name()) + ';' return ''
python
def create_sql(self, insert=False, version=False, version_fieldname=None, fields=None, ec=None, compare=False): """ Create sql statement, do not process manytomany """ version_fieldname = version_fieldname or 'version' #fix when d is empty, orm will not insert record bug 2013/04/07 if not self._key or insert: d = self._get_data(fields, compare=compare) if d: return rawsql(self.table.insert().values(**d), ec or self.get_engine_name()) + ';' else: d = self._get_data(fields, compare=compare) _key = d.pop(self._primary_field) if d: _cond = self.table.c[self._primary_field] == self._key if version: version_field = self.table.c.get(version_fieldname) if version_field is None: raise KindError("version_fieldname %s is not existed in Model %s" % (version_fieldname, self.__class__.__name__)) _version_value = getattr(self, version_fieldname, 0) # setattr(self, version_fieldname, _version_value+1) d[version_fieldname] = _version_value+1 _cond = (version_field == _version_value) & _cond return rawsql(self.table.update(_cond).values(**d), ec or self.get_engine_name()) + ';' return ''
[ "def", "create_sql", "(", "self", ",", "insert", "=", "False", ",", "version", "=", "False", ",", "version_fieldname", "=", "None", ",", "fields", "=", "None", ",", "ec", "=", "None", ",", "compare", "=", "False", ")", ":", "version_fieldname", "=", "version_fieldname", "or", "'version'", "#fix when d is empty, orm will not insert record bug 2013/04/07", "if", "not", "self", ".", "_key", "or", "insert", ":", "d", "=", "self", ".", "_get_data", "(", "fields", ",", "compare", "=", "compare", ")", "if", "d", ":", "return", "rawsql", "(", "self", ".", "table", ".", "insert", "(", ")", ".", "values", "(", "*", "*", "d", ")", ",", "ec", "or", "self", ".", "get_engine_name", "(", ")", ")", "+", "';'", "else", ":", "d", "=", "self", ".", "_get_data", "(", "fields", ",", "compare", "=", "compare", ")", "_key", "=", "d", ".", "pop", "(", "self", ".", "_primary_field", ")", "if", "d", ":", "_cond", "=", "self", ".", "table", ".", "c", "[", "self", ".", "_primary_field", "]", "==", "self", ".", "_key", "if", "version", ":", "version_field", "=", "self", ".", "table", ".", "c", ".", "get", "(", "version_fieldname", ")", "if", "version_field", "is", "None", ":", "raise", "KindError", "(", "\"version_fieldname %s is not existed in Model %s\"", "%", "(", "version_fieldname", ",", "self", ".", "__class__", ".", "__name__", ")", ")", "_version_value", "=", "getattr", "(", "self", ",", "version_fieldname", ",", "0", ")", "# setattr(self, version_fieldname, _version_value+1)", "d", "[", "version_fieldname", "]", "=", "_version_value", "+", "1", "_cond", "=", "(", "version_field", "==", "_version_value", ")", "&", "_cond", "return", "rawsql", "(", "self", ".", "table", ".", "update", "(", "_cond", ")", ".", "values", "(", "*", "*", "d", ")", ",", "ec", "or", "self", ".", "get_engine_name", "(", ")", ")", "+", "';'", "return", "''" ]
Create sql statement, do not process manytomany
[ "Create", "sql", "statement", "do", "not", "process", "manytomany" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L4202-L4231
train
limodou/uliweb
uliweb/orm/__init__.py
Model.get_collection_name
def get_collection_name(cls, from_class_name, collection_name=None, prefix=None): """ Get reference collection_name, if the collection_name is None then make sure the collection_name is not conflict, but if the collection_name is not None, then check if the collection_name is already exists, if existed then raise Exception. """ if not collection_name: collection_name = prefix + '_set' if hasattr(cls, collection_name): #if the xxx_set is already existed, then automatically #create unique collection_set id collection_name = prefix + '_set_' + str(cls._collection_set_id) cls._collection_set_id += 1 else: if collection_name in cls._collection_names: if cls._collection_names.get(collection_name) != from_class_name: raise DuplicatePropertyError("Model %s already has collection property %s" % (cls.__name__, collection_name)) #add property check if collection_name in cls.properties: raise DuplicatePropertyError("Model %s already has property %s" % (cls.__name__, collection_name)) return collection_name
python
def get_collection_name(cls, from_class_name, collection_name=None, prefix=None): """ Get reference collection_name, if the collection_name is None then make sure the collection_name is not conflict, but if the collection_name is not None, then check if the collection_name is already exists, if existed then raise Exception. """ if not collection_name: collection_name = prefix + '_set' if hasattr(cls, collection_name): #if the xxx_set is already existed, then automatically #create unique collection_set id collection_name = prefix + '_set_' + str(cls._collection_set_id) cls._collection_set_id += 1 else: if collection_name in cls._collection_names: if cls._collection_names.get(collection_name) != from_class_name: raise DuplicatePropertyError("Model %s already has collection property %s" % (cls.__name__, collection_name)) #add property check if collection_name in cls.properties: raise DuplicatePropertyError("Model %s already has property %s" % (cls.__name__, collection_name)) return collection_name
[ "def", "get_collection_name", "(", "cls", ",", "from_class_name", ",", "collection_name", "=", "None", ",", "prefix", "=", "None", ")", ":", "if", "not", "collection_name", ":", "collection_name", "=", "prefix", "+", "'_set'", "if", "hasattr", "(", "cls", ",", "collection_name", ")", ":", "#if the xxx_set is already existed, then automatically", "#create unique collection_set id", "collection_name", "=", "prefix", "+", "'_set_'", "+", "str", "(", "cls", ".", "_collection_set_id", ")", "cls", ".", "_collection_set_id", "+=", "1", "else", ":", "if", "collection_name", "in", "cls", ".", "_collection_names", ":", "if", "cls", ".", "_collection_names", ".", "get", "(", "collection_name", ")", "!=", "from_class_name", ":", "raise", "DuplicatePropertyError", "(", "\"Model %s already has collection property %s\"", "%", "(", "cls", ".", "__name__", ",", "collection_name", ")", ")", "#add property check", "if", "collection_name", "in", "cls", ".", "properties", ":", "raise", "DuplicatePropertyError", "(", "\"Model %s already has property %s\"", "%", "(", "cls", ".", "__name__", ",", "collection_name", ")", ")", "return", "collection_name" ]
Get reference collection_name, if the collection_name is None then make sure the collection_name is not conflict, but if the collection_name is not None, then check if the collection_name is already exists, if existed then raise Exception.
[ "Get", "reference", "collection_name", "if", "the", "collection_name", "is", "None", "then", "make", "sure", "the", "collection_name", "is", "not", "conflict", "but", "if", "the", "collection_name", "is", "not", "None", "then", "check", "if", "the", "collection_name", "is", "already", "exists", "if", "existed", "then", "raise", "Exception", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L4313-L4334
train
limodou/uliweb
uliweb/orm/__init__.py
Model._use
def _use(cls, ec): """ underly implement of use """ # class ConnectModel(cls): # pass ConnectModel = type(cls.__name__, (cls,), {}) ConnectModel.tablename = cls.tablename ConnectModel._base_class = cls if isinstance(ec, (str, unicode)): ConnectModel._engine_name = ec elif isinstance(ec, Session): ConnectModel._engine_name = ec.engine_name ConnectModel._connection = ec return ConnectModel
python
def _use(cls, ec): """ underly implement of use """ # class ConnectModel(cls): # pass ConnectModel = type(cls.__name__, (cls,), {}) ConnectModel.tablename = cls.tablename ConnectModel._base_class = cls if isinstance(ec, (str, unicode)): ConnectModel._engine_name = ec elif isinstance(ec, Session): ConnectModel._engine_name = ec.engine_name ConnectModel._connection = ec return ConnectModel
[ "def", "_use", "(", "cls", ",", "ec", ")", ":", "# class ConnectModel(cls):", "# pass", "ConnectModel", "=", "type", "(", "cls", ".", "__name__", ",", "(", "cls", ",", ")", ",", "{", "}", ")", "ConnectModel", ".", "tablename", "=", "cls", ".", "tablename", "ConnectModel", ".", "_base_class", "=", "cls", "if", "isinstance", "(", "ec", ",", "(", "str", ",", "unicode", ")", ")", ":", "ConnectModel", ".", "_engine_name", "=", "ec", "elif", "isinstance", "(", "ec", ",", "Session", ")", ":", "ConnectModel", ".", "_engine_name", "=", "ec", ".", "engine_name", "ConnectModel", ".", "_connection", "=", "ec", "return", "ConnectModel" ]
underly implement of use
[ "underly", "implement", "of", "use" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L4413-L4428
train
limodou/uliweb
uliweb/orm/__init__.py
Model.use
def use(cls, ec): """ use will duplicate a new Model class and bind ec ec is Engine name or Sesstion object """ if isinstance(ec, (str, unicode)): m = get_model(cls._alias, ec, signal=False) else: m = cls._use(ec) return m
python
def use(cls, ec): """ use will duplicate a new Model class and bind ec ec is Engine name or Sesstion object """ if isinstance(ec, (str, unicode)): m = get_model(cls._alias, ec, signal=False) else: m = cls._use(ec) return m
[ "def", "use", "(", "cls", ",", "ec", ")", ":", "if", "isinstance", "(", "ec", ",", "(", "str", ",", "unicode", ")", ")", ":", "m", "=", "get_model", "(", "cls", ".", "_alias", ",", "ec", ",", "signal", "=", "False", ")", "else", ":", "m", "=", "cls", ".", "_use", "(", "ec", ")", "return", "m" ]
use will duplicate a new Model class and bind ec ec is Engine name or Sesstion object
[ "use", "will", "duplicate", "a", "new", "Model", "class", "and", "bind", "ec", "ec", "is", "Engine", "name", "or", "Sesstion", "object" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L4431-L4442
train
limodou/uliweb
uliweb/orm/__init__.py
Model.get_tree
def get_tree(cls, *condition, **kwargs): """ parent is root parent value, default is None current is current value condition is extra condition for select root records mode is search method, value is 'wide' or 'deep' """ parent_field = kwargs.pop('parent_field', 'parent') parent = kwargs.pop('parent', None) parent_order_by = kwargs.pop('parent_order_by', None) current = kwargs.pop('current', None) order_by = kwargs.pop('order_by', None) id_field = kwargs.pop('id_field', 'id') mode = kwargs.pop('mode', 'wide') if mode not in ('wide', 'deep'): raise Exception("mode parameter should be 'wide' or 'deep', but '{}' found.".format(mode)) def _f(parent): query = cls.filter(cls.c[parent_field]==parent, *condition) if order_by is not None: query.order_by(order_by) for row in query: if mode == 'wide': yield row for _row in _f(getattr(row, id_field)): yield _row if mode == 'deep': yield row if current: query = cls.filter(cls.c[id_field]==current) else: if is_condition(parent): query = cls.filter(parent) else: query = cls.filter(cls.c[parent_field]==parent) if parent_order_by is not None: query.order_by(parent_order_by) for row in query: if mode == 'wide': yield row for r in _f(getattr(row, id_field)): yield r if mode == 'deep': yield row
python
def get_tree(cls, *condition, **kwargs): """ parent is root parent value, default is None current is current value condition is extra condition for select root records mode is search method, value is 'wide' or 'deep' """ parent_field = kwargs.pop('parent_field', 'parent') parent = kwargs.pop('parent', None) parent_order_by = kwargs.pop('parent_order_by', None) current = kwargs.pop('current', None) order_by = kwargs.pop('order_by', None) id_field = kwargs.pop('id_field', 'id') mode = kwargs.pop('mode', 'wide') if mode not in ('wide', 'deep'): raise Exception("mode parameter should be 'wide' or 'deep', but '{}' found.".format(mode)) def _f(parent): query = cls.filter(cls.c[parent_field]==parent, *condition) if order_by is not None: query.order_by(order_by) for row in query: if mode == 'wide': yield row for _row in _f(getattr(row, id_field)): yield _row if mode == 'deep': yield row if current: query = cls.filter(cls.c[id_field]==current) else: if is_condition(parent): query = cls.filter(parent) else: query = cls.filter(cls.c[parent_field]==parent) if parent_order_by is not None: query.order_by(parent_order_by) for row in query: if mode == 'wide': yield row for r in _f(getattr(row, id_field)): yield r if mode == 'deep': yield row
[ "def", "get_tree", "(", "cls", ",", "*", "condition", ",", "*", "*", "kwargs", ")", ":", "parent_field", "=", "kwargs", ".", "pop", "(", "'parent_field'", ",", "'parent'", ")", "parent", "=", "kwargs", ".", "pop", "(", "'parent'", ",", "None", ")", "parent_order_by", "=", "kwargs", ".", "pop", "(", "'parent_order_by'", ",", "None", ")", "current", "=", "kwargs", ".", "pop", "(", "'current'", ",", "None", ")", "order_by", "=", "kwargs", ".", "pop", "(", "'order_by'", ",", "None", ")", "id_field", "=", "kwargs", ".", "pop", "(", "'id_field'", ",", "'id'", ")", "mode", "=", "kwargs", ".", "pop", "(", "'mode'", ",", "'wide'", ")", "if", "mode", "not", "in", "(", "'wide'", ",", "'deep'", ")", ":", "raise", "Exception", "(", "\"mode parameter should be 'wide' or 'deep', but '{}' found.\"", ".", "format", "(", "mode", ")", ")", "def", "_f", "(", "parent", ")", ":", "query", "=", "cls", ".", "filter", "(", "cls", ".", "c", "[", "parent_field", "]", "==", "parent", ",", "*", "condition", ")", "if", "order_by", "is", "not", "None", ":", "query", ".", "order_by", "(", "order_by", ")", "for", "row", "in", "query", ":", "if", "mode", "==", "'wide'", ":", "yield", "row", "for", "_row", "in", "_f", "(", "getattr", "(", "row", ",", "id_field", ")", ")", ":", "yield", "_row", "if", "mode", "==", "'deep'", ":", "yield", "row", "if", "current", ":", "query", "=", "cls", ".", "filter", "(", "cls", ".", "c", "[", "id_field", "]", "==", "current", ")", "else", ":", "if", "is_condition", "(", "parent", ")", ":", "query", "=", "cls", ".", "filter", "(", "parent", ")", "else", ":", "query", "=", "cls", ".", "filter", "(", "cls", ".", "c", "[", "parent_field", "]", "==", "parent", ")", "if", "parent_order_by", "is", "not", "None", ":", "query", ".", "order_by", "(", "parent_order_by", ")", "for", "row", "in", "query", ":", "if", "mode", "==", "'wide'", ":", "yield", "row", "for", "r", "in", "_f", "(", "getattr", "(", "row", ",", "id_field", ")", ")", ":", "yield", "r", "if", "mode", "==", "'deep'", ":", "yield", "row" ]
parent is root parent value, default is None current is current value condition is extra condition for select root records mode is search method, value is 'wide' or 'deep'
[ "parent", "is", "root", "parent", "value", "default", "is", "None", "current", "is", "current", "value", "condition", "is", "extra", "condition", "for", "select", "root", "records", "mode", "is", "search", "method", "value", "is", "wide", "or", "deep" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L4628-L4672
train
limodou/uliweb
uliweb/orm/__init__.py
Model.refresh
def refresh(self, fields=None, **kwargs): """ Re get the instance of current id """ cond = self.c[self._primary_field]==self._key query = self.filter(cond, **kwargs) if not fields: fields = list(self.table.c) v = query.values_one(*fields) if not v: raise NotFound('Instance <{0}:{1}> can not be found'.format(self.tablename, self._key)) d = self._data_prepare(v.items()) self.update(**d) self.set_saved()
python
def refresh(self, fields=None, **kwargs): """ Re get the instance of current id """ cond = self.c[self._primary_field]==self._key query = self.filter(cond, **kwargs) if not fields: fields = list(self.table.c) v = query.values_one(*fields) if not v: raise NotFound('Instance <{0}:{1}> can not be found'.format(self.tablename, self._key)) d = self._data_prepare(v.items()) self.update(**d) self.set_saved()
[ "def", "refresh", "(", "self", ",", "fields", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cond", "=", "self", ".", "c", "[", "self", ".", "_primary_field", "]", "==", "self", ".", "_key", "query", "=", "self", ".", "filter", "(", "cond", ",", "*", "*", "kwargs", ")", "if", "not", "fields", ":", "fields", "=", "list", "(", "self", ".", "table", ".", "c", ")", "v", "=", "query", ".", "values_one", "(", "*", "fields", ")", "if", "not", "v", ":", "raise", "NotFound", "(", "'Instance <{0}:{1}> can not be found'", ".", "format", "(", "self", ".", "tablename", ",", "self", ".", "_key", ")", ")", "d", "=", "self", ".", "_data_prepare", "(", "v", ".", "items", "(", ")", ")", "self", ".", "update", "(", "*", "*", "d", ")", "self", ".", "set_saved", "(", ")" ]
Re get the instance of current id
[ "Re", "get", "the", "instance", "of", "current", "id" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L4744-L4759
train
limodou/uliweb
uliweb/orm/__init__.py
Model.dump
def dump(self, fields=None, exclude=None): """ Dump current object to dict, but the value is string for manytomany fields will not automatically be dumpped, only when they are given in fields parameter """ exclude = exclude or [] d = {} if fields and self._primary_field not in fields: fields = list(fields) fields.append(self._primary_field) for k, v in self.properties.items(): if ((not fields) or (k in fields)) and (not exclude or (k not in exclude)): if not isinstance(v, ManyToMany): t = v.get_value_for_datastore(self) if t is Lazy: self.refresh() t = v.get_value_for_datastore(self) if isinstance(t, Model): t = t._key d[k] = v.to_str(t) else: if fields: d[k] = ','.join([str(x) for x in getattr(self, v._lazy_value(), [])]) if self._primary_field and d and self._primary_field not in d: d[self._primary_field] = str(self._key) return d
python
def dump(self, fields=None, exclude=None): """ Dump current object to dict, but the value is string for manytomany fields will not automatically be dumpped, only when they are given in fields parameter """ exclude = exclude or [] d = {} if fields and self._primary_field not in fields: fields = list(fields) fields.append(self._primary_field) for k, v in self.properties.items(): if ((not fields) or (k in fields)) and (not exclude or (k not in exclude)): if not isinstance(v, ManyToMany): t = v.get_value_for_datastore(self) if t is Lazy: self.refresh() t = v.get_value_for_datastore(self) if isinstance(t, Model): t = t._key d[k] = v.to_str(t) else: if fields: d[k] = ','.join([str(x) for x in getattr(self, v._lazy_value(), [])]) if self._primary_field and d and self._primary_field not in d: d[self._primary_field] = str(self._key) return d
[ "def", "dump", "(", "self", ",", "fields", "=", "None", ",", "exclude", "=", "None", ")", ":", "exclude", "=", "exclude", "or", "[", "]", "d", "=", "{", "}", "if", "fields", "and", "self", ".", "_primary_field", "not", "in", "fields", ":", "fields", "=", "list", "(", "fields", ")", "fields", ".", "append", "(", "self", ".", "_primary_field", ")", "for", "k", ",", "v", "in", "self", ".", "properties", ".", "items", "(", ")", ":", "if", "(", "(", "not", "fields", ")", "or", "(", "k", "in", "fields", ")", ")", "and", "(", "not", "exclude", "or", "(", "k", "not", "in", "exclude", ")", ")", ":", "if", "not", "isinstance", "(", "v", ",", "ManyToMany", ")", ":", "t", "=", "v", ".", "get_value_for_datastore", "(", "self", ")", "if", "t", "is", "Lazy", ":", "self", ".", "refresh", "(", ")", "t", "=", "v", ".", "get_value_for_datastore", "(", "self", ")", "if", "isinstance", "(", "t", ",", "Model", ")", ":", "t", "=", "t", ".", "_key", "d", "[", "k", "]", "=", "v", ".", "to_str", "(", "t", ")", "else", ":", "if", "fields", ":", "d", "[", "k", "]", "=", "','", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "getattr", "(", "self", ",", "v", ".", "_lazy_value", "(", ")", ",", "[", "]", ")", "]", ")", "if", "self", ".", "_primary_field", "and", "d", "and", "self", ".", "_primary_field", "not", "in", "d", ":", "d", "[", "self", ".", "_primary_field", "]", "=", "str", "(", "self", ".", "_key", ")", "return", "d" ]
Dump current object to dict, but the value is string for manytomany fields will not automatically be dumpped, only when they are given in fields parameter
[ "Dump", "current", "object", "to", "dict", "but", "the", "value", "is", "string", "for", "manytomany", "fields", "will", "not", "automatically", "be", "dumpped", "only", "when", "they", "are", "given", "in", "fields", "parameter" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L4802-L4828
train
limodou/uliweb
uliweb/orm/__init__.py
Model.clear_relation
def clear_relation(cls): """ Clear relation properties for reference Model, such as OneToOne, Reference, ManyToMany """ for k, v in cls.properties.items(): if isinstance(v, ReferenceProperty): if hasattr(v, 'collection_name') and hasattr(v.reference_class, v.collection_name): delattr(v.reference_class, v.collection_name) if isinstance(v, OneToOne): #append to reference_class._onetoone del v.reference_class._onetoone[v.collection_name]
python
def clear_relation(cls): """ Clear relation properties for reference Model, such as OneToOne, Reference, ManyToMany """ for k, v in cls.properties.items(): if isinstance(v, ReferenceProperty): if hasattr(v, 'collection_name') and hasattr(v.reference_class, v.collection_name): delattr(v.reference_class, v.collection_name) if isinstance(v, OneToOne): #append to reference_class._onetoone del v.reference_class._onetoone[v.collection_name]
[ "def", "clear_relation", "(", "cls", ")", ":", "for", "k", ",", "v", "in", "cls", ".", "properties", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "ReferenceProperty", ")", ":", "if", "hasattr", "(", "v", ",", "'collection_name'", ")", "and", "hasattr", "(", "v", ".", "reference_class", ",", "v", ".", "collection_name", ")", ":", "delattr", "(", "v", ".", "reference_class", ",", "v", ".", "collection_name", ")", "if", "isinstance", "(", "v", ",", "OneToOne", ")", ":", "#append to reference_class._onetoone", "del", "v", ".", "reference_class", ".", "_onetoone", "[", "v", ".", "collection_name", "]" ]
Clear relation properties for reference Model, such as OneToOne, Reference, ManyToMany
[ "Clear", "relation", "properties", "for", "reference", "Model", "such", "as", "OneToOne", "Reference", "ManyToMany" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L4840-L4852
train
limodou/uliweb
uliweb/orm/__init__.py
Bulk.put
def put(self, _name, **values): """ Put data to cach, if reached size value, it'll execute at once. """ try: sql = self.sqles[_name] data = sql['data'] if sql['positional']: d = [values[k] for k, v in sql['fields'].items()] else: d = {v:values[k] for k, v in sql['fields'].items()} data.append(d) if self.size and len(data) >= self.size: do_(sql['raw_sql'], args=data) sql['data'] = [] except: if self.transcation: Rollback(self.engine) raise
python
def put(self, _name, **values): """ Put data to cach, if reached size value, it'll execute at once. """ try: sql = self.sqles[_name] data = sql['data'] if sql['positional']: d = [values[k] for k, v in sql['fields'].items()] else: d = {v:values[k] for k, v in sql['fields'].items()} data.append(d) if self.size and len(data) >= self.size: do_(sql['raw_sql'], args=data) sql['data'] = [] except: if self.transcation: Rollback(self.engine) raise
[ "def", "put", "(", "self", ",", "_name", ",", "*", "*", "values", ")", ":", "try", ":", "sql", "=", "self", ".", "sqles", "[", "_name", "]", "data", "=", "sql", "[", "'data'", "]", "if", "sql", "[", "'positional'", "]", ":", "d", "=", "[", "values", "[", "k", "]", "for", "k", ",", "v", "in", "sql", "[", "'fields'", "]", ".", "items", "(", ")", "]", "else", ":", "d", "=", "{", "v", ":", "values", "[", "k", "]", "for", "k", ",", "v", "in", "sql", "[", "'fields'", "]", ".", "items", "(", ")", "}", "data", ".", "append", "(", "d", ")", "if", "self", ".", "size", "and", "len", "(", "data", ")", ">=", "self", ".", "size", ":", "do_", "(", "sql", "[", "'raw_sql'", "]", ",", "args", "=", "data", ")", "sql", "[", "'data'", "]", "=", "[", "]", "except", ":", "if", "self", ".", "transcation", ":", "Rollback", "(", "self", ".", "engine", ")", "raise" ]
Put data to cach, if reached size value, it'll execute at once.
[ "Put", "data", "to", "cach", "if", "reached", "size", "value", "it", "ll", "execute", "at", "once", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/orm/__init__.py#L4931-L4949
train
limodou/uliweb
uliweb/contrib/secretkey/__init__.py
get_key
def get_key(keyfile=None): """ Read the key content from secret_file """ keyfile = keyfile or application_path(settings.SECRETKEY.SECRET_FILE) with file(keyfile, 'rb') as f: return f.read()
python
def get_key(keyfile=None): """ Read the key content from secret_file """ keyfile = keyfile or application_path(settings.SECRETKEY.SECRET_FILE) with file(keyfile, 'rb') as f: return f.read()
[ "def", "get_key", "(", "keyfile", "=", "None", ")", ":", "keyfile", "=", "keyfile", "or", "application_path", "(", "settings", ".", "SECRETKEY", ".", "SECRET_FILE", ")", "with", "file", "(", "keyfile", ",", "'rb'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
Read the key content from secret_file
[ "Read", "the", "key", "content", "from", "secret_file" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/secretkey/__init__.py#L34-L40
train
limodou/uliweb
uliweb/contrib/secretkey/__init__.py
get_cipher_key
def get_cipher_key(keyfile=None): """ Create key which will be used in des, because des need 8bytes chars """ _key = get_key(keyfile) _k = md5(_key).hexdigest() key = xor(_k[:8], _k[8:16], _k[16:24], _k[24:]) return key
python
def get_cipher_key(keyfile=None): """ Create key which will be used in des, because des need 8bytes chars """ _key = get_key(keyfile) _k = md5(_key).hexdigest() key = xor(_k[:8], _k[8:16], _k[16:24], _k[24:]) return key
[ "def", "get_cipher_key", "(", "keyfile", "=", "None", ")", ":", "_key", "=", "get_key", "(", "keyfile", ")", "_k", "=", "md5", "(", "_key", ")", ".", "hexdigest", "(", ")", "key", "=", "xor", "(", "_k", "[", ":", "8", "]", ",", "_k", "[", "8", ":", "16", "]", ",", "_k", "[", "16", ":", "24", "]", ",", "_k", "[", "24", ":", "]", ")", "return", "key" ]
Create key which will be used in des, because des need 8bytes chars
[ "Create", "key", "which", "will", "be", "used", "in", "des", "because", "des", "need", "8bytes", "chars" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/secretkey/__init__.py#L42-L49
train
limodou/uliweb
uliweb/lib/werkzeug/contrib/cache.py
BaseCache.set_many
def set_many(self, mapping, timeout=None): """Sets multiple keys and values from a mapping. :param mapping: a mapping with the keys/values to set. :param timeout: the cache timeout for the key (if not specified, it uses the default timeout). """ for key, value in _items(mapping): self.set(key, value, timeout)
python
def set_many(self, mapping, timeout=None): """Sets multiple keys and values from a mapping. :param mapping: a mapping with the keys/values to set. :param timeout: the cache timeout for the key (if not specified, it uses the default timeout). """ for key, value in _items(mapping): self.set(key, value, timeout)
[ "def", "set_many", "(", "self", ",", "mapping", ",", "timeout", "=", "None", ")", ":", "for", "key", ",", "value", "in", "_items", "(", "mapping", ")", ":", "self", ".", "set", "(", "key", ",", "value", ",", "timeout", ")" ]
Sets multiple keys and values from a mapping. :param mapping: a mapping with the keys/values to set. :param timeout: the cache timeout for the key (if not specified, it uses the default timeout).
[ "Sets", "multiple", "keys", "and", "values", "from", "a", "mapping", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/cache.py#L166-L174
train
limodou/uliweb
uliweb/lib/werkzeug/contrib/cache.py
BaseCache.dec
def dec(self, key, delta=1): """Decrements the value of a key by `delta`. If the key does not yet exist it is initialized with `-delta`. For supporting caches this is an atomic operation. :param key: the key to increment. :param delta: the delta to subtract. """ self.set(key, (self.get(key) or 0) - delta)
python
def dec(self, key, delta=1): """Decrements the value of a key by `delta`. If the key does not yet exist it is initialized with `-delta`. For supporting caches this is an atomic operation. :param key: the key to increment. :param delta: the delta to subtract. """ self.set(key, (self.get(key) or 0) - delta)
[ "def", "dec", "(", "self", ",", "key", ",", "delta", "=", "1", ")", ":", "self", ".", "set", "(", "key", ",", "(", "self", ".", "get", "(", "key", ")", "or", "0", ")", "-", "delta", ")" ]
Decrements the value of a key by `delta`. If the key does not yet exist it is initialized with `-delta`. For supporting caches this is an atomic operation. :param key: the key to increment. :param delta: the delta to subtract.
[ "Decrements", "the", "value", "of", "a", "key", "by", "delta", ".", "If", "the", "key", "does", "not", "yet", "exist", "it", "is", "initialized", "with", "-", "delta", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/cache.py#L202-L211
train
limodou/uliweb
uliweb/lib/werkzeug/contrib/cache.py
MemcachedCache.import_preferred_memcache_lib
def import_preferred_memcache_lib(self, servers): """Returns an initialized memcache client. Used by the constructor.""" try: import pylibmc except ImportError: pass else: return pylibmc.Client(servers) try: from google.appengine.api import memcache except ImportError: pass else: return memcache.Client() try: import memcache except ImportError: pass else: return memcache.Client(servers)
python
def import_preferred_memcache_lib(self, servers): """Returns an initialized memcache client. Used by the constructor.""" try: import pylibmc except ImportError: pass else: return pylibmc.Client(servers) try: from google.appengine.api import memcache except ImportError: pass else: return memcache.Client() try: import memcache except ImportError: pass else: return memcache.Client(servers)
[ "def", "import_preferred_memcache_lib", "(", "self", ",", "servers", ")", ":", "try", ":", "import", "pylibmc", "except", "ImportError", ":", "pass", "else", ":", "return", "pylibmc", ".", "Client", "(", "servers", ")", "try", ":", "from", "google", ".", "appengine", ".", "api", "import", "memcache", "except", "ImportError", ":", "pass", "else", ":", "return", "memcache", ".", "Client", "(", ")", "try", ":", "import", "memcache", "except", "ImportError", ":", "pass", "else", ":", "return", "memcache", ".", "Client", "(", "servers", ")" ]
Returns an initialized memcache client. Used by the constructor.
[ "Returns", "an", "initialized", "memcache", "client", ".", "Used", "by", "the", "constructor", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/cache.py#L420-L441
train
limodou/uliweb
uliweb/lib/werkzeug/contrib/cache.py
RedisCache.dump_object
def dump_object(self, value): """Dumps an object into a string for redis. By default it serializes integers as regular string and pickle dumps everything else. """ t = type(value) if t is int or t is long: return str(value) return '!' + pickle.dumps(value)
python
def dump_object(self, value): """Dumps an object into a string for redis. By default it serializes integers as regular string and pickle dumps everything else. """ t = type(value) if t is int or t is long: return str(value) return '!' + pickle.dumps(value)
[ "def", "dump_object", "(", "self", ",", "value", ")", ":", "t", "=", "type", "(", "value", ")", "if", "t", "is", "int", "or", "t", "is", "long", ":", "return", "str", "(", "value", ")", "return", "'!'", "+", "pickle", ".", "dumps", "(", "value", ")" ]
Dumps an object into a string for redis. By default it serializes integers as regular string and pickle dumps everything else.
[ "Dumps", "an", "object", "into", "a", "string", "for", "redis", ".", "By", "default", "it", "serializes", "integers", "as", "regular", "string", "and", "pickle", "dumps", "everything", "else", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/cache.py#L491-L498
train
limodou/uliweb
uliweb/utils/common.py
extract_dirs
def extract_dirs(mod, path, dst, verbose=False, exclude=None, exclude_ext=None, recursion=True, replace=True): """ mod name path mod path dst output directory resursion True will extract all sub module of mod """ default_exclude = ['.svn', '_svn', '.git'] default_exclude_ext = ['.pyc', '.pyo', '.bak', '.tmp'] exclude = exclude or [] exclude_ext = exclude_ext or [] # log = logging.getLogger('uliweb') if not os.path.exists(dst): os.makedirs(dst) if verbose: print 'Make directory %s' % dst for r in pkg.resource_listdir(mod, path): if r in exclude or r in default_exclude: continue fpath = os.path.join(path, r) if pkg.resource_isdir(mod, fpath): if recursion: extract_dirs(mod, fpath, os.path.join(dst, r), verbose, exclude, exclude_ext, recursion, replace) else: ext = os.path.splitext(fpath)[1] if ext in exclude_ext or ext in default_exclude_ext: continue extract_file(mod, fpath, dst, verbose, replace)
python
def extract_dirs(mod, path, dst, verbose=False, exclude=None, exclude_ext=None, recursion=True, replace=True): """ mod name path mod path dst output directory resursion True will extract all sub module of mod """ default_exclude = ['.svn', '_svn', '.git'] default_exclude_ext = ['.pyc', '.pyo', '.bak', '.tmp'] exclude = exclude or [] exclude_ext = exclude_ext or [] # log = logging.getLogger('uliweb') if not os.path.exists(dst): os.makedirs(dst) if verbose: print 'Make directory %s' % dst for r in pkg.resource_listdir(mod, path): if r in exclude or r in default_exclude: continue fpath = os.path.join(path, r) if pkg.resource_isdir(mod, fpath): if recursion: extract_dirs(mod, fpath, os.path.join(dst, r), verbose, exclude, exclude_ext, recursion, replace) else: ext = os.path.splitext(fpath)[1] if ext in exclude_ext or ext in default_exclude_ext: continue extract_file(mod, fpath, dst, verbose, replace)
[ "def", "extract_dirs", "(", "mod", ",", "path", ",", "dst", ",", "verbose", "=", "False", ",", "exclude", "=", "None", ",", "exclude_ext", "=", "None", ",", "recursion", "=", "True", ",", "replace", "=", "True", ")", ":", "default_exclude", "=", "[", "'.svn'", ",", "'_svn'", ",", "'.git'", "]", "default_exclude_ext", "=", "[", "'.pyc'", ",", "'.pyo'", ",", "'.bak'", ",", "'.tmp'", "]", "exclude", "=", "exclude", "or", "[", "]", "exclude_ext", "=", "exclude_ext", "or", "[", "]", "# log = logging.getLogger('uliweb')", "if", "not", "os", ".", "path", ".", "exists", "(", "dst", ")", ":", "os", ".", "makedirs", "(", "dst", ")", "if", "verbose", ":", "print", "'Make directory %s'", "%", "dst", "for", "r", "in", "pkg", ".", "resource_listdir", "(", "mod", ",", "path", ")", ":", "if", "r", "in", "exclude", "or", "r", "in", "default_exclude", ":", "continue", "fpath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "r", ")", "if", "pkg", ".", "resource_isdir", "(", "mod", ",", "fpath", ")", ":", "if", "recursion", ":", "extract_dirs", "(", "mod", ",", "fpath", ",", "os", ".", "path", ".", "join", "(", "dst", ",", "r", ")", ",", "verbose", ",", "exclude", ",", "exclude_ext", ",", "recursion", ",", "replace", ")", "else", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "fpath", ")", "[", "1", "]", "if", "ext", "in", "exclude_ext", "or", "ext", "in", "default_exclude_ext", ":", "continue", "extract_file", "(", "mod", ",", "fpath", ",", "dst", ",", "verbose", ",", "replace", ")" ]
mod name path mod path dst output directory resursion True will extract all sub module of mod
[ "mod", "name", "path", "mod", "path", "dst", "output", "directory", "resursion", "True", "will", "extract", "all", "sub", "module", "of", "mod" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/common.py#L110-L137
train
limodou/uliweb
uliweb/utils/common.py
walk_dirs
def walk_dirs(path, include=None, include_ext=None, exclude=None, exclude_ext=None, recursion=True, file_only=False, use_default_pattern=True, patterns=None): """ path directory path resursion True will extract all sub module of mod """ default_exclude = ['.svn', '_svn', '.git'] default_exclude_ext = ['.pyc', '.pyo', '.bak', '.tmp'] exclude = exclude or [] exclude_ext = exclude_ext or [] include_ext = include_ext or [] include = include or [] if not os.path.exists(path): raise StopIteration for r in os.listdir(path): if match(r, exclude) or (use_default_pattern and r in default_exclude): continue if include and r not in include: continue fpath = os.path.join(path, r) if os.path.isdir(fpath): if not file_only: if patterns and match(r, patterns): yield os.path.normpath(fpath).replace('\\', '/') if recursion: for f in walk_dirs(fpath, include, include_ext, exclude, exclude_ext, recursion, file_only, use_default_pattern, patterns): yield os.path.normpath(f).replace('\\', '/') else: ext = os.path.splitext(fpath)[1] if ext in exclude_ext or (use_default_pattern and ext in default_exclude_ext): continue if include_ext and ext not in include_ext: continue if patterns: if not match(r, patterns): continue yield os.path.normpath(fpath).replace('\\', '/')
python
def walk_dirs(path, include=None, include_ext=None, exclude=None, exclude_ext=None, recursion=True, file_only=False, use_default_pattern=True, patterns=None): """ path directory path resursion True will extract all sub module of mod """ default_exclude = ['.svn', '_svn', '.git'] default_exclude_ext = ['.pyc', '.pyo', '.bak', '.tmp'] exclude = exclude or [] exclude_ext = exclude_ext or [] include_ext = include_ext or [] include = include or [] if not os.path.exists(path): raise StopIteration for r in os.listdir(path): if match(r, exclude) or (use_default_pattern and r in default_exclude): continue if include and r not in include: continue fpath = os.path.join(path, r) if os.path.isdir(fpath): if not file_only: if patterns and match(r, patterns): yield os.path.normpath(fpath).replace('\\', '/') if recursion: for f in walk_dirs(fpath, include, include_ext, exclude, exclude_ext, recursion, file_only, use_default_pattern, patterns): yield os.path.normpath(f).replace('\\', '/') else: ext = os.path.splitext(fpath)[1] if ext in exclude_ext or (use_default_pattern and ext in default_exclude_ext): continue if include_ext and ext not in include_ext: continue if patterns: if not match(r, patterns): continue yield os.path.normpath(fpath).replace('\\', '/')
[ "def", "walk_dirs", "(", "path", ",", "include", "=", "None", ",", "include_ext", "=", "None", ",", "exclude", "=", "None", ",", "exclude_ext", "=", "None", ",", "recursion", "=", "True", ",", "file_only", "=", "False", ",", "use_default_pattern", "=", "True", ",", "patterns", "=", "None", ")", ":", "default_exclude", "=", "[", "'.svn'", ",", "'_svn'", ",", "'.git'", "]", "default_exclude_ext", "=", "[", "'.pyc'", ",", "'.pyo'", ",", "'.bak'", ",", "'.tmp'", "]", "exclude", "=", "exclude", "or", "[", "]", "exclude_ext", "=", "exclude_ext", "or", "[", "]", "include_ext", "=", "include_ext", "or", "[", "]", "include", "=", "include", "or", "[", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "StopIteration", "for", "r", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "match", "(", "r", ",", "exclude", ")", "or", "(", "use_default_pattern", "and", "r", "in", "default_exclude", ")", ":", "continue", "if", "include", "and", "r", "not", "in", "include", ":", "continue", "fpath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "r", ")", "if", "os", ".", "path", ".", "isdir", "(", "fpath", ")", ":", "if", "not", "file_only", ":", "if", "patterns", "and", "match", "(", "r", ",", "patterns", ")", ":", "yield", "os", ".", "path", ".", "normpath", "(", "fpath", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "if", "recursion", ":", "for", "f", "in", "walk_dirs", "(", "fpath", ",", "include", ",", "include_ext", ",", "exclude", ",", "exclude_ext", ",", "recursion", ",", "file_only", ",", "use_default_pattern", ",", "patterns", ")", ":", "yield", "os", ".", "path", ".", "normpath", "(", "f", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "else", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "fpath", ")", "[", "1", "]", "if", "ext", "in", "exclude_ext", "or", "(", "use_default_pattern", "and", "ext", "in", "default_exclude_ext", ")", ":", "continue", "if", "include_ext", "and", "ext", "not", "in", "include_ext", ":", "continue", "if", "patterns", ":", "if", "not", "match", "(", "r", ",", "patterns", ")", ":", "continue", "yield", "os", ".", "path", ".", "normpath", "(", "fpath", ")", ".", "replace", "(", "'\\\\'", ",", "'/'", ")" ]
path directory path resursion True will extract all sub module of mod
[ "path", "directory", "path", "resursion", "True", "will", "extract", "all", "sub", "module", "of", "mod" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/common.py#L147-L187
train
limodou/uliweb
uliweb/utils/common.py
camel_to_
def camel_to_(s): """ Convert CamelCase to camel_case """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
python
def camel_to_(s): """ Convert CamelCase to camel_case """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
[ "def", "camel_to_", "(", "s", ")", ":", "s1", "=", "re", ".", "sub", "(", "'(.)([A-Z][a-z]+)'", ",", "r'\\1_\\2'", ",", "s", ")", "return", "re", ".", "sub", "(", "'([a-z0-9])([A-Z])'", ",", "r'\\1_\\2'", ",", "s1", ")", ".", "lower", "(", ")" ]
Convert CamelCase to camel_case
[ "Convert", "CamelCase", "to", "camel_case" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/common.py#L605-L610
train
limodou/uliweb
uliweb/utils/common.py
application_path
def application_path(path): """ Join application project_dir and path """ from uliweb import application return os.path.join(application.project_dir, path)
python
def application_path(path): """ Join application project_dir and path """ from uliweb import application return os.path.join(application.project_dir, path)
[ "def", "application_path", "(", "path", ")", ":", "from", "uliweb", "import", "application", "return", "os", ".", "path", ".", "join", "(", "application", ".", "project_dir", ",", "path", ")" ]
Join application project_dir and path
[ "Join", "application", "project_dir", "and", "path" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/common.py#L612-L617
train
limodou/uliweb
uliweb/utils/common.py
get_uuid
def get_uuid(type=4): """ Get uuid value """ import uuid name = 'uuid'+str(type) u = getattr(uuid, name) return u().hex
python
def get_uuid(type=4): """ Get uuid value """ import uuid name = 'uuid'+str(type) u = getattr(uuid, name) return u().hex
[ "def", "get_uuid", "(", "type", "=", "4", ")", ":", "import", "uuid", "name", "=", "'uuid'", "+", "str", "(", "type", ")", "u", "=", "getattr", "(", "uuid", ",", "name", ")", "return", "u", "(", ")", ".", "hex" ]
Get uuid value
[ "Get", "uuid", "value" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/common.py#L619-L627
train
limodou/uliweb
uliweb/utils/common.py
request_url
def request_url(req=None): """ Get full url of a request """ from uliweb import request r = req or request if request: if r.query_string: return r.path + '?' + r.query_string else: return r.path else: return ''
python
def request_url(req=None): """ Get full url of a request """ from uliweb import request r = req or request if request: if r.query_string: return r.path + '?' + r.query_string else: return r.path else: return ''
[ "def", "request_url", "(", "req", "=", "None", ")", ":", "from", "uliweb", "import", "request", "r", "=", "req", "or", "request", "if", "request", ":", "if", "r", ".", "query_string", ":", "return", "r", ".", "path", "+", "'?'", "+", "r", ".", "query_string", "else", ":", "return", "r", ".", "path", "else", ":", "return", "''" ]
Get full url of a request
[ "Get", "full", "url", "of", "a", "request" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/common.py#L658-L671
train
limodou/uliweb
uliweb/utils/common.py
compare_dict
def compare_dict(da, db): """ Compare differencs from two dicts """ sa = set(da.items()) sb = set(db.items()) diff = sa & sb return dict(sa - diff), dict(sb - diff)
python
def compare_dict(da, db): """ Compare differencs from two dicts """ sa = set(da.items()) sb = set(db.items()) diff = sa & sb return dict(sa - diff), dict(sb - diff)
[ "def", "compare_dict", "(", "da", ",", "db", ")", ":", "sa", "=", "set", "(", "da", ".", "items", "(", ")", ")", "sb", "=", "set", "(", "db", ".", "items", "(", ")", ")", "diff", "=", "sa", "&", "sb", "return", "dict", "(", "sa", "-", "diff", ")", ",", "dict", "(", "sb", "-", "diff", ")" ]
Compare differencs from two dicts
[ "Compare", "differencs", "from", "two", "dicts" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/common.py#L711-L719
train
limodou/uliweb
uliweb/utils/common.py
get_configrable_object
def get_configrable_object(key, section, cls=None): """ if obj is a class, then check if the class is subclass of cls or it should be object path, and it'll be imported by import_attr """ from uliweb import UliwebError, settings import inspect if inspect.isclass(key) and cls and issubclass(key, cls): return key elif isinstance(key, (str, unicode)): path = settings[section].get(key) if path: _cls = import_attr(path) return _cls else: raise UliwebError("Can't find section name %s in settings" % section) else: raise UliwebError("Key %r should be subclass of %r object or string path format!" % (key, cls))
python
def get_configrable_object(key, section, cls=None): """ if obj is a class, then check if the class is subclass of cls or it should be object path, and it'll be imported by import_attr """ from uliweb import UliwebError, settings import inspect if inspect.isclass(key) and cls and issubclass(key, cls): return key elif isinstance(key, (str, unicode)): path = settings[section].get(key) if path: _cls = import_attr(path) return _cls else: raise UliwebError("Can't find section name %s in settings" % section) else: raise UliwebError("Key %r should be subclass of %r object or string path format!" % (key, cls))
[ "def", "get_configrable_object", "(", "key", ",", "section", ",", "cls", "=", "None", ")", ":", "from", "uliweb", "import", "UliwebError", ",", "settings", "import", "inspect", "if", "inspect", ".", "isclass", "(", "key", ")", "and", "cls", "and", "issubclass", "(", "key", ",", "cls", ")", ":", "return", "key", "elif", "isinstance", "(", "key", ",", "(", "str", ",", "unicode", ")", ")", ":", "path", "=", "settings", "[", "section", "]", ".", "get", "(", "key", ")", "if", "path", ":", "_cls", "=", "import_attr", "(", "path", ")", "return", "_cls", "else", ":", "raise", "UliwebError", "(", "\"Can't find section name %s in settings\"", "%", "section", ")", "else", ":", "raise", "UliwebError", "(", "\"Key %r should be subclass of %r object or string path format!\"", "%", "(", "key", ",", "cls", ")", ")" ]
if obj is a class, then check if the class is subclass of cls or it should be object path, and it'll be imported by import_attr
[ "if", "obj", "is", "a", "class", "then", "check", "if", "the", "class", "is", "subclass", "of", "cls", "or", "it", "should", "be", "object", "path", "and", "it", "ll", "be", "imported", "by", "import_attr" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/common.py#L824-L842
train
limodou/uliweb
uliweb/utils/common.py
convert_bytes
def convert_bytes(n): """ Convert a size number to 'K', 'M', .etc """ symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, s in enumerate(symbols): prefix[s] = 1 << (i + 1) * 10 for s in reversed(symbols): if n >= prefix[s]: value = float(n) / prefix[s] return '%.1f%s' % (value, s) return "%sB" % n
python
def convert_bytes(n): """ Convert a size number to 'K', 'M', .etc """ symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} for i, s in enumerate(symbols): prefix[s] = 1 << (i + 1) * 10 for s in reversed(symbols): if n >= prefix[s]: value = float(n) / prefix[s] return '%.1f%s' % (value, s) return "%sB" % n
[ "def", "convert_bytes", "(", "n", ")", ":", "symbols", "=", "(", "'K'", ",", "'M'", ",", "'G'", ",", "'T'", ",", "'P'", ",", "'E'", ",", "'Z'", ",", "'Y'", ")", "prefix", "=", "{", "}", "for", "i", ",", "s", "in", "enumerate", "(", "symbols", ")", ":", "prefix", "[", "s", "]", "=", "1", "<<", "(", "i", "+", "1", ")", "*", "10", "for", "s", "in", "reversed", "(", "symbols", ")", ":", "if", "n", ">=", "prefix", "[", "s", "]", ":", "value", "=", "float", "(", "n", ")", "/", "prefix", "[", "s", "]", "return", "'%.1f%s'", "%", "(", "value", ",", "s", ")", "return", "\"%sB\"", "%", "n" ]
Convert a size number to 'K', 'M', .etc
[ "Convert", "a", "size", "number", "to", "K", "M", ".", "etc" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/common.py#L868-L880
train
limodou/uliweb
uliweb/contrib/template/__init__.py
init_static_combine
def init_static_combine(): """ Process static combine, create md5 key according each static filename """ from uliweb import settings from hashlib import md5 import os d = {} if settings.get_var('STATIC_COMBINE_CONFIG/enable', False): for k, v in settings.get('STATIC_COMBINE', {}).items(): key = '_cmb_'+md5(''.join(v)).hexdigest()+os.path.splitext(v[0])[1] d[key] = v return d
python
def init_static_combine(): """ Process static combine, create md5 key according each static filename """ from uliweb import settings from hashlib import md5 import os d = {} if settings.get_var('STATIC_COMBINE_CONFIG/enable', False): for k, v in settings.get('STATIC_COMBINE', {}).items(): key = '_cmb_'+md5(''.join(v)).hexdigest()+os.path.splitext(v[0])[1] d[key] = v return d
[ "def", "init_static_combine", "(", ")", ":", "from", "uliweb", "import", "settings", "from", "hashlib", "import", "md5", "import", "os", "d", "=", "{", "}", "if", "settings", ".", "get_var", "(", "'STATIC_COMBINE_CONFIG/enable'", ",", "False", ")", ":", "for", "k", ",", "v", "in", "settings", ".", "get", "(", "'STATIC_COMBINE'", ",", "{", "}", ")", ".", "items", "(", ")", ":", "key", "=", "'_cmb_'", "+", "md5", "(", "''", ".", "join", "(", "v", ")", ")", ".", "hexdigest", "(", ")", "+", "os", ".", "path", ".", "splitext", "(", "v", "[", "0", "]", ")", "[", "1", "]", "d", "[", "key", "]", "=", "v", "return", "d" ]
Process static combine, create md5 key according each static filename
[ "Process", "static", "combine", "create", "md5", "key", "according", "each", "static", "filename" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/template/__init__.py#L9-L23
train
limodou/uliweb
uliweb/contrib/csrf/__init__.py
csrf_token
def csrf_token(): """ Get csrf token or create new one """ from uliweb import request, settings from uliweb.utils.common import safe_str v = {} token_name = settings.CSRF.cookie_token_name if not request.session.deleted and request.session.get(token_name): v = request.session[token_name] if time.time() >= v['created_time'] + v['expiry_time']: v = {} else: v['created_time'] = time.time() if not v: token = request.cookies.get(token_name) if not token: token = uuid.uuid4().get_hex() v = {'token':token, 'expiry_time':settings.CSRF.timeout, 'created_time':time.time()} if not request.session.deleted: request.session[token_name] = v return safe_str(v['token'])
python
def csrf_token(): """ Get csrf token or create new one """ from uliweb import request, settings from uliweb.utils.common import safe_str v = {} token_name = settings.CSRF.cookie_token_name if not request.session.deleted and request.session.get(token_name): v = request.session[token_name] if time.time() >= v['created_time'] + v['expiry_time']: v = {} else: v['created_time'] = time.time() if not v: token = request.cookies.get(token_name) if not token: token = uuid.uuid4().get_hex() v = {'token':token, 'expiry_time':settings.CSRF.timeout, 'created_time':time.time()} if not request.session.deleted: request.session[token_name] = v return safe_str(v['token'])
[ "def", "csrf_token", "(", ")", ":", "from", "uliweb", "import", "request", ",", "settings", "from", "uliweb", ".", "utils", ".", "common", "import", "safe_str", "v", "=", "{", "}", "token_name", "=", "settings", ".", "CSRF", ".", "cookie_token_name", "if", "not", "request", ".", "session", ".", "deleted", "and", "request", ".", "session", ".", "get", "(", "token_name", ")", ":", "v", "=", "request", ".", "session", "[", "token_name", "]", "if", "time", ".", "time", "(", ")", ">=", "v", "[", "'created_time'", "]", "+", "v", "[", "'expiry_time'", "]", ":", "v", "=", "{", "}", "else", ":", "v", "[", "'created_time'", "]", "=", "time", ".", "time", "(", ")", "if", "not", "v", ":", "token", "=", "request", ".", "cookies", ".", "get", "(", "token_name", ")", "if", "not", "token", ":", "token", "=", "uuid", ".", "uuid4", "(", ")", ".", "get_hex", "(", ")", "v", "=", "{", "'token'", ":", "token", ",", "'expiry_time'", ":", "settings", ".", "CSRF", ".", "timeout", ",", "'created_time'", ":", "time", ".", "time", "(", ")", "}", "if", "not", "request", ".", "session", ".", "deleted", ":", "request", ".", "session", "[", "token_name", "]", "=", "v", "return", "safe_str", "(", "v", "[", "'token'", "]", ")" ]
Get csrf token or create new one
[ "Get", "csrf", "token", "or", "create", "new", "one" ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/csrf/__init__.py#L5-L29
train
limodou/uliweb
uliweb/lib/werkzeug/contrib/wrappers.py
JSONRequestMixin.json
def json(self): """Get the result of simplejson.loads if possible.""" if 'json' not in self.environ.get('CONTENT_TYPE', ''): raise BadRequest('Not a JSON request') try: return loads(self.data) except Exception: raise BadRequest('Unable to read JSON request')
python
def json(self): """Get the result of simplejson.loads if possible.""" if 'json' not in self.environ.get('CONTENT_TYPE', ''): raise BadRequest('Not a JSON request') try: return loads(self.data) except Exception: raise BadRequest('Unable to read JSON request')
[ "def", "json", "(", "self", ")", ":", "if", "'json'", "not", "in", "self", ".", "environ", ".", "get", "(", "'CONTENT_TYPE'", ",", "''", ")", ":", "raise", "BadRequest", "(", "'Not a JSON request'", ")", "try", ":", "return", "loads", "(", "self", ".", "data", ")", "except", "Exception", ":", "raise", "BadRequest", "(", "'Unable to read JSON request'", ")" ]
Get the result of simplejson.loads if possible.
[ "Get", "the", "result", "of", "simplejson", ".", "loads", "if", "possible", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/wrappers.py#L53-L60
train
limodou/uliweb
uliweb/lib/werkzeug/contrib/wrappers.py
ProtobufRequestMixin.parse_protobuf
def parse_protobuf(self, proto_type): """Parse the data into an instance of proto_type.""" if 'protobuf' not in self.environ.get('CONTENT_TYPE', ''): raise BadRequest('Not a Protobuf request') obj = proto_type() try: obj.ParseFromString(self.data) except Exception: raise BadRequest("Unable to parse Protobuf request") # Fail if not all required fields are set if self.protobuf_check_initialization and not obj.IsInitialized(): raise BadRequest("Partial Protobuf request") return obj
python
def parse_protobuf(self, proto_type): """Parse the data into an instance of proto_type.""" if 'protobuf' not in self.environ.get('CONTENT_TYPE', ''): raise BadRequest('Not a Protobuf request') obj = proto_type() try: obj.ParseFromString(self.data) except Exception: raise BadRequest("Unable to parse Protobuf request") # Fail if not all required fields are set if self.protobuf_check_initialization and not obj.IsInitialized(): raise BadRequest("Partial Protobuf request") return obj
[ "def", "parse_protobuf", "(", "self", ",", "proto_type", ")", ":", "if", "'protobuf'", "not", "in", "self", ".", "environ", ".", "get", "(", "'CONTENT_TYPE'", ",", "''", ")", ":", "raise", "BadRequest", "(", "'Not a Protobuf request'", ")", "obj", "=", "proto_type", "(", ")", "try", ":", "obj", ".", "ParseFromString", "(", "self", ".", "data", ")", "except", "Exception", ":", "raise", "BadRequest", "(", "\"Unable to parse Protobuf request\"", ")", "# Fail if not all required fields are set", "if", "self", ".", "protobuf_check_initialization", "and", "not", "obj", ".", "IsInitialized", "(", ")", ":", "raise", "BadRequest", "(", "\"Partial Protobuf request\"", ")", "return", "obj" ]
Parse the data into an instance of proto_type.
[ "Parse", "the", "data", "into", "an", "instance", "of", "proto_type", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/wrappers.py#L79-L94
train
limodou/uliweb
uliweb/lib/werkzeug/contrib/wrappers.py
DynamicCharsetRequestMixin.charset
def charset(self): """The charset from the content type.""" header = self.environ.get('CONTENT_TYPE') if header: ct, options = parse_options_header(header) charset = options.get('charset') if charset: if is_known_charset(charset): return charset return self.unknown_charset(charset) return self.default_charset
python
def charset(self): """The charset from the content type.""" header = self.environ.get('CONTENT_TYPE') if header: ct, options = parse_options_header(header) charset = options.get('charset') if charset: if is_known_charset(charset): return charset return self.unknown_charset(charset) return self.default_charset
[ "def", "charset", "(", "self", ")", ":", "header", "=", "self", ".", "environ", ".", "get", "(", "'CONTENT_TYPE'", ")", "if", "header", ":", "ct", ",", "options", "=", "parse_options_header", "(", "header", ")", "charset", "=", "options", ".", "get", "(", "'charset'", ")", "if", "charset", ":", "if", "is_known_charset", "(", "charset", ")", ":", "return", "charset", "return", "self", ".", "unknown_charset", "(", "charset", ")", "return", "self", ".", "default_charset" ]
The charset from the content type.
[ "The", "charset", "from", "the", "content", "type", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/contrib/wrappers.py#L222-L232
train
limodou/uliweb
uliweb/core/template.py
utf8
def utf8(value): """Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. """ if isinstance(value, _UTF8_TYPES): return value elif isinstance(value, unicode_type): return value.encode("utf-8") else: return str(value)
python
def utf8(value): """Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. """ if isinstance(value, _UTF8_TYPES): return value elif isinstance(value, unicode_type): return value.encode("utf-8") else: return str(value)
[ "def", "utf8", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "_UTF8_TYPES", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "unicode_type", ")", ":", "return", "value", ".", "encode", "(", "\"utf-8\"", ")", "else", ":", "return", "str", "(", "value", ")" ]
Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8.
[ "Converts", "a", "string", "argument", "to", "a", "byte", "string", ".", "If", "the", "argument", "is", "already", "a", "byte", "string", "or", "None", "it", "is", "returned", "unchanged", ".", "Otherwise", "it", "must", "be", "a", "unicode", "string", "and", "is", "encoded", "as", "utf8", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/template.py#L249-L260
train
limodou/uliweb
uliweb/core/template.py
to_basestring
def to_basestring(value): """Converts a string argument to a subclass of basestring. In python2, byte and unicode strings are mostly interchangeable, so functions that deal with a user-supplied argument in combination with ascii string constants can use either and should return the type the user supplied. In python3, the two types are not interchangeable, so this method is needed to convert byte strings to unicode. """ if value is None: return 'None' if isinstance(value, _BASESTRING_TYPES): return value elif isinstance(value, unicode_type): return value.decode("utf-8") else: return str(value)
python
def to_basestring(value): """Converts a string argument to a subclass of basestring. In python2, byte and unicode strings are mostly interchangeable, so functions that deal with a user-supplied argument in combination with ascii string constants can use either and should return the type the user supplied. In python3, the two types are not interchangeable, so this method is needed to convert byte strings to unicode. """ if value is None: return 'None' if isinstance(value, _BASESTRING_TYPES): return value elif isinstance(value, unicode_type): return value.decode("utf-8") else: return str(value)
[ "def", "to_basestring", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "'None'", "if", "isinstance", "(", "value", ",", "_BASESTRING_TYPES", ")", ":", "return", "value", "elif", "isinstance", "(", "value", ",", "unicode_type", ")", ":", "return", "value", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "return", "str", "(", "value", ")" ]
Converts a string argument to a subclass of basestring. In python2, byte and unicode strings are mostly interchangeable, so functions that deal with a user-supplied argument in combination with ascii string constants can use either and should return the type the user supplied. In python3, the two types are not interchangeable, so this method is needed to convert byte strings to unicode.
[ "Converts", "a", "string", "argument", "to", "a", "subclass", "of", "basestring", ".", "In", "python2", "byte", "and", "unicode", "strings", "are", "mostly", "interchangeable", "so", "functions", "that", "deal", "with", "a", "user", "-", "supplied", "argument", "in", "combination", "with", "ascii", "string", "constants", "can", "use", "either", "and", "should", "return", "the", "type", "the", "user", "supplied", ".", "In", "python3", "the", "two", "types", "are", "not", "interchangeable", "so", "this", "method", "is", "needed", "to", "convert", "byte", "strings", "to", "unicode", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/template.py#L293-L309
train
limodou/uliweb
uliweb/core/template.py
LRUTmplatesCacheDict.clear
def clear(self): """ Clears the dict. """ self.__values.clear() self.__access_keys = [] self.__modified_times.clear()
python
def clear(self): """ Clears the dict. """ self.__values.clear() self.__access_keys = [] self.__modified_times.clear()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "__values", ".", "clear", "(", ")", "self", ".", "__access_keys", "=", "[", "]", "self", ".", "__modified_times", ".", "clear", "(", ")" ]
Clears the dict.
[ "Clears", "the", "dict", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/template.py#L677-L683
train
limodou/uliweb
uliweb/core/template.py
LRUTmplatesCacheDict.has
def has(self, key, mtime=None): """ This method should almost NEVER be used. The reason is that between the time has_key is called, and the key is accessed, the key might vanish. """ v = self.__values.get(key, None) if not v: return False if self.check_modified_time: mtime = self._get_mtime(key, mtime) if mtime != self.__modified_times[key]: del self[key] return False return True
python
def has(self, key, mtime=None): """ This method should almost NEVER be used. The reason is that between the time has_key is called, and the key is accessed, the key might vanish. """ v = self.__values.get(key, None) if not v: return False if self.check_modified_time: mtime = self._get_mtime(key, mtime) if mtime != self.__modified_times[key]: del self[key] return False return True
[ "def", "has", "(", "self", ",", "key", ",", "mtime", "=", "None", ")", ":", "v", "=", "self", ".", "__values", ".", "get", "(", "key", ",", "None", ")", "if", "not", "v", ":", "return", "False", "if", "self", ".", "check_modified_time", ":", "mtime", "=", "self", ".", "_get_mtime", "(", "key", ",", "mtime", ")", "if", "mtime", "!=", "self", ".", "__modified_times", "[", "key", "]", ":", "del", "self", "[", "key", "]", "return", "False", "return", "True" ]
This method should almost NEVER be used. The reason is that between the time has_key is called, and the key is accessed, the key might vanish.
[ "This", "method", "should", "almost", "NEVER", "be", "used", ".", "The", "reason", "is", "that", "between", "the", "time", "has_key", "is", "called", "and", "the", "key", "is", "accessed", "the", "key", "might", "vanish", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/template.py#L694-L708
train
limodou/uliweb
uliweb/core/template.py
Loader.reset
def reset(self): """Resets the cache of compiled templates.""" with self.lock: if self.cache: if self.use_tmp: shutil.rmtree(self.tmp_dir, ignore_errors=True) else: self.templates = {}
python
def reset(self): """Resets the cache of compiled templates.""" with self.lock: if self.cache: if self.use_tmp: shutil.rmtree(self.tmp_dir, ignore_errors=True) else: self.templates = {}
[ "def", "reset", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "cache", ":", "if", "self", ".", "use_tmp", ":", "shutil", ".", "rmtree", "(", "self", ".", "tmp_dir", ",", "ignore_errors", "=", "True", ")", "else", ":", "self", ".", "templates", "=", "{", "}" ]
Resets the cache of compiled templates.
[ "Resets", "the", "cache", "of", "compiled", "templates", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/core/template.py#L796-L803
train
limodou/uliweb
uliweb/contrib/rbac/rbac.py
has_role
def has_role(user, *roles, **kwargs): """ Judge is the user belongs to the role, and if does, then return the role object if not then return False. kwargs will be passed to role_func. """ Role = get_model('role') if isinstance(user, (unicode, str)): User = get_model('user') user = User.get(User.c.username==user) for role in roles: if isinstance(role, (str, unicode)): role = Role.get(Role.c.name==role) if not role: continue name = role.name func = __role_funcs__.get(name, None) if func: if isinstance(func, (unicode, str)): func = import_attr(func) assert callable(func) para = kwargs.copy() para['user'] = user flag = call_func(func, para) if flag: return role flag = role.users.has(user) if flag: return role flag = role.usergroups_has_user(user) if flag: return role return False
python
def has_role(user, *roles, **kwargs): """ Judge is the user belongs to the role, and if does, then return the role object if not then return False. kwargs will be passed to role_func. """ Role = get_model('role') if isinstance(user, (unicode, str)): User = get_model('user') user = User.get(User.c.username==user) for role in roles: if isinstance(role, (str, unicode)): role = Role.get(Role.c.name==role) if not role: continue name = role.name func = __role_funcs__.get(name, None) if func: if isinstance(func, (unicode, str)): func = import_attr(func) assert callable(func) para = kwargs.copy() para['user'] = user flag = call_func(func, para) if flag: return role flag = role.users.has(user) if flag: return role flag = role.usergroups_has_user(user) if flag: return role return False
[ "def", "has_role", "(", "user", ",", "*", "roles", ",", "*", "*", "kwargs", ")", ":", "Role", "=", "get_model", "(", "'role'", ")", "if", "isinstance", "(", "user", ",", "(", "unicode", ",", "str", ")", ")", ":", "User", "=", "get_model", "(", "'user'", ")", "user", "=", "User", ".", "get", "(", "User", ".", "c", ".", "username", "==", "user", ")", "for", "role", "in", "roles", ":", "if", "isinstance", "(", "role", ",", "(", "str", ",", "unicode", ")", ")", ":", "role", "=", "Role", ".", "get", "(", "Role", ".", "c", ".", "name", "==", "role", ")", "if", "not", "role", ":", "continue", "name", "=", "role", ".", "name", "func", "=", "__role_funcs__", ".", "get", "(", "name", ",", "None", ")", "if", "func", ":", "if", "isinstance", "(", "func", ",", "(", "unicode", ",", "str", ")", ")", ":", "func", "=", "import_attr", "(", "func", ")", "assert", "callable", "(", "func", ")", "para", "=", "kwargs", ".", "copy", "(", ")", "para", "[", "'user'", "]", "=", "user", "flag", "=", "call_func", "(", "func", ",", "para", ")", "if", "flag", ":", "return", "role", "flag", "=", "role", ".", "users", ".", "has", "(", "user", ")", "if", "flag", ":", "return", "role", "flag", "=", "role", ".", "usergroups_has_user", "(", "user", ")", "if", "flag", ":", "return", "role", "return", "False" ]
Judge is the user belongs to the role, and if does, then return the role object if not then return False. kwargs will be passed to role_func.
[ "Judge", "is", "the", "user", "belongs", "to", "the", "role", "and", "if", "does", "then", "return", "the", "role", "object", "if", "not", "then", "return", "False", ".", "kwargs", "will", "be", "passed", "to", "role_func", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/rbac/rbac.py#L42-L78
train
limodou/uliweb
uliweb/contrib/rbac/rbac.py
has_permission
def has_permission(user, *permissions, **role_kwargs): """ Judge if an user has permission, and if it does return role object, and if it doesn't return False. role_kwargs will be passed to role functions. With role object, you can use role.relation to get Role_Perm_Rel object. """ Role = get_model('role') Perm = get_model('permission') if isinstance(user, (unicode, str)): User = get_model('user') user = User.get(User.c.username==user) for name in permissions: perm = Perm.get(Perm.c.name==name) if not perm: continue flag = has_role(user, *list(perm.perm_roles.with_relation().all()), **role_kwargs) if flag: return flag return False
python
def has_permission(user, *permissions, **role_kwargs): """ Judge if an user has permission, and if it does return role object, and if it doesn't return False. role_kwargs will be passed to role functions. With role object, you can use role.relation to get Role_Perm_Rel object. """ Role = get_model('role') Perm = get_model('permission') if isinstance(user, (unicode, str)): User = get_model('user') user = User.get(User.c.username==user) for name in permissions: perm = Perm.get(Perm.c.name==name) if not perm: continue flag = has_role(user, *list(perm.perm_roles.with_relation().all()), **role_kwargs) if flag: return flag return False
[ "def", "has_permission", "(", "user", ",", "*", "permissions", ",", "*", "*", "role_kwargs", ")", ":", "Role", "=", "get_model", "(", "'role'", ")", "Perm", "=", "get_model", "(", "'permission'", ")", "if", "isinstance", "(", "user", ",", "(", "unicode", ",", "str", ")", ")", ":", "User", "=", "get_model", "(", "'user'", ")", "user", "=", "User", ".", "get", "(", "User", ".", "c", ".", "username", "==", "user", ")", "for", "name", "in", "permissions", ":", "perm", "=", "Perm", ".", "get", "(", "Perm", ".", "c", ".", "name", "==", "name", ")", "if", "not", "perm", ":", "continue", "flag", "=", "has_role", "(", "user", ",", "*", "list", "(", "perm", ".", "perm_roles", ".", "with_relation", "(", ")", ".", "all", "(", ")", ")", ",", "*", "*", "role_kwargs", ")", "if", "flag", ":", "return", "flag", "return", "False" ]
Judge if an user has permission, and if it does return role object, and if it doesn't return False. role_kwargs will be passed to role functions. With role object, you can use role.relation to get Role_Perm_Rel object.
[ "Judge", "if", "an", "user", "has", "permission", "and", "if", "it", "does", "return", "role", "object", "and", "if", "it", "doesn", "t", "return", "False", ".", "role_kwargs", "will", "be", "passed", "to", "role", "functions", ".", "With", "role", "object", "you", "can", "use", "role", ".", "relation", "to", "get", "Role_Perm_Rel", "object", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/contrib/rbac/rbac.py#L80-L101
train
limodou/uliweb
uliweb/lib/werkzeug/serving.py
load_ssl_context
def load_ssl_context(cert_file, pkey_file): """Loads an SSL context from a certificate and private key file.""" from OpenSSL import SSL ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.use_certificate_file(cert_file) ctx.use_privatekey_file(pkey_file) return ctx
python
def load_ssl_context(cert_file, pkey_file): """Loads an SSL context from a certificate and private key file.""" from OpenSSL import SSL ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.use_certificate_file(cert_file) ctx.use_privatekey_file(pkey_file) return ctx
[ "def", "load_ssl_context", "(", "cert_file", ",", "pkey_file", ")", ":", "from", "OpenSSL", "import", "SSL", "ctx", "=", "SSL", ".", "Context", "(", "SSL", ".", "SSLv23_METHOD", ")", "ctx", ".", "use_certificate_file", "(", "cert_file", ")", "ctx", ".", "use_privatekey_file", "(", "pkey_file", ")", "return", "ctx" ]
Loads an SSL context from a certificate and private key file.
[ "Loads", "an", "SSL", "context", "from", "a", "certificate", "and", "private", "key", "file", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/serving.py#L344-L350
train
limodou/uliweb
uliweb/lib/werkzeug/serving.py
select_ip_version
def select_ip_version(host, port): """Returns AF_INET4 or AF_INET6 depending on where to connect to.""" # disabled due to problems with current ipv6 implementations # and various operating systems. Probably this code also is # not supposed to work, but I can't come up with any other # ways to implement this. ##try: ## info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, ## socket.SOCK_STREAM, 0, ## socket.AI_PASSIVE) ## if info: ## return info[0][0] ##except socket.gaierror: ## pass if ':' in host and hasattr(socket, 'AF_INET6'): return socket.AF_INET6 return socket.AF_INET
python
def select_ip_version(host, port): """Returns AF_INET4 or AF_INET6 depending on where to connect to.""" # disabled due to problems with current ipv6 implementations # and various operating systems. Probably this code also is # not supposed to work, but I can't come up with any other # ways to implement this. ##try: ## info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, ## socket.SOCK_STREAM, 0, ## socket.AI_PASSIVE) ## if info: ## return info[0][0] ##except socket.gaierror: ## pass if ':' in host and hasattr(socket, 'AF_INET6'): return socket.AF_INET6 return socket.AF_INET
[ "def", "select_ip_version", "(", "host", ",", "port", ")", ":", "# disabled due to problems with current ipv6 implementations", "# and various operating systems. Probably this code also is", "# not supposed to work, but I can't come up with any other", "# ways to implement this.", "##try:", "## info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,", "## socket.SOCK_STREAM, 0,", "## socket.AI_PASSIVE)", "## if info:", "## return info[0][0]", "##except socket.gaierror:", "## pass", "if", "':'", "in", "host", "and", "hasattr", "(", "socket", ",", "'AF_INET6'", ")", ":", "return", "socket", ".", "AF_INET6", "return", "socket", ".", "AF_INET" ]
Returns AF_INET4 or AF_INET6 depending on where to connect to.
[ "Returns", "AF_INET4", "or", "AF_INET6", "depending", "on", "where", "to", "connect", "to", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/serving.py#L380-L396
train
limodou/uliweb
uliweb/lib/werkzeug/serving.py
make_server
def make_server(host, port, app=None, threaded=False, processes=1, request_handler=None, passthrough_errors=False, ssl_context=None): """Create a new server instance that is either threaded, or forks or just processes one request after another. """ if threaded and processes > 1: raise ValueError("cannot have a multithreaded and " "multi process server.") elif threaded: return ThreadedWSGIServer(host, port, app, request_handler, passthrough_errors, ssl_context) elif processes > 1: return ForkingWSGIServer(host, port, app, processes, request_handler, passthrough_errors, ssl_context) else: return BaseWSGIServer(host, port, app, request_handler, passthrough_errors, ssl_context)
python
def make_server(host, port, app=None, threaded=False, processes=1, request_handler=None, passthrough_errors=False, ssl_context=None): """Create a new server instance that is either threaded, or forks or just processes one request after another. """ if threaded and processes > 1: raise ValueError("cannot have a multithreaded and " "multi process server.") elif threaded: return ThreadedWSGIServer(host, port, app, request_handler, passthrough_errors, ssl_context) elif processes > 1: return ForkingWSGIServer(host, port, app, processes, request_handler, passthrough_errors, ssl_context) else: return BaseWSGIServer(host, port, app, request_handler, passthrough_errors, ssl_context)
[ "def", "make_server", "(", "host", ",", "port", ",", "app", "=", "None", ",", "threaded", "=", "False", ",", "processes", "=", "1", ",", "request_handler", "=", "None", ",", "passthrough_errors", "=", "False", ",", "ssl_context", "=", "None", ")", ":", "if", "threaded", "and", "processes", ">", "1", ":", "raise", "ValueError", "(", "\"cannot have a multithreaded and \"", "\"multi process server.\"", ")", "elif", "threaded", ":", "return", "ThreadedWSGIServer", "(", "host", ",", "port", ",", "app", ",", "request_handler", ",", "passthrough_errors", ",", "ssl_context", ")", "elif", "processes", ">", "1", ":", "return", "ForkingWSGIServer", "(", "host", ",", "port", ",", "app", ",", "processes", ",", "request_handler", ",", "passthrough_errors", ",", "ssl_context", ")", "else", ":", "return", "BaseWSGIServer", "(", "host", ",", "port", ",", "app", ",", "request_handler", ",", "passthrough_errors", ",", "ssl_context", ")" ]
Create a new server instance that is either threaded, or forks or just processes one request after another.
[ "Create", "a", "new", "server", "instance", "that", "is", "either", "threaded", "or", "forks", "or", "just", "processes", "one", "request", "after", "another", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/serving.py#L469-L486
train
limodou/uliweb
uliweb/lib/werkzeug/serving.py
_reloader_stat_loop
def _reloader_stat_loop(extra_files=None, interval=1): """When this function is run from the main thread, it will force other threads to exit when any modules currently loaded change. Copyright notice. This function is based on the autoreload.py from the CherryPy trac which originated from WSGIKit which is now dead. :param extra_files: a list of additional files it should watch. """ from itertools import chain mtimes = {} while 1: for filename in chain(_iter_module_files(), extra_files or ()): try: mtime = os.stat(filename).st_mtime except OSError: continue old_time = mtimes.get(filename) if old_time is None: mtimes[filename] = mtime continue elif mtime > old_time: _log('info', ' * Detected change in %r, reloading' % filename) sys.exit(3) time.sleep(interval)
python
def _reloader_stat_loop(extra_files=None, interval=1): """When this function is run from the main thread, it will force other threads to exit when any modules currently loaded change. Copyright notice. This function is based on the autoreload.py from the CherryPy trac which originated from WSGIKit which is now dead. :param extra_files: a list of additional files it should watch. """ from itertools import chain mtimes = {} while 1: for filename in chain(_iter_module_files(), extra_files or ()): try: mtime = os.stat(filename).st_mtime except OSError: continue old_time = mtimes.get(filename) if old_time is None: mtimes[filename] = mtime continue elif mtime > old_time: _log('info', ' * Detected change in %r, reloading' % filename) sys.exit(3) time.sleep(interval)
[ "def", "_reloader_stat_loop", "(", "extra_files", "=", "None", ",", "interval", "=", "1", ")", ":", "from", "itertools", "import", "chain", "mtimes", "=", "{", "}", "while", "1", ":", "for", "filename", "in", "chain", "(", "_iter_module_files", "(", ")", ",", "extra_files", "or", "(", ")", ")", ":", "try", ":", "mtime", "=", "os", ".", "stat", "(", "filename", ")", ".", "st_mtime", "except", "OSError", ":", "continue", "old_time", "=", "mtimes", ".", "get", "(", "filename", ")", "if", "old_time", "is", "None", ":", "mtimes", "[", "filename", "]", "=", "mtime", "continue", "elif", "mtime", ">", "old_time", ":", "_log", "(", "'info'", ",", "' * Detected change in %r, reloading'", "%", "filename", ")", "sys", ".", "exit", "(", "3", ")", "time", ".", "sleep", "(", "interval", ")" ]
When this function is run from the main thread, it will force other threads to exit when any modules currently loaded change. Copyright notice. This function is based on the autoreload.py from the CherryPy trac which originated from WSGIKit which is now dead. :param extra_files: a list of additional files it should watch.
[ "When", "this", "function", "is", "run", "from", "the", "main", "thread", "it", "will", "force", "other", "threads", "to", "exit", "when", "any", "modules", "currently", "loaded", "change", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/serving.py#L507-L532
train
limodou/uliweb
uliweb/lib/werkzeug/serving.py
run_simple
def run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, ssl_context=None): """Start an application using wsgiref and with an optional reloader. This wraps `wsgiref` to fix the wrong default reporting of the multithreaded WSGI variable and adds optional multithreading and fork support. This function has a command-line interface too:: python -m werkzeug.serving --help .. versionadded:: 0.5 `static_files` was added to simplify serving of static files as well as `passthrough_errors`. .. versionadded:: 0.6 support for SSL was added. .. versionadded:: 0.8 Added support for automatically loading a SSL context from certificate file and private key. .. versionadded:: 0.9 Added command-line interface. :param hostname: The host for the application. eg: ``'localhost'`` :param port: The port for the server. eg: ``8080`` :param application: the WSGI application to execute :param use_reloader: should the server automatically restart the python process if modules were changed? :param use_debugger: should the werkzeug debugging system be used? :param use_evalex: should the exception evaluation feature be enabled? :param extra_files: a list of files the reloader should watch additionally to the modules. For example configuration files. :param reloader_interval: the interval for the reloader in seconds. :param threaded: should the process handle each request in a separate thread? :param processes: if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes. :param request_handler: optional parameter that can be used to replace the default one. You can use this to replace it with a different :class:`~BaseHTTPServer.BaseHTTPRequestHandler` subclass. :param static_files: a dict of paths for static files. This works exactly like :class:`SharedDataMiddleware`, it's actually just wrapping the application in that middleware before serving. :param passthrough_errors: set this to `True` to disable the error catching. This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc.) :param ssl_context: an SSL context for the connection. Either an OpenSSL context, a tuple in the form ``(cert_file, pkey_file)``, the string ``'adhoc'`` if the server should automatically create one, or `None` to disable SSL (which is the default). """ if use_debugger: from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, use_evalex) if static_files: from werkzeug.wsgi import SharedDataMiddleware application = SharedDataMiddleware(application, static_files) def inner(): make_server(hostname, port, application, threaded, processes, request_handler, passthrough_errors, ssl_context).serve_forever() if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': display_hostname = hostname != '*' and hostname or 'localhost' if ':' in display_hostname: display_hostname = '[%s]' % display_hostname _log('info', ' * Running on %s://%s:%d/', ssl_context is None and 'http' or 'https', display_hostname, port) if use_reloader: # Create and destroy a socket so that any exceptions are raised before # we spawn a separate Python interpreter and lose this ability. address_family = select_ip_version(hostname, port) test_socket = socket.socket(address_family, socket.SOCK_STREAM) test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) test_socket.bind((hostname, port)) test_socket.close() run_with_reloader(inner, extra_files, reloader_interval) else: inner()
python
def run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, ssl_context=None): """Start an application using wsgiref and with an optional reloader. This wraps `wsgiref` to fix the wrong default reporting of the multithreaded WSGI variable and adds optional multithreading and fork support. This function has a command-line interface too:: python -m werkzeug.serving --help .. versionadded:: 0.5 `static_files` was added to simplify serving of static files as well as `passthrough_errors`. .. versionadded:: 0.6 support for SSL was added. .. versionadded:: 0.8 Added support for automatically loading a SSL context from certificate file and private key. .. versionadded:: 0.9 Added command-line interface. :param hostname: The host for the application. eg: ``'localhost'`` :param port: The port for the server. eg: ``8080`` :param application: the WSGI application to execute :param use_reloader: should the server automatically restart the python process if modules were changed? :param use_debugger: should the werkzeug debugging system be used? :param use_evalex: should the exception evaluation feature be enabled? :param extra_files: a list of files the reloader should watch additionally to the modules. For example configuration files. :param reloader_interval: the interval for the reloader in seconds. :param threaded: should the process handle each request in a separate thread? :param processes: if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes. :param request_handler: optional parameter that can be used to replace the default one. You can use this to replace it with a different :class:`~BaseHTTPServer.BaseHTTPRequestHandler` subclass. :param static_files: a dict of paths for static files. This works exactly like :class:`SharedDataMiddleware`, it's actually just wrapping the application in that middleware before serving. :param passthrough_errors: set this to `True` to disable the error catching. This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc.) :param ssl_context: an SSL context for the connection. Either an OpenSSL context, a tuple in the form ``(cert_file, pkey_file)``, the string ``'adhoc'`` if the server should automatically create one, or `None` to disable SSL (which is the default). """ if use_debugger: from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, use_evalex) if static_files: from werkzeug.wsgi import SharedDataMiddleware application = SharedDataMiddleware(application, static_files) def inner(): make_server(hostname, port, application, threaded, processes, request_handler, passthrough_errors, ssl_context).serve_forever() if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': display_hostname = hostname != '*' and hostname or 'localhost' if ':' in display_hostname: display_hostname = '[%s]' % display_hostname _log('info', ' * Running on %s://%s:%d/', ssl_context is None and 'http' or 'https', display_hostname, port) if use_reloader: # Create and destroy a socket so that any exceptions are raised before # we spawn a separate Python interpreter and lose this ability. address_family = select_ip_version(hostname, port) test_socket = socket.socket(address_family, socket.SOCK_STREAM) test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) test_socket.bind((hostname, port)) test_socket.close() run_with_reloader(inner, extra_files, reloader_interval) else: inner()
[ "def", "run_simple", "(", "hostname", ",", "port", ",", "application", ",", "use_reloader", "=", "False", ",", "use_debugger", "=", "False", ",", "use_evalex", "=", "True", ",", "extra_files", "=", "None", ",", "reloader_interval", "=", "1", ",", "threaded", "=", "False", ",", "processes", "=", "1", ",", "request_handler", "=", "None", ",", "static_files", "=", "None", ",", "passthrough_errors", "=", "False", ",", "ssl_context", "=", "None", ")", ":", "if", "use_debugger", ":", "from", "werkzeug", ".", "debug", "import", "DebuggedApplication", "application", "=", "DebuggedApplication", "(", "application", ",", "use_evalex", ")", "if", "static_files", ":", "from", "werkzeug", ".", "wsgi", "import", "SharedDataMiddleware", "application", "=", "SharedDataMiddleware", "(", "application", ",", "static_files", ")", "def", "inner", "(", ")", ":", "make_server", "(", "hostname", ",", "port", ",", "application", ",", "threaded", ",", "processes", ",", "request_handler", ",", "passthrough_errors", ",", "ssl_context", ")", ".", "serve_forever", "(", ")", "if", "os", ".", "environ", ".", "get", "(", "'WERKZEUG_RUN_MAIN'", ")", "!=", "'true'", ":", "display_hostname", "=", "hostname", "!=", "'*'", "and", "hostname", "or", "'localhost'", "if", "':'", "in", "display_hostname", ":", "display_hostname", "=", "'[%s]'", "%", "display_hostname", "_log", "(", "'info'", ",", "' * Running on %s://%s:%d/'", ",", "ssl_context", "is", "None", "and", "'http'", "or", "'https'", ",", "display_hostname", ",", "port", ")", "if", "use_reloader", ":", "# Create and destroy a socket so that any exceptions are raised before", "# we spawn a separate Python interpreter and lose this ability.", "address_family", "=", "select_ip_version", "(", "hostname", ",", "port", ")", "test_socket", "=", "socket", ".", "socket", "(", "address_family", ",", "socket", ".", "SOCK_STREAM", ")", "test_socket", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_REUSEADDR", ",", "1", ")", "test_socket", ".", "bind", "(", "(", "hostname", ",", "port", ")", ")", "test_socket", ".", "close", "(", ")", "run_with_reloader", "(", "inner", ",", "extra_files", ",", "reloader_interval", ")", "else", ":", "inner", "(", ")" ]
Start an application using wsgiref and with an optional reloader. This wraps `wsgiref` to fix the wrong default reporting of the multithreaded WSGI variable and adds optional multithreading and fork support. This function has a command-line interface too:: python -m werkzeug.serving --help .. versionadded:: 0.5 `static_files` was added to simplify serving of static files as well as `passthrough_errors`. .. versionadded:: 0.6 support for SSL was added. .. versionadded:: 0.8 Added support for automatically loading a SSL context from certificate file and private key. .. versionadded:: 0.9 Added command-line interface. :param hostname: The host for the application. eg: ``'localhost'`` :param port: The port for the server. eg: ``8080`` :param application: the WSGI application to execute :param use_reloader: should the server automatically restart the python process if modules were changed? :param use_debugger: should the werkzeug debugging system be used? :param use_evalex: should the exception evaluation feature be enabled? :param extra_files: a list of files the reloader should watch additionally to the modules. For example configuration files. :param reloader_interval: the interval for the reloader in seconds. :param threaded: should the process handle each request in a separate thread? :param processes: if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes. :param request_handler: optional parameter that can be used to replace the default one. You can use this to replace it with a different :class:`~BaseHTTPServer.BaseHTTPRequestHandler` subclass. :param static_files: a dict of paths for static files. This works exactly like :class:`SharedDataMiddleware`, it's actually just wrapping the application in that middleware before serving. :param passthrough_errors: set this to `True` to disable the error catching. This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc.) :param ssl_context: an SSL context for the connection. Either an OpenSSL context, a tuple in the form ``(cert_file, pkey_file)``, the string ``'adhoc'`` if the server should automatically create one, or `None` to disable SSL (which is the default).
[ "Start", "an", "application", "using", "wsgiref", "and", "with", "an", "optional", "reloader", ".", "This", "wraps", "wsgiref", "to", "fix", "the", "wrong", "default", "reporting", "of", "the", "multithreaded", "WSGI", "variable", "and", "adds", "optional", "multithreading", "and", "fork", "support", "." ]
34472f25e4bc0b954a35346672f94e84ef18b076
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/lib/werkzeug/serving.py#L626-L714
train