本文整理汇总了Python中trac.mimeview.Context类的典型用法代码示例。如果您正苦于以下问题:Python Context类的具体用法?Python Context怎么用?Python Context使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Context类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _do_remove
def _do_remove(self, identifier):
# Get downloads API component.
api = self.env[DownloadsApi]
# Create context.
context = Context('downloads-consoleadmin')
db = self.env.get_db_cnx()
context.cursor = db.cursor()
context.req = FakeRequest(self.env, self.consoleadmin_user)
# Get download by ID or filename.
try:
download_id = int(identifier)
download = api.get_download(context, download_id)
except ValueError:
download = api.get_download_by_file(context, identifier)
# Check if download exists.
if not download:
raise AdminCommandError(_('Invalid download identifier: %(value)s',
value = identifier))
# Delete download by ID.
api.delete_download(context, download_id)
# Commit changes in DB.
db.commit()
示例2: test_converted_doctest
def test_converted_doctest(self):
self.repos.get_changeset=lambda x: Mock(date=to_datetime(12345, utc))
BuildConfig(self.env, name='trunk', path='trunk').insert()
Build(self.env, rev=123, config='trunk', rev_time=12345, platform=1
).insert()
rpt = Report(self.env, build=1, step='test', category='coverage')
rpt.items.append({'file': 'foo.py', 'line_hits': '5 - 0'})
rpt.insert()
ann = TestCoverageAnnotator(self.env)
req = Mock(href=Href('/'), perm=MockPerm(),
chrome={'warnings': []}, args={})
# Version in the branch should not match:
context = Context.from_request(req, 'source', '/branches/blah/foo.py', 123)
self.assertEquals(ann.get_annotation_data(context), [])
# Version in the trunk should match:
context = Context.from_request(req, 'source', '/trunk/foo.py', 123)
data = ann.get_annotation_data(context)
self.assertEquals(data, [u'5', u'-', u'0'])
def annotate_row(lineno, line):
row = tag.tr()
ann.annotate_row(context, row, lineno, line, data)
return unicode(row.generate().render('html'))
self.assertEquals(annotate_row(1, 'x = 1'),
u'<tr><th class="covered">5</th></tr>')
self.assertEquals(annotate_row(2, ''),
u'<tr><th></th></tr>')
self.assertEquals(annotate_row(3, 'y = x'),
u'<tr><th class="uncovered">0</th></tr>')
示例3: _do_add
def _do_add(self, filename, *arguments):
# Get downloads API component.
api = self.env[DownloadsApi]
# Create context.
context = Context('downloads-consoleadmin')
db = self.env.get_db_cnx()
context.cursor = db.cursor()
context.req = FakeRequest(self.env, self.consoleadmin_user)
# Convert relative path to absolute.
if not os.path.isabs(filename):
filename = os.path.join(self.path, filename)
# Open file object.
file, filename, file_size = self._get_file(filename)
# Create download dictionary from arbitrary attributes.
download = {'file' : filename,
'size' : file_size,
'time' : to_timestamp(datetime.now(utc)),
'count' : 0}
# Read optional attributes from arguments.
for argument in arguments:
# Check correct format.
argument = argument.split("=")
if len(argument) != 2:
AdminCommandError(_('Invalid format of download attribute:'
' %(value)s', value = argument))
name, value = argument
# Check known arguments.
if not name in ('description', 'author', 'tags', 'component', 'version',
'architecture', 'platform', 'type'):
raise AdminCommandError(_('Invalid download attribute:'
' %(value)s', value = name))
# Transform architecture, platform and type name to ID.
if name == 'architecture':
value = api.get_architecture_by_name(context, value)['id']
elif name == 'platform':
value = api.get_platform_by_name(context, value)['id']
elif name == 'type':
value = api.get_type_by_name(context, value)['id']
# Add attribute to download.
download[name] = value
self.log.debug(download)
# Upload file to DB and file storage.
api._add_download(context, download, file)
# Close input file and commit changes in DB.
file.close()
db.commit()
示例4: _resolve_ids
def _resolve_ids(self, download):
# Create context.
context = Context('downloads-core')
db = self.env.get_db_cnx()
context.cursor = db.cursor()
# Resolve platform and type names.
api = self.env[DownloadsApi]
platform = api.get_platform(context, download['platform'])
type = api.get_type(context, download['type'])
download['platform'] = platform['name']
download['type'] = type['name']
示例5: get_resource_description
def get_resource_description(self, resource, format="default", context=None, **kwargs):
# Create context.
context = Context("downloads-core")
db = self.env.get_db_cnx()
context.cursor = db.cursor()
# Get download from ID.
api = self.env[DownloadsApi]
download = api.get_download(context, safe_int(resource.id))
if format == "compact":
return download["file"]
elif format == "summary":
return "(%s) %s" % (pretty_size(download["size"]), download["description"])
return download["file"]
示例6: _do_list
def _do_list(self):
# Get downloads API component.
api = self.env[DownloadsApi]
# Create context.
context = Context('downloads-consoleadmin')
db = self.env.get_db_cnx()
context.cursor = db.cursor()
# Print uploded download
downloads = api.get_downloads(context)
print_table([(download['id'], download['file'], pretty_size(
download['size']), format_datetime(download['time']), download['component'], download['version'],
download['platform']['name'], download['type']['name']) for download in downloads], ['ID',
'Filename', 'Size', 'Uploaded', 'Component', 'Version', 'Platform', 'Type'])
示例7: _download_link
def _download_link(self, formatter, ns, params, label):
if ns == 'download':
if formatter.req.perm.has_permission('DOWNLOADS_VIEW'):
# Create context.
context = Context.from_request(formatter.req)('downloads-wiki')
db = self.env.get_db_cnx()
context.cursor = db.cursor()
# Get API component.
api = self.env[DownloadsApi]
# Get download.
if re.match(r'\d+', params):
download = api.get_download(context, params)
else:
download = api.get_download_by_file(context, params)
if download:
# Return link to existing file.
return html.a(label, href = formatter.href.downloads(params),
title = '%s (%s)' % (download['file'],
pretty_size(download['size'])))
else:
# Return link to non-existing file.
return html.a(label, href = '#', title = 'File not found.',
class_ = 'missing')
else:
# Return link to file to which is no permission.
return html.a(label, href = '#', title = 'No permission to file.',
class_ = 'missing')
示例8: render_admin_panel
def render_admin_panel(self, req, category, page, path_info):
# Prepare request object.
if page == "forum":
if not req.args.has_key("group"):
req.args["group"] = "-1"
if path_info:
req.args["forum"] = path_info
else:
if path_info:
req.args["group"] = path_info
# Create request context.
context = Context.from_request(req)
context.realm = "discussion-admin"
# Process request.
api = self.env[DiscussionApi]
template, data = api.process_discussion(context)
if context.redirect_url:
# Redirect request if needed.
href = req.href(context.redirect_url[0]) + context.redirect_url[1]
self.log.debug("Redirecting to %s" % (href))
req.redirect(req.href("discussion", "redirect", redirect_url=href))
else:
# Return template and data.
return template, data
示例9: process_request
def process_request(self, req):
link = req.args.get("link", "")
parts = link.split(":", 1)
if len(parts) > 1:
resolver, target = parts
if target and (target[0] not in "'\"" or target[0] != target[-1]):
link = '%s:"%s"' % (resolver, target)
link_frag = extract_link(self.env, Context.from_request(req), link)
def get_first_href(item):
"""Depth-first search for the first `href` attribute."""
if isinstance(item, Element):
href = item.attrib.get("href")
if href is not None:
return href
if isinstance(item, Fragment):
for each in item.children:
href = get_first_href(each)
if href is not None:
return href
if isinstance(link_frag, (Element, Fragment)):
href = get_first_href(link_frag)
if href is None: # most probably no permissions to view
raise PermissionError(_("Can't view %(link)s:", link=link))
else:
href = req.href(link.rstrip(":"))
req.redirect(href)
示例10: create_trac_ctx
def create_trac_ctx(self, website_url, author_name, timezone_str, uri):
req = Mock(href=Href(uri),
abs_href=Href(website_url),
authname=author_name,
perm=MockPerm(),
tz=timezone_str,
args={})
context = Context.from_request(req, 'wiki', 'WikiStart')
env = EnvironmentStub(enable=['trac.*']) # + additional components
# -- macros support
env.path = ''
# -- intertrac support
env.config.set('intertrac', 'trac.title', "Trac's Trac")
env.config.set('intertrac', 'trac.url',
website_url)
env.config.set('intertrac', 't', 'trac')
env.config.set('intertrac', 'th.title', "Trac Hacks")
env.config.set('intertrac', 'th.url',
"http://trac-hacks.org")
env.config.set('intertrac', 'th.compat', 'false')
# -- safe schemes
env.config.set('wiki', 'safe_schemes',
'file,ftp,http,https,svn,svn+ssh,git,'
'rfc-2396.compatible,rfc-2396+under_score')
env.href = req.href
env.abs_href = req.abs_href
return (env, context)
示例11: process_request
def process_request(self, req):
# Create request context.
context = Context.from_request(req)("downloads-core")
# Process request and return content.
api = self.env[DownloadsApi]
return api.process_downloads(context) + (None,)
示例12: _check_quickjump
def _check_quickjump(self, req, kwd):
"""Look for search shortcuts"""
noquickjump = int(req.args.get('noquickjump', '0'))
# Source quickjump FIXME: delegate to ISearchSource.search_quickjump
quickjump_href = None
if kwd[0] == '/':
quickjump_href = req.href.browser(kwd)
name = kwd
description = _('Browse repository path %(path)s', path=kwd)
else:
link = extract_link(self.env, Context.from_request(req, 'search'),
kwd)
if isinstance(link, Element):
quickjump_href = link.attrib.get('href')
name = link.children
description = link.attrib.get('title', '')
if quickjump_href:
# Only automatically redirect to local quickjump links
if not quickjump_href.startswith(req.base_path or '/'):
noquickjump = True
if noquickjump:
return {'href': quickjump_href, 'name': tag.EM(name),
'description': description}
else:
req.redirect(quickjump_href)
示例13: _render_editor
def _render_editor(self, req, db, milestone):
data = {
'milestone': milestone,
'ticket': milestone.ticket,
'datefields' : self.date_fields,
'date_hint': get_date_format_hint(),
'datetime_hint': get_datetime_format_hint(),
'milestone_groups': [],
'jump_to' : req.args.get('jump_to') or referer_module(req)
}
if milestone.exists:
req.perm(milestone.resource).require('MILESTONE_VIEW')
milestones = [m for m in StructuredMilestone.select(self.env, db=db)
if m.name != milestone.name
and 'MILESTONE_VIEW' in req.perm(m.resource)]
data['milestone_groups'] = group_milestones(milestones,
'TICKET_ADMIN' in req.perm)
else:
req.perm(milestone.resource).require('MILESTONE_CREATE')
TicketModule(self.env)._insert_ticket_data(req, milestone.ticket, data,
get_reporter_id(req, 'author'), {})
self._add_tickets_report_data(milestone, req, data)
context = Context.from_request(req, milestone.resource)
data['attachments']=AttachmentModule(self.env).attachment_data(context)
return 'itteco_milestone_edit.html', data, None
示例14: process_request
def process_request(self, req):
# Create request context.
context = Context.from_request(req)
context.realm = 'screenshots-core'
# Template data dictionary.
req.data = {}
# Get database access.
db = self.env.get_db_cnx()
context.cursor = db.cursor()
# Prepare data structure.
req.data['title'] = self.mainnav_title or self.metanav_title
req.data['has_tags'] = self.env.is_component_enabled(
'tracscreenshots.tags.ScreenshotsTags')
# Get action from request and perform them.
actions = self._get_actions(context)
self.log.debug('actions: %s' % (actions,))
template, content_type = self._do_actions(context, actions)
# Add CSS style and JavaScript scripts.
add_stylesheet(req, 'screenshots/css/screenshots.css')
add_script(req, 'screenshots/js/screenshots.js')
# Return template and its data.
db.commit()
return (template + '.html', {'screenshots' : req.data}, content_type)
示例15: __init__
def __init__(self, title, input, correct, file, line, setup=None,
teardown=None, context=None):
unittest.TestCase.__init__(self, 'test')
self.title = title
self.input = input
self.correct = correct
self.file = file
self.line = line
self._setup = setup
self._teardown = teardown
req = Mock(href=Href('/'), abs_href=Href('http://www.example.com/'),
authname='anonymous', perm=MockPerm(), tz=None, args={})
if context:
if isinstance(context, tuple):
context = Context.from_request(req, *context)
else:
context = Context.from_request(req, 'wiki', 'WikiStart')
self.context = context
all_test_components = [
HelloWorldMacro, DivHelloWorldMacro, TableHelloWorldMacro,
DivCodeMacro, DivCodeElementMacro, DivCodeStreamMacro,
NoneMacro, WikiProcessorSampleMacro, SampleResolver]
self.env = EnvironmentStub(enable=['trac.*'] + all_test_components)
# -- macros support
self.env.path = ''
# -- intertrac support
self.env.config.set('intertrac', 'trac.title', "Trac's Trac")
self.env.config.set('intertrac', 'trac.url',
"http://trac.edgewall.org")
self.env.config.set('intertrac', 't', 'trac')
self.env.config.set('intertrac', 'th.title', "Trac Hacks")
self.env.config.set('intertrac', 'th.url',
"http://trac-hacks.org")
self.env.config.set('intertrac', 'th.compat', 'false')
# -- safe schemes
self.env.config.set('wiki', 'safe_schemes',
'file,ftp,http,https,svn,svn+ssh,'
'rfc-2396.compatible,rfc-2396+under_score')
# TODO: remove the following lines in order to discover
# all the places were we should use the req.href
# instead of env.href
self.env.href = req.href
self.env.abs_href = req.abs_href