Example #1
0
def date_fmt(value, format="EE, d MMMM y"):
    """
    @deprecated: use flask_babel's dateformat filter instead.
    """
    if isinstance(value, date):
        return babel.format_date(value, format)
    else:
        return babel.format_date(local_dt(value), format)
Example #2
0
def date(value, format="EE, d MMMM y"):
    """
    @deprecated: use flask_babel's dateformat filter instead.
    """
    if isinstance(value, datetime.date):
        return babel.format_date(value, format)
    else:
        return babel.format_date(local_dt(value), format)
Example #3
0
def extend_search_term(
    searchterm,
    author_name,
    book_title,
    publisher,
    pub_start,
    pub_end,
    tags,
    rating_high,
    rating_low,
    read_status,
):
    searchterm.extend((author_name.replace('|', ','), book_title, publisher))
    if pub_start:
        try:
            searchterm.extend([
                _(u"Published after ") + format_date(
                    datetime.strptime(pub_start, "%Y-%m-%d"), format='medium')
            ])
        except ValueError:
            pub_start = u""
    if pub_end:
        try:
            searchterm.extend([
                _(u"Published before ") + format_date(
                    datetime.strptime(pub_end, "%Y-%m-%d"), format='medium')
            ])
        except ValueError:
            pub_end = u""
    elements = {'tag': db.Tags, 'serie': db.Series, 'shelf': ub.Shelf}
    for key, db_element in elements.items():
        tag_names = calibre_db.session.query(db_element).filter(
            db_element.id.in_(tags['include_' + key])).all()
        searchterm.extend(tag.name for tag in tag_names)
        tag_names = calibre_db.session.query(db_element).filter(
            db_element.id.in_(tags['exclude_' + key])).all()
        searchterm.extend(tag.name for tag in tag_names)
    language_names = calibre_db.session.query(db.Languages). \
        filter(db.Languages.id.in_(tags['include_language'])).all()
    if language_names:
        language_names = calibre_db.speaking_language(language_names)
    searchterm.extend(language.name for language in language_names)
    language_names = calibre_db.session.query(db.Languages). \
        filter(db.Languages.id.in_(tags['exclude_language'])).all()
    if language_names:
        language_names = calibre_db.speaking_language(language_names)
    searchterm.extend(language.name for language in language_names)
    if rating_high:
        searchterm.extend([_(u"Rating <= %(rating)s", rating=rating_high)])
    if rating_low:
        searchterm.extend([_(u"Rating >= %(rating)s", rating=rating_low)])
    if read_status:
        searchterm.extend([_(u"Read Status = %(status)s", status=read_status)])
    searchterm.extend(ext for ext in tags['include_extension'])
    searchterm.extend(ext for ext in tags['exclude_extension'])
    # handle custom columns
    searchterm = " + ".join(filter(None, searchterm))
    return searchterm, pub_start, pub_end
Example #4
0
    def __call__(self, field, **kwargs):
        kwargs.setdefault('name', field.name)

        if not field.data:
            field.data = ""
        else:
            if isinstance(field.data, str):
                date_obj = datetime.datetime.strptime(field.data, '%H:%M')
                field.data = format_date(date_obj, format="short")
            elif isinstance(field.data, datetime.date):
                field.data = format_date(field.data, format="short")
        return HTMLString(
            render_template_string(self.data_template, field=field, **kwargs))
Example #5
0
def search():

    form = forms.SearchForm(request.form)
    if form.validate():
        date_start = form.date_start.data
        date_end = form.date_end.data

    title = u'Gastos {} - {}'.format(
        babel.format_date(date_start, format='medium'),
        babel.format_date(date_end, format='medium'))
    pie = plotter.PiePlotter(title)

    pie.add_list(read.get_total_ratio(date_start, date_end))
    return render_template('search.html', title=pie.title, chart=pie, form=form)
Example #6
0
def activity_time_format(time, now=None):
    if not time:
        return ""

    if not now:
        now = datetime.utcnow()
    time_delta = now - time
    month_abbreviation = format_date(time, "MMM")
    days, hours, minutes, seconds = (
        time_delta.days,
        time_delta.seconds // 3600,
        time_delta.seconds // 60,
        time_delta.seconds,
    )

    if days == 0 and hours == 0 and minutes == 0:
        return "{}{}".format(seconds, _l("s"))

    if days == 0 and hours == 0:
        return "{}{}".format(minutes, _l("m"))

    if days == 0:
        return "{}{}".format(hours, _l("h"))

    if days < 30:
        return "{}{}".format(days, _l("d"))

    if time.year == now.year:
        return f"{month_abbreviation} {time.day}"

    return "{} {}".format(month_abbreviation, str(time.year))
Example #7
0
def formatdate_filter(val):
    try:
        return format_date(val, format='medium')
    except AttributeError as e:
        log.error('Babel error: %s, Current user locale: %s, Current User: %s',
                  e, current_user.locale, current_user.name)
        return val
