本文整理汇总了Python中trac.util.as_bool函数的典型用法代码示例。如果您正苦于以下问题:Python as_bool函数的具体用法?Python as_bool怎么用?Python as_bool使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了as_bool函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_user_setting
def get_user_setting(self, sid):
"""Returns tuple of (value, authenticated).
Value is always True or None. This will work with Genshi template
checkbox logic.
"""
with self.env.db_query as db:
cursor = db.cursor()
cursor.execute("""
SELECT value, authenticated
FROM session_attribute
WHERE sid=%s
AND name=%s
""", (sid, self._attr_name()))
row = cursor.fetchone()
if row:
dists, v = decode(row[0])
value = as_bool(v)
authenticated = as_bool(row[1])
else:
dists = self.default['dists']
value = as_bool(self.default['value'])
authenticated = False
# We use None here so that Genshi templates check their checkboxes
# properly and without confusion.
return dists, value and True or None, authenticated
示例2: check_permission
def check_permission(self, action, username, resource, perm):
# We add the 'SENSITIVE_VIEW' pre-requisite for any action
# other than 'SENSITIVE_VIEW' itself, as this would lead
# to recursion.
if action == 'SENSITIVE_VIEW':
return
# Check whether we're dealing with a ticket resource
while resource:
if resource.realm == 'ticket':
break
resource = resource.parent
if resource and resource.realm == 'ticket' and resource.id is not None:
bypass = False
try:
ticket = Ticket(self.env, int(resource.id))
sensitive = ticket['sensitive']
if as_bool(sensitive):
bypass = self.bypass_sensitive_view(ticket, username)
except ResourceNotFound:
sensitive = 1 # Fail safe to prevent a race condition.
if as_bool(sensitive):
if 'SENSITIVE_VIEW' not in perm and not bypass:
return False
示例3: check_permission
def check_permission(self, action, username, resource, perm):
"""Check that the action can be performed by username on the resource."""
# To prevent recursion
if action in self.get_permission_actions():
return
# To prevent recursion when used together with sensitive tickets
if action == 'SENSITIVE_VIEW':
return
# Check whether we're dealing with a ticket resource
while resource:
if resource.realm == 'ticket':
break
resource = resource.parent
if resource and resource.realm == 'ticket' and resource.id is not None:
component_permission = 'COMPONENT_VIEW' # Default just to make check logic simpler
bypass = False
try:
ticket = model.Ticket(self.env, int(resource.id))
should_check_permissions = not self.ticket_field_name or ticket.values.get(self.ticket_field_name, 0)
if as_bool(should_check_permissions):
if 'component' in ticket.values and ticket['component'] and self._get_permission_name(ticket['component']) in self.get_permission_actions():
component_permission = self._get_permission_name(ticket['component'])
bypass = self._get_bypass(ticket, username)
except ResourceNotFound:
should_check_permissions = 1 # Fail safe to prevent a race condition
if as_bool(should_check_permissions):
if component_permission not in perm and 'COMPONENT_VIEW' not in perm and not bypass:
return False
示例4: expand_macro
def expand_macro(self, formatter, name, text):
req = formatter.req
context = formatter.context
resource = context.resource
# Process the arguments.
args, kwargs = parse_args(text)
if 'ticket' not in kwargs and len(args)>0:
kwargs['ticket'] = args[0]
elif 'ticket' not in kwargs and not len(args):
kwargs['ticket'] = str( WikiPage(self.env, resource).name ) # This seems to provide the correct ticket id.
try:
kwargs['ticket'] = int( kwargs.get('ticket').lstrip('#') )
except ValueError:
raise TracError('No ticket id supplied or it is not valid integer value.')
ticket = Ticket( self.env, kwargs['ticket'] )
self.childtickets = {} # { parent -> children } - 1:n
db = self.env.get_db_cnx()
cursor = db.cursor()
cursor.execute("SELECT ticket,value FROM ticket_custom WHERE name='parent'")
for child,parent in cursor.fetchall():
if parent and re.match('#\d+',parent):
self.childtickets.setdefault( int(parent.lstrip('#')), [] ).append(child)
# First ticket has no indentation.
ticket['indent'] = '0'
# List of tickets that will be displayed.
if as_bool( kwargs.get('root') ):
self.tickets = [ ticket, ]
else:
self.tickets = []
# Do this neater!
self.indent_children(ticket)
def ticket_anchor(t):
return tag.a( '#%s' % t.id, class_=t['status'], href=req.href.ticket(int(t.id)), title="%s : %s : %s" % (t['type'],t['owner'],t['status']))
def_list = tag.dl(
[( tag.dt(ticket_anchor(t),style='padding-left: %spx;' % (t['indent']*20)), tag.dd("%s" % t['summary'])) for t in self.tickets],
class_='wiki compact',
)
if as_bool( kwargs.get('border') ):
return tag.fieldset(
def_list,
tag.legend('Ticket Child Tree (#%s)' % ticket.id),
class_='description',
)
else:
return tag.div(def_list)
示例5: expand_macro
def expand_macro(self, formatter, name, content):
args, kwargs = parse_args(content)
format = kwargs.get('format', 'compact')
glob = kwargs.get('glob', '*')
order = kwargs.get('order')
desc = as_bool(kwargs.get('desc', 0))
rm = RepositoryManager(self.env)
all_repos = dict(rdata for rdata in rm.get_all_repositories().items()
if fnmatchcase(rdata[0], glob))
if format == 'table':
repo = self._render_repository_index(formatter.context, all_repos,
order, desc)
add_stylesheet(formatter.req, 'common/css/browser.css')
wiki_format_messages = self.config['changeset'] \
.getbool('wiki_format_messages')
data = {'repo': repo, 'order': order, 'desc': 1 if desc else None,
'reponame': None, 'path': '/', 'stickyrev': None,
'wiki_format_messages': wiki_format_messages}
from trac.web.chrome import Chrome
return Chrome(self.env).render_template(
formatter.req, 'repository_index.html', data, None,
fragment=True)
def get_repository(reponame):
try:
return rm.get_repository(reponame)
except TracError:
return
all_repos = [(reponame, get_repository(reponame))
for reponame in all_repos]
all_repos = sorted(((reponame, repos) for reponame, repos in all_repos
if repos
and not as_bool(repos.params.get('hidden'))
and repos.is_viewable(formatter.perm)),
reverse=desc)
def repolink(reponame, repos):
label = reponame or _('(default)')
return Markup(tag.a(label,
title=_('View repository %(repo)s', repo=label),
href=formatter.href.browser(repos.reponame or None)))
if format == 'list':
return tag.dl([
tag(tag.dt(repolink(reponame, repos)),
tag.dd(repos.params.get('description')))
for reponame, repos in all_repos])
else: # compact
return Markup(', ').join([repolink(reponame, repos)
for reponame, repos in all_repos])
示例6: pre_process_request
def pre_process_request(self, req, handler):
from trac.web.chrome import Chrome, add_warning
if handler is not Chrome(self.env):
for repo_info in self.get_all_repositories().values():
if not as_bool(repo_info.get('sync_per_request')):
continue
start = time.time()
repo_name = repo_info['name'] or '(default)'
try:
repo = self.get_repository(repo_info['name'])
repo.sync()
except TracError as e:
add_warning(req,
_("Can't synchronize with repository \"%(name)s\" "
"(%(error)s). Look in the Trac log for more "
"information.", name=repo_name,
error=to_unicode(e)))
except Exception as e:
add_warning(req,
_("Failed to sync with repository \"%(name)s\": "
"%(error)s; repository information may be out of "
"date. Look in the Trac log for more information "
"including mitigation strategies.",
name=repo_name, error=to_unicode(e)))
self.log.error(
"Failed to sync with repository \"%s\"; You may be "
"able to reduce the impact of this issue by "
"configuring the sync_per_request option; see "
"http://trac.edgewall.org/wiki/TracRepositoryAdmin"
"#ExplicitSync for more detail: %s", repo_name,
exception_to_unicode(e, traceback=True))
self.log.info("Synchronized '%s' repository in %0.2f seconds",
repo_name, time.time() - start)
return handler
示例7: _do_set
def _do_set(self, section, option, value):
self.config.set(section, option, value)
if section == 'components' and as_bool(value):
self.config.set_defaults(component=option)
self.config.save()
if section == 'inherit' and option == 'file':
self.config.parse_if_needed(force=True) # Full reload
示例8: process_request
def process_request(self, req):
presel = req.args.get('preselected')
if presel and (presel + '/').startswith(req.href.browser() + '/'):
req.redirect(presel)
path = req.args.get('path', '/')
rev = req.args.get('rev', '')
if rev.lower() in ('', 'head'):
rev = None
format = req.args.get('format')
order = req.args.get('order', 'name').lower()
desc = 'desc' in req.args
xhr = req.get_header('X-Requested-With') == 'XMLHttpRequest'
rm = RepositoryManager(self.env)
all_repositories = rm.get_all_repositories()
reponame, repos, path = rm.get_repository_by_path(path)
# Repository index
show_index = not reponame and path == '/'
if show_index:
if repos and (as_bool(all_repositories[''].get('hidden'))
or not repos.is_viewable(req.perm)):
repos = None
if not repos and reponame:
raise ResourceNotFound(_("Repository '%(repo)s' not found",
repo=reponame))
if reponame and reponame != repos.reponame: # Redirect alias
qs = req.query_string
req.redirect(req.href.browser(repos.reponame or None, path)
+ ('?' + qs if qs else ''))
reponame = repos.reponame if repos else None
# Find node for the requested path/rev
context = web_context(req)
node = None
changeset = None
display_rev = lambda rev: rev
if repos:
try:
if rev:
rev = repos.normalize_rev(rev)
# If `rev` is `None`, we'll try to reuse `None` consistently,
# as a special shortcut to the latest revision.
rev_or_latest = rev or repos.youngest_rev
node = get_existing_node(req, repos, path, rev_or_latest)
except NoSuchChangeset, e:
raise ResourceNotFound(e, _('Invalid changeset number'))
if node:
try:
# use changeset instance to retrieve branches and tags
changeset = repos.get_changeset(node.rev)
except NoSuchChangeset:
pass
context = context.child(repos.resource.child('source', path,
version=rev_or_latest))
display_rev = repos.display_rev
示例9: set_user_setting
def set_user_setting(self, session, value=None, dists=('email',),
save=True):
"""Sets session attribute to 1 or 0."""
session[self._attr_name()] = \
encode(dists, '1' if as_bool(value) else '0')
if save:
session.save()
示例10: _render_repository_index
def _render_repository_index(self, context, all_repositories, order, desc):
# Color scale for the age column
timerange = custom_colorizer = None
if self.color_scale:
custom_colorizer = self.get_custom_colorizer()
rm = RepositoryManager(self.env)
repositories = []
for reponame, repoinfo in all_repositories.iteritems():
if not reponame or as_bool(repoinfo.get("hidden")):
continue
try:
repos = rm.get_repository(reponame)
except TracError as err:
entry = (reponame, repoinfo, None, None, exception_to_unicode(err), None)
else:
if repos:
if not repos.is_viewable(context.perm):
continue
try:
youngest = repos.get_changeset(repos.youngest_rev)
except NoSuchChangeset:
youngest = None
if self.color_scale and youngest:
if not timerange:
timerange = TimeRange(youngest.date)
else:
timerange.insert(youngest.date)
raw_href = self._get_download_href(context.href, repos, None, None)
entry = (reponame, repoinfo, repos, youngest, None, raw_href)
else:
entry = (reponame, repoinfo, None, None, u"\u2013", None)
if entry[4] is not None: # Check permission in case of error
root = Resource("repository", reponame).child(self.realm, "/")
if "BROWSER_VIEW" not in context.perm(root):
continue
repositories.append(entry)
# Ordering of repositories
if order == "date":
def repo_order((reponame, repoinfo, repos, youngest, err, href)):
return (youngest.date if youngest else to_datetime(0), embedded_numbers(reponame.lower()))
elif order == "author":
def repo_order((reponame, repoinfo, repos, youngest, err, href)):
return (youngest.author.lower() if youngest else "", embedded_numbers(reponame.lower()))
else:
def repo_order((reponame, repoinfo, repos, youngest, err, href)):
return embedded_numbers(reponame.lower())
repositories = sorted(repositories, key=repo_order, reverse=desc)
return {"repositories": repositories, "timerange": timerange, "colorize_age": custom_colorizer}
示例11: getbool
def getbool(self, key, default=''):
"""Return the value of the specified option as boolean.
This method returns `True` if the option value is one of "yes", "true",
"enabled", "on", or non-zero numbers, ignoring case. Otherwise `False`
is returned.
Valid default input is a string or a bool. Returns a bool.
"""
return as_bool(self.get(key, default))
示例12: get_subscriptions
def get_subscriptions(self):
"""Generates tuples of (distributor, sid, authenticated, email).
Tuples are suitable for yielding from IAnnouncementSubscriber's
subscriptions method.
"""
with self.env.db_query as db:
cursor = db.cursor()
cursor.execute("""
SELECT sid, authenticated, value
FROM session_attribute
WHERE name=%s
""", (self._attr_name(),))
for result in cursor.fetchall():
dists, val = decode(result[2])
for dist in dists:
if as_bool(val):
authenticated = as_bool(result[1])
yield (dist, result[0], authenticated, None)
示例13: process_request
def process_request(self, req):
req.perm.require('BROWSER_VIEW')
presel = req.args.get('preselected')
if presel and (presel + '/').startswith(req.href.browser() + '/'):
req.redirect(presel)
path = req.args.get('path', '/')
rev = req.args.get('rev', '')
if rev in ('', 'HEAD'):
rev = None
order = req.args.get('order', 'name').lower()
desc = req.args.has_key('desc')
xhr = req.get_header('X-Requested-With') == 'XMLHttpRequest'
rm = RepositoryManager(self.env)
all_repositories = rm.get_all_repositories()
reponame, repos, path = rm.get_repository_by_path(path)
# Repository index
show_index = not reponame and path == '/'
if show_index:
if repos and (as_bool(all_repositories[''].get('hidden'))
or not repos.can_view(req.perm)):
repos = None
if not repos and reponame:
raise ResourceNotFound(_("Repository '%(repo)s' not found",
repo=reponame))
if reponame and reponame != repos.reponame: # Redirect alias
qs = req.query_string
req.redirect(req.href.browser(repos.reponame or None, path)
+ (qs and '?' + qs or ''))
reponame = repos and repos.reponame or None
# Find node for the requested path/rev
context = Context.from_request(req)
node = None
display_rev = lambda rev: rev
if repos:
try:
if rev:
rev = repos.normalize_rev(rev)
# If `rev` is `None`, we'll try to reuse `None` consistently,
# as a special shortcut to the latest revision.
rev_or_latest = rev or repos.youngest_rev
node = get_existing_node(req, repos, path, rev_or_latest)
except NoSuchChangeset, e:
raise ResourceNotFound(e.message,
_('Invalid changeset number'))
context = context(repos.resource.child('source', path,
version=rev_or_latest))
display_rev = repos.display_rev
示例14: get_ticket_group_stats
def get_ticket_group_stats(self, ticket_ids):
stat = TicketGroupStats(self.drilldown_label, self.sum_label)
for group in self._get_groups(ticket_ids):
stat.add_interval(
title=group.get('label', group['name']),
count=group.get('total', 0),
qry_args=group.get('query_args', {}),
css_class=group.get('css_class', group['name']),
overall_completion=as_bool(group.get('overall_completion')))
stat.refresh_calcs()
return stat
示例15: _extend_info
def _extend_info(self, reponame, info, editable):
"""Extend repository info for rendering."""
info['name'] = reponame
info['hidden'] = as_bool(info.get('hidden'))
info['editable'] = editable
if 'alias' not in info:
if info.get('dir') is not None:
info['prettydir'] = breakable_path(info['dir']) or ''
try:
repos = RepositoryManager(self.env).get_repository(reponame)
except InvalidRepository, e:
info['error'] = e
except TracError:
pass # Probably "unsupported connector"