def get_users_dt_helper(request=None): """ Get authenticated users timezone, lang and return DateTimeHelper for it. """ if request is None: request = get_current_request() userid = authenticated_userid(request) root = find_root(request.context) if root is None: tz = request.registry.getUtility(ISettings)['default_timezone'] locale = get_locale_name(request) else: user = root['users'][userid] tz = user.get_time_zone() datetime_localisation = user.get_field_value('datetime_localisation', None) locale = datetime_localisation and datetime_localisation or get_locale_name(request) return createObject('dt_helper', tz, locale)
def root_view(request): request.locale_name = 'fr' localizer = get_localizer(request) return { 'pyramid_translated': localizer.translate(_('Hello World')), 'locale_name': get_locale_name(request) }
def test_i18n_view(request): locale_name = get_locale_name(request) print "DEBUG: locale_name is " + str(locale_name) locale = Locale(locale_name) print "DEBUG: babel locale is " + str(locale) locale_name = get_locale_name(request) print "DEBUG: locale_name is " + str(locale_name) locale = Locale(locale_name) print "DEBUG: babel locale is " + str(locale) return {'project':'myapp', 'name':'Foo Bar', 'country_of_birth':'Baz'}
def i18n(self): minmax = {'min':1, 'max':10} locale_name = get_locale_name(self.request) class Schema(colander.Schema): number = colander.SchemaNode( colander.Integer(), title=_('A number between ${min} and ${max}', mapping=minmax), description=_('A number between ${min} and ${max}', mapping=minmax), validator = colander.Range(1, 10), ) _LOCALE_ = colander.SchemaNode( colander.String(), widget = deform.widget.HiddenWidget(), default=locale_name) schema = Schema() form = deform.Form( schema, buttons=[deform.Button('submit', _('Submit'))], ) return self.render_form(form)
def locale(self): try: # Country is optional lang_country = get_locale_name(self).split('-') except AttributeError: # Testing, registry has no settings lang_country = ('en', 'US') return locales.getLocale(*lang_country)
def get_ixiacr_tests(request): lang = get_locale_name(request) # JSON feed that is responsible for the ixiacr_tests. test_id = request.params.get('test_id', None) tests = TestCases.query.filter(TestCases.active=='1').order_by(TestCases.id.desc()).all() items = [] try: for test in tests: config = { "id": test.id, "name": test.name.get_translation(lang), "bpt_name": test.bpt_name, "type": test.type, "description": test.description.get_translation(lang), #"duration": test.duration, "topology_image": test.topology_image, "topology_description": test.topology_description.get_translation(lang), "attack_task": test.attack_task.get_translation(lang), "attack_steps": test.attack_steps.get_translation(lang), "attack_criteria": test.attack_criteria.get_translation(lang), "defense_task": test.defense_task.get_translation(lang), "defense_steps": test.defense_steps.get_translation(lang), "defense_criteria": test.defense_criteria.get_translation(lang), "traffic_direction": test.traffic_direction.get_translation(lang) } items.append(config) return items except DBAPIError, e: return Response("Error: DB Error: {0}".format(e), content_type='text/plain', status_int=500)
def create_user(request): localizer = get_localizer(request) name = request.params['name'] email = request.params['email'] user = User().queryObject().filter(User.email == email).scalar() if (user != None): msg = _('email_already_use', domain='Ondestan') return localizer.translate(msg) user = User() user.name = name user.email = email user.locale = get_locale_name(request) user.phone = request.params['phone'] user.activated = False user.password = sha512(request.params['password']).hexdigest() user.role_id = 2 user.save() url = request.route_url('activate_user', loginhash=sha512(email).hexdigest()) parameters = {'name': name, 'url': url} ondestan.services.notification_service.process_notification('signup', user.email, False, 0, True, False, parameters) return ''
def project(request): check_task_expiration() id = request.matchdict['project'] project = DBSession.query(Project).get(id) if project is None: _ = request.translate request.session.flash(_("Sorry, this project doesn't exist")) return HTTPFound(location=route_path('home', request)) project.locale = get_locale_name(request) filter = and_(TaskHistory.project_id == id, TaskHistory.state != TaskHistory.state_removed, TaskHistory.update.isnot(None)) history = DBSession.query(TaskHistory) \ .filter(filter) \ .order_by(TaskHistory.update.desc()) \ .limit(10).all() user_id = authenticated_userid(request) locked_task = None if user_id: user = DBSession.query(User).get(user_id) locked_task = get_locked_task(project.id, user) return dict( page_id='project', project=project, locked_task=locked_task, history=history, )
def title_to_name(title): request = get_current_request() if request is not None: locale_name = get_locale_name(request) else: locale_name = "en" return unicode(urlnormalizer.normalize(title, locale_name, max_length=40))
def add_page(request): user = authenticated_userid(request) if 'form.submitted' in request.params: name = request.params['name'] content = request.params['content'] if 'visible' in request.params: visible = True else: visible = False max_id = DBSession.query(func.max(Page.id)).all() if max_id[0][0]: position = max_id[0][0] + 1 else: position = 1 page = Page(user, name, content, position, visible) if 'parent_id' in request.params: page.parent_id = request.params['parent_id'] else: page.parent_id = 0 if 'lang' in request.params: page.language = request.params['lang'] if 'translated_page' in request.params: page.orign_page_id = request.params['translated_page'] page.created_by = user page.tags = [] tags = re.split(r'[,;]+', request.params['tags']) tags = filter(lambda x: x not in (None, '', ' '), tags) tags = map(lambda x: x.strip(), tags) tags = list(set(tags)) for tag in tags: exist_tag = DBSession.query(Tag).filter_by(name=tag).all() if exist_tag: tag = exist_tag[0] else: tag = Tag(tag) page.tags.append(tag) DBSession.add(page) return HTTPFound(location=request.route_url('admin')) # if it child page if 'parent_id' in request.params: parent_id = request.params['parent_id'] else: parent_id = '' LOCALE = get_locale_name(request) # if it translated page if 'add_translate' in request.params: translated_page_id = request.params['translated_page'] translated_page = DBSession.query(Page).\ filter_by(id=translated_page_id).one() lang_list = get_lang(translated_page) else: lang_list = translated_page = None page = Page(user, '', '', '', '') return dict(page=page, parent_id=parent_id, translate_lang=lang_list, translated=translated_page, LOCALE=LOCALE)
def view_page(request): page_name = request.matchdict['page_name'] page_locale = get_locale_name(request) page = DBSession.query(Page).filter_by(translite_name=page_name).\ filter_by(visible=True).one() # clause for choised locale if not page.language == page_locale: page_on_lang = False if page.orign_page_id == 0: page_id = page.id else: page_id = page.orign_page_id page_on_lang = DBSession.query(Page).\ filter_by(orign_page_id=page_id).\ filter_by(language=page_locale).all() if page_on_lang: page = page_on_lang[0] childs = DBSession.query(Page).filter_by(parent_id=page.id).\ filter_by(visible=True).all() def get_breadcrumbs_chain(page): chain = [] chain.append(page) while page.parent_id: page = DBSession.query(Page).filter_by(id=page.parent_id).one() chain.append(page) if len(chain) == 1: chain = [] return reversed(chain) breadcrumbs = get_breadcrumbs_chain(page) return dict(page=page, childs=childs, breadcrumbs=breadcrumbs)
def __init__(self, request): self.request = request init_cache_control(request, "entry") self.settings = request.registry.settings self.mapserver_settings = self.settings.get("mapserverproxy", {}) self.debug = "debug" in request.params self.lang = get_locale_name(request)
def get_localizer(request): """ Retrieve a :class:`pyramid.i18n.Localizer` object corresponding to the current request's locale name. """ localizer = getattr(request, 'localizer', None) if localizer is None: # no locale object cached on request try: registry = request.registry except AttributeError: registry = get_current_registry() current_locale_name = get_locale_name(request) localizer = registry.queryUtility(ILocalizer, name=current_locale_name) if localizer is None: # no localizer utility registered yet tdirs = registry.queryUtility(ITranslationDirectories, default=[]) localizer = make_localizer(current_locale_name, tdirs) registry.registerUtility(localizer, ILocalizer, name=current_locale_name) request.localizer = localizer return localizer
def view_home(self): request = self.request my_bootstrap.need() # we need css log.debug("Locale: " + get_locale_name(request)) if not request.POST and self.logged_in and self.user: data = {'HomeForm--yourmail': self.user.email, 'HomeForm--yourname': self.user.username } else: data = None form = home_form(request, data=request.POST or data) if request.POST and form.validate(): # if submitted and and valid, create Pot and participant, and then go to pot site log.debug("gutes Formular!") pot = Pot(form.potname.value) DBSession.add(pot) participant = Participant(name=form.yourname.value, email=form.yourmail.value) pot.participants.append(participant) if form .yourmail.value: mails.new_pot_mail(request, pot, participant, request.route_url('pot', identifier=participant.identifier)) if self.logged_in: self.user.participations.append(participant) return HTTPFound(location=request.route_url('pot', identifier=participant.identifier)) log.debug("Form: %s with model %s", str(id(form)), str(form.model)) log.debug("Field: %s", str(id(form.potname))) log.debug("Form has errors? %s", str(form.errors)) return {'form': form, 'logged_in': self.logged_in}
def sponsor_view(request): """ show a page confirming the sponsors payment """ #print "this is sponsor view" _code = request.matchdict['linkcode'] _abo = Abo.get_by_linkcode(_code) if 'de' in get_locale_name(request): financial_blog_url = request.registry.settings['financial_blog_url_de'] else: financial_blog_url = request.registry.settings['financial_blog_url_en'] if isinstance(_abo, NoneType): #print "=== not found in DB" request.session.flash('this linkcode is invalid', 'messages') return { 'financial_situation_blog': financial_blog_url, 'invalid': True, 'message': "this linkcode is invalid.", 'abo': None } return { 'financial_situation_blog': financial_blog_url, 'invalid': False, 'message': '', 'abo': _abo }
def add_custom_functions(event): locale_name = get_locale_name(event['request']) event.update({ 'dates_formatter': DatesFormatter(locale_name), })
def add_localizer(event): """ Localization event subscriber. Automaticaly translate strings in the templates. :param event: a ``pyramid.event.NewRequest`` object """ def auto_translate(string): """ Use the message factory to translate strings.""" return localizer.translate(MessageFactory(string)) def gettext_translate(string): """ Translate untranslated strings with FormEncode.""" # Try default translation first translation = localizer.old_translate(i18n.TranslationString(string)) if translation == string: # translation failed then use FormEncode translation = formencode_api._stdtrans(string) return translation request = event.request localizer = i18n.get_localizer(request) request.localizer = localizer request.translate = auto_translate if not hasattr(localizer, "old_translate"): localizer.old_translate = localizer.translate locale_name = i18n.get_locale_name(request) formencode_api.set_stdtranslation(languages=[locale_name]) localizer.translate = gettext_translate
def title_to_name(title): request = get_current_request() if request is not None: locale_name = get_locale_name(request) else: locale_name = 'en' return unicode(urlnormalizer.normalize(title, locale_name, max_length=40))
def __init__(self, context, request): self.context = context self.request = request # Logged User self.logged_in = authenticated_userid(request) # Main message for pages if needed self.message = u'' from easyblog.utilities import Provider from pyramid.renderers import get_renderer base = get_renderer('templates/base.pt').implementation() # This dict will be returned in every view def is_active(interface): if provides(self.context, interface): return 'active' return '' try: lang = self.request.cookies['lang'], except KeyError: from pyramid.i18n import get_locale_name lang = get_locale_name(self.request) self.base_dict = { 'logged_in': self.logged_in, 'message': self.message, 'resource_url': resource_url, 'provider': Provider(self.context, self.request), 'is_active': is_active, 'base': base, 'lang': lang }
def project(request): check_project_expiration() id = request.matchdict['project'] project = DBSession.query(Project).get(id) if project is None: _ = request.translate request.session.flash(_("Sorry, this project doesn't exist")) return HTTPFound(location=route_path('home', request)) project.locale = get_locale_name(request) filter = and_(TaskState.project_id == id, TaskState.state != TaskState.state_removed, TaskState.state != TaskState.state_ready) history = DBSession.query(TaskState) \ .filter(filter) \ .order_by(TaskState.date.desc()) \ .limit(20).all() user_id = authenticated_userid(request) locked_task = None user = None if user_id: user = DBSession.query(User).get(user_id) locked_task = get_locked_task(project.id, user) features = [] for area in project.priority_areas: features.append(Feature(geometry=shape.to_shape(area.geometry))) return dict(page_id='project', project=project, locked_task=locked_task, history=history, priority_areas=FeatureCollection(features),)
def survey_dt(self): survey = find_interface(self.context, ISurvey) if not survey: return tz = survey.get_time_zone() loc = get_locale_name(self.request) return createObject('dt_helper', tz, loc)
def locale_negotiator(request): lang = request.params.get('lang') settings = get_current_registry().settings languages = settings['available_languages'].split() if lang is None or lang not in languages: # the default_locale_name configuration variable return get_locale_name(request) return lang
def render_form( self, form, appstruct=colander.null, submitted="submit", success=None, readonly=False, is_i18n=False, ): captured = None if submitted in self.request.POST: # the request represents a form submission try: # try to validate the submitted values controls = self.request.POST.items() captured = form.validate(controls) if success: response = success() if response is not None: return response html = form.render(captured) except deform.ValidationFailure as e: # the submitted values could not be validated html = e.render() else: # the request requires a simple form rendering html = form.render(appstruct, readonly=readonly) if self.request.is_xhr: return Response(html) code, start, end = self.get_code(2) locale_name = get_locale_name(self.request) reqts = form.get_widget_resources() printer = pprint.PrettyPrinter() printer.format = my_safe_repr output = printer.pformat(captured) captured = highlight(output, PythonLexer(), formatter) # values passed to template for rendering return { "form": html, "captured": captured, "code": code, "start": start, "end": end, "is_i18n": is_i18n, "locale": locale_name, "demos": self.get_demos(), "title": self.get_title(), "css_links": reqts["css"], "js_links": reqts["js"], }
def locale(request): # pragma: no cover ''' When called for the first time, it ask enviroment for languagecode, which is later available as a pure property overriding this method :returns: language code needed for translations :rtype: string ''' return get_locale_name(request)
def view_contactform(context, request): locale_name = get_locale_name(request) tmpstore = FileUploadTempStore(request) def file_size_limit(node, value): value['fp'].seek(0, 2) size = value['fp'].tell() value['fp'].seek(0) max_size = 10 if size > max_size * 1024 * 1024: msg = _('Maximum file size: ${size}MB', mapping={'size': max_size}) raise colander.Invalid(node, msg) def maybe_show_attachment(node, kw): if kw.get('maybe_show_attachment', True) is False: del node['attachment'] class SubmissionSchema(colander.MappingSchema): name = colander.SchemaNode(colander.String(), title=_("Full Name")) sender = colander.SchemaNode(colander.String(), validator=colander.Email(), title=_("E-Mail Address")) subject = colander.SchemaNode(colander.String(), title=_("Subject")) content = colander.SchemaNode( colander.String(), widget=TextAreaWidget(cols=40, rows=5), title=_("Your message") ) attachment = colander.SchemaNode( FileData(), title=_('Attachment'), widget=FileUploadWidget(tmpstore), validator=file_size_limit, missing=None, ) _LOCALE_ = colander.SchemaNode( colander.String(), widget=HiddenWidget(), default=locale_name) schema = SubmissionSchema(after_bind=maybe_show_attachment) schema = schema.bind(maybe_show_attachment=context.show_attachment) form = Form(schema, buttons=[Button('submit', _('Submit'))]) appstruct = None rendered_form = None if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) mail_submission(context, request, appstruct) except ValidationFailure, e: appstruct = None rendered_form = e.render()
def terms(self): '''Renders the terms of service.''' locale_name = get_locale_name(self.request) if locale_name == 'en': return HTTPFound(location='http://mootiro.org/form/en/terms') elif locale_name == 'pt_BR': return HTTPFound(location='http://mootiro.org/form/pt-br/termos') else: return HTTPFound(location='/')
def title_to_name(title, blacklist=()): request = get_current_request() if request is not None: locale_name = get_locale_name(request) else: locale_name = 'en' name = unicode(urlnormalizer.normalize(title, locale_name, max_length=40)) while name in blacklist: name = disambiguate_name(name) return name
def __init__(self, request, current_page): self.request = request self.layout = get_renderer('templates/layout.pt').implementation() self.current_page = current_page self.notifications = { 'success': self.request.session.pop_flash('success'), 'error': self.request.session.pop_flash('error')} locale_name = get_locale_name(request) self.format_date = lambda d: babel.dates.format_date( d, 'medium', locale_name)
def add_template_globals(event): '''Makes the following variables readily available in template context: * *enabled_locales*: OrderedDict containing the enabled locales * *locale_code*: a string containing the locale of the current request, which you can use to set the xml:lang attribute on your <html> tag. ''' event['enabled_locales'] = \ event['request'].registry.settings[SETTING_NAME] event['locale_code'] = get_locale_name(event['request'])
def home_screen(request): mmgr = request.registry.getUtility(IModuleManager) lang = get_locale_name(request) tpldef = { 'res_css' : mmgr.get_css(request), 'res_js' : mmgr.get_js(request), 'res_ljs' : mmgr.get_local_js(request, lang), 'cur_loc' : lang } return tpldef
def do_forbidden(request): mmgr = request.registry.getUtility(IModuleManager) lang = get_locale_name(request) request.response.status_code = 403 return { 'res_css' : mmgr.get_css(request), 'res_js' : mmgr.get_js(request), 'res_ljs' : mmgr.get_local_js(request, lang), 'cur_loc' : lang }
def login_form(self): '''Redirects to the CAS login page if there is no logged user.''' settings = self.request.registry.settings if self.request.user: return HTTPFound(location='/') else: service = self.url('user', action='verify') return HTTPFound(settings['CAS.url'] + \ '/login?' + urlencode(dict(service=service, locale=get_locale_name(self.request))))
def wrap_schema(schema, request): locale_name = get_locale_name(request) class Schema(schema): _LOCALE_ = colander.SchemaNode( colander.String(), widget=HiddenWidget(), default=locale_name) return Schema
def render_form(self, form, appstruct=colander.null, submitted='submit', success=None, readonly=False, is_i18n=False): captured = None if submitted in self.request.POST: # the request represents a form submission try: # try to validate the submitted values controls = self.request.POST.items() captured = form.validate(controls) if success: response = success() if response is not None: return response html = form.render(captured) except deform.ValidationFailure as e: # the submitted values could not be validated html = e.render() else: # the request requires a simple form rendering html = form.render(appstruct, readonly=readonly) if self.request.is_xhr: return Response(html) code, start, end = self.get_code(2) locale_name = get_locale_name(self.request) reqts = form.get_widget_resources() printer = pprint.PrettyPrinter(width=1) printer.format = my_safe_repr output = printer.pformat(captured) captured = highlight(output, PythonLexer(), formatter) # values passed to template for rendering return { 'form': html, 'captured': captured, 'code': code, 'start': start, 'end': end, 'is_i18n': is_i18n, 'locale': locale_name, 'demos': self.get_demos(), 'title': self.get_title(), 'css_links': reqts['css'], 'js_links': reqts['js'], }
def __init__(self, request): self.request = request if request.user: request.response.cache_control.private = True else: request.response.cache_control.public = True request.response.cache_control.max_age = \ request.registry.settings["default_max_age"] self.settings = request.registry.settings self.debug = "debug" in request.params self.lang = get_locale_name(request)
def title_to_name(title, blacklist=()): request = get_current_request() if request is not None: locale_name = get_locale_name(request) else: locale_name = 'en' from kotti import get_settings urlnormalizer = get_settings()['kotti.url_normalizer'][0] name = unicode(urlnormalizer(title, locale_name, max_length=40)) while name in blacklist: name = disambiguate_name(name) return name
def view_contactform(context, request): locale_name = get_locale_name(request) tmpstore = FileUploadTempStore(request) def file_size_limit(node, value): value['fp'].seek(0, 2) size = value['fp'].tell() value['fp'].seek(0) max_size = 10 if size > max_size * 1024 * 1024: msg = _('Maximum file size: ${size}MB', mapping={'size': max_size}) raise colander.Invalid(node, msg) def maybe_show_attachment(node, kw): if kw.get('maybe_show_attachment', True) is False: del node['attachment'] class SubmissionSchema(colander.MappingSchema): name = colander.SchemaNode(colander.String(), title=_("Full Name")) sender = colander.SchemaNode(colander.String(), validator=colander.Email(), title=_("E-Mail Address")) subject = colander.SchemaNode(colander.String(), title=_("Subject")) content = colander.SchemaNode(colander.String(), widget=TextAreaWidget(cols=40, rows=5), title=_("Your message")) attachment = colander.SchemaNode( FileData(), title=_('Attachment'), widget=FileUploadWidget(tmpstore), validator=file_size_limit, missing=None, ) _LOCALE_ = colander.SchemaNode(colander.String(), widget=HiddenWidget(), default=locale_name) schema = SubmissionSchema(after_bind=maybe_show_attachment) schema = schema.bind(maybe_show_attachment=context.show_attachment) form = Form(schema, buttons=[Button('submit', _('Submit'))]) appstruct = None rendered_form = None if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) mail_submission(context, request, appstruct) except ValidationFailure, e: appstruct = None rendered_form = e.render()
def __init__(self, request): self.request = request self.settings = request.registry.settings self.debug = "debug" in request.params self.lang = get_locale_name(request) # detect if HTTPS scheme must be set https_flag = self.settings.get('https_flag_header') if https_flag: # pragma: no cover if https_flag in self.request.headers and \ self.request.headers[https_flag] == self.settings.get('https_flag_value'): self.request.scheme = 'https'
def locale_negotiator(request): lang = request.params.get('lang') settings = get_current_registry().settings languages = settings['available_languages'].split() if lang == 'rm': return 'fi' elif lang is None or lang not in languages: if request.accept_language: return request.accept_language.best_match(languages, 'de') # the default_locale_name configuration variable return get_locale_name(request) return lang
def __init__(self, request): self.request = request if request.user: request.response.cache_control.private = True else: request.response.cache_control.public = True request.response.cache_control.max_age = \ request.registry.settings["default_max_age"] self.settings = request.registry.settings self.debug = "debug" in request.params self.lang = get_locale_name(request) self.useSecurityMetadata = bool( request.registry.settings.get('use_security_metadata', False))
def __init__(self, context, request): self.context = context self.request = request self.session = request.session_factory self.fieldset_class = request.forms.FieldSet self.grid_class = request.forms.Grid if '_LOCALE_' not in request.cookies: locale = get_locale_name(request) request.cookies['_LOCALE_'] = locale if '_LOCALE_' not in request.cookies: theme = request.registry.settings.get('default_theme_name', 'smoothness') request.cookies['_LOCALE_'] = theme
def faq(request): # We don't want to mess up the gettext .po file # with a lot of strings which don't belong to the # application interface. # # We consider the FAQ as application content # so we simple use a different template for each # language. When a new locale is added to the # application it needs to translate the .po files # as well as this template locale_name = get_locale_name(request) template = 'yithlibraryserver:templates/faq-%s.pt' % locale_name return render_to_response(template, {}, request=request)
def add_global(event): settings = get_current_registry().settings event['settings'] = get_settings() event['languages'] = settings['available_languages'].split() locale = get_locale_name(event['request']) event['partition'] = DBSession.query(Page).\ filter(Page.visible == True).\ filter(Page.parent_id == 0).\ filter(Page.language == locale).\ filter(or_(Page.orign_page.has(Page.parent_id == 0), Page.orign_page_id == 0)).\ order_by(Page.position).all() event['logged_in'] = authenticated_userid(event['request'])
def view_calendar(context, request): kotti_calendar_resources.need() locale_name = get_locale_name(request) if locale_name in fullcalendar_locales: fullcalendar_locales[locale_name].need() else: # pragma: no cover (safety belt only, should never happen) fullcalendar_locales["en"].need() session = DBSession() now = datetime.datetime.now() query = session.query(Event).filter(Event.parent_id == context.id) future = or_(Event.start > now, Event.end > now) upcoming = query.filter(future).order_by(Event.start).all() past = query.filter(Event.start < now).order_by(desc(Event.start)).all() upcoming = [event for event in upcoming if has_permission('view', event, request)] past = [event for event in past if has_permission('view', event, request)] fmt = '%Y-%m-%d %H:%M:%S' fullcalendar_events = [] for event in (upcoming + past): json_event = { 'title': event.title, 'url': resource_url(event, request), 'start': event.start.strftime(fmt), 'allDay': event.all_day, } if event.end: json_event['end'] = event.end.strftime(fmt) fullcalendar_events.append(json_event) fullcalendar_options = { 'header': { 'left': 'prev,next today', 'center': 'title', 'right': 'month,agendaWeek,agendaDay' }, 'eventSources': context.feeds, 'weekends': context.weekends, 'events': fullcalendar_events, } return { 'api': template_api(context, request), 'upcoming_events': upcoming, 'past_events': past, 'fullcalendar_options': json.dumps(fullcalendar_options), }
def sorted_countries(arg, top_entry=True): # TODO memoized version '''*arg* may be either the desired locale code or the request object, from which the locale will be discovered. Returns a list of tuples like ``('BR', 'Brazil')``, already sorted, ready for inclusion in your web form. ''' code = arg if isinstance(arg, basestring) else get_locale_name(arg) def generator(territories): if top_entry: yield (native_str(''), _("- Choose -")) # TODO translate somehow for tup in territories: if len(tup[0]) == 2: # Keep only countries yield tup return sorted(generator(iteritems(Locale(code).territories)), key=lambda x: x[1])
def edit_page(request): user = authenticated_userid(request) page_id = request.matchdict['target'] page = DBSession.query(Page).filter_by(id=page_id).one() if 'form.submitted' in request.params: page.name = request.params['name'] page.content = request.params['content'] page.updated_by = user if 'visible' in request.params: page.visible = True else: page.visible = False page.tags = [] tags = re.split(r'[,;]+', request.params['tags']) tags = filter(lambda x: x not in (None, '', ' '), tags) tags = map(lambda x: x.strip(), tags) tags = list(set(tags)) for tag in tags: exist_tag = DBSession.query(Tag).filter_by(name=tag).all() if exist_tag: tag = exist_tag[0] else: tag = Tag(tag) page.tags.append(tag) DBSession.add(page) return HTTPFound(location=request.environ['HTTP_REFERER']) # if it translated page LOCALE = get_locale_name(request) translated_page = DBSession.query(Page).\ filter_by(id=page.orign_page_id).all() translated_page = translated_page[0] if translated_page else None if translated_page: exist_translations = DBSession.query(Page).\ filter_by(orign_page_id=translated_page.id).all() lang_list = get_lang(translated_page) else: exist_translations = DBSession.query(Page).\ filter_by(orign_page_id=page.id).all() lang_list = None return dict(page=page, translated=translated_page, LOCALE=LOCALE, exist_translations=exist_translations, translate_lang=lang_list)
def _cl_tpldef(tpldef, req): cfg = req.registry.settings comb_js = asbool(cfg.get('netprofile.client.combine_js', False)) cur_locale = get_locale_name(req) loc = req.localizer menu = [{ 'route' : 'access.cl.home', 'text' : _('Portal') }] if 'trans' in tpldef: tpldef['trans'] = {txt: loc.translate(txt) for txt in tpldef['trans']} req.run_hook('access.cl.menu', menu, req) tpldef.update({ 'menu' : menu, 'cur_loc' : cur_locale, 'comb_js' : comb_js, 'loc' : loc, 'i18n' : Locale(cur_locale) })
def __init__(self, resource, request): locale = get_locale_name(request) if isinstance(resource, PokedexIndex) or (isinstance( resource, type) and issubclass(resource, PokedexIndex)): resource_type = resource.table resource_chain = [] else: resource_type = type(resource) resource_chain = [resource] # TODO make this use adapters or whatever if issubclass(resource_type, t.Pokemon): prefix = 'pokemon' elif issubclass(resource_type, t.PokemonSpecies): prefix = 'pokemon' elif issubclass(resource_type, t.Move): prefix = 'moves' elif issubclass(resource_type, t.Type): prefix = 'types' elif issubclass(resource_type, t.Item): prefix = 'items' elif issubclass(resource_type, t.Region): prefix = 'places' elif issubclass(resource_type, t.Location): prefix = 'places' if resource_chain: resource_chain.insert(0, resource.region) elif issubclass(resource_type, t.Ability): prefix = 'abilities' elif issubclass(resource_type, t.Nature): prefix = 'natures' else: raise TypeError(repr(resource)) path_parts = [u'', locale, LANGUAGES[locale][prefix]] path_parts.extend(res.name.lower() for res in resource_chain) self.virtual_path = u'/'.join(path_parts) self.physical_path = self.virtual_path
def __init__(self, request): self.request = request if request.user: request.response.cache_control.private = True else: request.response.cache_control.public = True request.response.cache_control.max_age = \ request.registry.settings["default_max_age"] self.settings = request.registry.settings self.debug = "debug" in request.params if ("lang" in request.params is True): self.lang = request.params['lang'] else: self.lang = get_locale_name(request) self.noheader = "noheader" in request.params self.noleftpanel = "noleftpanel" in request.params self.nobottompanel = "nobottompanel" in request.params self.notoolbar = "notoolbar" in request.params self.themechoice = "themechoice" in request.params self.showoverview = "showoverview" in request.params
def fullcalendar_options(self): """ Options object suitable for FullCalendar initialization. :result: JSON serializable FullCalendar options. :rtype: dict """ lang = get_locale_name(self.request) or 'en' return { 'header': { 'left': 'prev,next today', 'center': 'title', 'right': 'month,agendaWeek,agendaDay' }, 'eventSources': self.context.feeds, 'weekends': self.context.weekends, 'events': self.fullcalendar_events, 'lang': lang, }