Example #8
0
def index():

    lukasz = gettext('Lukasz')

    us_num = numbers.format_decimal(12345, locale='en_US')
    se_num = numbers.format_decimal(12345, locale='sv_SE')
    pl_num = numbers.format_decimal(12345, locale='pl_PL')

    d = date(2018, 12, 10)

    us_date = dates.format_date(d, locale='en_US')
    local_date = format_date(d)
    pl_date = dates.format_date(d, locale='pl_PL')

    dt = datetime.now()
    us_dt = dates.format_datetime(dt, locale='en_US')
    se_dt = dates.format_datetime(dt, locale='sv_SE')
    pl_dt = dates.format_datetime(dt, locale='pl_PL')

    results = {
        'us_num': us_num,
        'se_num': se_num,
        'pl_num': pl_num,
        'us_date': us_date,
        'local_date': local_date,
        'pl_date': pl_date,
        'us_dt': us_dt,
        'se_dt': se_dt,
        'pl_dt': pl_dt,
        'lukasz': lukasz
    }
    return render_template('index.html', results=results)
Example #9
0
    def __get_date_formatter(self, quantum: str):
        """
        Returns the correct lambda to format a date given a quantum.

        Arguments:
            quantum {str} -- Dataset quantum ("hour", "month", "day")

        Returns:
            [lambda] -- Lambda that formats a given date string
        """

        if quantum == 'month':
            return lambda x: format_date(x, "MMMM yyyy")
        elif quantum == 'hour':
            return lambda x: format_datetime(x)
        else:
            return lambda x: format_date(x, "long")
Example #10
0
 def macro(self, content, arguments, page_url, alternative):
     if arguments is None:
         tm = time.time()  # always UTC
     else:
         # XXX looks like args are split at ':' -> <Arguments([u'2010-12-31T23', u'59', u'00'], {})>
         stamp = arguments[0]
         tm = self.parse_time(stamp)
     return format_date(datetime.utcfromtimestamp(tm))
Example #11
0
def date_filter(dt, format=None):
    """Format date or datetime objects using Flask-Babel
    :param datetime|date|None dt: a datetime object or None
    :param str format: format as understood by Flask-Babel's format_datetime
    :rtype: unicode
    """
    if dt is None:
        return u"k/A"
    return flask_babel.format_date(dt, format)
Example #12
0
def blood_pressure_csv():
    rows = [(row.date.date().isoformat(), row.date.time().isoformat(),
             row.systolic, row.diastolic, row.pulse)
            for row in BloodPressure.query.filter_by(
                user=current_user).order_by(BloodPressure.date)]
    today = format_date(datetime.date.today())
    filename = f"{gettext('Blood Pressure')} - {current_user.username} - {today}.csv"
    return send_csv(filename,
                    ['date', 'time', 'systolic', 'diastolic', 'pulse'], rows)
Example #13
0
def home():
    forum = ForumModel.query().get()
    if not forum:
        forum = ForumModel(
            date = datetime.datetime.now().date(),
            address = ''
        )
    forum.formated_date = format_date(forum.date, 'full')
    return render_template('home.html', forum=forum)
Example #14
0
def date_filter(dt, format=None):
    """Format date or datetime objects using Flask-Babel
    :param datetime|date|None dt: a datetime object or None
    :param str format: format as understood by Flask-Babel's format_datetime
    :rtype: unicode
    """
    if dt is None:
        return "k/A"
    return flask_babel.format_date(dt, format)
Example #15
0
def index():
    """Usersuite landing page with user account information
    and traffic overview.
    """
    info = current_user.finance_information
    last_update = info.last_update if info else None
    finance_update_string = (
        " ({}: {})".format(gettext("Stand"),
                           format_date(last_update, 'short', rebase=False))
        if last_update
        else ""
    )
    descriptions = OrderedDict([
        ('id', gettext("Nutzer-ID")),
        ('realname', gettext("Voller Name")),
        ('login', gettext("Accountname")),
        ('status', gettext("Mitgliedsschaftsstatus")),
        ('address', gettext("Aktuelles Zimmer")),
        ('ips', gettext("Aktuelle IP-Adresse")),
        ('mac', gettext("Aktuelle MAC-Adresse")),
        ('mail', gettext("E-Mail-Weiterleitung")),
        ('use_cache', gettext("Cache-Nutzung")),
        ('hostname', gettext("Hostname")),
        ('hostalias', gettext("Hostalias")),
        ('userdb_status', gettext("MySQL Datenbank")),
        ('finance_balance', gettext("Kontostand") + finance_update_string),
    ])

    try:
        rows = current_user.generate_rows(descriptions)
    except DBQueryEmpty as e:
        logger.error('Userinfo DB query could not be finished',
                     extra={'data': {'exception_args': e.args}, 'stack': True})
        flash(gettext("Es gab einen Fehler bei der Datenbankanfrage!"),
              "error")
        return redirect(url_for('generic.index'))

    datasource = current_user.datasource
    context = dict(rows=rows,
                   webmailer_url=datasource.webmailer_url,
                   payment_details=render_payment_details(current_user.payment_details()))

    if current_user.has_connection:
        context.update(
            show_traffic_data=True,
            traffic_user=current_user,
        )

    if info and info.has_to_pay:
        context.update(
            show_transaction_log=True,
            last_update=info.last_update,
            balance=info.balance.raw_value,
            logs=info.history,
        )

    return render_template("usersuite/index.html", **context)
Example #16
0
def index():
    d = date(2011, 1, 8)
    dt = datetime(2010, 4, 9, 21, 13)

    local_date = format_date(d)  # local selected according web page
    # local_date2 = dates.format_date(d, locale='en_US') #<- you select locale
    local_datetime = format_datetime(dt)

    return render_template('index.html', Local=get_locale(), \
                           Local_date=local_date, Local_datetime=local_datetime)
