Example #1
0
def get_translations():
    """ Load .po file, cache .mo file repr in memory and return
    a Babel Translations object. This function is meant for monkey patching
    into Flask-Babel."""
    ctx = _request_ctx_stack.top
    if ctx is None:
        return None
    translations_dict = ctx.app.babel_translations_dict
    lock = ctx.app.babel_translations_lock
    locale = str(get_locale())
    lock.acquire()
    if translations_dict.get(locale) is None:
        mo_file = StringIO()
        dirname = os.path.join(ctx.app.root_path, 'translations')
        transfilename = os.path.join(dirname, taint_filename(locale),
                'LC_MESSAGES', "messages.po")
        if os.path.exists(transfilename):
            catalog = read_po(file(transfilename, "r"))
            write_mo(mo_file, catalog)
            mo_file.seek(0)
            translations = Translations(fileobj=mo_file)
        else:
            translations = gettext.NullTranslations()
        translations_dict[locale] = translations
    else:
        translations = translations_dict[locale]
    lock.release()
    return translations
Example #2
0
def create_project():
    form = ProjectForm()
    if request.method == "GET" and 'project_id' in request.values:
        form.name.data = request.values['project_id']

    if request.method == "POST":
        # At first, we don't want the user to bother with the identifier
        # so it will automatically be missing because not displayed into
        # the form
        # Thus we fill it with the same value as the filled name,
        # the validation will take care of the slug
        if not form.id.data:
            form.id.data = form.name.data
        if form.validate():
            # save the object in the db
            project = form.save()
            db.session.add(project)
            db.session.commit()

            # create the session object (authenticate)
            session[project.id] = project.password
            session.update()

            # send reminder email
            g.project = project

            message_title = _("You have just created '%(project)s' "
                "to share your expenses", project=g.project.name)

            message_body = render_template("reminder_mail.%s" %
                get_locale().language)

            msg = Message(message_title,
                body=message_body,
                recipients=[project.contact_email])
            try:
                mail.send(msg)
            except SMTPRecipientsRefused:
                msg_compl = 'Problem sending mail. '
                # TODO: destroy the project and cancel instead?
            else:
                msg_compl = ''

            # redirect the user to the next step (invite)
            flash(_("%(msg_compl)sThe project identifier is %(project)s",
                msg_compl=msg_compl, project=project.id))
            return redirect(url_for(".invite", project_id=project.id))

    return render_template("create_project.html", form=form)
Example #3
0
def localization_js():
    global _localization_cache
    locale = repr(get_locale())
    if _localization_cache.get(locale,None) is None:
        data = render_template(os.path.join('js/localization.js'))
        _localization_cache[locale] = (data, sha1(repr(data)).hexdigest())
    data, datahash = _localization_cache[locale]

    if request.environ.get('HTTP_IF_NONE_MATCH', None) == datahash:
        response = make_response('', 304)
    else:
        response = make_response(data)
        response.headers['Content-Type'] = 'text/javascript; charset=utf-8'
        response.headers['Etag'] = datahash
    return response
Example #4
0
def remind_password():
    form = PasswordReminder()
    if request.method == "POST":
        if form.validate():
            # get the project
            project = Project.query.get(form.id.data)

            # send the password reminder
            password_reminder = "password_reminder.%s" % get_locale().language
            mail.send(Message("password recovery",
                body=render_template(password_reminder, project=project),
                recipients=[project.contact_email]))
            flash(_("a mail has been sent to you with the password"))

    return render_template("password_reminder.html", form=form)
Example #5
0
def localization_js():
    global _localization_cache
    locale = repr(get_locale())
    if _localization_cache.get(locale,None) is None:
        data = render_template(os.path.join('js/localization.js'))
        _localization_cache[locale] = (data, sha1(repr(data)).hexdigest())
    data, datahash = _localization_cache[locale]

    if request.environ.get('HTTP_IF_NONE_MATCH', None) == datahash:
        response = make_response('', 304)
    else:
        response = make_response(data)
        response.headers['Content-Type'] = 'text/javascript; charset=utf-8'
        response.headers['Etag'] = datahash
    return response
Example #6
0
def remind_password():
    form = PasswordReminder()
    if request.method == "POST":
        if form.validate():
            # get the project
            project = Project.query.get(form.id.data)

            # send the password reminder
            mail.send(Message("password recovery",
                body=render_template("password_reminder.%s" % get_locale().language,
                    project=project),
                recipients=[project.contact_email]))
            flash(_("a mail has been sent to you with the password"))

    return render_template("password_reminder.html", form=form)
