本文整理汇总了Python中tractags.api.TagSystem类的典型用法代码示例。如果您正苦于以下问题:Python TagSystem类的具体用法?Python TagSystem怎么用?Python TagSystem使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TagSystem类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render_admin_panel
def render_admin_panel(self, req, cat, page, version):
req.perm.require("TAGS_ADMIN")
data = {}
tag_system = TagSystem(self.env)
if req.method == "POST":
# Replace Tag
allow_delete = req.args.get("allow_delete")
new_tag = req.args.get("tag_new_name").strip()
new_tag = not new_tag == u"" and new_tag or None
if not (allow_delete or new_tag):
data["error"] = _(
"""Selected current tag(s) and either
new tag or delete approval are required"""
)
else:
comment = req.args.get("comment", u"")
old_tags = req.args.get("tag_name")
if old_tags:
# Provide list regardless of single or multiple selection.
old_tags = isinstance(old_tags, list) and old_tags or [old_tags]
tag_system.replace_tag(req, old_tags, new_tag, comment, allow_delete)
data["selected"] = new_tag
all_tags = sorted(tag_system.get_all_tags(req, "-dummy"))
data["tags"] = all_tags
try:
Chrome(self.env).add_textarea_grips(req)
except AttributeError:
# Element modifiers unavailable before Trac 0.12, skip gracefully.
pass
return "admin_tag_change.html", data
示例2: expand_macro
def expand_macro(self, formatter, name, args):
req = formatter.req
add_stylesheet(req, 'hacks/css/trachacks.css')
tag_system = TagSystem(self.env)
categories = natural_sort([r.id for r, _ in
tag_system.query(req, 'realm:wiki type')])
def link(resource):
return render_resource_link(self.env, formatter.context,
resource, 'compact')
dl = builder.dl(class_='hacktypesmacro')
for category in categories:
page = WikiPage(self.env, category)
match = self.title_extract.search(page.text)
if match:
cat_title = '%s' % match.group(1).strip()
cat_body = self.title_extract.sub('', page.text, 1)
else:
cat_title = '%s' % category
cat_body = page.text
cat_body = self.self_extract.sub('', cat_body).strip()
dl(builder.dt(link(Resource('wiki', category))))
dl(builder.dd(wiki_to_html(cat_body, self.env, req)))
return dl
示例3: _page_tags
def _page_tags(self, req):
pagename = req.args.get('page', 'WikiStart')
tag_system = TagSystem(self.env)
resource = Resource('wiki', pagename)
tags = sorted(tag_system.get_tags(req, resource))
return tags
示例4: screenshot_deleted
def screenshot_deleted(self, req, screenshot):
# Create temporary resource.
resource = Resource('screenshots', to_unicode(screenshot['id']))
# Delete tags of screenshot.
tag_system = TagSystem(self.env)
tag_system.delete_tags(req, resource)
示例5: process_request
def process_request(self, req):
"""Process the request. For ClearSilver, return a (template_name,
content_type) tuple, where `template` is the ClearSilver template to use
(either a `neo_cs.CS` object, or the file name of the template), and
`content_type` is the MIME type of the content. For Genshi, return a
(template_name, data, content_type) tuple, where `data` is a dictionary
of substitutions for the template.
For both templating systems, "text/html" is assumed if `content_type` is
`None`.
Note that if template processing should not occur, this method can
simply send the response itself and not return anything.
"""
query = req.args.get('q', '').lower()
tagsystem = TagSystem(self.env)
alltags = tagsystem.query(req)
tags = {}
for resource, _tags in alltags:
for tag in _tags:
if query in tag.lower():
tags[tag] = tags.setdefault(tag, 0) + 1
tags = sorted(tags.items(), key=lambda x: x[1], reverse=True)
writeOut=str('\n'.join(['%s|%d' % (name, number) for name, number in tags]))
req.send_header('Content-length', str(len(writeOut)))
req.end_headers()
req.write(writeOut)
示例6: _update_tags
def _update_tags(self, req, page):
tag_system = TagSystem(self.env)
newtags = tag_system.split_into_tags(req.args.get('tags', ''))
oldtags = tag_system.get_tags(req, page.resource)
if oldtags != newtags:
tag_system.set_tags(req, page.resource, newtags)
return True
return False
示例7: Main
def Main(opts):
""" Cross your fingers and pray """
env = Environment(opts.envpath)
from tractags.api import TagSystem
tlist = opts.tags or split_tags(env.config.get('blog', 'default_tag',
'blog'))
tags = TagSystem(env)
req = Mock(perm=MockPerm())
blog = tags.query(req, ' '.join(tlist + ['realm:wiki']))
cnx = env.get_db_cnx()
for resource, page_tags in list(blog):
try:
page = WikiPage(env, version=1, name=resource.id)
_, publish_time, author, _, _ = page.get_history().next()
if opts.deleteonly:
page.delete()
continue
categories = ' '.join([t for t in page_tags if t not in tlist])
page = WikiPage(env, name=resource.id)
for version, version_time, version_author, version_comment, \
_ in page.get_history():
# Currently the basename of the post url is used due to
# http://trac-hacks.org/ticket/2956
#name = resource.id.replace('/', '_')
name = resource.id
# extract title from text:
fulltext = page.text
match = _title_split_match(fulltext)
if match:
title = match.group(1)
fulltext = match.group(2)
else:
title = name
body = fulltext
print "Adding post %s, v%s: %s" % (name, version, title)
insert_blog_post(cnx, name, version, title, body,
publish_time, version_time,
version_comment, version_author, author,
categories)
reparent_blog_attachments(env, resource.id, name)
continue
cnx.commit()
if opts.delete:
page.delete()
continue
except:
env.log.debug("Error loading wiki page %s" % resource.id,
exc_info=True)
print "Failed to add post %s, v%s: %s" % (name, version, title)
cnx.rollback()
cnx.close()
return 1
cnx.close()
return 0
示例8: __call__
def __call__(self, context, type_):
if not (type_ and isinstance(type_, basestring) and len(type_)):
raise ValidationError('No type selected?!')
tags = TagSystem(self.env)
req = FakeRequest(self.env)
types = [r.id for r, _ in tags.query(req, 'realm:wiki type')]
if type_ not in types:
raise ValidationError('Selected type "%s" invalid?!' % str(type_))
return type_
示例9: download_deleted
def download_deleted(self, req, download):
# Check proper permissions to modify tags.
if not req.perm.has_permission('TAGS_MODIFY'):
return
# Create temporary resource.
resource = Resource('downloads', download['id'])
# Delete tags of download.
tag_system = TagSystem(self.env)
tag_system.delete_tags(req, resource)
示例10: user_created
def user_created(self, user, password):
req = FakeRequest(self.env, user)
resource = Resource('wiki', user)
tag_system = TagSystem(self.env)
tag_system.add_tags(req, resource, ['user',])
page = WikiPage(self.env, user)
page.text = '''= %(user)s =\n\n[[ListTagged(%(user)s)]]\n''' % {'user' : user}
page.save(user, 'New user %s registered' % user, None)
self.env.log.debug("New user %s registered" % user)
示例11: screenshot_created
def screenshot_created(self, req, screenshot):
# Create temporary resource.
resource = Resource('screenshots', to_unicode(screenshot['id']))
# Delete tags of screenshot with same ID for sure.
tag_system = TagSystem(self.env)
tag_system.delete_tags(req, resource)
# Add tags of new screenshot.
new_tags = self._get_tags(screenshot)
tag_system.add_tags(req, resource, new_tags)
示例12: wiki_page_renamed
def wiki_page_renamed(self, page, old_name):
"""Called when a page has been renamed (since Trac 0.12)."""
new_resource = Resource('wiki', page.name)
old_resource = Resource('wiki', old_name)
self.log.debug("Moving tags from %s to %s",
old_resource.id, new_resource.id)
tag_system = TagSystem(self.env)
# XXX Ugh. Hopefully this will be sufficient to fool any endpoints.
from trac.test import Mock, MockPerm
req = Mock(authname='anonymous', perm=MockPerm())
tag_system.reparent_tags(req, old_resource, new_resource)
示例13: _update_tags
def _update_tags(self, req, resource, new_tags):
# Get old tags of the resource.
tag_system = TagSystem(self.env)
old_tags = self._get_stored_tags(req, resource)
self.log.debug("setting tags: %s" % (new_tags,))
# Replace with new tags if different.
if old_tags != new_tags:
tag_system.set_tags(req, resource, new_tags)
return True
return False
示例14: screenshot_changed
def screenshot_changed(self, req, screenshot, old_screenshot):
# Update old screenshot with new values.
old_screenshot.update(screenshot)
# Create temporary resource.
resource = Resource('screenshots', to_unicode(old_screenshot['id']))
# Delete old tags.
tag_system = TagSystem(self.env)
tag_system.delete_tags(req, resource)
# Add new ones.
new_tags = self._get_tags(old_screenshot)
tag_system.add_tags(req, resource, new_tags)
示例15: post_process_request
def post_process_request(self, req, template, data, content_type):
if data and req.path_info == '/timeline' and \
'TAGS_VIEW' in req.perm(Resource('tags')):
def realm_handler(_, node, context):
return query.match(node, [context.realm])
query_str = req.args.get(self.key)
if query_str is None and req.args.get('format') != 'rss':
query_str = req.session.get('timeline.%s' % self.key)
else:
query_str = (query_str or '').strip()
# Record tag query expression between visits.
req.session['timeline.%s' % self.key] = query_str
if data.get('events') and query_str:
tag_system = TagSystem(self.env)
try:
query = Query(query_str,
attribute_handlers=dict(realm=realm_handler)
)
except InvalidQuery, e:
add_warning(req, _("Tag query syntax error: %s"
% to_unicode(e)))
else:
all_realms = tag_system.get_taggable_realms(req.perm)
query_realms = set()
for m in REALM_RE.finditer(query.as_string()):
query_realms.add(m.group(1))
# Don't care about resources from non-taggable realms.
realms = not query_realms and all_realms or \
query_realms.intersection(all_realms)
events = []
self.log.debug("Filtering timeline events by tags '%s'",
query_str)
for event in data['events']:
resource = event['data'][0]
if resource.realm in realms:
# Shortcut view permission checks here.
tags = tag_system.get_tags(None, resource)
if query(tags, context=resource):
events.append(event)
# Overwrite with filtered list.
data['events'] = events
if query_str:
# Add current value for next form rendering.
data[self.key] = query_str
elif self.key in req.session:
del req.session[self.key]