def format_datetime(context, value):
    london_date_time = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f")
    london_date = london_date_time.date()
    formatted_date = flask_babel.format_date(london_date, format="d MMMM yyyy")
    formatted_time = flask_babel.format_time(london_date_time, format="HH:mm")

    result = "<span class='date'>{date}</span>".format(
        date=flask_babel.gettext(
            "%(date)s at %(time)s", date=formatted_date, time=formatted_time))
    return mark_safe(context, result)
Example #18
0
    def test_basics(self):
        app = flask.Flask(__name__)
        babel.Babel(app)
        d = datetime(2010, 4, 12, 13, 46)

        with app.test_request_context():
            assert babel.format_datetime(d) == 'Apr 12, 2010, 1:46:00 PM'
            assert babel.format_date(d) == 'Apr 12, 2010'
            assert babel.format_time(d) == '1:46:00 PM'

        with app.test_request_context():
            app.config['BABEL_DEFAULT_TIMEZONE'] = 'Europe/Vienna'
            assert babel.format_datetime(d) == 'Apr 12, 2010, 3:46:00 PM'
            assert babel.format_date(d) == 'Apr 12, 2010'
            assert babel.format_time(d) == '3:46:00 PM'

        with app.test_request_context():
            app.config['BABEL_DEFAULT_LOCALE'] = 'de_DE'
            assert babel.format_datetime(d, 'long') == \
                '12. April 2010 um 15:46:00 MESZ'
Example #19
0
def date_format(date, format='medium'):
    import dateutil
    import flask_babel
    LOG.debug("formatting date %s", date)
    try:
        if isinstance(date, str):
            date = dateutil.parser.isoparse(date)
        return flask_babel.format_date(date, format)
    except ValueError:
        LOG.exception("Value '%s' is not in a valid ISO format (or is too obscure format)", date)
    return date
Example #20
0
    def test_basics(self):
        app = flask.Flask(__name__)
        b = babel.Babel(app)
        d = datetime(2010, 4, 12, 13, 46)

        with app.test_request_context():
            assert babel.format_datetime(d) == 'Apr 12, 2010, 1:46:00 PM'
            assert babel.format_date(d) == 'Apr 12, 2010'
            assert babel.format_time(d) == '1:46:00 PM'

        with app.test_request_context():
            app.config['BABEL_DEFAULT_TIMEZONE'] = 'Europe/Vienna'
            assert babel.format_datetime(d) == 'Apr 12, 2010, 3:46:00 PM'
            assert babel.format_date(d) == 'Apr 12, 2010'
            assert babel.format_time(d) == '3:46:00 PM'

        with app.test_request_context():
            app.config['BABEL_DEFAULT_LOCALE'] = 'de_DE'
            assert babel.format_datetime(d, 'long') == \
                '12. April 2010 15:46:00 MESZ'
Example #21
0
 def _value(self) -> str:
     if self.raw_data:
         return " ".join(self.raw_data)
     else:
         date_fmt = get_locale().date_formats["short"].pattern
         # force numerical months and 4 digit years
         date_fmt = (date_fmt.replace("MMMM", "MM").replace(
             "MMM", "MM").replace("yyyy",
                                  "y").replace("yy",
                                               "y").replace("y", "yyyy"))
         return format_date(self.data, date_fmt) if self.data else ""
Example #22
0
def index():
    d = date(2011, 1, 8)
    dt = datetime(2010, 4, 9, 21, 13)

    local_date = format_date(d)
    local_datetime = format_datetime(dt)

    anthony = gettext('Anthony')
    python = gettext('Python')
    return render_template('index.html', locale=get_locale(), local_date=local_date, local_datetime=local_datetime,
                           anthony=anthony, python=python)
Example #23
0
def date_l10n(value, format='full'):
    if g.current_lang and g.current_lang == app.config['BABEL_DEFAULT_LOCALE']:
        if format == 'full':
            format = "EEEE, dd.MM.yyyy'"
        elif format == 'light':
            format = "dd.MM.yyyy"
    else:
        if format == 'full':
            format = "full"
        elif format == 'light':
            format = "short"
    return format_date(value, format)
def format_datetime(context, date_time):
    # flask babel on formatting will automatically convert based on the time zone specified in setup.py
    formatted_date = flask_babel.format_date(date_time, format="d MMMM yyyy")
    formatted_time = flask_babel.format_time(date_time, format="HH:mm")

    date = flask_babel.gettext("%(date)s at %(time)s",
                               date=formatted_date,
                               time=formatted_time)

    result = f"<span class='date'>{date}</span>"

    return mark_safe(context, result)
Example #25
0
 def _value(self):
   if self.raw_data:
     return ' '.join(self.raw_data)
   else:
     date_fmt = get_locale().date_formats['short'].pattern
     # force numerical months and 4 digit years
     date_fmt = date_fmt.replace('MMMM', 'MM')\
                        .replace('MMM', 'MM')\
                        .replace('yyyy', 'y')\
                        .replace('yy', 'y')\
                        .replace('y', 'yyyy')
     return format_date(self.data, date_fmt) if self.data else ''
Example #26
0
    def test_macro(self):
        macro_obj = Macro()
        # when arguments is None
        result = macro_obj.macro('content', None, 'page_url', 'alternative')
        test_time = time.time()
        test_time = format_date(datetime.utcfromtimestamp(test_time))
        assert result == test_time

        arguments = ['2011-08-07T11:11:11+0533', 'argument2']
        result = macro_obj.macro('content', arguments, 'page_url', 'alternative')
        expected = u'Aug 7, 2011'
        assert result == expected
