Formatting of dates and times in Flask templates using moment.js.

Overview

Flask-Moment

Build Status

This extension enhances Jinja2 templates with formatting of dates and times using moment.js.

Quick Start

Step 1: Initialize the extension:

from flask_moment import Moment
moment = Moment(app)

Step 2: In your <head> section of your base template add the following code:

<head>
    {{ moment.include_jquery() }}
    {{ moment.include_moment() }}
</head>

This extension also supports the Flask application factory pattern by allowing you to create a Moment object and then separately initialize it for an app:

    moment = Moment()

    def create_app(config):
        app = Flask(__name__)
        app.config.from_object(config)
        # initialize moment on the app within create_app()
        moment.init_app(app)

    app = create_app(prod_config)

Note that jQuery is required. If you are already including it on your own then you can remove the include_jquery() line. Secure HTTP is always used to request the external js files..

The include_jquery() and include_moment() methods take some optional arguments. If you pass a version argument to any of these two calls, then the requested version will be loaded from the default CDN. If you pass local_js, then the given local path will be used to load the library. The include_moment() argument takes a third argument no_js that when set to True will assume that the Moment JavaScript library is already loaded and will only add the JavaScript code that supports this extension.

Step 3: Render timestamps in your template. For example:

<p>The current date and time is: {{ moment().format('MMMM Do YYYY, h:mm:ss a') }}.</p>
<p>Something happened {{ moment(then).fromTime(now) }}.</p>
<p>{{ moment(then).calendar() }}.</p>

In the second and third examples template variables then and now are used. These must be instances of Python's datetime class, and must be "naive" objects. See the documentation for a discussion of naive date and time objects. As an example, now can be set as follows:

now = datetime.utcnow()

By default the timestamps will be converted from UTC to the local time in each client's machine before rendering. To disable the conversion to local time pass local=True.

Note that even though the timestamps are provided in UTC the rendered dates and times will be in the local time of the client computer, so each users will always see their local time regardless of where they are located.

Function Reference

The supported list of display functions is shown below:

  • moment(timestamp=None, local=False).format(format_string=None)
  • moment(timestamp=None, local=False).fromNow(no_suffix=False)
  • moment(timestamp=None, local=False).fromTime(another_timesatmp, no_suffix=False)
  • moment(timestamp=None, local=False).toNow(no_suffix=False)
  • moment(timestamp=None, local=False).toTime(another_timesatmp, no_suffix=False)
  • moment(timestamp=None, local=False).calendar()
  • moment(timestamp=None, local=False).valueOf()
  • moment(timestamp=None, local=False).unix()

Consult the moment.js documentation for details on these functions.

Auto-Refresh

All the display functions take an optional refresh argument that when set to True will re-render timestamps every minute. This can be useful for relative time formats such as the one returned by the fromNow() or fromTime() functions. By default refreshing is disabled.

Default Format

The format() function can be invoked without arguments, in which case a default format of ISO8601 defined by the moment.js library is used. If you want to set a different default, you can set the MOMENT_DEFAULT_FORMAT variable in the Flask configuration. Consult the moment.js format documentation for a list of accepted tokens.

Internationalization

By default dates and times are rendered in English. To change to a different language add the following line in the <head> section after the include_moment() line:

{{ moment.locale("es") }}

The above example sets the language to Spanish. Moment.js supports a large number of languages, consult the documentation for the list of languages and their two letter codes.

The extension also supports auto-detection of the client's browser language:

{{ moment.locale(auto_detect=True) }}

Custom locales can also be included as a dictionary:

{{ moment.locale(customizations={ ... }) }}

See the Moment.js locale customizations documentation for details on how to define a custom locale.

Ajax Support

It is also possible to create Flask-Moment timestamps in Python code, for cases where a template is not used. This is the syntax:

timestamp = moment.create(datetime.utcnow()).calendar()

The moment variable is the Moment instance that was created at initialization time.

A timestamp created in this way is an HTML string that can be returned as part of a response. For example, here is how a timestamp can be returned in a JSON object:

return jsonify({ 'timestamp': moment.create(datetime.utcnow()).format('L') })

The Ajax callback in the browser needs to call flask_moment_render_all() each time an element containing a timestamp is added to the DOM. The included application demonstrates how this is done.

Subresource Integrity(SRI)

SRI is a security feature that enables browsers to verify that resources they fetch are not maliciously manipulated. To do so a cryptographic hash is provided that proves integrity.

SRI is enabled by default. If you wish to use another version or want to host your own javascript, a separate hash can be provided. Just add sri=<YOUR-HASH> when calling either moment.include_moment() or moment.include_jquery(). If no sri hash is provided and you choose to use a non default version of javascript, no sri hash will be added.

You can always choose to disable sri. To do so just set sri=False.

Development

Currently the tests are written using pytest.

pip install pytest

To run the tests from the root directory use: py.test.

Reports on coverage with missing line numbers can be generated using pytest-cov:

pip install pytest-cov

And then running: py-test --cov-report term-missing --cov=flask_moment

Owner
Miguel Grinberg
Miguel Grinberg
A RESTful API for creating and monitoring resource components of a hypothetical build system. Built with FastAPI and pydantic. Complete with testing and CI.

