signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def rlen(self):
n = <NUM_LIT:0><EOL>for a in self.real():<EOL><INDENT>n += <NUM_LIT:1><EOL><DEDENT>return n<EOL>
Get the number of I{real} attributes which exclude xs and xml attributes. @return: A count of I{real} attributes. @rtype: L{int}
f9714:c0:m2
def lang(self):
for a in self.raw:<EOL><INDENT>if a.qname() == '<STR_LIT>':<EOL><INDENT>return a.value<EOL><DEDENT>return None<EOL><DEDENT>
Get list of I{filtered} attributes which exclude xs. @return: A list of I{filtered} attributes. @rtype: I{generator}
f9714:c0:m3
def skip(self, attr):
ns = attr.namespace()<EOL>skip = (<EOL>Namespace.xmlns[<NUM_LIT:1>],<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>)<EOL>return Namespace.xs(ns) or ns[<NUM_LIT:1>] in skip<EOL>
Get whether to skip (filter-out) the specified attribute. @param attr: An attribute. @type attr: I{Attribute} @return: True if should be skipped. @rtype: bool
f9714:c0:m4
def process(self, content):
self.reset()<EOL>return self.append(content)<EOL>
Process an object graph representation of the xml I{node}. @param content: The current content being unmarshalled. @type content: L{Content} @return: A suds object. @rtype: L{Object}
f9716:c0:m0
def append(self, content):
self.start(content)<EOL>self.append_attributes(content)<EOL>self.append_children(content)<EOL>self.append_text(content)<EOL>self.end(content)<EOL>return self.postprocess(content)<EOL>
Process the specified node and convert the XML document into a I{suds} L{object}. @param content: The current content being unmarshalled. @type content: L{Content} @return: A I{append-result} tuple as: (L{Object}, I{value}) @rtype: I{append-result} @note: This is not the proper entry point. @see: L{process()}
f9716:c0:m1
def postprocess(self, content):
node = content.node<EOL>if len(node.children) and node.hasText():<EOL><INDENT>return node<EOL><DEDENT>attributes = AttrList(node.attributes)<EOL>if (<EOL>attributes.rlen() and<EOL>not len(node.children) and<EOL>node.hasText()<EOL>):<EOL><INDENT>p = Factory.property(node.name, node.getText())<EOL>return merge(content.data, p)<EOL><DEDENT>if len(content.data):<EOL><INDENT>return content.data<EOL><DEDENT>lang = attributes.lang()<EOL>if content.node.isnil():<EOL><INDENT>return None<EOL><DEDENT>if not len(node.children) and content.text is None:<EOL><INDENT>if self.nillable(content):<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return Text('<STR_LIT>', lang=lang)<EOL><DEDENT><DEDENT>if isinstance(content.text, basestring):<EOL><INDENT>return Text(content.text, lang=lang)<EOL><DEDENT>else:<EOL><INDENT>return content.text<EOL><DEDENT>
Perform final processing of the resulting data structure as follows: - Mixed values (children and text) will have a result of the I{content.node}. - Semi-simple values (attributes, no-children and text) will have a result of a property object. - Simple values (no-attributes, no-children with text nodes) will have a string result equal to the value of the content.node.getText(). @param content: The current content being unmarshalled. @type content: L{Content} @return: The post-processed result. @rtype: I{any}
f9716:c0:m2
def append_attributes(self, content):
attributes = AttrList(content.node.attributes)<EOL>for attr in attributes.real():<EOL><INDENT>name = attr.name<EOL>value = attr.value<EOL>self.append_attribute(name, value, content)<EOL><DEDENT>
Append attribute nodes into L{Content.data}. Attributes in the I{schema} or I{xml} namespaces are skipped. @param content: The current content being unmarshalled. @type content: L{Content}
f9716:c0:m3
def append_attribute(self, name, value, content):
key = name<EOL>key = '<STR_LIT>' % reserved.get(key, key)<EOL>setattr(content.data, key, value)<EOL>
Append an attribute name/value into L{Content.data}. @param name: The attribute name @type name: basestring @param value: The attribute's value @type value: basestring @param content: The current content being unmarshalled. @type content: L{Content}
f9716:c0:m4
def append_children(self, content):
for child in content.node:<EOL><INDENT>cont = Content(child)<EOL>cval = self.append(cont)<EOL>key = reserved.get(child.name, child.name)<EOL>if key in content.data:<EOL><INDENT>v = getattr(content.data, key)<EOL>if isinstance(v, list):<EOL><INDENT>v.append(cval)<EOL><DEDENT>else:<EOL><INDENT>setattr(content.data, key, [v, cval])<EOL><DEDENT>continue<EOL><DEDENT>if self.unbounded(cont):<EOL><INDENT>if cval is None:<EOL><INDENT>setattr(content.data, key, [])<EOL><DEDENT>else:<EOL><INDENT>setattr(content.data, key, [cval, ])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>setattr(content.data, key, cval)<EOL><DEDENT><DEDENT>
Append child nodes into L{Content.data} @param content: The current content being unmarshalled. @type content: L{Content}
f9716:c0:m5
def append_text(self, content):
if content.node.hasText():<EOL><INDENT>content.text = content.node.getText()<EOL><DEDENT>
Append text nodes into L{Content.data} @param content: The current content being unmarshalled. @type content: L{Content}
f9716:c0:m6
def start(self, content):
content.data = Factory.object(content.node.name)<EOL>
Processing on I{node} has started. Build and return the proper object. @param content: The current content being unmarshalled. @type content: L{Content} @return: A subclass of Object. @rtype: L{Object}
f9716:c0:m8
def end(self, content):
pass<EOL>
Processing on I{node} has ended. @param content: The current content being unmarshalled. @type content: L{Content}
f9716:c0:m9
def bounded(self, content):
return not self.unbounded(content)<EOL>
Get whether the content is bounded (not a list). @param content: The current content being unmarshalled. @type content: L{Content} @return: True if bounded, else False @rtype: boolean
f9716:c0:m10
def unbounded(self, content):
return False<EOL>
Get whether the object is unbounded (a list). @param content: The current content being unmarshalled. @type content: L{Content} @return: True if unbounded, else False @rtype: boolean
f9716:c0:m11
def nillable(self, content):
return False<EOL>
Get whether the object is nillable. @param content: The current content being unmarshalled. @type content: L{Content} @return: True if nillable, else False @rtype: boolean
f9716:c0:m12
def __init__(self, schema):
self.resolver = NodeResolver(schema)<EOL>
@param schema: A schema object. @type schema: L{xsd.schema.Schema}
f9717:c0:m0
def process(self, node, type):
content = Content(node)<EOL>content.type = type<EOL>return Core.process(self, content)<EOL>
Process an object graph representation of the xml L{node}. @param node: An XML tree. @type node: L{sax.element.Element} @param type: The I{optional} schema type. @type type: L{xsd.sxbase.SchemaObject} @return: A suds object. @rtype: L{Object}
f9717:c0:m1
def append_attribute(self, name, value, content):
type = self.resolver.findattr(name)<EOL>if type is None:<EOL><INDENT>log.warn('<STR_LIT>', name)<EOL><DEDENT>else:<EOL><INDENT>value = self.translated(value, type)<EOL><DEDENT>Core.append_attribute(self, name, value, content)<EOL>
Append an attribute name/value into L{Content.data}. @param name: The attribute name @type name: basestring @param value: The attribute's value @type value: basestring @param content: The current content being unmarshalled. @type content: L{Content}
f9717:c0:m7
def append_text(self, content):
Core.append_text(self, content)<EOL>known = self.resolver.top().resolved<EOL>content.text = self.translated(content.text, known)<EOL>
Append text nodes into L{Content.data} Here is where the I{true} type is used to translate the value into the proper python type. @param content: The current content being unmarshalled. @type content: L{Content}
f9717:c0:m8
def translated(self, value, type):
if value is not None:<EOL><INDENT>resolved = type.resolve()<EOL>return resolved.translate(value)<EOL><DEDENT>else:<EOL><INDENT>return value<EOL><DEDENT>
translate using the schema type
f9717:c0:m9
def initialized(self, context):
pass<EOL>
Suds client initialization. Called after wsdl the has been loaded. Provides the plugin with the opportunity to inspect/modify the WSDL. @param context: The init context. @type context: L{InitContext}
f9719:c5:m0
def loaded(self, context):
pass<EOL>
Suds has loaded a WSDL/XSD document. Provides the plugin with an opportunity to inspect/modify the unparsed document. Called after each WSDL/XSD document is loaded. @param context: The document context. @type context: L{DocumentContext}
f9719:c6:m0
def parsed(self, context):
pass<EOL>
Suds has parsed a WSDL/XSD document. Provides the plugin with an opportunity to inspect/modify the parsed document. Called after each WSDL/XSD document is parsed. @param context: The document context. @type context: L{DocumentContext}
f9719:c6:m1
def marshalled(self, context):
pass<EOL>
Suds will send the specified soap envelope. Provides the plugin with the opportunity to inspect/modify the envelope Document before it is sent. @param context: The send context. The I{envelope} is the envelope docuemnt. @type context: L{MessageContext}
f9719:c7:m0
def sending(self, context):
pass<EOL>
Suds will send the specified soap envelope. Provides the plugin with the opportunity to inspect/modify the message text it is sent. @param context: The send context. The I{envelope} is the envelope text. @type context: L{MessageContext}
f9719:c7:m1
def received(self, context):
pass<EOL>
Suds has received the specified reply. Provides the plugin with the opportunity to inspect/modify the received XML text before it is SAX parsed. @param context: The reply context. The I{reply} is the raw text. @type context: L{MessageContext}
f9719:c7:m2
def parsed(self, context):
pass<EOL>
Suds has sax parsed the received reply. Provides the plugin with the opportunity to inspect/modify the sax parsed DOM tree for the reply before it is unmarshalled. @param context: The reply context. The I{reply} is DOM tree. @type context: L{MessageContext}
f9719:c7:m3
def unmarshalled(self, context):
pass<EOL>
Suds has unmarshalled the received reply. Provides the plugin with the opportunity to inspect/modify the unmarshalled reply object before it is returned. @param context: The reply context. The I{reply} is unmarshalled suds object. @type context: L{MessageContext}
f9719:c7:m4
def __init__(self, plugins):
self.plugins = plugins<EOL>
@param plugins: A list of plugin objects. @type plugins: [L{Plugin},]
f9719:c8:m0
def __init__(self, name, domain):
self.name = name<EOL>self.domain = domain<EOL>
@param name: The method name. @type name: str @param domain: A plugin domain. @type domain: L{PluginDomain}
f9719:c10:m0
def __init__(self, url, message=None):
self.url = url<EOL>self.headers = {}<EOL>self.message = message<EOL>
@param url: The url for the request. @type url: str @param message: The (optional) message to be send in the request. @type message: str
f9721:c1:m0
def __init__(self, code, headers, message):
self.code = code<EOL>self.headers = headers<EOL>self.message = message<EOL>
@param code: The http code returned. @type code: int @param headers: The http returned headers. @type headers: dict @param message: The (optional) reply message received. @type message: str
f9721:c2:m0
def __init__(self):
from suds.transport.options import Options<EOL>self.options = Options()<EOL>del Options<EOL>
Constructor.
f9721:c3:m0
def open(self, request):
raise Exception('<STR_LIT>')<EOL>
Open the url in the specified request. @param request: A transport request. @type request: L{Request} @return: An input stream. @rtype: stream @raise TransportError: On all transport errors.
f9721:c3:m1
def send(self, request):
raise Exception('<STR_LIT>')<EOL>
Send soap message. Implementations are expected to handle: - proxies - I{http} headers - cookies - sending message - brokering exceptions into L{TransportError} @param request: A transport request. @type request: L{Request} @return: The reply @rtype: L{Reply} @raise TransportError: On all transport errors.
f9721:c3:m2
def __init__(self, **kwargs):
Transport.__init__(self)<EOL>Unskin(self.options).update(kwargs)<EOL>self.cookiejar = CookieJar()<EOL>self.proxy = {}<EOL>self.urlopener = None<EOL>
@param kwargs: Keyword arguments. - B{proxy} - An http proxy to be specified on requests. The proxy is defined as {protocol:proxy,} - type: I{dict} - default: {} - B{timeout} - Set the url open timeout (seconds). - type: I{float} - default: 90
f9722:c0:m0
def addcookies(self, u2request):
self.cookiejar.add_cookie_header(u2request)<EOL>
Add cookies in the cookiejar to the request. @param u2request: A urllib2 request. @rtype: u2request: urllib2.Requet.
f9722:c0:m3
def getcookies(self, fp, u2request):
self.cookiejar.extract_cookies(fp, u2request)<EOL>
Add cookies in the request to the cookiejar. @param u2request: A urllib2 request. @rtype: u2request: urllib2.Requet.
f9722:c0:m4
def u2open(self, u2request):
tm = self.options.timeout<EOL>url = self.u2opener()<EOL>if self.u2ver() < <NUM_LIT>:<EOL><INDENT>socket.setdefaulttimeout(tm)<EOL>return url.open(u2request)<EOL><DEDENT>else:<EOL><INDENT>return url.open(u2request, timeout=tm)<EOL><DEDENT>
Open a connection. @param u2request: A urllib2 request. @type u2request: urllib2.Requet. @return: The opened file-like urllib2 object. @rtype: fp
f9722:c0:m5
def u2opener(self):
if self.urlopener is None:<EOL><INDENT>return u2.build_opener(*self.u2handlers())<EOL><DEDENT>else:<EOL><INDENT>return self.urlopener<EOL><DEDENT>
Create a urllib opener. @return: An opener. @rtype: I{OpenerDirector}
f9722:c0:m6
def u2handlers(self):
handlers = []<EOL>handlers.append(u2.ProxyHandler(self.proxy))<EOL>return handlers<EOL>
Get a collection of urllib handlers. @return: A list of handlers to be installed in the opener. @rtype: [Handler,...]
f9722:c0:m7
def u2ver(self):
try:<EOL><INDENT>part = u2.__version__.split('<STR_LIT:.>', <NUM_LIT:1>)<EOL>n = float('<STR_LIT:.>'.join(part))<EOL>return n<EOL><DEDENT>except Exception as e:<EOL><INDENT>log.exception(e)<EOL>return <NUM_LIT:0><EOL><DEDENT>
Get the major/minor version of the urllib2 lib. @return: The urllib2 version. @rtype: float
f9722:c0:m8
def __init__(self, **kwargs):
HttpTransport.__init__(self, **kwargs)<EOL>self.pm = HTTPPasswordMgrWithDefaultRealm()<EOL>
@param kwargs: Keyword arguments. - B{proxy} - An http proxy to be specified on requests. The proxy is defined as {protocol:proxy,} - type: I{dict} - default: {} - B{timeout} - Set the url open timeout (seconds). - type: I{float} - default: 90 - B{username} - The username used for http authentication. - type: I{str} - default: None - B{password} - The password used for http authentication. - type: I{str} - default: None
f9723:c0:m0
def load_module(filename):
path, name = os.path.split(filename)<EOL>name, ext = os.path.splitext(name)<EOL>(file, filename, desc) = imp.find_module(name, [path])<EOL>try:<EOL><INDENT>return imp.load_module(name, file, filename, desc)<EOL><DEDENT>finally:<EOL><INDENT>if file:<EOL><INDENT>file.close()<EOL><DEDENT><DEDENT>
Loads a module from anywhere in the system. Does not depend on or modify sys.path.
f9733:m0
def execute(<EOL>command,<EOL>abort=True,<EOL>capture=False,<EOL>verbose=False,<EOL>echo=False,<EOL>stream=None,<EOL>):
stream = stream or sys.stdout<EOL>if echo:<EOL><INDENT>out = stream<EOL>out.write(u'<STR_LIT>' % command)<EOL><DEDENT>command = u'<STR_LIT>' % command<EOL>if verbose:<EOL><INDENT>out = stream<EOL>err = stream<EOL><DEDENT>else:<EOL><INDENT>out = subprocess.PIPE<EOL>err = subprocess.PIPE<EOL><DEDENT>process = subprocess.Popen(<EOL>command,<EOL>shell=True,<EOL>stdout=out,<EOL>stderr=err,<EOL>)<EOL>signal.signal(<EOL>signal.SIGTERM,<EOL>make_terminate_handler(process)<EOL>)<EOL>stdout, _ = process.communicate()<EOL>stdout = stdout.strip() if stdout else '<STR_LIT>'<EOL>if not isinstance(stdout, unicode):<EOL><INDENT>stdout = stdout.decode('<STR_LIT:utf-8>')<EOL><DEDENT>if abort and process.returncode != <NUM_LIT:0>:<EOL><INDENT>message = (<EOL>u'<STR_LIT>' % (<EOL>process.returncode,<EOL>command,<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (<EOL>stdout<EOL>) if stdout else '<STR_LIT>'<EOL>)<EOL>)<EOL>raise Exception(message)<EOL><DEDENT>if capture:<EOL><INDENT>return stdout<EOL><DEDENT>else:<EOL><INDENT>return process<EOL><DEDENT>
Run a command locally. Arguments: command: a command to execute. abort: If True, a non-zero return code will trigger an exception. capture: If True, returns the output of the command. If False, returns a subprocess result. echo: if True, prints the command before executing it. verbose: If True, prints the output of the command. stream: If set, stdout/stderr will be redirected to the given stream. Ignored if `capture` is True.
f9734:m7
@click.command()<EOL>def version():
stdout.write(VERSION)<EOL>
Display application version.
f9738:m0
@click.argument('<STR_LIT>')<EOL>@click.option('<STR_LIT>', is_flag=True)<EOL>@click.option(<EOL>'<STR_LIT>',<EOL>is_flag=True,<EOL>default=True<EOL>)<EOL>@click.command()<EOL>def add(addon, dev, interactive):
application = get_current_application()<EOL>application.add(<EOL>addon,<EOL>dev=dev,<EOL>interactive=interactive<EOL>)<EOL>
Add a dependency. Examples: $ django add dynamic-rest==1.5.0 + dynamic-rest == 1.5.0
f9739:m0
@click.command()<EOL>def info():
application = get_current_application()<EOL>info = application.info()<EOL>stdout.write(info)<EOL>return info<EOL>
Display app info. Examples: $ dj info No application, try running dj init. $ dj info Application: foo @ 2.7.9 Requirements: Django == 1.10
f9740:m0
@click.command(cls=GenerateCommand)<EOL>@click.option(<EOL>'<STR_LIT>',<EOL>default=True<EOL>)<EOL>def generate(*args, **kwargs):
pass<EOL>
Generate a code stub.
f9743:m0
@click.command()<EOL>@click.argument('<STR_LIT:name>')<EOL>@click.option(<EOL>'<STR_LIT>',<EOL>prompt=style.prompt('<STR_LIT>'),<EOL>default=style.default(Config.defaults['<STR_LIT>'])<EOL>)<EOL>def init(name, runtime):
runtime = click.unstyle(runtime)<EOL>stdout.write(<EOL>style.format_command(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % (name, style.gray('<STR_LIT:@>'), style.green(runtime))<EOL>)<EOL>)<EOL>config = Config(os.getcwd())<EOL>config.set('<STR_LIT>', runtime)<EOL>config.save()<EOL>generate.main(['<STR_LIT>', name], standalone_mode=False)<EOL>run.main(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>
Create a new Django app.
f9744:m0
@click.command(cls=_MultiCommand)<EOL>def dj(*args, **kwargs):
pass<EOL>
DJ, the Django CLI.
f9745:m0
@click.command()<EOL>def help():
from .dj import dj<EOL>dj.main(['<STR_LIT>'])<EOL>
Display usage info.
f9746:m0
@click.command()<EOL>@click.argument('<STR_LIT:port>', required=False)<EOL>def server(port):
args = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>if port:<EOL><INDENT>args.append(port)<EOL><DEDENT>run.main(args)<EOL>
Start the Django dev server.
f9747:m0
@click.argument('<STR_LIT:args>', nargs=-<NUM_LIT:1>, type=click.UNPROCESSED)<EOL>@click.command(<EOL>context_settings={<EOL>'<STR_LIT>': True<EOL>}<EOL>)<EOL>def lint(args):
application = get_current_application()<EOL>if not args:<EOL><INDENT>args = [application.name, '<STR_LIT>']<EOL><DEDENT>args = ['<STR_LIT>'] + list(args)<EOL>run.main(args, standalone_mode=False)<EOL>
Run lint checks using flake8.
f9748:m0
@click.command()<EOL>def shell():
run.main(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>
Start the Django shell.
f9749:m0
@click.option('<STR_LIT>', is_flag=True, default=False)<EOL>@click.argument('<STR_LIT:args>', nargs=-<NUM_LIT:1>, type=click.UNPROCESSED)<EOL>@click.command(<EOL>context_settings={<EOL>'<STR_LIT>': True<EOL>}<EOL>)<EOL>def run(quiet, args):
if not args:<EOL><INDENT>raise ClickException('<STR_LIT>')<EOL><DEDENT>cmd = '<STR_LIT:U+0020>'.join(args)<EOL>application = get_current_application()<EOL>name = application.name<EOL>settings = os.environ.get('<STR_LIT>', '<STR_LIT>' % name)<EOL>return application.run(<EOL>cmd,<EOL>verbose=not quiet,<EOL>abort=False,<EOL>capture=True,<EOL>env={<EOL>'<STR_LIT>': settings<EOL>}<EOL>)<EOL>
Run a local command. Examples: $ django run manage.py runserver ...
f9750:m0
@click.command()<EOL>def migrate():
run.main(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'], standalone_mode=False)<EOL>run.main(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>'], standalone_mode=False)<EOL>
Run Django migrations. This runs "makemigrations" and "migrate".
f9751:m0
@click.argument('<STR_LIT>')<EOL>@click.option('<STR_LIT>', is_flag=True)<EOL>@click.command()<EOL>def remove(addon, dev):
application = get_current_application()<EOL>application.remove(addon, dev=dev)<EOL>
Remove a dependency. Examples: $ django remove dynamic-rest - dynamic-rest == 1.5.0
f9753:m0
@staticmethod<EOL><INDENT>def parse_application_name(setup_filename):<DEDENT>
with open(setup_filename, '<STR_LIT>') as setup_file:<EOL><INDENT>fst = RedBaron(setup_file.read())<EOL>for node in fst:<EOL><INDENT>if (<EOL>node.type == '<STR_LIT>' and<EOL>str(node.name) == '<STR_LIT>'<EOL>):<EOL><INDENT>for call in node.call:<EOL><INDENT>if str(call.name) == '<STR_LIT:name>':<EOL><INDENT>value = call.value<EOL>if hasattr(value, '<STR_LIT>'):<EOL><INDENT>value = value.to_python()<EOL><DEDENT>name = str(value)<EOL>break<EOL><DEDENT><DEDENT>if name:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return name<EOL>
Parse a setup.py file for the name. Returns: name, or None
f9754:c0:m3
def build(self):
if self.exists:<EOL><INDENT>self._build(<EOL>'<STR_LIT>',<EOL>self.requirements_last_modified,<EOL>'<STR_LIT>' % self.requirements_file<EOL>)<EOL>try:<EOL><INDENT>self._build(<EOL>'<STR_LIT>',<EOL>self.dev_requirements_last_modified,<EOL>'<STR_LIT>' % self.dev_requirements_file<EOL>)<EOL><DEDENT>except Exception as e:<EOL><INDENT>if '<STR_LIT>' not in str(e):<EOL><INDENT>raise e<EOL><DEDENT>self.stdout.write(<EOL>style.yellow('<STR_LIT>')<EOL>)<EOL><DEDENT>try:<EOL><INDENT>self._build(<EOL>'<STR_LIT>',<EOL>self.local_requirements_last_modified,<EOL>'<STR_LIT>' % self.local_requirements_file<EOL>)<EOL><DEDENT>except Exception as e:<EOL><INDENT>if '<STR_LIT>' not in str(e):<EOL><INDENT>raise e<EOL><DEDENT>self.stdout.write(<EOL>style.yellow('<STR_LIT>')<EOL>)<EOL><DEDENT>self._build(<EOL>'<STR_LIT>',<EOL>self.setup_last_modified,<EOL>'<STR_LIT>' % self.setup_file<EOL>)<EOL><DEDENT>
Builds the app in the app's environment. Only builds if the build is out-of-date and is non-empty. Builds in 3 stages: requirements, dev requirements, and app. pip is used to install requirements, and setup.py is used to install the app itself. Raises: ValidationError if the app fails to build.
f9754:c0:m18
def generate(self, blueprint, context, interactive=True):
if not isinstance(blueprint, Blueprint):<EOL><INDENT>bp = self.blueprints.get(blueprint)<EOL>if not bp:<EOL><INDENT>raise ValueError('<STR_LIT>' % blueprint)<EOL><DEDENT>blueprint = bp<EOL><DEDENT>self.stdout.write(<EOL>style.format_command(<EOL>'<STR_LIT>',<EOL>blueprint.full_name<EOL>)<EOL>)<EOL>generator = Generator(<EOL>self,<EOL>blueprint,<EOL>context,<EOL>interactive=interactive<EOL>)<EOL>result = generator.generate()<EOL>if blueprint.name == '<STR_LIT>':<EOL><INDENT>self.refresh()<EOL><DEDENT>return result<EOL>
Generate a blueprint within this application.
f9754:c0:m21
def add(self, addon, dev=False, interactive=True):
dependencies = self.get_dependency_manager(dev=dev)<EOL>other_dependencies = self.get_dependency_manager(dev=not dev)<EOL>existing = dependencies.get(addon)<EOL>self.stdout.write(style.format_command('<STR_LIT>', addon))<EOL>dependencies.add(addon)<EOL>try:<EOL><INDENT>self.build()<EOL>self.refresh()<EOL>other_dependencies.remove(addon, warn=False)<EOL>constructor_name = '<STR_LIT>' % Dependency(addon).module_name<EOL>constructor = self.blueprints.get(constructor_name)<EOL>if constructor:<EOL><INDENT>context = constructor.load_context().main(<EOL>[], standalone_mode=False<EOL>)<EOL>self.generate(constructor, context, interactive=interactive)<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>self.stdout.write(style.red(str(e)))<EOL>self.stdout.write(<EOL>style.yellow('<STR_LIT>' % addon)<EOL>)<EOL>dependencies.remove(addon)<EOL>if existing:<EOL><INDENT>dependencies.add(existing)<EOL><DEDENT>return<EOL><DEDENT>
Add a new dependency and install it.
f9754:c0:m23
def remove(self, addon, dev=False):
dependencies = self.get_dependency_manager(dev=dev)<EOL>other_dependencies = self.get_dependency_manager(dev=not dev)<EOL>self.stdout.write(style.format_command('<STR_LIT>', addon))<EOL>removed = dependencies.remove(addon, warn=False)<EOL>if not removed:<EOL><INDENT>removed = other_dependencies.remove(addon, warn=False)<EOL><DEDENT>if removed:<EOL><INDENT>self.build()<EOL><DEDENT>else:<EOL><INDENT>exception = '<STR_LIT>' % Dependency(addon).to_stdout()<EOL>self.stdout.write(style.red(exception))<EOL><DEDENT>
Remove a dependency and uninstall it.
f9754:c0:m24
@click.command()<EOL>@click.argument('<STR_LIT:name>')<EOL>def get_context(name):
return {<EOL>'<STR_LIT:name>': inflection.underscore(name),<EOL>'<STR_LIT>': inflection.camelize(name)<EOL>}<EOL>
Generate a model with given name. You will need to run "dj migrate" to create the migration file and apply it to your local development database. For example: dj generate model Foo dj migrate
f9755:m0
@click.command()<EOL>@click.argument('<STR_LIT:name>')<EOL>@click.option('<STR_LIT>')<EOL>def get_context(name, doc):
name = inflection.underscore(name)<EOL>return {<EOL>'<STR_LIT:name>': name,<EOL>'<STR_LIT>': doc or name<EOL>}<EOL>
Generate a command with given name. The command can be run immediately after generation. For example: dj generate command bar dj run manage.py bar
f9756:m0
def generate(self):
self.render()<EOL>self.merge()<EOL>
Generate the blueprint.
f9759:c0:m2
def render(self):
context = self.context<EOL>if '<STR_LIT>' not in context:<EOL><INDENT>context['<STR_LIT>'] = self.application.name<EOL><DEDENT>temp_dir = self.temp_dir<EOL>templates_root = self.blueprint.templates_directory<EOL>for root, dirs, files in os.walk(templates_root):<EOL><INDENT>for directory in dirs:<EOL><INDENT>directory = os.path.join(root, directory)<EOL>directory = render_from_string(directory, context)<EOL>directory = directory.replace(templates_root, temp_dir, <NUM_LIT:1>)<EOL>os.mkdir(directory)<EOL><DEDENT>for file in files:<EOL><INDENT>full_file = os.path.join(root, file)<EOL>stat = os.stat(full_file)<EOL>content = render_from_file(full_file, context)<EOL>full_file = strip_extension(<EOL>render_from_string(full_file, context))<EOL>full_file = full_file.replace(templates_root, temp_dir, <NUM_LIT:1>)<EOL>with open(full_file, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(content)<EOL><DEDENT>os.chmod(full_file, stat.st_mode)<EOL><DEDENT><DEDENT>
Render the blueprint into a temp directory using the context.
f9759:c0:m3
def merge(self):
temp_dir = self.temp_dir<EOL>app_dir = self.application.directory<EOL>for root, dirs, files in os.walk(temp_dir):<EOL><INDENT>for directory in dirs:<EOL><INDENT>directory = os.path.join(root, directory)<EOL>directory = directory.replace(temp_dir, app_dir, <NUM_LIT:1>)<EOL>try:<EOL><INDENT>os.mkdir(directory)<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>for file in files:<EOL><INDENT>source = os.path.join(root, file)<EOL>target = source.replace(temp_dir, app_dir, <NUM_LIT:1>)<EOL>relative_target = target.replace(app_dir, '<STR_LIT:.>')<EOL>action = '<STR_LIT:r>'<EOL>if (<EOL>os.path.exists(target)<EOL>and not filecmp.cmp(source, target, shallow=False)<EOL>and os.stat(target).st_size > <NUM_LIT:0><EOL>):<EOL><INDENT>if target.endswith('<STR_LIT>'):<EOL><INDENT>action = '<STR_LIT:m>'<EOL><DEDENT>elif target.endswith('<STR_LIT>'):<EOL><INDENT>action = '<STR_LIT:s>'<EOL><DEDENT>else:<EOL><INDENT>default = '<STR_LIT:m>'<EOL>action = click.prompt(<EOL>style.prompt(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>' % (<EOL>relative_target<EOL>),<EOL>),<EOL>default=style.default(default)<EOL>) if self.interactive else default<EOL>action = click.unstyle(action).lower()<EOL>if action not in {'<STR_LIT:r>', '<STR_LIT:m>', '<STR_LIT:s>'}:<EOL><INDENT>action = default<EOL><DEDENT><DEDENT><DEDENT>if action == '<STR_LIT:s>':<EOL><INDENT>self.stdout.write(<EOL>'<STR_LIT>' % style.white(relative_target),<EOL>fg='<STR_LIT>'<EOL>)<EOL>continue<EOL><DEDENT>if action == '<STR_LIT:r>':<EOL><INDENT>with open(source, '<STR_LIT:r>') as source_file:<EOL><INDENT>with open(target, '<STR_LIT:w>') as target_file:<EOL><INDENT>target_file.write(source_file.read())<EOL><DEDENT><DEDENT>self.stdout.write(<EOL>style.green(<EOL>'<STR_LIT>' % style.white(relative_target)<EOL>)<EOL>)<EOL><DEDENT>if action == '<STR_LIT:m>':<EOL><INDENT>with open(target, '<STR_LIT:r>') as target_file:<EOL><INDENT>with open(source, '<STR_LIT:r>') as source_file:<EOL><INDENT>merged = merge(<EOL>target_file.read(),<EOL>source_file.read()<EOL>)<EOL><DEDENT><DEDENT>with open(target, '<STR_LIT:w>') as target_file:<EOL><INDENT>target_file.write(merged)<EOL><DEDENT>self.stdout.write(<EOL>style.yellow('<STR_LIT>' % style.white(relative_target))<EOL>)<EOL><DEDENT><DEDENT><DEDENT>
Merges the rendered blueprint into the application.
f9759:c0:m4
def get_logger(logger_name):
<EOL>if logger_name is None:<EOL><INDENT>return __instance<EOL><DEDENT>assert isinstance(logger_name, str), '<STR_LIT>'<EOL>with __lock:<EOL><INDENT>if logger_name in __loggers:<EOL><INDENT>return __loggers[logger_name]<EOL><DEDENT>logger_instance = LogOne(logger_name=logger_name)<EOL>__loggers[logger_name] = logger_instance<EOL>return logger_instance<EOL><DEDENT>
Return a logger with the specified name, creating it if necessary.
f9761:m0
def __init__(self, logger_name,<EOL>level=logging.WARNING,<EOL>use_colors=True,<EOL>log_format=None,<EOL>date_format=None,<EOL>level_styles=None,<EOL>field_styles=None):
<EOL>self.logger = logging.getLogger(logger_name)<EOL>if not log_format:<EOL><INDENT>log_format = '<STR_LIT>''<STR_LIT>''<STR_LIT>'<EOL><DEDENT>coloredlogs.install(level=level,<EOL>logger=self.logger,<EOL>fmt=log_format,<EOL>datefmt=date_format,<EOL>level_styles=level_styles,<EOL>field_styles=field_styles,<EOL>isatty=use_colors,<EOL>stream=_original_stderr)<EOL>self.__stdout_wrapper = None<EOL>self.__stderr_wrapper = None<EOL>self.__stdout_stream = _original_stdout<EOL>self.__stderr_stream = _original_stderr<EOL>self.__file_handler = None<EOL>self.__loggly_handler = None<EOL>self.__coloredlogs_handlers = list(self.logger.handlers)<EOL>self.name = self.logger.name<EOL>self.add_handler = self.logger.addHandler<EOL>self.remove_handler = self.logger.removeHandler<EOL>self.add_filter = self.logger.addFilter<EOL>self.remove_filter = self.logger.removeFilter<EOL>self.log = self.logger.log<EOL>self.debug = self.logger.debug<EOL>self.info = self.logger.info<EOL>self.warning = self.logger.warning<EOL>self.error = self.logger.error<EOL>self.exception = self.logger.exception<EOL>self.critical = self.logger.critical<EOL>
Initialize the logger with a name and an optional level. :param logger_name: The name of the logger. :param level: The default logging level. :param use_colors: Use ColoredFormatter class for coloring logs or not. :param log_format: Use the specified format string for the handler. :param date_format: Use the specified date/time format. :param level_styles: A dictionary with custom level styles. :param field_styles: A dictionary with custom field styles.
f9762:c0:m0
def set_level(self, level):
for handler in self.__coloredlogs_handlers:<EOL><INDENT>handler.setLevel(level=level)<EOL><DEDENT>self.logger.setLevel(level=level)<EOL>
Set the logging level of this logger. :param level: must be an int or a str.
f9762:c0:m1
def disable_logger(self, disabled=True):
<EOL>if disabled:<EOL><INDENT>sys.stdout = _original_stdout<EOL>sys.stderr = _original_stderr<EOL><DEDENT>else:<EOL><INDENT>sys.stdout = self.__stdout_stream<EOL>sys.stderr = self.__stderr_stream<EOL><DEDENT>self.logger.disabled = disabled<EOL>
Disable all logging calls.
f9762:c0:m2
def redirect_stdout(self, enabled=True, log_level=logging.INFO):
if enabled:<EOL><INDENT>if self.__stdout_wrapper:<EOL><INDENT>self.__stdout_wrapper.update_log_level(log_level=log_level)<EOL><DEDENT>else:<EOL><INDENT>self.__stdout_wrapper = StdOutWrapper(logger=self, log_level=log_level)<EOL><DEDENT>self.__stdout_stream = self.__stdout_wrapper<EOL><DEDENT>else:<EOL><INDENT>self.__stdout_stream = _original_stdout<EOL><DEDENT>sys.stdout = self.__stdout_stream<EOL>
Redirect sys.stdout to file-like object.
f9762:c0:m3
def redirect_stderr(self, enabled=True, log_level=logging.ERROR):
if enabled:<EOL><INDENT>if self.__stderr_wrapper:<EOL><INDENT>self.__stderr_wrapper.update_log_level(log_level=log_level)<EOL><DEDENT>else:<EOL><INDENT>self.__stderr_wrapper = StdErrWrapper(logger=self, log_level=log_level)<EOL><DEDENT>self.__stderr_stream = self.__stderr_wrapper<EOL><DEDENT>else:<EOL><INDENT>self.__stderr_stream = _original_stderr<EOL><DEDENT>sys.stderr = self.__stderr_stream<EOL>
Redirect sys.stderr to file-like object.
f9762:c0:m4
def use_file(self, enabled=True,<EOL>file_name=None,<EOL>level=logging.WARNING,<EOL>when='<STR_LIT:d>',<EOL>interval=<NUM_LIT:1>,<EOL>backup_count=<NUM_LIT:30>,<EOL>delay=False,<EOL>utc=False,<EOL>at_time=None,<EOL>log_format=None,<EOL>date_format=None):
if enabled:<EOL><INDENT>if not self.__file_handler:<EOL><INDENT>assert file_name, '<STR_LIT>'<EOL>kwargs = {<EOL>'<STR_LIT:filename>': file_name,<EOL>'<STR_LIT>': when,<EOL>'<STR_LIT>': interval,<EOL>'<STR_LIT>': backup_count,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': delay,<EOL>'<STR_LIT>': utc,<EOL>}<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>kwargs['<STR_LIT>'] = at_time<EOL><DEDENT>self.__file_handler = TimedRotatingFileHandler(**kwargs)<EOL>if not log_format:<EOL><INDENT>log_format = '<STR_LIT>''<STR_LIT>''<STR_LIT>'<EOL><DEDENT>formatter = logging.Formatter(fmt=log_format, datefmt=date_format)<EOL>self.__file_handler.setFormatter(fmt=formatter)<EOL>self.__file_handler.setLevel(level=level)<EOL>self.add_handler(hdlr=self.__file_handler)<EOL><DEDENT><DEDENT>elif self.__file_handler:<EOL><INDENT>self.remove_handler(hdlr=self.__file_handler)<EOL>self.__file_handler = None<EOL><DEDENT>
Handler for logging to a file, rotating the log file at certain timed intervals.
f9762:c0:m5
def use_loggly(self, enabled=True,<EOL>loggly_token=None,<EOL>loggly_tag=None,<EOL>level=logging.WARNING,<EOL>log_format=None,<EOL>date_format=None):
if enabled:<EOL><INDENT>if not self.__loggly_handler:<EOL><INDENT>assert loggly_token, '<STR_LIT>'<EOL>if not loggly_tag:<EOL><INDENT>loggly_tag = self.name<EOL><DEDENT>self.__loggly_handler = LogglyHandler(token=loggly_token, tag=loggly_tag)<EOL>if not log_format:<EOL><INDENT>log_format = '<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>'<EOL><DEDENT>formatter = logging.Formatter(fmt=log_format, datefmt=date_format)<EOL>self.__loggly_handler.setFormatter(fmt=formatter)<EOL>self.__loggly_handler.setLevel(level=level)<EOL>self.add_handler(hdlr=self.__loggly_handler)<EOL><DEDENT><DEDENT>elif self.__loggly_handler:<EOL><INDENT>self.remove_handler(hdlr=self.__loggly_handler)<EOL>self.__loggly_handler = None<EOL><DEDENT>
Enable handler for sending the record to Loggly service.
f9762:c0:m6
@staticmethod<EOL><INDENT>def __find_caller(stack_info=False):<DEDENT>
frame = logging.currentframe()<EOL>if frame:<EOL><INDENT>frame = frame.f_back<EOL><DEDENT>caller_info = '<STR_LIT>', <NUM_LIT:0>, '<STR_LIT>', None<EOL>while hasattr(frame, '<STR_LIT>'):<EOL><INDENT>co = frame.f_code<EOL>if _logone_src in os.path.normcase(co.co_filename):<EOL><INDENT>frame = frame.f_back<EOL>continue<EOL><DEDENT>tb_info = None<EOL>if stack_info:<EOL><INDENT>with StringIO() as _buffer:<EOL><INDENT>_buffer.write('<STR_LIT>')<EOL>traceback.print_stack(frame, file=_buffer)<EOL>tb_info = _buffer.getvalue().strip()<EOL><DEDENT><DEDENT>caller_info = co.co_filename, frame.f_lineno, co.co_name, tb_info<EOL>break<EOL><DEDENT>return caller_info<EOL>
Find the stack frame of the caller so that we can note the source file name, line number and function name.
f9762:c0:m7
def _log(self, level, msg, *args, **kwargs):
if not isinstance(level, int):<EOL><INDENT>if logging.raiseExceptions:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT><DEDENT>if self.logger.isEnabledFor(level=level):<EOL><INDENT>"""<STR_LIT>"""<EOL>exc_info = kwargs.get('<STR_LIT>', None)<EOL>extra = kwargs.get('<STR_LIT>', None)<EOL>stack_info = kwargs.get('<STR_LIT>', False)<EOL>record_filter = kwargs.get('<STR_LIT>', None)<EOL>tb_info = None<EOL>if _logone_src:<EOL><INDENT>try:<EOL><INDENT>fn, lno, func, tb_info = self.__find_caller(stack_info=stack_info)<EOL><DEDENT>except ValueError: <EOL><INDENT>fn, lno, func = '<STR_LIT>', <NUM_LIT:0>, '<STR_LIT>'<EOL><DEDENT><DEDENT>else: <EOL><INDENT>fn, lno, func = '<STR_LIT>', <NUM_LIT:0>, '<STR_LIT>'<EOL><DEDENT>if exc_info:<EOL><INDENT>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>if isinstance(exc_info, BaseException):<EOL><INDENT>exc_info = type(exc_info), exc_info, exc_info.__traceback__<EOL><DEDENT>elif not isinstance(exc_info, tuple):<EOL><INDENT>exc_info = sys.exc_info()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not isinstance(exc_info, tuple):<EOL><INDENT>exc_info = sys.exc_info()<EOL><DEDENT><DEDENT><DEDENT>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>record = self.logger.makeRecord(self.name, level, fn, lno, msg, args,<EOL>exc_info, func, extra, tb_info)<EOL><DEDENT>else:<EOL><INDENT>record = self.logger.makeRecord(self.name, level, fn, lno, msg, args,<EOL>exc_info, func, extra)<EOL><DEDENT>if record_filter:<EOL><INDENT>record = record_filter(record)<EOL><DEDENT>self.logger.handle(record=record)<EOL><DEDENT>
Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
f9762:c0:m8
def update_log_level(self, log_level=logging.INFO):
self.__log_level = log_level<EOL>
Update the logging level of this stream.
f9762:c3:m1
def flush(self):
if self.__buffer.tell() > <NUM_LIT:0>:<EOL><INDENT>self.__logger._log(level=self.__log_level, msg=self.__buffer.getvalue().strip())<EOL>self.__buffer.truncate(<NUM_LIT:0>)<EOL>self.__buffer.seek(<NUM_LIT:0>)<EOL><DEDENT>
Flush the buffer, if applicable.
f9762:c3:m2
def update_log_level(self, log_level=logging.ERROR):
self.__log_level = log_level<EOL>
Update the logging level of this stream.
f9762:c4:m1
def flush(self):
if self.__buffer.tell() > <NUM_LIT:0>:<EOL><INDENT>self.__logger._log(level=self.__log_level, msg=self.__buffer.getvalue().strip(),<EOL>record_filter=StdErrWrapper.__filter_record)<EOL>self.__buffer.truncate(<NUM_LIT:0>)<EOL>self.__buffer.seek(<NUM_LIT:0>)<EOL><DEDENT>
Flush the buffer, if applicable.
f9762:c4:m3
@verify_type(section=str, option=str)<EOL><INDENT>def split_option(self, section, option):<DEDENT>
value = self[section][option].strip()<EOL>if value == "<STR_LIT>":<EOL><INDENT>return []<EOL><DEDENT>return [x.strip() for x in (value.split("<STR_LIT:U+002C>"))]<EOL>
Return list of strings that are made by splitting coma-separated option value. Method returns empty list if option value is empty string :param section: option section name :param option: option name :return: list of strings
f9831:c0:m0
@verify_type(config=(str, ConfigParser))<EOL><INDENT>@verify_value(config=lambda x: isinstance(x, ConfigParser) or os.path.isfile(x))<EOL>def merge(self, config):<DEDENT>
if isinstance(config, ConfigParser) is True:<EOL><INDENT>self.update(config)<EOL><DEDENT>elif isinstance(config, str):<EOL><INDENT>self.read(config)<EOL><DEDENT>
Load configuration from given configuration. :param config: config to load. If config is a string type, then it's treated as .ini filename :return: None
f9831:c0:m1
@verify_type(config=ConfigParser, section_to=str, section_from=(str, None))<EOL><INDENT>def merge_section(self, config, section_to, section_from=None):<DEDENT>
section_from = section_from if section_from is not None else section_to<EOL>if section_from not in config.sections():<EOL><INDENT>raise ValueError('<STR_LIT>' % section_from)<EOL><DEDENT>if section_to not in self.sections():<EOL><INDENT>self.add_section(section_to)<EOL><DEDENT>for option in config[section_from].keys():<EOL><INDENT>self.set(section_to, option, config[section_from][option])<EOL><DEDENT>
Load configuration section from other configuration. If specified section doesn't exist in current configuration, then it will be added automatically. :param config: source configuration :param section_to: destination section name :param section_from: source section name (if it is None, then section_to is used as source section name) :return: None
f9831:c0:m2
def select_options(self, section, options_prefix=None):
return WConfigSelection(self, section, options_prefix=options_prefix)<EOL>
Select options from section :param section: target section :param options_prefix: prefix of options that should be selected :return: WConfigSelection
f9831:c0:m3
@verify_type(config=WConfig, section=str, options_prefix=(str, None))<EOL><INDENT>@verify_value(section=lambda x: len(x) > <NUM_LIT:0>)<EOL>def __init__(self, config, section, options_prefix=None):<DEDENT>
self.__config = config<EOL>self.__section = section<EOL>self.__options_prefix = options_prefix if options_prefix is not None else '<STR_LIT>'<EOL>if self.__config.has_section(section) is False:<EOL><INDENT>raise NoSectionError('<STR_LIT>' % section)<EOL><DEDENT>
Create a configuration selection :param config: source configuration :param section: source section name :param options_prefix: name prefix of options that should be selected. If it is not specified, then \ it is treated as empty string
f9831:c1:m0
def config(self):
return self.__config<EOL>
Return source configuration :return: WConfig
f9831:c1:m1
def section(self):
return self.__section<EOL>
Return source section name :return: str
f9831:c1:m2
def option_prefix(self):
return self.__options_prefix<EOL>
Return name prefix of options that may be selected :return: str
f9831:c1:m3
def __option(self):
section = self.section()<EOL>option = self.option_prefix()<EOL>if self.config().has_option(section, option) is False:<EOL><INDENT>raise NoOptionError(option, section)<EOL><DEDENT>return section, option<EOL>
Check and return option from section from configuration. Option name is equal to option prefix :return: tuple of section name and option prefix
f9831:c1:m4
def __str__(self):
section, option = self.__option()<EOL>return self.config()[section][option]<EOL>
Return string value of this option :return: str
f9831:c1:m5
def __int__(self):
section, option = self.__option()<EOL>return self.config().getint(section, option)<EOL>
Return integer value of this option :return: int
f9831:c1:m6
def __float__(self):
section, option = self.__option()<EOL>return self.config().getfloat(section, option)<EOL>
Return float value of this option :return: float
f9831:c1:m7
def __bool__(self):
section, option = self.__option()<EOL>return self.config().getboolean(section, option)<EOL>
Return boolean value of this option :return: bool
f9831:c1:m8
@verify_type(option_prefix=str)<EOL><INDENT>@verify_value(option_prefix=lambda x: len(x) > <NUM_LIT:0>)<EOL>def select_options(self, options_prefix):<DEDENT>
return WConfigSelection(<EOL>self.config(), self.section(), self.option_prefix() + options_prefix<EOL>)<EOL>
Select options from this selection, that are started with the specified prefix :param options_prefix: name prefix of options that should be selected :return: WConfigSelection
f9831:c1:m9
@verify_type('<STR_LIT>', item=str)<EOL><INDENT>@verify_value('<STR_LIT>', item=lambda x: len(x) > <NUM_LIT:0>)<EOL>def __getitem__(self, item):<DEDENT>
return self.select_options(item)<EOL>
Alias for :meth:`.WConfigSelection.select_options` method :param item: :return:
f9831:c1:m10
@verify_type(option_name=(str, None))<EOL><INDENT>def has_option(self, option_name=None):<DEDENT>
if option_name is None:<EOL><INDENT>option_name = '<STR_LIT>'<EOL><DEDENT>return self.config().has_option(self.section(), self.option_prefix() + option_name)<EOL>
Check whether configuration selection has the specified option. :param option_name: option name to check. If no option is specified, then check is made for this option :return: bool
f9831:c1:m11
@verify_type(storage=(None, WCacheStorage))<EOL>@verify_value(validator=lambda x: x is None or callable(x))<EOL>def cache_control(validator=None, storage=None):
def default_validator(*args, **kwargs):<EOL><INDENT>return True<EOL><DEDENT>if validator is None:<EOL><INDENT>validator = default_validator<EOL><DEDENT>if storage is None:<EOL><INDENT>storage = WGlobalSingletonCacheStorage()<EOL><DEDENT>def first_level_decorator(decorated_function):<EOL><INDENT>def second_level_decorator(original_function, *args, **kwargs):<EOL><INDENT>validator_check = validator(original_function, *args, **kwargs)<EOL>cache_entry = storage.get_cache(original_function, *args, **kwargs)<EOL>if validator_check is not True or cache_entry.has_value is False:<EOL><INDENT>result = original_function(*args, **kwargs)<EOL>storage.put(result, original_function, *args, **kwargs)<EOL>return result<EOL><DEDENT>else:<EOL><INDENT>return cache_entry.cached_value<EOL><DEDENT><DEDENT>return decorator(second_level_decorator)(decorated_function)<EOL><DEDENT>return first_level_decorator<EOL>
Decorator that is used for caching result. :param validator: function, that has following signature (decorated_function, \*args, \*\*kwargs), where \ decorated_function - original function, args - function arguments, kwargs - function keyword arguments. \ This function must return True if cache is valid (old result must be use if it there is one), or False - to \ generate and to store new result. So function that always return True can be used as singleton. And function \ that always return False won't cache anything at all. By default (if no validator is specified), it presumes \ that cache is always valid. :param storage: storage that is used for caching results. see :class:`.WCacheStorage` class. :return: decorated function
f9832:m0
@abstractmethod<EOL><INDENT>@verify_value(decorated_function=lambda x: callable(x))<EOL>def put(self, result, decorated_function, *args, **kwargs):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Save (or replace) result for given function :param result: result to be saved :param decorated_function: called function (original) :param args: args with which function is called :param kwargs: kwargs with which function is called :return: None
f9832:c0:m0