Example #27
0
def format_datetime(context, value):

    london_date_time = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')
    formatted_date = flask_babel.format_date(london_date_time,
                                             format='d MMMM YYYY')
    formatted_time = flask_babel.format_time(london_date_time, format='HH:mm')

    result = "<span class='date'>{date}</span>".format(
        date=flask_babel.gettext('%(date)s at %(time)s',
                                 date=formatted_date,
                                 time=formatted_time), )
    return mark_safe(context, result)
Example #28
0
def index():
    d = date(2001, 9, 11)
    dt = datetime(2010, 5, 13, 15, 16)

    local_date = format_date(d)
    local_datetime= format_datetime(dt, 'short')
    
    dog = gettext('Dog')
    cat = gettext('Cat')

    return render_template('index.html', locale=get_locale(), local_date=local_date,
                           local_datetime=local_datetime, dog=dog, cat=cat)
Example #29
0
def monthly_report():
    month_year = request.form.get('month', None)

    if not month_year:
        flash_error('Informe o Mês!')
        return render_template('finance/monthly.html')

    year = int(month_year[:4])
    month = int(month_year[-2:])

    plans = plan_repository.get_by_month(year, month)
    sorted_plans = _sort_plan_by_payment_type(plans)
    return render_template('finance/monthly.html', sorted_plans=sorted_plans, month=format_date(date(year, month, 1), 'MMMM yyyy'))
Example #30
0
def index():
    d = date(2011, 1, 8)
    dt = datetime(2010, 4, 9, 21, 13)

    local_date = format_date(d)
    local_datetime = format_datetime(dt)

    python = gettext('Python')
    chris = gettext('Christopher')


    return render_template('index.html', Local=get_locale(), \
       Local_date=local_date, Local_datetime=local_datetime, \
       chris=chris, python=python)
Example #31
0
 def _value(self):
     if self.raw_data:
         return " ".join(self.raw_data)
     else:
         date_fmt = get_locale().date_formats["short"].pattern
         # force numerical months and 4 digit years
         date_fmt = (
             date_fmt.replace("MMMM", "MM")
             .replace("MMM", "MM")
             .replace("yyyy", "y")
             .replace("yy", "y")
             .replace("y", "yyyy")
         )
         return format_date(self.data, date_fmt) if self.data else ""
Example #32
0
    def test_macro(self):
        flaskg.user.valid = True  # show_time creates ISO 8601 dates if user is not logged in
        macro_obj = Macro()
        # when arguments is None
        result = macro_obj.macro('content', None, 'page_url', 'alternative')
        test_time = time.time()
        test_time = format_date(datetime.utcfromtimestamp(test_time))
        assert result == test_time

        arguments = ['2011-08-07T11:11:11+0533', 'argument2']
        result = macro_obj.macro('content', arguments, 'page_url',
                                 'alternative')
        expected = 'Aug 7, 2011'
        assert result == expected
Example #33
0
def index():
    anthony = gettext(u'Anthony')

    num = format_decimal(12345)

    d = datetime.fromtimestamp(1594460958.12345)

    day = format_date(d)

    results = {
        'num' : num, 
        'date' : day, 
        'anthony' : anthony
    }
    return render_template('index.html', results = results)
Example #34
0
def hello():
    hello_text = gettext("Hello World")
    us_no = numbers.format_decimal('12345', locale='en_US')
    se_no = numbers.format_decimal('12345', locale='sv_SE')
    de_no = numbers.format_decimal('12345', locale='de_DE')

    d = date(2019, 10, 10)
    us_date = dates.format_date(d, locale="en_US")
    dt = format_date(d)
    data = {
        "us_no": us_no,
        "se_no": se_no,
        "de_no": de_no,
        "us_date": us_date,
        "text": hello_text
    }
    return render_template("translation_check.html", data=data)
Example #35
0
 def _value(self) -> str:
     if self.raw_data:
         # pyre-fixme[6]: Expected `Iterable[str]` for 1st param but got `None`.
         return " ".join(self.raw_data)
     else:
         date_fmt = get_locale().date_formats["short"].pattern
         # force numerical months and 4 digit years
         date_fmt = (
             date_fmt.replace("MMMM", "MM")
             .replace("MMM", "MM")
             .replace("yyyy", "y")
             .replace("yy", "y")
             .replace("y", "yyyy")
         )
         # pyre-fixme[16]: `DateField` has no attribute `data`.
         # pyre-fixme[16]: `DateField` has no attribute `data`.
         return format_date(self.data, date_fmt) if self.data else ""
