本文整理汇总了Python中zope.site.hooks.getSite函数的典型用法代码示例。如果您正苦于以下问题:Python getSite函数的具体用法?Python getSite怎么用?Python getSite使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getSite函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: clean_old_interfaces
def clean_old_interfaces(context):
log = logging.getLogger("policy CIRB clean old interfaces")
registry = context.getImportStepRegistry()
old_steps = ["cirb.site.various", "setupFolderNav"]
for old_step in old_steps:
if old_step in registry.listSteps():
registry.unregisterStep(old_step)
# Unfortunately we manually have to signal the context
# (portal_setup)
# that it has changed otherwise this change is not persisted.
context._p_changed = True
log.info("Old %s import step removed from import registry.",
old_step)
# XXX clean some unused skins !
adapters = getSite().getSiteManager().adapters._adapters
# 'IThemeSpecific' from module 'cirb.site.browser.interfaces
for adapter in adapters:
if adapter.keys():
if adapter.keys()[0].__module__ == 'zope.interface':
dic = adapter.values()[0]
for key in dic.keys():
if key.__module__ == 'cirb.site.browser.interfaces':
del dic[key]
log.info("delete {0} ".format(key.__module__))
getSite().getSiteManager().adapters._p_changed = True
getSite().getSiteManager().adapters._adapters = adapters
context._p_jar.sync()
示例2: resolveResource
def resolveResource(url):
"""Resolve the given URL to a unicode string. If the URL is an absolute
path, it will be made relative to the Plone site root.
"""
if url.startswith('/'):
site = getSite()
url = '/'.join(site.getPhysicalPath()) + url
response = subrequest(url)
if response.status == 404:
raise NotFound(url)
resolved = response.getBody()
if isinstance(resolved, str):
charset = extractCharset(response)
resolved = resolved.decode(charset)
if response.status in (301, 302):
site = getSite()
location = response.headers.get('location') or ''
if location.startswith(site.absolute_url()):
return resolveResource(location[len(site.absolute_url()):])
elif response.status != 200:
raise RuntimeError(resolved)
return resolved
示例3: test_site
def test_site(self):
traverse('/folder1')
site_url1 = getSite().absolute_url()
response = subrequest('/folder2/@@url')
self.assertEqual(response.status, 200)
site_url2 = getSite().absolute_url()
self.assertEqual(site_url1, site_url2)
示例4: __init__
def __init__(self, context, request):
self.request = request
self.context = getSite()
self.configuration = interfaces.IConfiguration(getSite())
self.membership = getToolByName(self.context, 'portal_membership')
self.registration = getToolByName(self.context, 'portal_registration')
self.groups = getToolByName(self.context, 'portal_groups')
示例5: __init__
def __init__(self, rel):
# XXX: wrap our relationship in the current Site
site_chain = getSite().aq_chain
site_chain.insert(0, rel)
rel = site_chain.pop(-1)
for item in reversed(site_chain):
rel = aq_base(site_chain.pop(-1)).__of__(rel)
self.rel = rel
# Use annotations for storing state
self.annotations = IAnnotations(rel).setdefault(ANNOTATIONS_KEY,
PersistentMapping())
# use the current Site for the tool lookup
self.wf_tool = getToolByName(getSite(), 'portal_workflow')
示例6: handle_apply
def handle_apply(self, action):
data, errors = self.extractData()
if errors:
return
portal = getSite()
# create a new rand
expires = datetime.now() + timedelta(days=2)
data = {'email': data['email']}
rand = IFridgeManager(self.context).add_entry(data, expires)
# send mail to user
mail_to = data['email']
url = u"%s/%s/%s" % (self.context.absolute_url(), FORM_ID, rand)
link = u'<a href="%s">%s</a>' % (url, url)
message = translate(msgid=u'request_registration_mail_text',
domain=DOMAIN,
mapping={'link': link,
'expires': expires.strftime('%d.%m.%Y %H:%M')},
context=self.request,
default=u'Finish your registration here ${link} by ${expires}.',
)
mail_subject = translate(msgid="request_registration_mail_subject",
domain=DOMAIN,
context=self.request,
default=u'Registration',
)
notify(MailEvent(message, mail_to, subject=mail_subject))
IStatusMessage(self.request).add(_(u'request_registration_success_notification'),
type='warn')
return self._redirect()
示例7: getCurrentSkinName
def getCurrentSkinName(self):
"""Get the currently active skin name
"""
# For reasons of horridness, we can't use acquisition here
portal_url = getToolByName(getSite(), 'portal_url')
return portal_url.getPortalObject().getCurrentSkinName()
示例8: CMFDefaultPortal
def CMFDefaultPortal(db=None, connection=None, environ=None):
"""Context manager for working with the Plone portal during layer setup::
with CMFDefaultPortal() as portal:
...
This is based on the ``z2.zopeApp()`` context manager. See the module
``plone.testing.z2`` for details.
Do not use this in a test. Use the 'portal' resource from the PloneFixture
layer instead!
Pass a ZODB handle as ``db`` to use a specificdatabase. Alternatively,
pass an open connection as ``connection`` (the connection will not be
closed).
"""
from zope.site.hooks import setSite, getSite, setHooks
setHooks()
site = getSite()
with z2.zopeApp(db, connection, environ) as app:
portal = app[SITE_ID]
setSite(portal)
z2.login(portal['acl_users'], TEST_USER_ID)
try:
yield portal
finally:
z2.logout()
if site is not portal:
setSite(site)
示例9: __call__
def __call__(self, context):
site = getSite()
groups_tool = getToolByName(site, "portal_groups")
is_zope_manager = getSecurityManager().checkPermission(ManagePortal, context)
groups = groups_tool.listGroups()
# Get group id, title tuples for each, omitting virtual group
# 'AuthenticatedUsers'
terms = []
for g in groups:
if g.id == "AuthenticatedUsers":
continue
if "Manager" in g.getRoles() and not is_zope_manager:
continue
group_title = safe_unicode(g.getGroupTitleOrName())
if group_title != g.id:
title = u"%s (%s)" % (group_title, g.id)
else:
title = group_title
terms.append(SimpleTerm(g.id, g.id, title))
# Sort by title
terms.sort(key=lambda x: normalizeString(x.title))
return SimpleVocabulary(terms)
示例10: __init__
def __init__(self, context):
self.context = context
self.portal = getSite()
registry = getUtility(IRegistry)
self.encoding = 'utf-8'
self.mail_settings = registry.forInterface(
IMailSchema, prefix="plone")
示例11: breadcrumbs
def breadcrumbs(self):
context = aq_inner(self.context)
request = self.request
if hasattr(context, 'route') and context.route.breadcrumbFactory:
return context.route.breadcrumbFactory(context, request)
# XXX this is the main part here:
# to up 2 parents since the current context
# is wrapped
if IWrappedContext.providedBy(context):
container = utils.parent(utils.parent(context))
elif IFragmentContext.providedBy(context):
container = getSite()
name, item_url = get_view_url(context)
view = getMultiAdapter((container, request), name='breadcrumbs_view')
base = tuple(view.breadcrumbs())
if base:
item_url = '%s/%s' % (base[-1]['absolute_url'], name)
base += ({'absolute_url': item_url,
'Title': utils.pretty_title_or_id(context, context)},)
return base
示例12: CreateOrgEvent
def CreateOrgEvent(event):
"""this event be fired by member join event, username,address password parameters to create a membrane object"""
site = getSite()
catalog = getToolByName(site,'portal_catalog')
try:
newest = catalog.unrestrictedSearchResults({'object_provides': IOrgnizationFolder.__identifier__})
except:
return
memberfolder = newest[0].getObject()
memberid = event.id
try:
item =createContentInContainer(memberfolder,"my315ok.socialorgnization.orgnization",checkConstraints=False,id=memberid)
# setattr(memberfolder,'registrant_increment',memberid)
item.title = event.title
item.description = event.description
item.address = event.address
item.legal_person = event.legal_person
item.supervisor = event.supervisor
item.register_code = event.register_code
ot = event.belondto_area
if isinstance(ot, unicode):
ot = ot.encode("utf-8")
if ot == '\xe5\xb2\xb3\xe5\xa1\x98\xe5\x8c\xba': # 岳塘区
item.belondto_area = "yuetangqu"
elif ot == '\xe9\x9b\xa8\xe6\xb9\x96\xe5\x8c\xba': #雨湖区
item.belondto_area = "yuhuqu"
elif ot == '\xe9\x9f\xb6\xe5\xb1\xb1\xe5\xb8\x82': #韶山市
item.belondto_area = "shaoshanshi"
elif ot == '\xe6\xb9\x98\xe4\xb9\xa1\xe5\xb8\x82': #湘乡市
item.belondto_area = "xiangxiangshi"
elif ot == '\xe6\xb9\x98\xe6\xbd\xad\xe5\x8e\xbf': #湘潭县
item.belondto_area = "xiangtanxian"
else:
item.belondto_area = "xiangtanshi" #湘潭市
# item.belondto_area = event.belondto_area
ot = event.organization_type
if isinstance(ot, unicode):
ot = ot.encode("utf-8")
if ot == '\xe6\xb0\x91\xe9\x9d\x9e': # 民非
item.organization_type = "minfei"
elif ot == '\xe7\xa4\xbe\xe4\xbc\x9a\xe5\x9b\xa2\xe4\xbd\x93': #社会团体
item.organization_type = "shetuan"
else:
item.organization_type = "jijinhui"
# item.announcement_type = event.announcement_type
import datetime
datearray = event.passDate.split('-')
if len(datearray) >= 3:
val = map(int,datearray)
item.passDate = datetime.date(*val)
else:
item.passDate = datetime.date.today()
item.reindexObject()
# membrane = getToolByName(item, 'membrane_tool')
# membrane.reindexObject(item)
except:
return
示例13: loadContent
def loadContent(self):
""" Agregate content from content_aggregation_sources.
"""
# issue_template = self.restrictedTraverse(self.getTemplate())
enl_template_obj_id = self.getTemplate()
enl = self.getNewsletter()
if enl_template_obj_id not in enl.objectIds():
log.warn("No enl_template found, skip loadContent!")
return
issue_template = getattr(enl.aq_explicit, enl_template_obj_id, None)
# here we create a write on read, but we do not need to persist it:
sp = transaction.savepoint()
issue_template.setIssue(self.UID())
portal = getSite()
template_id = issue_template.getAggregationTemplate()
if template_id != 'custom':
template_obj = portal.restrictedTraverse(template_id)
# XXX we copy over the template here every time we load the content
# which is not perfect but ok for now.
# This will be refactored when we drop Plone 4 support and use
# behaviors on source object like Collections
issue_template.setBody(template_obj.read())
text = issue_template.body()
sp.rollback()
self.setText(text)
示例14: __call__
def __call__(self, context):
site = getSite()
wtool = getToolByName(site, "portal_workflow", None)
if wtool is None:
return SimpleVocabulary([])
transitions = {}
for wf in wtool.values():
transition_folder = getattr(wf, "transitions", None)
wf_name = wf.title or wf.id
if transition_folder is not None:
for transition in transition_folder.values():
# zope.i18nmessageid will choke
# if undecoded UTF-8 bytestrings slip through
# which we may encounter on international sites
# where transition names are in local language.
# This may break overlying functionality even
# if the terms themselves are never used
name = safe_unicode(transition.actbox_name)
transition_title = translate(_(name), context=aq_get(wtool, "REQUEST", None))
transitions.setdefault(transition.id, []).append(dict(title=transition_title, wf_name=wf_name))
items = []
transition_items = transitions.items()
transition_items.sort(key=lambda transition: transition[0])
for transition_id, info in transition_items:
titles = set([i["title"] for i in info])
item_title = " // ".join(sorted(titles))
item_title = "%s [%s]" % (item_title, transition_id)
items.append(SimpleTerm(transition_id, transition_id, item_title))
return SimpleVocabulary(items)
示例15: repl
def repl(cls, match):
groups = match.groupdict()
if groups.get('url'):
old_url = groups.get('url')
if not old_url.startswith('resolveuid/'):
site = getSite()
portal_url = site.portal_url
site_url = site.absolute_url()
if portal_url.isURLInPortal(old_url, cls.context or None):
path = old_url.replace('%s/' % site_url, '', 1)
suffix = []
content = None
while path:
content = site.unrestrictedTraverse(path, default=None)
if IUUIDAware.providedBy(content):
break
suffix.insert(0, path.split('/')[-1])
path = '/'.join(path.split('/')[:-1])
if content and IUUIDAware.providedBy(content):
uuid = IUUID(content)
suffix.insert(0, '')
new_url = 'resolveuid/%s' % uuid + '/'.join(suffix)
return match.string[match.start():match.end()].replace(old_url,
new_url)
return match.string[match.start():match.end()]