本文整理汇总了Python中trac.mimeview.Context.from_request方法的典型用法代码示例。如果您正苦于以下问题:Python Context.from_request方法的具体用法?Python Context.from_request怎么用?Python Context.from_request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类trac.mimeview.Context
的用法示例。
在下文中一共展示了Context.from_request方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_converted_doctest
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
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>')
示例2: render_admin_panel
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
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
示例3: process_request
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
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)
示例4: _render_editor
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
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
示例5: _download_link
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
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')
示例6: process_request
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
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,)
示例7: create_trac_ctx
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
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)
示例8: process_request
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
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)
示例9: _check_quickjump
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
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)
示例10: __init__
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
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
示例11: getPageHTML
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
def getPageHTML(self, req, pagename, version=None):
""" Return latest version of page as rendered HTML, utf8 encoded. """
page = self._fetch_page(req, pagename, version)
fields = {"text": page.text}
for manipulator in self.manipulators:
manipulator.prepare_wiki_page(req, page, fields)
context = Context.from_request(req, page.resource, absurls=True)
html = format_to_html(self.env, context, fields["text"])
return "<html><body>%s</body></html>" % html.encode("utf-8")
示例12: _replaces_formatter
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
def _replaces_formatter(self, formatter, ns, match):
replaces = match.group('replaces')
if replaces not in self.replace:
return match.group(0)
title = self.replace[replaces]
context = Context.from_request(formatter.req, formatter.resource)
return Markup('<span>%s</span>' % (format_to_oneliner(self.env,context,title)))
示例13: process_request
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
def process_request(self, req):
link = req.args.get('link', '')
link_elt = extract_link(self.env, Context.from_request(req), link)
if isinstance(link_elt, Element):
href = link_elt.attrib.get('href')
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)
示例14: process_request
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
def process_request(self, req):
api = TrackerApi
context = Context.from_request(req)
db = self.env.get_db_cnx()
context.cursor = db.cursor()
actions = self._get_actions(context)
if req.args.get('fromDMY') and req.args.get('toDMY') and req.args.get('username'):
username = req.args.get('username')
fromDMY = int(time.mktime(time.strptime(req.args.get('fromDMY'), '%d-%m-%Y'))).__str__()
toDMY = int(time.mktime(time.strptime(req.args.get('toDMY'), '%d-%m-%Y'))).__str__()
DEFAULT_TIME_VALUE = 10
screenshots = self._get_users_screenshots(username, fromDMY, toDMY)
summaryWorkedTimeInMinutes = len(screenshots) * DEFAULT_TIME_VALUE
temp_tasks = {}
for screenshot in screenshots:
if screenshot['ticketId'] in temp_tasks.keys():
temp_tasks[screenshot['ticketId']]['minutes'] += DEFAULT_TIME_VALUE
else:
temp_tasks[screenshot['ticketId']] = {'minutes': DEFAULT_TIME_VALUE, 'name': screenshot['summary'],
'id': screenshot['ticketId']}
tasks = []
for key, temp_task in temp_tasks.iteritems():
href = Href(req.base_path)
task = {
'hours': int(temp_task['minutes'] / 60),
'minutes': temp_task['minutes'] % 60,
'name': temp_task['name'],
'id': temp_task['id'],
'href': href.ticket(temp_task['id'])
}
tasks.append(task)
req.data = {
'screenshots': screenshots,
'tasks': tasks,
'summaryWorkedTimeHours': int(summaryWorkedTimeInMinutes / 60),
'summaryWorkedTimeMinutes': summaryWorkedTimeInMinutes % 60,
'fromDMY': req.args.get('fromDMY'),
'toDMY': req.args.get('toDMY'),
'username': req.args.get('username')
}
add_stylesheet(req, 'trac/css/tracker.css')
return "user_report.html", req.data, None
else:
add_script(req, 'common/js/jquery-ui.js')
add_stylesheet(req, 'common/css/jquery-ui/jquery-ui.css')
add_script(req, 'common/js/jquery-ui-addons.js')
add_stylesheet(req, 'common/css/jquery-ui-addons.css')
req.data = {
'users': api.get_users(TrackerApi(), context)
}
add_stylesheet(req, 'trac/css/tracker.css')
return "user_report_date_picker.html", req.data, None
示例15: _get_quickjump
# 需要导入模块: from trac.mimeview import Context [as 别名]
# 或者: from trac.mimeview.Context import from_request [as 别名]
def _get_quickjump(self, req, query):
"""Find quickjump requests if the search comes from the searchbox
in the header. The search is assumed to be from the header searchbox
if no page or per_page arguments are found.
"""
if req.args.get('page') or req.args.get('per_page'):
return None
link = extract_link(self.env,
Context.from_request(req, 'advsearch'), query)
if isinstance(link, Element):
return link.attrib.get('href')