Example #36
0
def localised_nice_date(datetime_: datetime.datetime,
                        show_date: bool = False,
                        with_hours: bool = False,
                        with_seconds: bool = False,
                        format: Optional[str] = None) -> str:
    ''' Returns a friendly localised unicode representation of a datetime.
    e.g. '31 minutes ago'
         '1 day ago'
         'April 24, 2013'  (show_date=True)
         'October 25, 2017, 16:03 (UTC)' (show_date=True, with_hours=True)
         'Apr 3, 2020, 4:00:31 PM' (
                 show_date=True, with_hours=True, format='medium')
         'April 03, 20' (show_date=True, format='MMMM dd, YY')

    :param datetime_: The date to format
    :type datetime_: datetime
    :param show_date: Show 'April 24, 2013' instead of '2 days ago'
    :type show_date: bool
    :param with_hours: should the `hours:mins` be shown for dates
    :type with_hours: bool
    :param with_seconds: should the `hours:mins:seconds` be shown for dates
    :type with_seconds: bool
    :param format: override format of datetime representation using babel
        date/time pattern syntax of predefined pattern.
    :type format: str


    :rtype: sting
    '''
    if datetime_.tzinfo is None:
        datetime_ = datetime_.replace(tzinfo=pytz.utc)
    if not show_date:
        now = datetime.datetime.now(pytz.utc)
        date_diff = datetime_ - now
        if abs(date_diff) < datetime.timedelta(seconds=1):
            return _('Just now')
        return format_timedelta(date_diff, add_direction=True)

    if with_seconds:
        return format_datetime(datetime_, format or 'long')
    elif with_hours:
        fmt_str = "MMMM d, YYYY, HH:mm (z)"
        return format_datetime(datetime_, format or fmt_str)
    else:
        return format_date(datetime_, format or 'long')
Example #37
0
def format_date(item):
	year = item.get("year");
	if item.get("year_circa"):
		return year
	#year_from == year_to == int(year) below
	year_from = item.get("year_from")
	month = item.get("month")
	day = item.get("day")

	if all([year_from, month, day]):
		date = datetime.date(year_from, month, day)
		return flask_babel.format_date(date, format="d MMMM y")
	elif all([year_from, month]):
		#babel is unable to format month correctly for Russian language
		#using own implementation here
		return (translate_month(month) + ", " + year)
	else:
		return year
Example #38
0
def costs(product_id):
    if request.method == 'POST':
        product_cost = tabapp.utils.current_product_cost(product_id)
        if product_cost:
            product_cost.end_date = date.today()
        product_cost = ProductCost()
        product_cost.product_id = product_id
        product_cost.value = request.form.get('product_cost')
        product_cost.start_date = date.today()
        db.session.add(product_cost)
        db.session.commit()
        return jsonify(result=True)
    product = Product.query.get(product_id)
    if not product:
        return abort(404)
    costs = []
    for product_cost in product.costs:
        costs.append({
            'date': format_date(product_cost.start_date),
            'value': format_currency(product_cost.value, 'EUR'),
        })
    return jsonify(costs=costs)
Example #39
0
def date_filter(date):
    return format_date(date)
Example #40
0
def jinja_format_date(date):
    return format_date(date)
Example #41
0
def index():
    """Render index page.

    Supported outputs: html, json, csv, rss.
    """

    # output_format
    output_format = request.form.get('format', 'html')
    if output_format not in ['html', 'csv', 'json', 'rss']:
        output_format = 'html'

    # check if there is query
    if request.form.get('q') is None:
        if output_format == 'html':
            return render(
                'index.html',
            )
        else:
            return index_error(output_format, 'No query'), 400

    # search
    search_query = None
    result_container = None
    try:
        search_query = get_search_query_from_webapp(request.preferences, request.form)
        # search = Search(search_query) #  without plugins
        search = SearchWithPlugins(search_query, request.user_plugins, request)
        result_container = search.search()
    except Exception as e:
        # log exception
        logger.exception('search error')

        # is it an invalid input parameter or something else ?
        if (issubclass(e.__class__, SearxParameterException)):
            return index_error(output_format, e.message), 400
        else:
            return index_error(output_format, gettext('search error')), 500

    # results
    results = result_container.get_ordered_results()
    number_of_results = result_container.results_number()
    if number_of_results < result_container.results_length():
        number_of_results = 0

    # UI
    advanced_search = request.form.get('advanced_search', None)

    # output
    for result in results:
        if output_format == 'html':
            if 'content' in result and result['content']:
                result['content'] = highlight_content(escape(result['content'][:1024]), search_query.query)
            result['title'] = highlight_content(escape(result['title'] or u''), search_query.query)
        else:
            if result.get('content'):
                result['content'] = html_to_text(result['content']).strip()
            # removing html content and whitespace duplications
            result['title'] = ' '.join(html_to_text(result['title']).strip().split())

        result['pretty_url'] = prettify_url(result['url'])

        # TODO, check if timezone is calculated right
        if 'publishedDate' in result:
            try:  # test if publishedDate >= 1900 (datetime module bug)
                result['pubdate'] = result['publishedDate'].strftime('%Y-%m-%d %H:%M:%S%z')
            except ValueError:
                result['publishedDate'] = None
            else:
                if result['publishedDate'].replace(tzinfo=None) >= datetime.now() - timedelta(days=1):
                    timedifference = datetime.now() - result['publishedDate'].replace(tzinfo=None)
                    minutes = int((timedifference.seconds / 60) % 60)
                    hours = int(timedifference.seconds / 60 / 60)
                    if hours == 0:
                        result['publishedDate'] = gettext(u'{minutes} minute(s) ago').format(minutes=minutes)
                    else:
                        result['publishedDate'] = gettext(u'{hours} hour(s), {minutes} minute(s) ago').format(hours=hours, minutes=minutes)  # noqa
                else:
                    result['publishedDate'] = format_date(result['publishedDate'])

    if output_format == 'json':
        return Response(json.dumps({'query': search_query.query.decode('utf-8'),
                                    'number_of_results': number_of_results,
                                    'results': results,
                                    'answers': list(result_container.answers),
                                    'corrections': list(result_container.corrections),
                                    'infoboxes': result_container.infoboxes,
                                    'suggestions': list(result_container.suggestions),
                                    'unresponsive_engines': list(result_container.unresponsive_engines)},
                                   default=lambda item: list(item) if isinstance(item, set) else item),
                        mimetype='application/json')
    elif output_format == 'csv':
        csv = UnicodeWriter(StringIO())
        keys = ('title', 'url', 'content', 'host', 'engine', 'score')
        csv.writerow(keys)
        for row in results:
            row['host'] = row['parsed_url'].netloc
            csv.writerow([row.get(key, '') for key in keys])
        csv.stream.seek(0)
        response = Response(csv.stream.read(), mimetype='application/csv')
        cont_disp = 'attachment;Filename=searx_-_{0}.csv'.format(search_query.query)
        response.headers.add('Content-Disposition', cont_disp)
        return response
    elif output_format == 'rss':
        response_rss = render(
            'opensearch_response_rss.xml',
            results=results,
            q=request.form['q'],
            number_of_results=number_of_results,
            base_url=get_base_url(),
            override_theme='__common__',
        )
        return Response(response_rss, mimetype='text/xml')

    return render(
        'results.html',
        results=results,
        q=request.form['q'],
        selected_categories=search_query.categories,
        pageno=search_query.pageno,
        time_range=search_query.time_range,
        number_of_results=format_decimal(number_of_results),
        advanced_search=advanced_search,
        suggestions=result_container.suggestions,
        answers=result_container.answers,
        corrections=result_container.corrections,
        infoboxes=result_container.infoboxes,
        paging=result_container.paging,
        unresponsive_engines=result_container.unresponsive_engines,
        current_language=match_language(search_query.lang,
                                        LANGUAGE_CODES,
                                        fallback=settings['search']['language']),
        base_url=get_base_url(),
        theme=get_current_theme_name(),
        favicons=global_favicons[themes.index(get_current_theme_name())]
    )
