本文整理汇总了Python中trac.web.chrome.Chrome.generate方法的典型用法代码示例。如果您正苦于以下问题:Python Chrome.generate方法的具体用法?Python Chrome.generate怎么用?Python Chrome.generate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类trac.web.chrome.Chrome
的用法示例。
在下文中一共展示了Chrome.generate方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _create_page_param
# 需要导入模块: from trac.web.chrome import Chrome [as 别名]
# 或者: from trac.web.chrome.Chrome import generate [as 别名]
def _create_page_param(self, req, page_param):
# page_param['workflow_config']
# sort config for display
section = self.config['ticket-workflow']
name_list = []
for (name, value) in section.options():
name_list.append(name)
name_list.sort()
# create config data for display
ret_val = ''
for name in name_list:
ret_val += name + '=' + section.get(name) + '\n'
page_param['workflow_config'] = ret_val
# page_param['workflow_default_config']
# localization
locale = LocaleUtil().get_locale(req)
if (locale == 'ja'):
init_file = 'trac_jp.ini'
else:
init_file = 'trac.ini'
# read defalut config
template = Chrome(self.env).load_template(init_file, 'text')
stream = template.generate()
default_config = stream.render('text', encoding=None)
page_param['workflow_default_config'] = default_config
示例2: expand_macro
# 需要导入模块: from trac.web.chrome import Chrome [as 别名]
# 或者: from trac.web.chrome.Chrome import generate [as 别名]
def expand_macro(self, formatter, name, content):
data=dict(user_profiles=[], user_profile_fields={})
rendered_result=""
content_args={}
layout_args={}
user_profile_templates=[]
# collecting arguments
if content:
for i, macro_args in enumerate( content.split('|') ):
if i == 0:
content_args = MacroArguments( macro_args )
continue
if i == 1:
layout_args = MacroArguments( macro_args )
break
# extracting userProfile attrs
if len(content_args)>0:
user_profile_templates.append(User(**content_args))
if len(content_args.get_list_args())>0:
for list_item in content_args.get_list_args():
user_profile_templates.append(User( **MacroArguments(list_item[1:len(list_item)-1])))
# adding profiles fields description
data['user_profile_fields'].update(UserProfileManager(self.env).get_user_profile_fields(ignore_internal=True))
# removing picture_href
data['user_profile_fields'].pop('picture_href')
def inline_wiki_to_html(text):
return wiki_to_html(text, self.env, formatter.req)
data['wiki_to_html'] = inline_wiki_to_html
# grabbing users
if len(user_profile_templates)>0:
data['user_profiles'] = UserManager(self.env).search_users(user_profile_templates)
else:
data['user_profiles'] = UserManager(self.env).get_active_users()
data['cells']=list(self._get_cells(data['user_profiles']))
# add stylesheet&script
add_stylesheet(formatter.req,'tracusermanager/css/macros_um_profile.css')
add_script(formatter.req,'tracusermanager/js/macros_um_profile.js')
# render template
template = Chrome(self.env).load_template('macro_um_profile.html',method='xhtml')
data = Chrome(self.env).populate_data(formatter.req, {'users':data})
rendered_result = template.generate(**data)
# wrap everything
if len(layout_args)>0:
rendered_result= html.div(rendered_result, **layout_args)
return rendered_result
示例3: _do_deploy
# 需要导入模块: from trac.web.chrome import Chrome [as 别名]
# 或者: from trac.web.chrome.Chrome import generate [as 别名]
def _do_deploy(self, dest):
target = os.path.normpath(dest)
chrome_target = os.path.join(target, "htdocs")
script_target = os.path.join(target, "cgi-bin")
# Copy static content
makedirs(target, overwrite=True)
makedirs(chrome_target, overwrite=True)
from trac.web.chrome import Chrome
printout(_("Copying resources from:"))
for provider in Chrome(self.env).template_providers:
paths = list(provider.get_htdocs_dirs() or [])
if not len(paths):
continue
printout(" %s.%s" % (provider.__module__, provider.__class__.__name__))
for key, root in paths:
if not root:
continue
source = os.path.normpath(root)
printout(" ", source)
if os.path.exists(source):
dest = os.path.join(chrome_target, key)
copytree(source, dest, overwrite=True)
# Create and copy scripts
makedirs(script_target, overwrite=True)
printout(_("Creating scripts."))
data = {"env": self.env, "executable": sys.executable}
for script in ("cgi", "fcgi", "wsgi"):
dest = os.path.join(script_target, "trac." + script)
template = Chrome(self.env).load_template("deploy_trac." + script, "text")
stream = template.generate(**data)
with open(dest, "w") as out:
stream.render("text", out=out, encoding="utf-8")
示例4: filter_stream
# 需要导入模块: from trac.web.chrome import Chrome [as 别名]
# 或者: from trac.web.chrome.Chrome import generate [as 别名]
def filter_stream(self, req, method, filename, stream, data):
if self.olark_identity:
template = Chrome(self.env).load_template('olark.html')
shortname = self.env.path.split("/")[-1]
jsblock = template.generate(visitor_name=javascript_quote("%s (%s) in %s" % (req.session.get('name'),
req.authname,
shortname)),
identity=self.olark_identity)
stream |= Transformer("//body").append(jsblock)
return stream
示例5: expand_macro
# 需要导入模块: from trac.web.chrome import Chrome [as 别名]
# 或者: from trac.web.chrome.Chrome import generate [as 别名]
def expand_macro(self, formatter, name, content, args):
data = parse_args(content)[1]
if data.has_key("id"):
data["form"] = "new-project-form-%s" % data["id"]
data["project"] = "project-name-%s" % data["id"]
else:
data["form"] = "new-project-form"
data["project"] = "project-name"
self.log.debug("EXPAND ARGUMENTS: %s " % data)
req = formatter.req
template = Chrome(self.env).load_template('newpageform.html',method='xhtml')
data = Chrome(self.env).populate_data(req, data)
rendered_result = template.generate(**data)
return rendered_result
示例6: do_deploy
# 需要导入模块: from trac.web.chrome import Chrome [as 别名]
# 或者: from trac.web.chrome.Chrome import generate [as 别名]
def do_deploy(self, line):
argv = self.arg_tokenize(line)
if not argv[0]:
self.do_help('deploy')
return
target = os.path.normpath(argv[0])
if os.path.exists(target):
raise TracError('Destination already exists. Remove and retry.')
chrome_target = os.path.join(target, 'htdocs')
script_target = os.path.join(target, 'cgi-bin')
# Copy static content
os.makedirs(target)
os.makedirs(chrome_target)
from trac.web.chrome import Chrome
env = self.env_open()
printout(_("Copying resources from:"))
for provider in Chrome(env).template_providers:
paths = list(provider.get_htdocs_dirs())
if not len(paths):
continue
printout(' %s.%s' % (provider.__module__,
provider.__class__.__name__))
for key, root in paths:
source = os.path.normpath(root)
printout(' ', source)
if os.path.exists(source):
dest = os.path.join(chrome_target, key)
copytree(source, dest, overwrite=True)
# Create and copy scripts
os.makedirs(script_target)
printout(_("Creating scripts."))
data = {'env': env, 'executable': sys.executable}
for script in ('cgi', 'fcgi', 'wsgi'):
dest = os.path.join(script_target, 'trac.'+script)
template = Chrome(env).load_template('deploy_trac.'+script, 'text')
stream = template.generate(**data)
out = open(dest, 'w')
stream.render('text', out=out)
out.close()
示例7: expand_macro
# 需要导入模块: from trac.web.chrome import Chrome [as 别名]
# 或者: from trac.web.chrome.Chrome import generate [as 别名]
def expand_macro(self, formatter, name, content, args):
data = parse_args(content)[1]
if data.has_key("id"):
data["form"] = "new-ticket-form-%s" % data["id"]
else:
data["form"] = "new-ticket-form"
for default in self.defaults:
data.setdefault(default[0], default[1])
data['form_fields'] = [i.strip() for i in data['form_fields'].split()
if i.strip()]
data['hidden_fields'] = [i.strip() for i in data['hidden_fields'].split()
if i.strip()]
_form_fields = []
if len(data['form_fields']):
fields = dict((i['name'], i) for i in TicketSystem(self.env).get_ticket_fields())
for field in data['form_fields']:
if '%s_placeholder' % field in data:
fields[field]['placeholder'] = data['%s_placeholder' % field]
else:
fields[field]['placeholder'] = fields[field]['label']
if field == 'owner':
TicketSystem(self.env).eventually_restrict_owner(fields[field])
_form_fields.append(fields[field])
data['form_fields'] = _form_fields
if len(data['hidden_fields']):
data['hidden_fields'] = [i.split("=") for i in data['hidden_fields']]
self.log.debug("EXPAND ARGUMENTS: %s " % data)
req = formatter.req
template = Chrome(self.env).load_template('newticketmacro_form.html',method='xhtml')
data = Chrome(self.env).populate_data(req, data)
rendered_result = template.generate(**data)
add_stylesheet(req, 'newticketmacro/form.css')
return rendered_result
示例8: filter_stream
# 需要导入模块: from trac.web.chrome import Chrome [as 别名]
# 或者: from trac.web.chrome.Chrome import generate [as 别名]
def filter_stream(self, req, method, filename, stream, data):
if req.path_info.startswith('/admin'):
return stream
options = self.get_options()
if not options.get('uid'):
self.log.debug('Plugin not configured, returning stream')
return stream
elif ('TRAC_ADMIN' in req.perm) and (not options['admin_logging']):
self.log.debug("Not tracking TRAC_ADMIN's, returning stream")
return stream
elif (req.authname and req.authname != "anonymous") \
and (not options['authenticated_logging']):
self.log.debug("Not tracking authenticated users, returning stream")
return stream
template = Chrome(self.env).load_template('google_analytics.html')
data = template.generate(
admin= 'TRAC_ADMIN' in req.perm,
opt=options,
base_url='http:\/\/%s' % req.environ.get('HTTP_HOST'))
return stream | Transformer('body').append(data)
示例9: _do_deploy
# 需要导入模块: from trac.web.chrome import Chrome [as 别名]
# 或者: from trac.web.chrome.Chrome import generate [as 别名]
def _do_deploy(self, dest):
target = os.path.normpath(dest)
chrome_target = os.path.join(target, 'htdocs')
script_target = os.path.join(target, 'cgi-bin')
# Copy static content
makedirs(target, overwrite=True)
makedirs(chrome_target, overwrite=True)
from trac.web.chrome import Chrome
printout(_("Copying resources from:"))
for provider in Chrome(self.env).template_providers:
paths = list(provider.get_htdocs_dirs() or [])
if not len(paths):
continue
printout(' %s.%s' % (provider.__module__,
provider.__class__.__name__))
for key, root in paths:
source = os.path.normpath(root)
printout(' ', source)
if os.path.exists(source):
dest = os.path.join(chrome_target, key)
copytree(source, dest, overwrite=True)
# Create and copy scripts
makedirs(script_target, overwrite=True)
printout(_("Creating scripts."))
data = {'env': self.env, 'executable': sys.executable}
for script in ('cgi', 'fcgi', 'wsgi'):
dest = os.path.join(script_target, 'trac.' + script)
template = Chrome(self.env).load_template('deploy_trac.' + script,
'text')
stream = template.generate(**data)
out = file(dest, 'w')
try:
stream.render('text', out=out)
finally:
out.close()
示例10: filter_stream
# 需要导入模块: from trac.web.chrome import Chrome [as 别名]
# 或者: from trac.web.chrome.Chrome import generate [as 别名]
def filter_stream(self, req, method, filename, stream, data):
if not self.config.getbool('google.search',
'google_search_active', True):
self.log.debug('Google search disabled. Returning regular stream.')
return stream
search_form_id = self.config.get('google.search',
'search_form_id', 'search')
forid = self.config.get('google.search', 'search_form_forid', None)
client_id = self.config.get('google.search',
'search_form_client_id', None)
if not search_form_id:
self.log.warn('The value of the search form id is empty. Returning '
'regular template stream')
return stream
elif not forid:
self.log.warn('The value of "FORID" for the search form is empty. '
'Returning regular template stream')
return stream
elif not client_id:
self.log.warn('The value of "Client ID" for the search form is '
'empty. Returning regular template stream')
return stream
template = Chrome(self.env).load_template('google_search_form.html')
data = dict(
req = req,
search_form_id = search_form_id,
input_width = self.config.get('google.search',
'search_form_text_input_width', 31),
charset = self.config.get('trac', 'default_charset', 'utf-8'),
forid = forid,
client_id = client_id
)
return stream | Transformer('//div/form[@id="%s"]' % search_form_id) \
.replace(template.generate(**data))
示例11: expand_macro
# 需要导入模块: from trac.web.chrome import Chrome [as 别名]
# 或者: from trac.web.chrome.Chrome import generate [as 别名]
#.........这里部分代码省略.........
extra_sql = u' AND '.join(extra_sql_constraints)
if hasattr(self.env, 'get_read_db'):
db = self.env.get_read_db()
else:
db = self.env.get_db_cnx()
cursor = db.cursor()
series = {
'openedTickets': {},
'closedTickets': {},
'reopenedTickets': {},
'openTickets': {}
}
# NOTE on casting times: in the sql statements below, we use:
# CAST((time / 86400) AS int) * 86400 AS date
# which homogenize all times during a day to the same day. Example:
# The following two values will have the same value
# 1386280739 (2013-12-05 22:58:59) -> 2013-12-05 00:00:00
# 1386270739 (2013-12-05 20:12:19) -> 2013-12-05 00:00:00
# number of created tickets for the time period, grouped by day
# a day has 86400 seconds
if init_stat in statuses:
sql = 'SELECT COUNT(DISTINCT id), ' \
'CAST((time / 86400000000) AS int) * 86400 AS date ' \
'FROM ticket WHERE {0} {1} time BETWEEN %s AND %s ' \
'GROUP BY date ORDER BY date ASC'.format(
extra_sql, ' AND ' if extra_sql else '', statuses_sql)
cursor.execute(sql, tuple(extra_parameters) + (sql_start, sql_end))
for count, timestamp in cursor:
# flot needs the time in milliseconds, not seconds, see
# https://github.com/flot/flot/blob/master/API.md#time-series-data
series['openedTickets'][timestamp*1000] = float(count)
# number of reopened tickets for the time period, grouped by day
# a day has 86400 seconds
cursor.execute("SELECT COUNT(DISTINCT tc.ticket), "
"CAST((tc.time / 86400000000) AS int) * 86400 as date "
"FROM ticket_change tc JOIN ticket t ON t.id = tc.ticket "
"WHERE {0} {1} field = 'status' AND newvalue in ({2}) AND oldvalue NOT IN ({2}) "
"AND tc.time BETWEEN %s AND %s "
"GROUP BY date ORDER BY date ASC".format(
extra_sql, ' AND ' if extra_sql else '', statuses_sql),
tuple(extra_parameters) + (sql_start, sql_end))
for count, timestamp in cursor:
# flot needs the time in milliseconds, not seconds, see
# https://github.com/flot/flot/blob/master/API.md#time-series-data
series['reopenedTickets'][float(timestamp*1000)] = float(count)
# number of closed tickets for the time period, grouped by day (ms)
cursor.execute("SELECT COUNT(DISTINCT ticket), "
"CAST((tc.time / 86400000000) AS int) * 86400 AS date "
"FROM ticket_change tc JOIN ticket t ON t.id = tc.ticket "
"WHERE {0} {1} tc.field = 'status' AND tc.newvalue not in ({2}) AND tc.oldvalue in ({2})"
"AND tc.time BETWEEN %s AND %s " \
"GROUP BY date ORDER BY date ASC".format(
extra_sql, ' AND ' if extra_sql else '', statuses_sql),
tuple(extra_parameters) + (sql_start, sql_end))
for count, timestamp in cursor:
# flot needs the time in milliseconds, not seconds, see
# https://github.com/flot/flot/blob/master/API.md#time-series-data
series['closedTickets'][float(timestamp*1000)] = -float(count)
# calculate number of open tickets for each day
# number of open tickets up to now
cursor.execute(
"SELECT COUNT(*) FROM ticket "
"WHERE {0} {1} status in ({2})".format(
extra_sql, ' AND ' if extra_sql else '', statuses_sql),
tuple(extra_parameters))
open_tickets = cursor.fetchone()[0]
series['openTickets'][ts_end * 1000] = open_tickets
formatter.env.log.debug('ts_end = {0}, ts_start = {1}'.format(ts_end, ts_start))
for day_ms in range(long(math.floor(ts_end / 86400.0) * 86400000), long(ts_start * 1000), -86400000):
open_tickets -= series['closedTickets'].get(day_ms, 0)
open_tickets -= series['openedTickets'].get(day_ms, 0)
open_tickets -= series['reopenedTickets'].get(day_ms, 0)
series['openTickets'][day_ms] = open_tickets
# sort all series and put them in data
for i in series:
keys = series[i].keys()
keys.sort()
data[i] = json.dumps([(k, series[i][k]) for k in keys])
# generate output
# NOTE: if you change the namespace below, you also need to change it
# when using in get_htdocs_dirs
add_javascript(formatter.req, 'stsm/js/excanvas.min.js')
add_javascript(formatter.req, 'stsm/js/jquery.flot.min.js')
add_javascript(formatter.req, 'stsm/js/jquery.flot.stack.min.js')
add_javascript(formatter.req, 'stsm/js/simpleticketstats.js')
template = Chrome(self.env).load_template(
'simpleticketstats_macro.html', method='text')
formatter.env.log.debug(data)
return Markup(template.generate(**data))
示例12: expand_macro
# 需要导入模块: from trac.web.chrome import Chrome [as 别名]
# 或者: from trac.web.chrome.Chrome import generate [as 别名]
def expand_macro(self, formatter, name, content, args):
data = parse_args(content)[1]
if data.has_key("order"):
if data["order"] == "ascending":
order = False
elif data["order"] == "descending":
order = True
else:
order = True
else:
order = True
self.log.debug("EXPAND ARGUMENTS: %s " % data)
req = formatter.req
wiki = formatter.wiki
db = self.env.get_db_cnx()
releasedata = {}
fields = []
first = True
for page in wiki.get_pages(data["prefix"]):
self.log.debug("PAGE: %s " % page)
if page == data["prefix"]:
continue
else:
sql = "SELECT tag from tags where name = '%s'" % page
cs = db.cursor()
cs.execute(sql)
row = cs.fetchone()
if row == None:
continue
pagetag = row[0]
if pagetag != data["tag"]:
continue
version = page.split("/")[-1]
releasedata[version] = []
sql = "SELECT text from wiki where name = '%s' order by version desc limit 1" % page
cs = db.cursor()
cs.execute(sql)
row = cs.fetchone()
if row == None:
continue
text = row[0].split("----")[0]
self.log.debug("CONTENT: %s" % text)
lines = text.split("\n")
for line in lines:
if line.startswith("||"):
parts = line.split("||")
releasedata[version].append(parts[2])
if first:
fields.append(parts[1])
first = False
self.log.debug("DATA: %s" % releasedata)
if data.has_key("subset"):
subset = data["subset"].split(" ")
self.log.debug("SUBSET: %s" % subset)
newfields = []
newreleasedata = {}
for x in subset:
x = int(x)-1
newfields.append(fields[x])
for release in releasedata:
if not newreleasedata.has_key(release):
newreleasedata[release] = []
newreleasedata[release].append(releasedata[release][x])
fields = newfields
releasedata = newreleasedata
self.log.debug("FIELDS: %s" % fields)
self.log.debug("DATA: %s" % releasedata)
if data.has_key("limit"):
limit = int(data["limit"])
else:
limit = len(releasedata.keys())
template = Chrome(self.env).load_template('recentreleases.html',method='xhtml')
data = Chrome(self.env).populate_data(req, {"context": formatter.context, "env": self.env, "fields":fields,"releasedata":releasedata,"limit":limit, "order":order})
rendered_result = template.generate(**data)
return rendered_result
示例13: expand_macro
# 需要导入模块: from trac.web.chrome import Chrome [as 别名]
# 或者: from trac.web.chrome.Chrome import generate [as 别名]
def expand_macro(self, formatter, name, args):
"""
@param formatter:
@param name:
@param args:
@return:
"""
args = _parse_args(args)
args = _get_args_defaults(formatter.env, args)
d_date_range = args["daterange"].split(";")
if len(d_date_range) == 1:
d_date_range.append("")
from_date = _parse_relative_time(d_date_range[0] or "10y", utc)
at_date = _parse_relative_time(d_date_range[1] or "now", utc)
graph_res = int(args["res_days"])
if "query" in args:
query = args["query"]
query_object = Query.from_string(self.env, query)
sql_format_string, format_string_arguments = query_object.get_sql()
# Hack to remove extra columns, I don't know another way to do it
sql_format_string = "SELECT t.id " + \
sql_format_string[
sql_format_string.index("FROM ticket"):]
ticketFilter = "AND t.id IN (%s)" % \
(sql_format_string % tuple(format_string_arguments))
else:
ticketFilter = ""
chart_title = args["title"]
req = formatter.req
count = []
# Calculate 0th point
last_date = from_date - timedelta(graph_res)
last_num_open = self._get_num_open_tix(last_date, req, ticketFilter)
# Calculate remaining points
for cur_date in date_range(from_date, at_date, graph_res):
num_open = self._get_num_open_tix(cur_date, req, ticketFilter)
num_closed = self._get_num_closed_tix(last_date, cur_date, req,
ticketFilter)
date = format_date(cur_date)
if graph_res != 1:
date = "%s thru %s" % (format_date(last_date), date)
count.append({
'date': date,
'new': num_open - last_num_open + num_closed,
'closed': num_closed,
'open': num_open})
last_num_open = num_open
last_date = cur_date
chart_data = ", \n".join(['{date: \'%(date)s\', new_tickets: %(new)d, '
'closed: %(closed)d, open: %(open)d}' % d
for d in count])
data = {
'chart_title': chart_title,
'chart_data': chart_data,
'height': args['height'],
'column_width': args['column_width'],
'id': random.randint(1, 9999999)
}
template = Chrome(self.env).load_template('ticketstats_macro.html')
return template.generate(**data)