Example #7
0
def create_project():
    form = ProjectForm()
    if request.method == "GET" and 'project_id' in request.values:
        form.name.data = request.values['project_id']

    if request.method == "POST":
        # At first, we don't want the user to bother with the identifier
        # so it will automatically be missing because not displayed into the form
        # Thus we fill it with the same value as the filled name, the validation will
        # take care of the slug
        if not form.id.data:
            form.id.data = form.name.data
        if form.validate():
            # save the object in the db
            project = form.save()
            db.session.add(project)
            db.session.commit()

            # create the session object (authenticate)
            session[project.id] = project.password
            session.update()

            # send reminder email
            g.project = project

            message_title = _("You have just created '%(project)s' to share your expenses",
                    project=g.project.name)

            message_body = render_template("reminder_mail.%s" % get_locale().language)

            msg = Message(message_title,
                body=message_body,
                recipients=[project.contact_email])
            try:
                mail.send(msg)
            except SMTPRecipientsRefused:
                msg_compl = 'Problem sending mail. '
                # TODO: destroy the project and cancel instead?
            else:
                msg_compl = ''

            # redirect the user to the next step (invite)
            flash(_("%(msg_compl)sThe project identifier is %(project)s",
                msg_compl=msg_compl, project=project.id))
            return redirect(url_for(".invite", project_id=project.id))

    return render_template("create_project.html", form=form)
Example #8
0
def invite():
    """Send invitations for this particular project"""

    form = InviteForm()

    if request.method == "POST":
        if form.validate():
            # send the email

            message_body = render_template("invitation_mail.%s" % get_locale().language)

            message_title = _("You have been invited to share your expenses for %(project)s",
                    project=g.project.name)
            msg = Message(message_title,
                body=message_body,
                recipients=[email.strip()
                    for email in form.emails.data.split(",")])
            mail.send(msg)
            flash(_("Your invitations have been sent"))
            return redirect(url_for(".list_bills"))

    return render_template("send_invites.html", form=form)
Example #9
0
 def execute(self, received_parameters, url_override="", locale=None):
     '''takes a dictionary of method parameters, executes the method
     and returns response'''
     if self.type!=rest_methods.GET:
         raise NotImplementedError("Can't execute a service method that is not a GET")
     method_url= url_override if url_override else self.resource.absolute_url()
     needed_parameters= dict([(p.parameter, rest_method_parameters.reverse[p.parameter]) for p in self.parameters])
     #all received parameters must be method parameters
     #assert all([r in needed_parameters for r in received_parameters.keys()])
     parameters_kv= dict([(needed_parameters.get(k) or k, v) for k,v in received_parameters.items()])
     for k,v in parameters_kv.items():
         if isinstance(v, unicode):
             parameters_kv[k] = v.encode('utf-8')
     locale = locale or get_locale()
     if locale:
         parameters_kv['lang'] = locale
     params= urllib.urlencode(parameters_kv)
     try:
         page = urllib.urlopen(method_url + "?" + params) #
     except:
         return '<entity type="list"/>'
     page = page.read()
     return page
Example #10
0
def populate_locale(*args, **extra):
    g.lang = get_locale().language
Example #11
0
File: search.py Project: akn/pi
def search_aux(query, services=None, add_to_history=True):
    '''give a list of services, and a query, executes the search on
    those services. If the list is None, search on all services.
    add_to_history is a boolean that indicates if this search should be
    added to the user search history'''
    if services==None:
        services= Service.query.all()
    if add_to_history:
        add_search_to_history(query, services)
    search_methods= [m.global_search() for m in services]
    matches = match_search_to_methods_keywords(query, search_methods)
    method_parameters = []
    for squery, method in matches:
        if method.parameters[0].parameter == rest_method_parameters.NOME:
            method_parameters.append((method, {rest_method_parameters.NOME: squery}))
        else:
            method_parameters.append((method, {rest_method_parameters.QUERY: query}))

    results= filter(lambda x:x is not None, ResourceMethod.execute_several(method_parameters, locale=get_locale()))

    xml = ElementTree.Element("entity", type='list')
    for result in results:
        result_xml = ElementTree.fromstring(result)
        if result_xml.tag == 'data':
            result_xml = result_xml.getchildren()[0]
        for e in result_xml:
            xml.append(e)

    html= xml_to_html.render(xml)
    return render_template('search.html', html=html)
Example #12
0
 def global_context():
     return dict(locale=get_locale(),
                 Markup=Markup,  # Flask's seems to be superior to Genshi's
                )