Example #42
0
    def parse_query(self, query):
        quantum = query.get('quantum')
        if quantum == 'month':
            self.date_formatter = lambda x: format_date(x, "MMMM yyyy")
        elif quantum == 'day':
            self.date_formatter = lambda x: format_date(x, "long")
        elif quantum == 'hour':
            self.date_formatter = lambda x: format_datetime(x)
        else:
            self.date_formatter = lambda x: format_date(x, "long")

        def get_time(param):
            if query.get(param) is None or len(str(query.get(param))) == 0:
                return -1
            else:
                try:
                    return int(query.get(param))
                except ValueError:
                    return query.get(param)

        self.time = get_time('time')
        self.starttime = get_time('starttime')
        self.endtime = get_time('endtime')

        scale = query.get('scale')
        if scale is None or 'auto' in scale:
            scale = None
        else:
            scale = [float(x) for x in scale.split(',')]
        self.scale = scale

        variables = query.get('variable')
        if variables is None:
            variables = ['votemper']

        if isinstance(variables, str) or isinstance(variables, unicode):
            variables = variables.split(',')

        variables = filter(lambda v: v != '', variables)

        self.variables_anom = variables
        self.variables = [re.sub('_anom$', '', v) for v in variables]

        cmap = query.get('colormap')
        if cmap is not None:
            cmap = colormap.colormaps.get(cmap)
        if cmap is None and self.variables != self.variables_anom:
            cmap = colormap.colormaps['anomaly']
        self.cmap = cmap

        linearthresh = query.get('linearthresh')
        if linearthresh is None or linearthresh == '':
            linearthresh = 200
        linearthresh = float(linearthresh)
        if not linearthresh > 0:
            linearthresh = 1
        self.linearthresh = linearthresh

        depth = query.get('depth')
        if depth is None or len(str(depth)) == 0:
            depth = 0

        if isinstance(depth, basestring) and depth.isdigit():
            depth = int(depth)

        if isinstance(depth, list):
            for i in range(0, len(depth)):
                if isinstance(depth[i], basestring) and depth[i].isdigit():
                    depth[i] = int(depth[i])

        self.depth = depth

        self.showmap = query.get('showmap') is None or \
            bool(query.get('showmap'))