diskspace-monitor-CRUD Background The build system is part of a large environment with a multitude of different components. Many of the components hav

Nick Hopewell 67 Dec 14, 2022
Easily integrate socket.io with your FastAPI app šŸš€

fastapi-socketio Easly integrate socket.io with your FastAPI app. Installation Install this plugin using pip: $ pip install fastapi-socketio Usage To

Srdjan Stankovic 210 Dec 23, 2022
A simple Redis Streams backed Chat app using Websockets, Asyncio and FastAPI/Starlette.

redis-streams-fastapi-chat A simple demo of Redis Streams backed Chat app using Websockets, Python Asyncio and FastAPI/Starlette. Requires Python vers

ludwig404 135 Dec 19, 2022
Complete Fundamental to Expert Codes of FastAPI for creating API's

FastAPI FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3 based on standard Python type hints. The key featu

Pranav Anand 1 Nov 28, 2021
Full stack, modern web application generator. Using FastAPI, PostgreSQL as database, Docker, automatic HTTPS and more.

Full Stack FastAPI and PostgreSQL - Base Project Generator Generate a backend and frontend stack using Python, including interactive API documentation

SebastiƔn Ramƭrez 10.8k Jan 08, 2023
FastAPI pagination

FastAPI Pagination Installation # Basic version pip install fastapi-pagination # All available integrations pip install fastapi-pagination[all] Avail

Yurii Karabas 561 Jan 07, 2023
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

Laurent Savaete 562 Jan 01, 2023
šŸš€ Cookiecutter Template for FastAPI + React Projects. Using PostgreSQL, SQLAlchemy, and Docker

FastAPI + React Ā· A cookiecutter template for bootstrapping a FastAPI and React project using a modern stack. Features FastAPI (Python 3.8) JWT authen

Gabriel Abud 1.4k Jan 02, 2023
Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Beyonic API Python Examples. The beyonic APIs Doc Reference: https://apidocs.beyonic.com/ To start using the Beyonic API Python API, you need to start

Harun Mbaabu Mwenda 46 Sep 01, 2022
High-performance Async REST API, in Python. FastAPI + GINO + Arq + Uvicorn (w/ Redis and PostgreSQL).

fastapi-gino-arq-uvicorn High-performance Async REST API, in Python. FastAPI + GINO + Arq + Uvicorn (powered by Redis & PostgreSQL). Contents Get Star

Leo Sussan 351 Jan 04, 2023
A comprehensive CRUD API generator for SQLALchemy.

FastAPI Quick CRUD Introduction Advantage Constraint Getting started Installation Usage Design Path Parameter Query Parameter Request Body Upsert Intr

192 Jan 06, 2023
šŸPywork is a Yeoman generator to scaffold a Bare-bone Python Application

Pywork python app yeoman generator Yeoman | Npm Pywork | Home PyWork is a Yeoman generator for a basic python-worker project that makes use of Pipenv,

Vu Tran 10 Dec 16, 2022
A FastAPI Plug-In to support authentication authorization using the Microsoft Authentication Library (MSAL)

FastAPI/MSAL - MSAL (Microsoft Authentication Library) plugin for FastAPI FastAPI - https://github.com/tiangolo/fastapi FastAPI is a modern, fast (hig

Dudi Levy 15 Jul 20, 2022
Prometheus integration for Starlette.

Starlette Prometheus Introduction Prometheus integration for Starlette. Requirements Python 3.6+ Starlette 0.9+ Installation $ pip install starlette-p

JosƩ Antonio Perdiguero 229 Dec 21, 2022
CURSO PROMETHEUS E GRAFANA: Observability in a real world

Curso de monitoraĆ§Ć£o com o Prometheus Esse curso ensina como usar o Prometheus como uma ferramenta integrada de monitoraĆ§Ć£o, entender seus conceitos,

Rafael Cirolini 318 Dec 23, 2022
Adds simple SQLAlchemy support to FastAPI

FastAPI-SQLAlchemy FastAPI-SQLAlchemy provides a simple integration between FastAPI and SQLAlchemy in your application. It gives access to useful help

Michael Freeborn 465 Jan 07, 2023
FastAPI IPyKernel Sandbox

FastAPI IPyKernel Sandbox This repository is a light-weight FastAPI project that is meant to provide a wrapper around IPyKernel interactions. It is in

Nick Wold 2 Oct 25, 2021
Boilerplate code for quick docker implementation of REST API with JWT Authentication using FastAPI, PostgreSQL and PgAdmin ā­

FRDP Boilerplate code for quick docker implementation of REST API with JWT Authentication using FastAPI, PostgreSQL and PgAdmin ā› . Getting Started Fe

BnademOverflow 53 Dec 29, 2022
MS Graph API authentication example with Fast API

MS Graph API authentication example with Fast API What it is & does This is a simple python service/webapp, using FastAPI with server side rendering,

Andrew Hart 4 Aug 11, 2022
Repository for the Demo of using DVC with PyCaret & MLOps (DVC Office Hours - 20th Jan, 2022)

Using DVC with PyCaret & FastAPI (Demo) This repo contains all the resources for my demo explaining how to use DVC along with other interesting tools

Tezan Sahu 6 Jul 22, 2022