bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def parseText(self): inDefinition = False inAnagram = False inSynonym = False inAntonym = False inPron = False wordType = "" wordSubType = ""
def parseText(self): inDefinition = False inAnagram = False inSynonym = False inAntonym = False inPron = False wordType = "" wordSubType = ""
476,800
def parseText(self): inDefinition = False inAnagram = False inSynonym = False inAntonym = False inPron = False wordType = "" wordSubType = ""
def parseText(self): inDefinition = False inAnagram = False inSynonym = False inAntonym = False inPron = False wordType = "" wordSubType = ""
476,801
def parseText(self): inDefinition = False inAnagram = False inSynonym = False inAntonym = False inPron = False wordType = "" wordSubType = ""
def parseText(self): inDefinition = False inAnagram = False inSynonym = False inAntonym = False inPron = False wordType = "" wordSubType = ""
476,802
def parseText(self): inDefinition = False inAnagram = False inSynonym = False inAntonym = False inPron = False wordType = "" wordSubType = ""
def parseText(self): inDefinition = False inAnagram = False inSynonym = False inAntonym = False inPron = False wordType = "" wordSubType = ""
476,803
def __init__(self, gcomprisBoard): # Save the gcomprisBoard, it defines everything we need # to know from the core self.gcomprisBoard = gcomprisBoard
def __init__(self, gcomprisBoard): # Save the gcomprisBoard, it defines everything we need # to know from the core self.gcomprisBoard = gcomprisBoard
476,804
def parseText(self): inWord = wiktio.Word() inDefinition = None inAnagram = False inSynonym = False inAntonym = False inPron = False wordType = "" wordSubType = "" filterIndent = "" gender = ""
defl = concat + l parseText(self):l = concat + l inWordl = concat + l =l = concat + l wiktio.Word()l = concat + l inDefinitionl = concat + l =l = concat + l Nonel = concat + l inAnagraml = concat + l =l = concat + l Falsel = concat + l inSynonyml = concat + l =l = concat + l Falsel = concat + l inAntonyml = concat + l =l = concat + l Falsel = concat + l inPronl = concat + l =l = concat + l Falsel = concat + l wordTypel = concat + l =l = concat + l ""l = concat + l wordSubTypel = concat + l =l = concat + l ""l = concat + l filterIndentl = concat + l =l = concat + l ""l = concat + l genderl = concat + l =l = concat + l ""
476,805
def end(self): gcompris.sound.reopen() global pid # force kill - data loss if pid != None: print "Tuxpaint not killed", self.pid #import os #os.kill(self.pid, signal.SIGKILL) if self.rootitem != None: self.rootitem.remove() self.rootitem = None
def end(self): gcompris.sound.reopen() global pid # force kill - data loss if pid != None: print "Tuxpaint not killed", pid #import os #os.kill(self.pid, signal.SIGKILL) if self.rootitem != None: self.rootitem.remove() self.rootitem = None
476,806
def child_callback(fd, cond, data): # restore pointergrab if running fullscreen if (gcompris.get_properties().fullscreen and not gcompris.get_properties().noxf86vm): gtk.gdk.pointer_grab(data.window.window, True, 0, data.window.window) #bug in gtk2.6/window if (gtk.gtk_version <= (2,6,10)): data.window.unfullscreen() data.window.fullscreen() global pid pid = None global fles fles.end() gcompris.end_board()
def child_callback(fd, cond, data): # restore pointergrab if running fullscreen if (gcompris.get_properties().fullscreen and not gcompris.get_properties().noxf86vm): gtk.gdk.pointer_grab(data.window.window, True, 0, data.window.window) #bug in gtk2.6/window if (gtk.gtk_version <= (2,6,10)): data.window.unfullscreen() data.window.fullscreen() global pid pid = None global fles fles.end() gcompris.end_board()
476,807
def show(self, line1="", line2="", duration=3, brightness=4, font="standard", centered=False): """Displays text on Player display""" if font == "huge": line1 = "" line1, line2 = urllib.quote(line1), urllib.quote(line2) req_string = "show line1:%s line2:%s duration:%i " req_string += "brightness:%i font:%s centered:%i" self.request(req_string % (line1, line2, duration, brightness, font, int(centered)))
def show(self, line1="", line2="", duration=3, brightness=4, font="standard", centered=False): """Displays text on Player display""" if font == "huge": line1 = "" line1, line2 = urllib.quote(line1), urllib.quote(line2) req_string = "show line1:%s line2:%s duration:%s " req_string += "brightness:%s font:%s centered:%i" self.request(req_string % (line1, line2, duration, brightness, font, int(centered)))
476,808
def show(self, line1="", line2="", duration=3, brightness=4, font="standard", centered=False): """Displays text on Player display""" if font == "huge": line1 = "" line1, line2 = urllib.quote(line1), urllib.quote(line2) req_string = "show line1:%s line2:%s duration:%i " req_string += "brightness:%i font:%s centered:%i" self.request(req_string % (line1, line2, duration, brightness, font, int(centered)))
def show(self, line1="", line2="", duration=3, brightness=4, font="standard", centered=False): """Displays text on Player display""" if font == "huge": line1 = "" line1, line2 = urllib.quote(line1), urllib.quote(line2) req_string = "show line1:%s line2:%s duration:%i " req_string += "brightness:%i font:%s centered:%i" self.request(req_string % (line1, line2, duration, brightness, font, int(centered)))
476,809
def display(self, line1="", line2="", duration=3): line1, line2 = urllib.quote(line1), urllib.quote(line2) req_string = "display line1:%s line2:%s duration:%s " self.request(req_string % (line1, line2, str(duration)))
def display(self, line1="", line2="", duration=3): line1, line2 = urllib.quote(line1), urllib.quote(line2) req_string = "display %s %s %s" self.request(req_string % (line1, line2, str(duration)))
476,810
def run_test_prog(bits, pagesize, cmd, **env): if paranoid_pool_check: beforepool = snapshot_pool_state() print "Pool state: %s" % str(beforepool) local_env = os.environ.copy() local_env.update(env) local_env["PATH"] = "./obj%d:../obj%d:%s" \ % (bits, bits, local_env.get("PATH", "")) local_env["LD_LIBRARY_PATH"] = "../obj%d:obj%d:%s" \ % (bits, bits, local_env.get("LD_LIBRARY_PATH", "")) local_env["HUGETLB_DEFAULT_PAGE_SIZE"] = repr(pagesize) p = subprocess.Popen(cmd, env=local_env, stdout=subprocess.PIPE) try: rc = p.wait() except KeyboardInterrupt: # Abort and mark this a strange test result return (None, "") out = p.stdout.read().strip() if paranoid_pool_check: afterpool = snapshot_pool_state() if afterpool != beforepool: print >>sys.stderr, "Hugepage pool state not preserved!" print >>sys.stderr, "BEFORE: %s" % str(beforepool) print >>sys.stderr, "AFTER: %s" % str(afterpool) sys.exit(98) return (rc, out)
def run_test_prog(bits, pagesize, cmd, **env): if paranoid_pool_check: beforepool = snapshot_pool_state() print "Pool state: %s" % str(beforepool) local_env = os.environ.copy() local_env.update(env) local_env["PATH"] = "./obj%d:../obj%d:%s" \ % (bits, bits, local_env.get("PATH", "")) local_env["LD_LIBRARY_PATH"] = "../obj%d:obj%d:%s" \ % (bits, bits, local_env.get("LD_LIBRARY_PATH", "")) local_env["HUGETLB_DEFAULT_PAGE_SIZE"] = repr(pagesize) try: rc = p.wait() except KeyboardInterrupt: # Abort and mark this a strange test result return (None, "") out = p.stdout.read().strip() if paranoid_pool_check: afterpool = snapshot_pool_state() if afterpool != beforepool: print >>sys.stderr, "Hugepage pool state not preserved!" print >>sys.stderr, "BEFORE: %s" % str(beforepool) print >>sys.stderr, "AFTER: %s" % str(afterpool) sys.exit(98) return (rc, out)
476,811
def main(): global wordsizes, pagesizes, dangerous, paranoid_pool_check, system_default_hpage_size testsets = set() env_override = {"QUIET_TEST": "1", "HUGETLBFS_MOUNTS": "", "HUGETLB_ELFMAP": None, "HUGETLB_MORECORE": None} env_defaults = {"HUGETLB_VERBOSE": "0"} dangerous = 0 paranoid_pool_check = False try: opts, args = getopt.getopt(sys.argv[1:], "vVfdt:b:p:c") except getopt.GetoptError, err: print str(err) sys.exit(1) for opt, arg in opts: if opt == "-v": env_override["QUIET_TEST"] = None env_defaults["HUGETLB_VERBOSE"] = "2" elif opt == "-V": env_defaults["HUGETLB_VERBOSE"] = "99" elif opt == "-f": dangerous = 1 elif opt == "-t": for t in arg.split(): testsets.add(t) elif opt == "-b": for b in arg.split(): wordsizes.add(int(b)) elif opt == "-p": for p in arg.split(): pagesizes.add(int(p)) elif opt == '-c': paranoid_pool_check = True else: assert False, "unhandled option" if len(testsets) == 0: testsets = set(["func", "stress"]) if len(wordsizes) == 0: wordsizes = set([32, 64]) if len(pagesizes) == 0: pagesizes = get_pagesizes() if len(pagesizes) == 0: print "Unable to find available page sizes, are you sure hugetlbfs" print "is mounted and there are available huge pages?" return 1 setup_env(env_override, env_defaults) init_results() (rc, system_default_hpage_size) = hpage_size() if rc != 0: print "Unable to find system default hugepage size." print "Is hugepage supported included in this kernel?" return 1 check_hugetlbfs_path() if "func" in testsets: functional_tests() if "stress" in testsets: stress_tests() results_summary()
def main(): global wordsizes, pagesizes, dangerous, paranoid_pool_check, system_default_hpage_size testsets = set() env_override = {"QUIET_TEST": "1", "HUGETLBFS_MOUNTS": "", "HUGETLB_ELFMAP": None, "HUGETLB_MORECORE": None} env_defaults = {"HUGETLB_VERBOSE": "0"} dangerous = 0 paranoid_pool_check = False try: opts, args = getopt.getopt(sys.argv[1:], "vVfdt:b:p:c") except getopt.GetoptError, err: print str(err) sys.exit(1) for opt, arg in opts: if opt == "-v": env_override["QUIET_TEST"] = None env_defaults["HUGETLB_VERBOSE"] = "2" elif opt == "-V": env_defaults["HUGETLB_VERBOSE"] = "99" elif opt == "-f": dangerous = 1 elif opt == "-t": for t in arg.split(): testsets.add(t) elif opt == "-b": for b in arg.split(): wordsizes.add(int(b)) elif opt == "-p": for p in arg.split(): pagesizes.add(int(p)) elif opt == '-c': paranoid_pool_check = True else: assert False, "unhandled option" if len(testsets) == 0: testsets = set(["func", "stress"]) if len(wordsizes) == 0: wordsizes = get_wordsizes() if len(pagesizes) == 0: pagesizes = get_pagesizes() if len(pagesizes) == 0: print "Unable to find available page sizes, are you sure hugetlbfs" print "is mounted and there are available huge pages?" return 1 setup_env(env_override, env_defaults) init_results() (rc, system_default_hpage_size) = hpage_size() if rc != 0: print "Unable to find system default hugepage size." print "Is hugepage supported included in this kernel?" return 1 check_hugetlbfs_path() if "func" in testsets: functional_tests() if "stress" in testsets: stress_tests() results_summary()
476,812
def reloadProfiles(br): profiles = ['profile-recensio.policy:default'] + additional_profiles for profile in profiles: print "Trying to load profile %s" % profile br.open(host + '/portal_setup/manage_importSteps') br.getControl(name='context_id', index=0).value = [profile] br.getForm('profileform').submit() br.getControl('Import all steps').click() print "Profile %s loaded" % profile
def reloadProfiles(br): profiles = ['profile-recensio.policy:default'] + additional_profiles +\ ['profile-recensio.policy:default'] for profile in profiles: print "Trying to load profile %s" % profile br.open(host + '/portal_setup/manage_importSteps') br.getControl(name='context_id', index=0).value = [profile] br.getForm('profileform').submit() br.getControl('Import all steps').click() print "Profile %s loaded" % profile
476,813
def configureCollection(collection, types, location): try: criterion = collection.addCriterion(field='created', \ criterion_type='ATFriendlyDateCriteria') criterion.setValue(31) criterion.setOperation('less') criterion.setDateRange('-') except BadRequest: pass try: criterion = collection.addCriterion(field='Type', \ criterion_type='ATPortalTypeCriterion') criterion.setValue(types) except BadRequest: pass try: criterion = collection.addCriterion(field='path', \ criterion_type='ATRelativePathCriterion') criterion.setLocation('/') except BadRequest: pass
def configureCollection(collection, types, location): try: criterion = collection.addCriterion(field='created', \ criterion_type='ATFriendlyDateCriteria') criterion.setValue(31) criterion.setOperation('less') criterion.setDateRange('-') except BadRequest: pass try: criterion = collection.addCriterion(field='Type', \ criterion_type='ATPortalTypeCriterion') criterion.setValue(types) except BadRequest: pass try: criterion = collection.addCriterion(field='path', \ criterion_type='ATRelativePathCriterion') criterion.setRelativePath('/') criterion.setRecurse(True) except BadRequest: pass
476,814
def configureContentRatings(context): portal = context.getSite() utility = getUtility(IRatingCategoryAssignment) portal_types = [] categories_to_set = [utility._avalable_categories.by_token[''].value] for type in portal_types: utility.assign_categories(type, categories_to_set)
def configureContentRatings(context): portal = context.getSite() utility = getUtility(IRatingCategoryAssignment) portal_types = ['Rezension'] categories_to_set = [utility._avalable_categories.by_token[''].value] for type in portal_types: utility.assign_categories(type, categories_to_set)
476,815
def configureCollection(collection, types, location): try: criterion = collection.addCriterion(field='created', \ criterion_type='ATFriendlyDateCriteria') criterion.setValue(31) criterion.setOperation('less') criterion.setDateRange('-') except BadRequest: pass try: criterion = collection.addCriterion(field='Type', \ criterion_type='ATPortalTypeCriterion') criterion.setValue(types) except BadRequest: pass try: criterion = collection.addCriterion(field='path', \ criterion_type='ATRelativePathCriterion') criterion.setLocation('/') except BadRequest: pass
def configureCollection(collection, types, location): try: criterion = collection.addCriterion(field='created', \ criterion_type='ATFriendlyDateCriteria') criterion.setValue(31) criterion.setOperation('less') criterion.setDateRange('-') except BadRequest: pass try: criterion = collection.addCriterion(field='Type', \ criterion_type='ATPortalTypeCriterion') criterion.setValue(types) except BadRequest: pass try: criterion = collection.addCriterion(field='path', \ criterion_type='ATRelativePathCriterion') criterion.setLocation('/') except BadRequest: pass
476,816
def setImportedContentLanguages(context): portal = context.getSite() for id in imported_content: ob = portal.unrestrictedTraverse(id, None) if not ob: log.warning('Object %s not found. Please run import step "Recensio initial content"' % (id)) continue if id not in ['images']: language = 'de' else: language = '' doSetLanguage(ob, language) def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans) else: log.warning('%s is already translated into %s!' % path,lang_trans) if language: for lang_trans in ['en', 'fr']: id_trans = id + '-' + lang_trans ob_trans = portal.unrestrictedTraverse(id_trans, None) if ob_trans: if not ob.hasTranslation(lang_trans): linkTranslations(portal, [[([id], language), ([id_trans], lang_trans)]]) if ob.portal_type == 'Folder': translate_folder([id], language, [id_trans], lang_trans) else: log.warning('%s is already translated into %s!' % (id,lang_trans)) else: log.warning('Object %s not found. No translation for %s will be set' % (id_trans, lang_trans)) portal.setLanguage('de')
def setImportedContentLanguages(context): portal = context.getSite() for id in imported_content: ob = portal.unrestrictedTraverse(id, None) if not ob: log.warning('Object %s not found. Please run import step "Recensio initial content"' % (id)) continue if id in ['images']: language = '' doSetLanguage(ob, language) def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans) else: log.warning('%s is already translated into %s!' % path,lang_trans) if language: for lang_trans in ['en', 'fr']: id_trans = id + '-' + lang_trans ob_trans = portal.unrestrictedTraverse(id_trans, None) if ob_trans: if not ob.hasTranslation(lang_trans): linkTranslations(portal, [[([id], language), ([id_trans], lang_trans)]]) if ob.portal_type == 'Folder': translate_folder([id], language, [id_trans], lang_trans) else: log.warning('%s is already translated into %s!' % (id,lang_trans)) else: log.warning('Object %s not found. No translation for %s will be set' % (id_trans, lang_trans)) portal.setLanguage('de')
476,817
def setImportedContentLanguages(context): portal = context.getSite() for id in imported_content: ob = portal.unrestrictedTraverse(id, None) if not ob: log.warning('Object %s not found. Please run import step "Recensio initial content"' % (id)) continue if id not in ['images']: language = 'de' else: language = '' doSetLanguage(ob, language) def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans) else: log.warning('%s is already translated into %s!' % path,lang_trans) if language: for lang_trans in ['en', 'fr']: id_trans = id + '-' + lang_trans ob_trans = portal.unrestrictedTraverse(id_trans, None) if ob_trans: if not ob.hasTranslation(lang_trans): linkTranslations(portal, [[([id], language), ([id_trans], lang_trans)]]) if ob.portal_type == 'Folder': translate_folder([id], language, [id_trans], lang_trans) else: log.warning('%s is already translated into %s!' % (id,lang_trans)) else: log.warning('Object %s not found. No translation for %s will be set' % (id_trans, lang_trans)) portal.setLanguage('de')
def setImportedContentLanguages(context): portal = context.getSite() for id in imported_content: ob = portal.unrestrictedTraverse(id, None) if not ob: log.warning('Object %s not found. Please run import step "Recensio initial content"' % (id)) continue if id not in ['images']: language = 'de' else: language = '' doSetLanguage(ob, language) def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans) else: log.warning('%s is already translated into %s!' % path,lang_trans) if language: for lang_trans in ['en', 'fr']: id_trans = id + '-' + lang_trans ob_trans = portal.unrestrictedTraverse(id_trans, None) if ob_trans: if not ob.hasTranslation(lang_trans): linkTranslations(portal, [[([id], language), ([id_trans], lang_trans)]]) if ob.portal_type == 'Folder': translate_folder([id], language, [id_trans], lang_trans) else: log.warning('%s is already translated into %s!' % (id,lang_trans)) else: log.warning('Object %s not found. No translation for %s will be set' % (id_trans, lang_trans)) portal.setLanguage('de')
476,818
def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans) else: log.warning('%s is already translated into %s!' % path,lang_trans)
def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) else: log.warning('%s is already translated into %s!' % path,lang_trans)
476,819
def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans) else: log.warning('%s is already translated into %s!' % path,lang_trans)
def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans) else: log.warning('%s is already translated into %s!' % path,lang_trans)
476,820
def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans) else: log.warning('%s is already translated into %s!' % path,lang_trans)
def translate_folder(path, language, path_trans, lang_trans): ob = portal.unrestrictedTraverse(path, None) ob_trans = portal.unrestrictedTraverse(path_trans, None) for item in ob.objectIds(): subob = ob.unrestrictedTraverse(item, None) subob_trans = ob_trans.unrestrictedTraverse(item, None) if not subob_trans: log.warning('Object %s not found. No translation for %s will be set' % ("/".join(path_trans + [item]), lang_trans)) else: if not subob.hasTranslation(lang_trans): linkTranslations(portal, [[(path + [item], language), (path_trans + [item], lang_trans)]]) log.debug('Setting translation for %s (%s): %s (%s)' % (path + [item], language, path_trans + [item], lang_trans)) if subob and subob.portal_type == 'Folder': translate_folder(path + [item], language, path_trans + [item], lang_trans) else: log.warning('%s is already translated into %s!' % path,lang_trans)
476,821
def setupHomepage(context): site = context.getSite() fp = getattr(site, 'front-page', None) if not fp: log.error('Front page not found') return id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='homepage-view', type='string') log.debug('Homepage view was set on the front page') # set up portlet mapping = assignment_mapping_from_key(fp, 'plone.rightcolumn', CONTEXT_CATEGORY, '/'.join(fp.getPhysicalPath())) id = 'homepage-intro' if id not in mapping: mapping[id] = static.Assignment(header=u'Intro', text=portlet_hp_text, omit_border=True)
def setupHomepage(context): site = context.getSite() for fp_id in ['front-page', 'front-page-en', 'front-page-fr']: fp = getattr(site, fp_id, None) if not fp: log.error('%s not found' % fp_id) continue id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='homepage-view', type='string') log.debug('Homepage view was set on the front page') # set up portlet mapping = assignment_mapping_from_key(fp, 'plone.rightcolumn', CONTEXT_CATEGORY, '/'.join(fp.getPhysicalPath())) id = 'homepage-intro' if id not in mapping: mapping[id] = static.Assignment(header=u'Intro', text=portlet_hp_text, omit_border=True)
476,822
def setViewsOnFolders(context): portal = context.getSite() autoren = getattr(portal, 'autoren', None) if not autoren: log.warning('Folder "autoren" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = getattr(autoren, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='authorsearch', type='string') autoren_en = getattr(portal, 'autoren-en', None) if not autoren_en: log.warning('Folder "autoren-en" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = getattr(autoren_en, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='authorsearch', type='string') autoren_fr = getattr(portal, 'autoren-fr', None) if not autoren_fr: log.warning('Folder "autoren-fr" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = getattr(autoren_fr, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='authorsearch', type='string') themen = getattr(portal, 'themen-epochen-regionen', None) if not themen: log.warning('Folder "themen-epochen-regionen" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = getattr(themen, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='browse-topics', type='string') rezensionen = getattr(portal, 'rezensionen', None) zeitschriften = getattr(rezensionen, 'zeitschriften', None) if not zeitschriften: log.warning('Folder "zeitschriften" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = zeitschriften id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='publications-view', type='string')
def setViewsOnFolders(context): portal = context.getSite() for autoren_id in ['autoren', 'autoren-en', 'autoren-fr']: autoren = getattr(portal, autoren_id, None) if not autoren: log.warning('Folder "%s" not found on portal. Please run recensio.contenttypes.initial_content' % autoren_id) else: fp = getattr(autoren, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='authorsearch', type='string') for themen_id in ['themen-epochen-regionen', 'themen-epochen-regionen-en', 'themen-epochen-regionen-fr']: themen = getattr(portal, themen_id, None) if not themen: log.warning('Folder "%s" not found on portal. Please run recensio.contenttypes.initial_content' % themen_id) else: fp = getattr(themen, 'index_html') id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='browse-topics', type='string') rezensionen = getattr(portal, 'rezensionen', None) zeitschriften = getattr(rezensionen, 'zeitschriften', None) if not zeitschriften: log.warning('Folder "zeitschriften" not found on portal. Please run recensio.contenttypes.initial_content') else: fp = zeitschriften id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='publications-view', type='string')
476,823
def publishImportedContent(context): portal = context.getSite() pwt = getToolByName(portal, 'portal_workflow') for id in imported_content: for lang in ['', '-en', '-fr']: obj = getattr(portal, id + lang, None) if not obj: log.warning('Object %s not found. Please run import step "Recensio initial content"' % id + lang) continue doPublish(obj, pwt)
def publishImportedContent(context): portal = context.getSite() pwt = getToolByName(portal, 'portal_workflow') for id in imported_content: for lang in ['', '-en', '-fr']: obj = getattr(portal, (id + lang), None) if not obj: log.warning('Object %s not found. Please run import step "Recensio initial content"' % id + lang) continue doPublish(obj, pwt)
476,824
def publishImportedContent(context): portal = context.getSite() pwt = getToolByName(portal, 'portal_workflow') for id in imported_content: for lang in ['', '-en', '-fr']: obj = getattr(portal, id + lang, None) if not obj: log.warning('Object %s not found. Please run import step "Recensio initial content"' % id + lang) continue doPublish(obj, pwt)
def publishImportedContent(context): portal = context.getSite() pwt = getToolByName(portal, 'portal_workflow') for id in imported_content: for lang in ['', '-en', '-fr']: obj = getattr(portal, id + lang, None) if not obj: log.warning('Object %s not found. Please run import step "Recensio initial content"' % (id + lang)) continue doPublish(obj, pwt)
476,825
def send(self, messageText, mto, mfrom, subject, charset): self.sentMail = messageText
def send(self, messageText, mto, mfrom, subject, charset): self.sentMail = messageText
476,826
def __call__(self): self.errors = [] mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() membership_tool = getToolByName(self.context, 'portal_membership') if membership_tool.isAnonymousUser(): self.errors.append(_('You are not logged in')) user = membership_tool.getAuthenticatedMember() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) if not mail_info.email_from_address: self.errors.append(_('Plone site is not configured')) mail_to = user.getProperty('email') or 'do3ccqrv@googlemail.com' if not mail_to: self.errors.append(_("You did not provide an e-mail address in your profile")) self.mail_to = mail_to registry = getUtility(IRegistry) settings = registry.forInterface(INewsletterSettings)
def __call__(self): self.errors = [] mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() membership_tool = getToolByName(self.context, 'portal_membership') if membership_tool.isAnonymousUser(): self.errors.append(_('You are not logged in')) user = membership_tool.getAuthenticatedMember() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) if not mail_info.email_from_address: self.errors.append(_('Plone site is not configured')) mail_to = user.getProperty('email') or 'do3ccqrv@googlemail.com' if not mail_to: self.errors.append(_("You did not provide an e-mail address in your profile")) self.mail_to = mail_to registry = getUtility(IRegistry) settings = registry.forInterface(INewsletterSettings)
476,827
def __call__(self): self.errors = [] mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() membership_tool = getToolByName(self.context, 'portal_membership') if membership_tool.isAnonymousUser(): self.errors.append(_('You are not logged in')) user = membership_tool.getAuthenticatedMember() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) if not mail_info.email_from_address: self.errors.append(_('Plone site is not configured')) mail_to = user.getProperty('email') or 'do3ccqrv@googlemail.com' if not mail_to: self.errors.append(_("You did not provide an e-mail address in your profile")) self.mail_to = mail_to registry = getUtility(IRegistry) settings = registry.forInterface(INewsletterSettings)
def __call__(self): self.errors = [] mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() membership_tool = getToolByName(self.context, 'portal_membership') if membership_tool.isAnonymousUser(): self.errors.append(_('You are not logged in')) user = membership_tool.getAuthenticatedMember() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) if not mail_info.email_from_address: self.errors.append(_('Plone site is not configured')) mail_to = user.getProperty('email') or 'do3ccqrv@googlemail.com' if not mail_to: self.errors.append(_("You did not provide an e-mail address in your profile")) self.mail_to = mail_to registry = getUtility(IRegistry) settings = registry.forInterface(INewsletterSettings)
476,828
def _addReview(self, review): if review['volume'] not in self.mag: self.mag.invokeFactory(type_name="Volume", id=review['volume']) volume = self.mag[review['volume']] if review['issue'] not in volume: volume.invokeFactory(type_name='Issue', id=review['issue']) issue = volume[review['issue']] new_id = self.plone_utils.normalizeString(review['title']) if new_id in issue: return review = self._extractAndSanitizeHTML(review) issue.invokeFactory(type_name='Review Monograph', id = new_id) review_ob = issue[new_id] for key, value in review.items(): setattr(review_ob, key, value) notify(ObjectEditedEvent(review_ob))
def _addReview(self, review): if review['volume'] not in self.mag: self.mag.invokeFactory(type_name="Volume", id=review['volume'], title=review['volume']) volume = self.mag[review['volume']] if review['issue'] not in volume: volume.invokeFactory(type_name='Issue', id=review['issue']) issue = volume[review['issue']] new_id = self.plone_utils.normalizeString(review['title']) if new_id in issue: return review = self._extractAndSanitizeHTML(review) issue.invokeFactory(type_name='Review Monograph', id = new_id) review_ob = issue[new_id] for key, value in review.items(): setattr(review_ob, key, value) notify(ObjectEditedEvent(review_ob))
476,829
def _addReview(self, review): if review['volume'] not in self.mag: self.mag.invokeFactory(type_name="Volume", id=review['volume']) volume = self.mag[review['volume']] if review['issue'] not in volume: volume.invokeFactory(type_name='Issue', id=review['issue']) issue = volume[review['issue']] new_id = self.plone_utils.normalizeString(review['title']) if new_id in issue: return review = self._extractAndSanitizeHTML(review) issue.invokeFactory(type_name='Review Monograph', id = new_id) review_ob = issue[new_id] for key, value in review.items(): setattr(review_ob, key, value) notify(ObjectEditedEvent(review_ob))
def _addReview(self, review): if review['volume'] not in self.mag: self.mag.invokeFactory(type_name="Volume", id=review['volume']) volume = self.mag[review['volume']] if review['issue'] not in volume: volume.invokeFactory(type_name='Issue', id=review['issue'], title=review['issue']) issue = volume[review['issue']] new_id = self.plone_utils.normalizeString(review['title']) if new_id in issue: return review = self._extractAndSanitizeHTML(review) issue.invokeFactory(type_name='Review Monograph', id = new_id) review_ob = issue[new_id] for key, value in review.items(): setattr(review_ob, key, value) notify(ObjectEditedEvent(review_ob))
476,830
def testFormat(self): portal = self.layer['portal'] setRoles(portal, TEST_USER_ID, ['Manager']) setRoles(portal, TEST_USER_NAME, ['Manager']) request = self.layer['request'] reviews = portal["sample-reviews"] reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
def testFormat(self): portal = self.layer['portal'] setRoles(portal, TEST_USER_ID, ['Manager']) setRoles(portal, TEST_USER_NAME, ['Manager']) request = self.layer['request'] reviews = portal["sample-reviews"] reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
476,831
def setUpPloneSite(self, portal): wftool = getToolByName(portal, 'portal_workflow') wftool.setDefaultChain('plone_workflow') applyProfile(portal, 'Products.CMFPlone:plone-content') applyProfile(portal, 'recensio.policy:test') applyProfile(portal, 'recensio.contenttypes:example_content')
def setUpPloneSite(self, portal): wftool = getToolByName(portal, 'portal_workflow') wftool.setDefaultChain('plone_workflow') applyProfile(portal, 'Products.CMFPlone:plone-content') applyProfile(portal, 'recensio.policy:test') applyProfile(portal, 'recensio.contenttypes:example_content')
476,832
def addWorkflowScriptsForComments(context): script = """
def addWorkflowScriptsForComments(context): script = """
476,833
def customizeWorkflowAndPermissions(context): portal = context.getSite() pwf = portal.portal_workflow spw = pwf.getWorkflowById('simple_publication_workflow') spw.description = ' - Simple workflow that is useful for basic web sites. - Things start out as private, and can either be submitted for review, or published directly. - The creator of a content item can edit the item even after it is published. - Modified for recensio.net: Added deleted state' guard = Guard() guard.roles = ('Manager', 'Editor', 'Owner', ) # delete existing states and transitions to avoid clashes if 'delete' in spw.transitions: spw.transitions.deleteTransitions(['delete']) if 'restore' in spw.transitions: spw.transitions.deleteTransitions(['restore']) if 'deleted' in spw.states: spw.states.deleteStates(['deleted']) # add Transitions spw.transitions.addTransition('delete') spw.transitions['delete'].guard = guard spw.transitions['delete'].title = 'Delete' spw.transitions['delete'].description = 'Mark the content as deleted and make it invisible for all except managers' spw.transitions['delete'].new_state_id = 'deleted' spw.transitions['delete'].after_script_name = 'handle_change' spw.transitions['delete'].actbox_name = 'Delete' spw.transitions['delete'].actbox_url = '%(content_url)s/content_status_modify?workflow_action=delete' spw.transitions.addTransition('restore') spw.transitions['restore'].guard = guard spw.transitions['restore'].title = 'Restore' spw.transitions['restore'].description = 'Restore the content from the deleted state and make it visible again' spw.transitions['restore'].new_state_id = 'private' spw.transitions['restore'].after_script_name = 'handle_change' spw.transitions['restore'].actbox_name = 'Restore' spw.transitions['restore'].actbox_url = '%(content_url)s/content_status_modify?workflow_action=restore' # add state and register transitions with states spw.states.addState('deleted') spw.states['deleted'].title = 'Deleted' spw.states['deleted'].description = 'Marked as deleted and invisible to all but managers' spw.states['deleted'].transitions = ('restore',) # access only for Manager for perm in spw.permissions: spw.states['deleted'].setPermission(perm, acquired=0, roles=['Manager', 'Editor', 'Owner']) for state in ['pending', 'private', 'published']: trans = spw.states[state].transitions if not 'delete' in trans: trans = list(trans) trans.append('delete') spw.states[state].transitions = tuple(trans)
def customizeWorkflowAndPermissions(context): portal = context.getSite() pwf = portal.portal_workflow spw = pwf.getWorkflowById('simple_publication_workflow') spw.description = ' - Simple workflow that is useful for basic web sites. - Things start out as private, and can either be submitted for review, or published directly. - The creator of a content item can edit the item even after it is published. - Modified for recensio.net: Added deleted state' guard = Guard() guard.roles = ('Manager', 'Editor', 'Owner', ) # delete existing states and transitions to avoid clashes if 'delete' in spw.transitions: spw.transitions.deleteTransitions(['delete']) if 'restore' in spw.transitions: spw.transitions.deleteTransitions(['restore']) if 'deleted' in spw.states: spw.states.deleteStates(['deleted']) # add Transitions spw.transitions.addTransition('delete') spw.transitions['delete'].guard = guard spw.transitions['delete'].title = 'Delete' spw.transitions['delete'].description = 'Mark the content as deleted and make it invisible for all except managers' spw.transitions['delete'].new_state_id = 'deleted' spw.transitions['delete'].after_script_name = 'handle_change' spw.transitions['delete'].actbox_name = 'Delete' spw.transitions['delete'].actbox_url = '%(content_url)s/content_status_modify?workflow_action=delete' spw.transitions.addTransition('restore') spw.transitions['restore'].guard = guard spw.transitions['restore'].title = 'Restore' spw.transitions['restore'].description = 'Restore the content from the deleted state and make it visible again' spw.transitions['restore'].new_state_id = 'private' spw.transitions['restore'].after_script_name = 'handle_change' spw.transitions['restore'].actbox_name = 'Restore' spw.transitions['restore'].actbox_url = '%(content_url)s/content_status_modify?workflow_action=restore' # add state and register transitions with states spw.states.addState('deleted') spw.states['deleted'].title = 'Deleted' spw.states['deleted'].description = 'Marked as deleted and invisible to all but managers' spw.states['deleted'].transitions = ('restore',) # access only for Manager for perm in spw.permissions: spw.states['deleted'].setPermission(perm, acquired=0, roles=['Manager', 'Editor', 'Owner']) for state in ['pending', 'private', 'published']: trans = spw.states[state].transitions if not 'delete' in trans: trans = list(trans) trans.append('delete') spw.states[state].transitions = tuple(trans)
476,834
def setupHomepage(context): site = context.getSite() for fp_id in ['front-page', 'front-page-en', 'front-page-fr']: fp = getattr(site, fp_id, None) if not fp: log.error('%s not found' % fp_id) continue id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='homepage-view', type='string') log.debug('Homepage view was set on the front page') # set up portlet mapping = assignment_mapping_from_key(fp, 'plone.rightcolumn', CONTEXT_CATEGORY, '/'.join(fp.getPhysicalPath())) id = 'homepage-intro' if id not in mapping: mapping[id] = static.Assignment(header=u'Intro', text=portlet_hp_text, omit_border=True)
def setupHomepage(context): site = context.getSite() for fp_id in ['front-page', 'front-page-en', 'front-page-fr']: fp = getattr(site, fp_id, None) if not fp: log.error('%s not found' % fp_id) continue id = 'layout' if fp.hasProperty(id): fp._delProperty(id) fp._setProperty(id=id, value='homepage-view', type='string') log.debug('Homepage view was set on the front page') # set up portlet mapping = assignment_mapping_from_key(fp, 'plone.rightcolumn', CONTEXT_CATEGORY, '/'.join(fp.getPhysicalPath())) id = 'homepage-intro' if id not in mapping: mapping[id] = static.Assignment(header=u'Intro', text=portlet_hp_text, omit_border=True)
476,835
def setUp(self): self.fake_logger = FakeLogger() importSehepunkte.logger = self.fake_logger self.originalUrlGetter = sehepunkte_parser._getHTMLData sehepunkte_parser._getHTMLData = lambda a:a
def setUp(self): self.fake_logger = FakeLogger() importSehepunkte.logger = self.fake_logger self.originalUrlGetter = sehepunkte_parser._getHTMLData sehepunkte_parser._getHTMLData = lambda a:a
476,836
def tearDown(self): sehepunkte_parser._getHTMLData = self.originalUrlGetter
def tearDown(self): sehepunkte_parser._getHTMLData = self.originalUrlGetter
476,837
def testImportGood(self): should_be = [] data = [x for x in sehepunkte_parser.parse(file(testdata_filename).read())] for dataset in data: dataset.pop('html') self.assertEquals(testdata_parsed, list(data))
def testImportGood(self): should_be = [] data = [x for x in sehepunkte_parser.parse(file(testdata_filename).read())] self.assertEquals(testdata_parsed, list(data))
476,838
def testImportBad(self): data1 = file(testdata_filename).read() data2 = data1.replace('<review id="17542">', '<somethingelse>') data2 = data2.replace('</review>', '</somethingelse>', 1) data1 = sehepunkte_parser.parse(data1) data2 = sehepunkte_parser.parse(data2) self.assertEquals(len(list(data1)), len(list(data2)) + 1)
def testImportBad(self): data1 = file(testdata_filename).read() data2 = data1.replace('<review id="17542">', '<somethingelse>') data2 = data2.replace('</review>', '</somethingelse>', 1) data1 = sehepunkte_parser.parse(data1) data2 = sehepunkte_parser.parse(data2) self.assertEquals(len(list(data1)), len(list(data2)) + 1)
476,839
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
476,840
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
476,841
def testFormat(self): expected_mail = u'''Liebe Redaktion,
def testFormat(self): expected_mail = u'''Liebe Redaktion,
476,842
def testFormat(self): expected_mail = u'''Liebe Redaktion,
def testFormat(self): expected_mail = u'''Liebe Redaktion,
476,843
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
476,844
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
476,845
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
476,846
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
476,847
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
476,848
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
def testFormat(self): portal = self.layer['portal'] request = self.layer['request'] setRoles(portal, TEST_USER_NAME, ['Manager']) reviews = portal.reviews reviews.invokeFactory('Publication', id='pub', title='pub') publication = reviews.pub publication.invokeFactory('Volume', id='vol', title='vol') vol = publication.vol vol.invokeFactory('Issue', id='issue', title='issue') issue = vol.issue pt = getToolByName(portal, 'portal_types') issueType = pt.getTypeInfo(issue) # We are lazy here, allowing an issue to contain all documents issueType.filter_content_types = False
476,849
def __call__(self): self.errors = [] messages = IStatusMessage(self.request) try: mail_from, mail_to = self.getMailAddresses() registry = getUtility(IRegistry) settings = registry.forInterface(INewsletterSettings) if not settings.mail_format: self.errors.append(_('Mailsettings not configured')) raise ValidationError()
def __call__(self): self.errors = [] messages = IStatusMessage(self.request) try: mail_from, mail_to = self.getMailAddresses() registry = getUtility(IRegistry) settings = registry.forInterface(INewsletterSettings) if not settings.mail_format: self.errors.append(_('Mailsettings not configured')) raise ValidationError()
476,850
def __call__(self): root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address)
def __call__(self): root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address)
476,851
def sendMail(self, msg, mail_from, mail_to, subject): if mail_to: self.mailhost.send(messageText=msg, mto=mail_to, mfrom=mail_from, subject=subject, charset='utf-8') else: messages = IStatusMessage(self.request) messages.addStatusMessage(self.ts.translate(_('mail_no_recipients'), context=self.context), type="warning")
def sendMail(self, msg, mail_from, mail_to, subject): if mail_to: self.mailhost.send(messageText=msg, mto=mail_to, mfrom=mail_from, subject=subject, charset='utf-8') else: messages = IStatusMessage(self.request) messages.addStatusMessage(self.ts.translate(_('mail_no_recipients'), context=self.context), type="warning")
476,852
def findRecipient(self): membership_tool = getToolByName(self.context, 'portal_membership') owner = membership_tool.getMemberById(self.context.__parent__.__parent__.Creator()).getUser() return owner.getProperty('email')
def findRecipient(self): membership_tool = getToolByName(self.context, 'portal_membership') owner = membership_tool.getMemberById(self.context.__parent__.__parent__.Creator()).getUser() return owner.getProperty('email')
476,853
def __call__(self): root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) referenceAuthors = getattr(self.context, 'referenceAuthors', [])
def __call__(self): root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) referenceAuthors = getattr(self.context, 'referenceAuthors', [])
476,854
def __call__(self): root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) referenceAuthors = getattr(self.context, 'referenceAuthors', [])
def __call__(self): root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) referenceAuthors = getattr(self.context, 'referenceAuthors', [])
476,855
def sendMail(self, result): msg = self.formatMessage(result) mail_to = self.findRecipient(result) mail_from = self.findSender() subject = self.ts.translate(_('mail_uncommented_subject'), context=self.context) self.mailhost.send(messageText=msg, mto=mail_to, mfrom=mail_from, subject=subject, charset='utf-8')
def sendMail(self, result): msg = self.formatMessage(result) mail_to, pref_lang = self.findRecipient(result) mail_from = self.findSender() subject = self.ts.translate(_('mail_uncommented_subject'), context=self.context) self.mailhost.send(messageText=msg, mto=mail_to, mfrom=mail_from, subject=subject, charset='utf-8')
476,856
def sendMail(self, result): msg = self.formatMessage(result) mail_to = self.findRecipient(result) mail_from = self.findSender() subject = self.ts.translate(_('mail_uncommented_subject'), context=self.context) self.mailhost.send(messageText=msg, mto=mail_to, mfrom=mail_from, subject=subject, charset='utf-8')
def sendMail(self, result): msg = self.formatMessage(result) mail_to = self.findRecipient(result) mail_from = self.findSender() subject = self.ts.translate(_('mail_uncommented_subject'), target_language=pref_lang) self.mailhost.send(messageText=msg, mto=mail_to, mfrom=mail_from, subject=subject, charset='utf-8')
476,857
def formatMessage(self, result): title = result.Title owner_name = result.Creator url = result.getURL() date = result.created.strftime('%d.%m.%Y') msg_template = self.ts.translate(_('mail_uncommented_body'), context=self.context)
def formatMessage(self, result): title = result.Title owner_name = result.Creator url = result.getURL() date = result.created.strftime('%d.%m.%Y') msg_template = self.ts.translate(_('mail_uncommented_body'), context=self.context)
476,858
def findRecipient(self, result): membership_tool = getToolByName(self.context, 'portal_membership') owner = membership_tool.getMemberById(result.Creator).getUser() return owner.getProperty('email') or self.findSender()
def findRecipient(self, result): membership_tool = getToolByName(self.context, 'portal_membership') owner = membership_tool.getMemberById(result.Creator).getUser() return owner.getProperty('email') or self.findSender()
476,859
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
476,860
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
476,861
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
def handleTransition(self, info): membership_tool = getToolByName(self.context, 'portal_membership') user = membership_tool.getAuthenticatedMember() mailhost = getToolByName(self.context, 'MailHost') root = getToolByName(self.context, 'portal_url').getPortalObject() mail_info = IMailSchema(root) mail_from = '%s <%s>' % (mail_info.email_from_name, mail_info.email_from_address) user_email = user.getProperty('email')
476,862
def findRecipient(self): membership_tool = getToolByName(self.context, 'portal_membership') owner = membership_tool.getMemberById(self.context.__parent__.__parent__.Creator()).getUser() return owner.getProperty('email'), owner.getProperty('preferred_language', 'de')
def findRecipient(self): membership_tool = getToolByName(self.context, 'portal_membership') owner = membership_tool.getMemberById(self.context.__parent__.__parent__.Creator()).getUser() return owner.getProperty('email'), owner.getProperty('preferred_language', 'de')
476,863
def get_preferred_language(email, default='de'): found = self.pas.searchUsers(email=args['mail_to']) if found: owner = self.membership_tool.getMemberById(found[0]['userid']).getUser() return owner.getProperty('preferred_language', default) else: return default
def get_preferred_language(email, default='en'): found = self.pas.searchUsers(email=args['mail_to']) if found: owner = self.membership_tool.getMemberById(found[0]['userid']).getUser() return owner.getProperty('preferred_language', default) else: return default
476,864
def get_preferred_language(email, default='de'): found = self.pas.searchUsers(email=args['mail_to']) if found: owner = self.membership_tool.getMemberById(found[0]['userid']).getUser() return owner.getProperty('preferred_language', default) else: return default
def get_preferred_language(email, default='de'): found = self.pas.searchUsers(email=args['mail_to']) if found: owner = self.membership_tool.getMemberById(found[0]['userid']).getUser() return owner.getProperty('preferred_language', default) else: return default
476,865
def findRecipient(self, result): membership_tool = getToolByName(self.context, 'portal_membership') owner = membership_tool.getMemberById(result.Creator).getUser() return owner.getProperty('email') or self.findSender(), owner.getProperty('preferred_language', 'de')
def findRecipient(self, result): membership_tool = getToolByName(self.context, 'portal_membership') owner = membership_tool.getMemberById(result.Creator).getUser() return owner.getProperty('email') or self.findSender(), owner.getProperty('preferred_language', 'de')
476,866
def publishImportedContent(context): portal = context.getSite() pwt = getToolByName(portal, 'portal_workflow') for id in imported_content: for lang in ['', 'en', 'fr']: if lang: id = id + '-' + lang obj = getattr(portal, id, None) if not obj: log.warning('Object %s not found. Please run import step "Recensio initial content"' % id) continue doPublish(obj, pwt)
def publishImportedContent(context): portal = context.getSite() pwt = getToolByName(portal, 'portal_workflow') for id in imported_content: for lang in ['', '-en', '-fr']: obj = getattr(portal, id + lang, None) if not obj: log.warning('Object %s not found. Please run import step "Recensio initial content"' % id) continue doPublish(obj, pwt)
476,867
def publishImportedContent(context): portal = context.getSite() pwt = getToolByName(portal, 'portal_workflow') for id in imported_content: for lang in ['', 'en', 'fr']: if lang: id = id + '-' + lang obj = getattr(portal, id, None) if not obj: log.warning('Object %s not found. Please run import step "Recensio initial content"' % id) continue doPublish(obj, pwt)
def publishImportedContent(context): portal = context.getSite() pwt = getToolByName(portal, 'portal_workflow') for id in imported_content: for lang in ['', 'en', 'fr']: if lang: id = id + '-' + lang obj = getattr(portal, id, None) if not obj: log.warning('Object %s not found. Please run import step "Recensio initial content"' % id + lang) continue doPublish(obj, pwt)
476,868
def addIndex(name, type, **kw): if not name in cat.indexes(): log.debug('adding %s %s, kw=%s' %(type, name, kw)) cat.addIndex(name, type, **kw) elif not filter(lambda x: x.getId() == name, cat.getIndexObjects())[0].meta_type == type: cat.delIndex(name) log.debug('adding %s %s, kw=%s' %(type, name, kw)) cat.addIndex(name, type, **kw)
def addIndex(name, type, **kw): if not name in cat.indexes(): log.debug('adding %s %s, kw=%s' %(type, name, kw)) cat.addIndex(name, type, **kw) elif not filter(lambda x: x.getId() == name, cat.getIndexObjects())[0].meta_type == type: cat.delIndex(name) log.debug('adding %s %s, kw=%s' %(type, name, kw)) cat.addIndex(name, type, **kw)
476,869
def __get_html(self):
def __get_html(self):
476,870
def get_messages(self):
def get_messages(self):
476,871
def test_update_of_review_portlet(self): self.loginAsPortalOwner() portal = self.portal portal.portal_workflow.doActionFor(self.portal['front-page'], 'retract') portal.portal_workflow.doActionFor(self.portal['front-page'], 'submit') self.create_portlet(u'review', ReviewAssignment()) descriptor = lifecycleevent.Attributes(IPortalObject, 'title') event = ActionSucceededEvent(self.folder, descriptor, None, None) event.old_state, event.new_state = 'private', 'pending' workflowTriggersReviewPortletReload(self.portal, self.view, event) result = self.view.render() command = result[0] self.failUnless(command.has_key('selector')) self.failUnless(command['selector'].startswith('portletwrapper')) self.failUnless(command.has_key('name')) self.assertEqual(command['name'], 'replaceInnerHTML') self.failUnless(command.has_key('params')) params = result[0]['params'] self.failUnless(params.has_key('html')) html = params['html'] self.failUnless('portletWorkflowReview' in html) self.failUnless(command.has_key('selectorType')) self.assertEqual(command['selectorType'], 'htmlid')
def test_update_of_review_portlet(self): self.loginAsPortalOwner() portal = self.portal portal.portal_workflow.doActionFor(self.portal['front-page'], 'retract') portal.portal_workflow.doActionFor(self.portal['front-page'], 'submit') self.create_portlet(u'review', ReviewAssignment()) event = ActionSucceededEvent(self.folder, None, None, None) event.old_state, event.new_state = 'private', 'pending' workflowTriggersReviewPortletReload(self.portal, self.view, event) result = self.view.render() command = result[0] self.failUnless(command.has_key('selector')) self.failUnless(command['selector'].startswith('portletwrapper')) self.failUnless(command.has_key('name')) self.assertEqual(command['name'], 'replaceInnerHTML') self.failUnless(command.has_key('params')) params = result[0]['params'] self.failUnless(params.has_key('html')) html = params['html'] self.failUnless('portletWorkflowReview' in html) self.failUnless(command.has_key('selectorType')) self.assertEqual(command['selectorType'], 'htmlid')
476,872
def requestonly(self, view): attr = self.attr if attr is None: attr = '__call__' if inspect.isfunction(view): fn = view elif inspect.isclass(view): try: fn = view.__init__ except AttributeError: return False else: try: fn = getattr(view, attr) except AttributeError: return False
def requestonly(self, view): attr = self.attr if attr is None: attr = '__call__' if inspect.isfunction(view): fn = view elif inspect.isclass(view): try: fn = view.__init__ except AttributeError: return False else: try: fn = getattr(view, attr) except AttributeError: return False
476,873
def model_url(self, model, *elements, **kw): """ Return the URL for the model object named ``model``, using ``*elements`` and ``**kw`` as modifiers.
def model_url(self, model, *elements, **kw): """ Return the URL for the model object named ``model``, using ``*elements`` and ``**kw`` as modifiers.
476,874
def model_url(self, model, *elements, **kw): """ Return the URL for the model object named ``model``, using ``*elements`` and ``**kw`` as modifiers.
def model_url(self, model, *elements, **kw): """ Return the URL for the model object named ``model``, using ``*elements`` and ``**kw`` as modifiers.
476,875
def fix_zcml(path): for root, dirs, files in os.walk(path): for file in files: if file.endswith('.zcml'): absfile = os.path.join(root, file) text = open(absfile, 'rb').read() newt =INCLUDES.sub('include package="pyramid.includes"', text) newt = NS.sub('xmlns="http://pyramid.pylonshq.com"', newt) if text != newt: newf = open(absfile, 'wb') newf.write(newt) newf.flush() newf.close() for dir in dirs: if dir.startswith('.'): dirs.remove(dir)
def fix_zcml(path): for root, dirs, files in os.walk(path): for file in files: if file.endswith('.zcml'): absfile = os.path.join(root, file) text = open(absfile, 'rb').read() newt =INCLUDES.sub('include package="pyramid.includes"', text) newt = NS.sub('xmlns="http://pylonshq.com/pyramid"', newt) if text != newt: newf = open(absfile, 'wb') newf.write(newt) newf.flush() newf.close() for dir in dirs: if dir.startswith('.'): dirs.remove(dir)
476,876
def _pkg_resources_style(self, value): """ package.module:attr style """ import pkg_resources if value.startswith('.') or value.startswith(':'): if not self.package: raise ConfigurationError( 'relative name %r irresolveable without package' % value) if value in ['.', ':']: value = self.package.__name__ else: value = self.package.__name__ + value return pkg_resources.EntryPoint.parse( 'x=%s' % value).load(False)
def _pkg_resources_style(self, value): """ package.module:attr style """ import pkg_resources if value.startswith('.') or value.startswith(':'): if not self.package: raise ConfigurationError( 'relative name %r irresolveable without package' % (value,)) if value in ['.', ':']: value = self.package.__name__ else: value = self.package.__name__ + value return pkg_resources.EntryPoint.parse( 'x=%s' % value).load(False)
476,877
def _zope_dottedname_style(self, value): """ package.module.attr style """ module = self.package and self.package.__name__ or None if value == '.': if self.package is None: raise ConfigurationError( 'relative name %r irresolveable without package' % value) name = module.split('.') else: name = value.split('.') if not name[0]: if module is None: raise ConfigurationError( 'relative name %r irresolveable without ' 'package' % value ) module = module.split('.') name.pop(0) while not name[0]: module.pop() name.pop(0) name = module + name
def _zope_dottedname_style(self, value): """ package.module.attr style """ module = self.package and self.package.__name__ or None if value == '.': if self.package is None: raise ConfigurationError( 'relative name %r irresolveable without package' % (value,)) name = module.split('.') else: name = value.split('.') if not name[0]: if module is None: raise ConfigurationError( 'relative name %r irresolveable without ' 'package' % value ) module = module.split('.') name.pop(0) while not name[0]: module.pop() name.pop(0) name = module + name
476,878
def _zope_dottedname_style(self, value): """ package.module.attr style """ module = self.package and self.package.__name__ or None if value == '.': if self.package is None: raise ConfigurationError( 'relative name %r irresolveable without package' % value) name = module.split('.') else: name = value.split('.') if not name[0]: if module is None: raise ConfigurationError( 'relative name %r irresolveable without ' 'package' % value ) module = module.split('.') name.pop(0) while not name[0]: module.pop() name.pop(0) name = module + name
def _zope_dottedname_style(self, value): """ package.module.attr style """ module = self.package and self.package.__name__ or None if value == '.': if self.package is None: raise ConfigurationError( 'relative name %r irresolveable without package' % value) name = module.split('.') else: name = value.split('.') if not name[0]: if module is None: raise ConfigurationError( 'relative name %r irresolveable without ' 'package' % (value,) ) module = module.split('.') name.pop(0) while not name[0]: module.pop() name.pop(0) name = module + name
476,879
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
476,880
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
476,881
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
476,882
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
476,883
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
476,884
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
476,885
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
def add_static_view(self, name, path, **kw): """ Add a view used to render static assets such as images and CSS files.
476,886
def main(argv=None): if argv is None: argv = sys.argv path = argv[1] fixer_names = get_fixers_from_package('repoze.bfg.fixers') tool = RefactoringTool(fixer_names) tool.refactor([path], write=True)
def main(argv=None): if argv is None: argv = sys.argv path = argv[1] fixer_names = get_fixers_from_package('pyramid.fixers') tool = RefactoringTool(fixer_names) tool.refactor([path], write=True)
476,887
def package_name(pkg_or_module): """ If this function is passed a module, return the dotted Python package name of the package in which the module lives. If this function is passed a package, return the dotted Python package name of the package itself.""" if pkg_or_module is None: return '__main__' pkg_filename = pkg_or_module.__file__ pkg_name = pkg_or_module.__name__ splitted = os.path.split(pkg_filename) if splitted[-1] in ('__init__.py', '__init__.pyc', '__init__.pyo'): # it's a package return pkg_name return pkg_name.rsplit('.', 1)[0]
def package_name(pkg_or_module): """ If this function is passed a module, return the dotted Python package name of the package in which the module lives. If this function is passed a package, return the dotted Python package name of the package itself.""" if pkg_or_module is None: return '__main__' pkg_filename = pkg_or_module.__file__ pkg_name = pkg_or_module.__name__ splitted = os.path.split(pkg_filename) if splitted[-1] in init_names: # it's a package return pkg_name return pkg_name.rsplit('.', 1)[0]
476,888
def add_route(self, name, path, view=None, view_for=None, permission=None, factory=None, for_=None, header=None, xhr=False, accept=None, path_info=None, request_method=None, request_param=None, custom_predicates=(), view_permission=None, renderer=None, view_renderer=None, view_context=None, view_attr=None, use_global_views=False, _info=u''): """ Add a :term:`route configuration` to the current configuration state, as well as possibly a :term:`view configuration` to be used to specify a :term:`view callable` that will be invoked when this route matches. The arguments to this method are divided into *predicate*, *non-predicate*, and *view-related* types. :term:`Route predicate` arguments narrow the circumstances in which a route will be match a request; non-predicate arguments are informational.
def add_route(self, name, path, view=None, view_for=None, permission=None, factory=None, for_=None, header=None, xhr=False, accept=None, path_info=None, request_method=None, request_param=None, custom_predicates=(), view_permission=None, renderer=None, view_renderer=None, view_context=None, view_attr=None, use_global_views=False, _info=u''): """ Add a :term:`route configuration` to the current configuration state, as well as possibly a :term:`view configuration` to be used to specify a :term:`view callable` that will be invoked when this route matches. The arguments to this method are divided into *predicate*, *non-predicate*, and *view-related* types. :term:`Route predicate` arguments narrow the circumstances in which a route will be match a request; non-predicate arguments are informational.
476,889
def my_view(context, request): return 'OK'
def my_view(context, request): return 'OK'
476,890
def get_settings(): """ Return a 'settings' object for the current application. A 'settings' object is a dictionary-like object that contains key/value pairs based on the dictionary passed as the ``settings`` argument to the :class:`pyramid.configuration.Configurator` constructor or the :func:`pyramid.router.make_app` API. .. note:: For backwards compatibility, dictionary keys can also be looked up as attributes of the settings object. .. note:: the :class:`pyramid.configuration.Configurator.get_settings` method performs the same duty. .. warning:: This method is deprecated as of Pyramid 1.0. Use ``pyramid.threadlocals.get_current_registry().settings`` instead or use ' the ``settings`` attribute of the registry available from the request (``request.registry.settings``). """ reg = get_current_registry() return reg.settings
def get_settings(): """ Return a 'settings' object for the current application. A 'settings' object is a dictionary-like object that contains key/value pairs based on the dictionary passed as the ``settings`` argument to the :class:`pyramid.configuration.Configurator` constructor or the :func:`pyramid.router.make_app` API. .. note:: For backwards compatibility, dictionary keys can also be looked up as attributes of the settings object. .. note:: the :class:`pyramid.configuration.Configurator.get_settings` method performs the same duty. .. warning:: This method is deprecated as of Pyramid 1.0. Use ``pyramid.threadlocals.get_current_registry().settings`` instead or use ' the ``settings`` attribute of the registry available from the request (``request.registry.settings``). """ reg = get_current_registry() return reg.settings
476,891
def set_renderer_globals_factory(self, factory): """ The object passed as ``factory`` will be used by the :mod:`repoze.bfg` rendering machinery as a renderers global factory (see :ref:`adding_renderer_globals`). The factory must return a dictionary of items that will be merged intto the *system* dictionary passed in to every renderer used by the application.
def set_renderer_globals_factory(self, factory): """ The object passed as ``factory`` will be used by the :mod:`repoze.bfg` rendering machinery as a renderers global factory (see :ref:`adding_renderer_globals`). The factory must return a dictionary of items that will be merged intto the *system* dictionary passed in to every renderer used by the application.
476,892
def __init__(self, default=None): # http://code.google.com/p/google-app-engine-django/issues/detail?id=119 # we *must* use a keword argument for ``default`` here instead # of a positional argument to work around a bug in the # implementation of _threading_local.local in Python, which is # used by GAE instead of _thread.local self.stack = [] self.default = default
def __init__(self, default=None): # http://code.google.com/p/google-app-engine-django/issues/detail?id=119 # we *must* use a keword argument for ``default`` here instead # of a positional argument to work around a bug in the # implementation of _threading_local.local in Python, which is # used by GAE instead of _thread.local self.stack = [] self.default = default
476,893
def __init__(self, default=None): # http://code.google.com/p/google-app-engine-django/issues/detail?id=119 # we *must* use a keword argument for ``default`` here instead # of a positional argument to work around a bug in the # implementation of _threading_local.local in Python, which is # used by GAE instead of _thread.local self.stack = [] self.default = default
def __init__(self, default=None): # http://code.google.com/p/google-app-engine-django/issues/detail?id=119 # we *must* use a keword argument for ``default`` here instead # of a positional argument to work around a bug in the # implementation of _threading_local.local in Python, which is # used by GAE instead of _thread.local self.stack = [] self.default = default
476,894
def route(_context, name, pattern=None, view=None, view_for=None, permission=None, factory=None, for_=None, header=None, xhr=False, accept=None, path_info=None, request_method=None, request_param=None, custom_predicates=(), view_permission=None, view_attr=None, renderer=None, view_renderer=None, view_context=None, traverse=None, use_global_views=False, path=None): """ Handle ``route`` ZCML directives """ # the strange ordering of the request kw args above is for b/w # compatibility purposes. # these are route predicates; if they do not match, the next route # in the routelist will be tried if view_context is None: view_context = view_for or for_ view_permission = view_permission or permission view_renderer = view_renderer or renderer if pattern is None: pattern = path if pattern is None: raise ConfigurationError('route directive must include a "pattern"') config = Configurator.with_context(_context) config.add_route( name, pattern, factory=factory, header=header, xhr=xhr, accept=accept, path_info=path_info, request_method=request_method, request_param=request_param, custom_predicates=custom_predicates, view=view, view_context=view_context, view_permission=view_permission, view_renderer=view_renderer, view_attr=view_attr, use_global_views=use_global_views, traverse=traverse, )
def route(_context, name, pattern=None, view=None, view_for=None, permission=None, factory=None, for_=None, header=None, xhr=False, accept=None, path_info=None, request_method=None, request_param=None, custom_predicates=(), view_permission=None, view_attr=None, renderer=None, view_renderer=None, view_context=None, traverse=None, use_global_views=False, path=None): """ Handle ``route`` ZCML directives """ # the strange ordering of the request kw args above is for b/w # compatibility purposes. # these are route predicates; if they do not match, the next route # in the routelist will be tried if view_context is None: view_context = view_for or for_ view_permission = view_permission or permission view_renderer = view_renderer or renderer if pattern is None: pattern = path if pattern is None: raise ConfigurationError('route directive must include a "pattern"') config = Configurator.with_context(_context) config.add_route( name, pattern, factory=factory, header=header, xhr=xhr, accept=accept, path_info=path_info, request_method=request_method, request_param=request_param, custom_predicates=custom_predicates, view=view, view_context=view_context, view_permission=view_permission, view_renderer=view_renderer, view_attr=view_attr, use_global_views=use_global_views, traverse=traverse, )
476,895
def route_url(route_name, request, *elements, **kw): """Generates a fully qualified URL for a named :mod:`pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Use a request object as the second positional argument. Additional positional arguments are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``:foo/:bar/*traverse``:: route_url('foobar', request, foo='1') => <KeyError exception> route_url('foobar', request, foo='1', bar='2') => <KeyError exception> route_url('foobar', request, foo='1', bar='2', 'traverse=('a','b')) => http://e.com/1/2/a/b route_url('foobar', request, foo='1', bar='2', 'traverse=('/a/b')) => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL untouched. If a keyword argument ``_query`` is present, it will used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the model URL is ``http://example.com/model/url``, the resulting generated URL will be ``http://example.com/model/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments arguments passed to this function might be augmented or changed. """ try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(request, elements, kw) anchor = '' qs = '' app_url = None if '_query' in kw: qs = '?' + urlencode(kw.pop('_query'), doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') if isinstance(anchor, unicode): anchor = anchor.encode('utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' if app_url is None: # we only defer lookup of application_url until here because # it's somewhat expensive; we won't need to do it if we've # been passed _app_url app_url = request.application_url return app_url + path + suffix + qs + anchor
def route_url(route_name, request, *elements, **kw): """Generates a fully qualified URL for a named :mod:`pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Use a request object as the second positional argument. Additional positional arguments are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``:foo/:bar/*traverse``:: route_url('foobar', request, foo='1') => <KeyError exception> route_url('foobar', request, foo='1', bar='2') => <KeyError exception> route_url('foobar', request, foo='1', bar='2', 'traverse=('a','b')) => http://e.com/1/2/a/b route_url('foobar', request, foo='1', bar='2', 'traverse=('/a/b')) => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL untouched. If a keyword argument ``_query`` is present, it will used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the model URL is ``http://example.com/model/url``, the resulting generated URL will be ``http://example.com/model/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments arguments passed to this function might be augmented or changed. """ try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(request, elements, kw) anchor = '' qs = '' app_url = None if '_query' in kw: qs = '?' + urlencode(kw.pop('_query'), doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') if isinstance(anchor, unicode): anchor = anchor.encode('utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' if app_url is None: # we only defer lookup of application_url until here because # it's somewhat expensive; we won't need to do it if we've # been passed _app_url app_url = request.application_url return app_url + path + suffix + qs + anchor
476,896
def route_url(route_name, request, *elements, **kw): """Generates a fully qualified URL for a named :mod:`pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Use a request object as the second positional argument. Additional positional arguments are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``:foo/:bar/*traverse``:: route_url('foobar', request, foo='1') => <KeyError exception> route_url('foobar', request, foo='1', bar='2') => <KeyError exception> route_url('foobar', request, foo='1', bar='2', 'traverse=('a','b')) => http://e.com/1/2/a/b route_url('foobar', request, foo='1', bar='2', 'traverse=('/a/b')) => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL untouched. If a keyword argument ``_query`` is present, it will used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the model URL is ``http://example.com/model/url``, the resulting generated URL will be ``http://example.com/model/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments arguments passed to this function might be augmented or changed. """ try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(request, elements, kw) anchor = '' qs = '' app_url = None if '_query' in kw: qs = '?' + urlencode(kw.pop('_query'), doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') if isinstance(anchor, unicode): anchor = anchor.encode('utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' if app_url is None: # we only defer lookup of application_url until here because # it's somewhat expensive; we won't need to do it if we've # been passed _app_url app_url = request.application_url return app_url + path + suffix + qs + anchor
def route_url(route_name, request, *elements, **kw): """Generates a fully qualified URL for a named :mod:`pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Use a request object as the second positional argument. Additional positional arguments are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``:foo/:bar/*traverse``:: route_url('foobar', request, foo='1') => <KeyError exception> route_url('foobar', request, foo='1', bar='2') => <KeyError exception> route_url('foobar', request, foo='1', bar='2', 'traverse=('a','b')) => http://e.com/1/2/a/b route_url('foobar', request, foo='1', bar='2', 'traverse=('/a/b')) => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL untouched. If a keyword argument ``_query`` is present, it will used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the model URL is ``http://example.com/model/url``, the resulting generated URL will be ``http://example.com/model/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments arguments passed to this function might be augmented or changed. """ try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(request, elements, kw) anchor = '' qs = '' app_url = None if '_query' in kw: qs = '?' + urlencode(kw.pop('_query'), doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') if isinstance(anchor, unicode): anchor = anchor.encode('utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' if app_url is None: # we only defer lookup of application_url until here because # it's somewhat expensive; we won't need to do it if we've # been passed _app_url app_url = request.application_url return app_url + path + suffix + qs + anchor
476,897
def route_url(route_name, request, *elements, **kw): """Generates a fully qualified URL for a named :mod:`pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Use a request object as the second positional argument. Additional positional arguments are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``:foo/:bar/*traverse``:: route_url('foobar', request, foo='1') => <KeyError exception> route_url('foobar', request, foo='1', bar='2') => <KeyError exception> route_url('foobar', request, foo='1', bar='2', 'traverse=('a','b')) => http://e.com/1/2/a/b route_url('foobar', request, foo='1', bar='2', 'traverse=('/a/b')) => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL untouched. If a keyword argument ``_query`` is present, it will used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the model URL is ``http://example.com/model/url``, the resulting generated URL will be ``http://example.com/model/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments arguments passed to this function might be augmented or changed. """ try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(request, elements, kw) anchor = '' qs = '' app_url = None if '_query' in kw: qs = '?' + urlencode(kw.pop('_query'), doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') if isinstance(anchor, unicode): anchor = anchor.encode('utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' if app_url is None: # we only defer lookup of application_url until here because # it's somewhat expensive; we won't need to do it if we've # been passed _app_url app_url = request.application_url return app_url + path + suffix + qs + anchor
def route_url(route_name, request, *elements, **kw): """Generates a fully qualified URL for a named :mod:`pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Use a request object as the second positional argument. Additional positional arguments are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``:foo/:bar/*traverse``:: route_url('foobar', request, foo='1') => <KeyError exception> route_url('foobar', request, foo='1', bar='2') => <KeyError exception> route_url('foobar', request, foo='1', bar='2', traverse=('a','b')) => http://e.com/1/2/a/b route_url('foobar', request, foo='1', bar='2', 'traverse=('/a/b')) => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL untouched. If a keyword argument ``_query`` is present, it will used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the model URL is ``http://example.com/model/url``, the resulting generated URL will be ``http://example.com/model/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments arguments passed to this function might be augmented or changed. """ try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(request, elements, kw) anchor = '' qs = '' app_url = None if '_query' in kw: qs = '?' + urlencode(kw.pop('_query'), doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') if isinstance(anchor, unicode): anchor = anchor.encode('utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' if app_url is None: # we only defer lookup of application_url until here because # it's somewhat expensive; we won't need to do it if we've # been passed _app_url app_url = request.application_url return app_url + path + suffix + qs + anchor
476,898
def route_url(route_name, request, *elements, **kw): """Generates a fully qualified URL for a named :mod:`pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Use a request object as the second positional argument. Additional positional arguments are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``:foo/:bar/*traverse``:: route_url('foobar', request, foo='1') => <KeyError exception> route_url('foobar', request, foo='1', bar='2') => <KeyError exception> route_url('foobar', request, foo='1', bar='2', 'traverse=('a','b')) => http://e.com/1/2/a/b route_url('foobar', request, foo='1', bar='2', 'traverse=('/a/b')) => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL untouched. If a keyword argument ``_query`` is present, it will used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the model URL is ``http://example.com/model/url``, the resulting generated URL will be ``http://example.com/model/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments arguments passed to this function might be augmented or changed. """ try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(request, elements, kw) anchor = '' qs = '' app_url = None if '_query' in kw: qs = '?' + urlencode(kw.pop('_query'), doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') if isinstance(anchor, unicode): anchor = anchor.encode('utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' if app_url is None: # we only defer lookup of application_url until here because # it's somewhat expensive; we won't need to do it if we've # been passed _app_url app_url = request.application_url return app_url + path + suffix + qs + anchor
def route_url(route_name, request, *elements, **kw): """Generates a fully qualified URL for a named :mod:`pyramid` :term:`route configuration`. Use the route's ``name`` as the first positional argument. Use a request object as the second positional argument. Additional positional arguments are appended to the URL as path segments after it is generated. Use keyword arguments to supply values which match any dynamic path elements in the route definition. Raises a :exc:`KeyError` exception if the URL cannot be generated for any reason (not enough arguments, for example). For example, if you've defined a route named "foobar" with the path ``:foo/:bar/*traverse``:: route_url('foobar', request, foo='1') => <KeyError exception> route_url('foobar', request, foo='1', bar='2') => <KeyError exception> route_url('foobar', request, foo='1', bar='2', 'traverse=('a','b')) => http://e.com/1/2/a/b route_url('foobar', request, foo='1', bar='2', traverse='/a/b') => http://e.com/1/2/a/b Values replacing ``:segment`` arguments can be passed as strings or Unicode objects. They will be encoded to UTF-8 and URL-quoted before being placed into the generated URL. Values replacing ``*remainder`` arguments can be passed as strings *or* tuples of Unicode/string values. If a tuple is passed as a ``*remainder`` replacement value, its values are URL-quoted and encoded to UTF-8. The resulting strings are joined with slashes and rendered into the URL. If a string is passed as a ``*remainder`` replacement value, it is tacked on to the URL untouched. If a keyword argument ``_query`` is present, it will used to compose a query string that will be tacked on to the end of the URL. The value of ``_query`` must be a sequence of two-tuples *or* a data structure with an ``.items()`` method that returns a sequence of two-tuples (presumably a dictionary). This data structure will be turned into a query string per the documentation of :func:`pyramid.encode.urlencode` function. After the query data is turned into a query string, a leading ``?`` is prepended, and the resulting string is appended to the generated URL. .. note:: Python data structures that are passed as ``_query`` which are sequences or dictionaries are turned into a string under the same rules as when run through :func:`urllib.urlencode` with the ``doseq`` argument equal to ``True``. This means that sequences can be passed as values, and a k=v pair will be placed into the query string for each value. If a keyword argument ``_anchor`` is present, its string representation will be used as a named anchor in the generated URL (e.g. if ``_anchor`` is passed as ``foo`` and the model URL is ``http://example.com/model/url``, the resulting generated URL will be ``http://example.com/model/url#foo``). .. note:: If ``_anchor`` is passed as a string, it should be UTF-8 encoded. If ``_anchor`` is passed as a Unicode object, it will be converted to UTF-8 before being appended to the URL. The anchor value is not quoted in any way before being appended to the generated URL. If both ``_anchor`` and ``_query`` are specified, the anchor element will always follow the query element, e.g. ``http://example.com?foo=1#bar``. If a keyword ``_app_url`` is present, it will be used as the protocol/hostname/port/leading path prefix of the generated URL. For example, using an ``_app_url`` of ``http://example.com:8080/foo`` would cause the URL ``http://example.com:8080/foo/fleeb/flub`` to be returned from this function if the expansion of the route pattern associated with the ``route_name`` expanded to ``/fleeb/flub``. If ``_app_url`` is not specified, the result of ``request.application_url`` will be used as the prefix (the default). This function raises a :exc:`KeyError` if the URL cannot be generated due to missing replacement names. Extra replacement names are ignored. If the route object which matches the ``route_name`` argument has a :term:`pregenerator`, the ``*elements`` and ``**kw`` arguments arguments passed to this function might be augmented or changed. """ try: reg = request.registry except AttributeError: reg = get_current_registry() # b/c mapper = reg.getUtility(IRoutesMapper) route = mapper.get_route(route_name) if route is None: raise KeyError('No such route named %s' % route_name) if route.pregenerator is not None: elements, kw = route.pregenerator(request, elements, kw) anchor = '' qs = '' app_url = None if '_query' in kw: qs = '?' + urlencode(kw.pop('_query'), doseq=True) if '_anchor' in kw: anchor = kw.pop('_anchor') if isinstance(anchor, unicode): anchor = anchor.encode('utf-8') anchor = '#' + anchor if '_app_url' in kw: app_url = kw.pop('_app_url') path = route.generate(kw) # raises KeyError if generate fails if elements: suffix = _join_elements(elements) if not path.endswith('/'): suffix = '/' + suffix else: suffix = '' if app_url is None: # we only defer lookup of application_url until here because # it's somewhat expensive; we won't need to do it if we've # been passed _app_url app_url = request.application_url return app_url + path + suffix + qs + anchor
476,899