Example #43
0
File: webapp.py Project: kvch/searx
def index():
    """Render index page.

    Supported outputs: html, json, csv, rss.
    """

    if request.form.get("q") is None:
        return render("index.html")

    # search
    search_query = None
    result_container = None
    try:
        search_query = get_search_query_from_webapp(request.preferences, request.form)
        # search = Search(search_query) #  without plugins
        search = SearchWithPlugins(search_query, request)
        result_container = search.search()
    except:
        request.errors.append(gettext("search error"))
        logger.exception("search error")
        return render("index.html")

    results = result_container.get_ordered_results()

    # UI
    advanced_search = request.form.get("advanced_search", None)
    output_format = request.form.get("format", "html")
    if output_format not in ["html", "csv", "json", "rss"]:
        output_format = "html"

    # output
    for result in results:
        if output_format == "html":
            if "content" in result and result["content"]:
                result["content"] = highlight_content(
                    escape(result["content"][:1024]), search_query.query.encode("utf-8")
                )
            result["title"] = highlight_content(escape(result["title"] or u""), search_query.query.encode("utf-8"))
        else:
            if result.get("content"):
                result["content"] = html_to_text(result["content"]).strip()
            # removing html content and whitespace duplications
            result["title"] = " ".join(html_to_text(result["title"]).strip().split())

        result["pretty_url"] = prettify_url(result["url"])

        # TODO, check if timezone is calculated right
        if "publishedDate" in result:
            try:  # test if publishedDate >= 1900 (datetime module bug)
                result["pubdate"] = result["publishedDate"].strftime("%Y-%m-%d %H:%M:%S%z")
            except ValueError:
                result["publishedDate"] = None
            else:
                if result["publishedDate"].replace(tzinfo=None) >= datetime.now() - timedelta(days=1):
                    timedifference = datetime.now() - result["publishedDate"].replace(tzinfo=None)
                    minutes = int((timedifference.seconds / 60) % 60)
                    hours = int(timedifference.seconds / 60 / 60)
                    if hours == 0:
                        result["publishedDate"] = gettext(u"{minutes} minute(s) ago").format(minutes=minutes)
                    else:
                        result["publishedDate"] = gettext(u"{hours} hour(s), {minutes} minute(s) ago").format(
                            hours=hours, minutes=minutes
                        )  # noqa
                else:
                    result["publishedDate"] = format_date(result["publishedDate"])

    number_of_results = result_container.results_number()
    if number_of_results < result_container.results_length():
        number_of_results = 0

    if output_format == "json":
        return Response(
            json.dumps(
                {
                    "query": search_query.query,
                    "number_of_results": number_of_results,
                    "results": results,
                    "answers": list(result_container.answers),
                    "infoboxes": result_container.infoboxes,
                    "suggestions": list(result_container.suggestions),
                }
            ),
            mimetype="application/json",
        )
    elif output_format == "csv":
        csv = UnicodeWriter(cStringIO.StringIO())
        keys = ("title", "url", "content", "host", "engine", "score")
        csv.writerow(keys)
        for row in results:
            row["host"] = row["parsed_url"].netloc
            csv.writerow([row.get(key, "") for key in keys])
        csv.stream.seek(0)
        response = Response(csv.stream.read(), mimetype="application/csv")
        cont_disp = "attachment;Filename=searx_-_{0}.csv".format(search_query.query.encode("utf-8"))
        response.headers.add("Content-Disposition", cont_disp)
        return response
    elif output_format == "rss":
        response_rss = render(
            "opensearch_response_rss.xml",
            results=results,
            q=request.form["q"],
            number_of_results=number_of_results,
            base_url=get_base_url(),
        )
        return Response(response_rss, mimetype="text/xml")

    return render(
        "results.html",
        results=results,
        q=request.form["q"],
        selected_categories=search_query.categories,
        pageno=search_query.pageno,
        time_range=search_query.time_range,
        number_of_results=format_decimal(number_of_results),
        advanced_search=advanced_search,
        suggestions=result_container.suggestions,
        answers=result_container.answers,
        infoboxes=result_container.infoboxes,
        paging=result_container.paging,
        base_url=get_base_url(),
        theme=get_current_theme_name(),
        favicons=global_favicons[themes.index(get_current_theme_name())],
    )
Example #44
0
 def date_filter(date, format=None, locale=None):
     return format_date(date, format, locale)
Example #45
0
def format_date_for_input(date):
    date_fmt = get_locale().date_formats["short"].pattern
    # force numerical months
    date_fmt = date_fmt.replace("MMMM", "MM").replace("MMM", "MM")
    return format_date(date, date_fmt)
Example #46
0
def index():
    """Render index page.

    Supported outputs: html, json, csv, rss.
    """

    if not request.args and not request.form:
        return render(
            'index.html',
        )

    try:
        search = Search(request)
    except:
        return render(
            'index.html',
        )

    if plugins.call('pre_search', request, locals()):
        search.search(request)

    plugins.call('post_search', request, locals())

    results = search.result_container.get_ordered_results()

    for result in results:

        plugins.call('on_result', request, locals())
        if not search.paging and engines[result['engine']].paging:
            search.paging = True

        if search.request_data.get('format', 'html') == 'html':
            if 'content' in result:
                result['content'] = highlight_content(result['content'],
                                                      search.query.encode('utf-8'))  # noqa
            result['title'] = highlight_content(result['title'],
                                                search.query.encode('utf-8'))
        else:
            if result.get('content'):
                result['content'] = html_to_text(result['content']).strip()
            # removing html content and whitespace duplications
            result['title'] = ' '.join(html_to_text(result['title']).strip().split())

        result['pretty_url'] = prettify_url(result['url'])

        # TODO, check if timezone is calculated right
        if 'publishedDate' in result:
            try:  # test if publishedDate >= 1900 (datetime module bug)
                result['pubdate'] = result['publishedDate'].strftime('%Y-%m-%d %H:%M:%S%z')
            except ValueError:
                result['publishedDate'] = None
            else:
                if result['publishedDate'].replace(tzinfo=None) >= datetime.now() - timedelta(days=1):
                    timedifference = datetime.now() - result['publishedDate'].replace(tzinfo=None)
                    minutes = int((timedifference.seconds / 60) % 60)
                    hours = int(timedifference.seconds / 60 / 60)
                    if hours == 0:
                        result['publishedDate'] = gettext(u'{minutes} minute(s) ago').format(minutes=minutes)
                    else:
                        result['publishedDate'] = gettext(u'{hours} hour(s), {minutes} minute(s) ago').format(hours=hours, minutes=minutes)  # noqa
                else:
                    result['publishedDate'] = format_date(result['publishedDate'])

    number_of_results = search.result_container.results_number()
    if number_of_results < search.result_container.results_length():
        number_of_results = 0

    if search.request_data.get('format') == 'json':
        return Response(json.dumps({'query': search.query,
                                    'number_of_results': number_of_results,
                                    'results': results}),
                        mimetype='application/json')
    elif search.request_data.get('format') == 'csv':
        csv = UnicodeWriter(cStringIO.StringIO())
        keys = ('title', 'url', 'content', 'host', 'engine', 'score')
        csv.writerow(keys)
        for row in results:
            row['host'] = row['parsed_url'].netloc
            csv.writerow([row.get(key, '') for key in keys])
        csv.stream.seek(0)
        response = Response(csv.stream.read(), mimetype='application/csv')
        cont_disp = 'attachment;Filename=searx_-_{0}.csv'.format(search.query.encode('utf-8'))
        response.headers.add('Content-Disposition', cont_disp)
        return response
    elif search.request_data.get('format') == 'rss':
        response_rss = render(
            'opensearch_response_rss.xml',
            results=results,
            q=search.request_data['q'],
            number_of_results=number_of_results,
            base_url=get_base_url()
        )
        return Response(response_rss, mimetype='text/xml')

    return render(
        'results.html',
        results=results,
        q=search.request_data['q'],
        selected_categories=search.categories,
        paging=search.paging,
        number_of_results=format_decimal(number_of_results),
        pageno=search.pageno,
        advanced_search=search.is_advanced,
        time_range=search.time_range,
        base_url=get_base_url(),
        suggestions=search.result_container.suggestions,
        answers=search.result_container.answers,
        infoboxes=search.result_container.infoboxes,
        theme=get_current_theme_name(),
        favicons=global_favicons[themes.index(get_current_theme_name())]
    )
Example #47
0
def format_date_for_input(date):
  date_fmt = get_locale().date_formats['short'].pattern
  date_fmt = date_fmt.replace('MMMM', 'MM')\
      .replace('MMM', 'MM')  # force numerical months
  return format_date(date, date_fmt)
Example #48
0
 def format_month(year, month):
     month = format_date(date(year, month, 1), "MMMM").capitalize()
     return f"{month} {year}"
Example #49
0
def index():
    """Usersuite landing page with user account information
    and traffic overview.
    """
    info = current_user.finance_information
    last_update = info.last_update if info else None
    finance_update_string = (
        " ({}: {})".format(gettext("Stand"),
                           format_date(last_update, 'short', rebase=False))
        if last_update
        else ""
    )
    descriptions = OrderedDict([
        ('id', gettext("Nutzer-ID")),
        ('realname', gettext("Voller Name")),
        ('login', gettext("Accountname")),
        ('status', gettext("Mitgliedsschaftsstatus")),
        ('address', gettext("Aktuelles Zimmer")),
        ('ips', gettext("Aktuelle IP-Adresse")),
        ('mac', gettext("Aktuelle MAC-Adresse")),
        ('mail', gettext("E-Mail-Weiterleitung")),
        ('use_cache', gettext("Cache-Nutzung")),
        ('hostname', gettext("Hostname")),
        ('hostalias', gettext("Hostalias")),
        ('userdb_status', gettext("MySQL Datenbank")),
        ('finance_balance', gettext("Kontostand") + finance_update_string),
    ])

    try:
        rows = current_user.generate_rows(descriptions)
    except DBQueryEmpty as e:
        logger.error('Userinfo DB query could not be finished',
                     extra={'data': {'exception_args': e.args}, 'stack': True})
        flash(gettext("Es gab einen Fehler bei der Datenbankanfrage!"),
              "error")
        return redirect(url_for('generic.index'))

    payment_form = PaymentForm()
    if payment_form.validate_on_submit():
        months = payment_form.months.data
    else:
        months = payment_form.months.default
        flash_formerrors(payment_form)

    datasource = current_user.datasource
    context = dict(rows=rows,
                   webmailer_url=datasource.webmailer_url,
                   payment_details=render_payment_details(current_user.payment_details(),
                                                          months),
                   girocode=generate_epc_qr_code(current_user.payment_details(), months))

    if current_user.has_connection:
        context.update(
            show_traffic_data=True,
            traffic_user=current_user,
        )

    if info and info.has_to_pay:
        context.update(
            show_transaction_log=True,
            last_update=info.last_update,
            balance=info.balance.raw_value,
            logs=info.history,
        )

    return render_template("usersuite/index.html", payment_form=payment_form, **context)
Example #50
0
def filter_format_date(dt, format=None, rebase=True):
    """Return a date formatted according to the given pattern."""
    return format_date(dt, format=format, rebase=rebase)
Example #51
0
 def render_view(self, field, **kwargs):
   return format_date(field.data) if field.data else u''
Example #52
0
def reformat_date(value, format=None):
    """Converts date into string formatted for current locale."""
    return format_date(value, format)
Example #53
0
def date(datetime, ref=current_user, year=False):
    fmt = date_formats.get(get_locale().language, 'EEE, dd MMM') + (' yyyy' if year else '')
    date = in_timezone_of(datetime, ref).date()
    return format_date(date, fmt, rebase=False)