Giter Site home page Giter Site logo

miguelgrinberg / flask-moment Goto Github PK

View Code? Open in Web Editor NEW
366.0 14.0 49.0 138 KB

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

License: MIT License

Python 93.97% HTML 6.03%
python timestamp moment-js render-timestamps flask-moment utc

flask-moment's Introduction

flask-moment's People

Contributors

chuxiaof avatar colekettler avatar dependabot[bot] avatar e2jk avatar ezeparziale avatar greendinosaur avatar greyli avatar jeffwidman avatar m0r13n avatar miguelgrinberg avatar mrf345 avatar nordenf avatar serenityik avatar sgraaf avatar small-yellow-rice avatar tals avatar timgates42 avatar tryhubov avatar wgwz avatar yuxiaoy1 avatar ziddey avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask-moment's Issues

Suggestion for using local moment.js instead of CDN

This solution works for me:

flask_moment.py

class _moment(object):
@staticmethod
def include_moment(localjs = None, version = '2.5.1'):
    js = ''
    if localjs is not None:
        js = '<script src="%s"></script>\n' % localjs
    else:
        if version is not None:
            js = '<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/%s/moment-with-langs.min.js"></script>\n' % version
    return Markup('''%s<script> ... 

Template:

{% block scripts %}
{{ super() }}
{{ moment.include_moment(localjs = '/static/js/moment.js') }}
{% endblock %}

include_moment(version=None) is broken

Hi,
I'm trying to serve moment-with-langs.min.js locally.
I presume this can be achieved with include_moment(version=None).
It appears to me the code forgets to set js when version is None.
My guess is the intent is...

if version is not None:
    js = "<script>...
js = js or ""

Support for moment-timezone

Does the current version argument support, or intend to support moment-timezone as well? If not, is there a known reason it wouldn't work? If not already supported and desirable, I can take a stab at it...

Fix for out of sync in flask-moment

Hi @miguelgrinberg,

I have followed your tutorial very closely to learn the flask, Thank you for the wonderful content.

I am having some trouble with flask-moment. Since the clocks are out of sync, moment.js has implemented a function to capture the offset and display the correct time. I have modified the moment.js accordingly. However, when I run the app it throws the error that function is not a part of flask-moment. How can I incorporate my new function in moment.js to flask-moment?

JS function:

     pastFromNow : function (withoutSuffix) {
            var now = moment();
            var past = this < now ? this : now;
            return past.from(now, withoutSuffix);
        },

Mentioned here:

I am using flask-appbuilder for creating my application.

Any help will be appreciated.

Thanks.,

new times always say in 4 hours or 4 hours ago

Hello,
If an item is less than 4 hours old, it will say in 4 hours or 4 hours ago. After 4 hours it utilizes correct time.

moment = Moment(app)


    {{ moment.include_jquery() }}
    {{ moment.include_moment() }}

timestamp = datetime.now()
<td width="10%">{{ moment(timestamp=rate.timestamp, local=True).fromTime(now) }}

where now = datetime.now()
I also have tried ..

moment(timestamp=rate.timestamp, local=False).fromNow(no_suffix = False)

version 1.0.0 breaks import

After building a new image that depends on Flask-Moment I suddenly get import errors
Installed Version:

$ pip freeze
...
Flask-Moment==1.0.0
...

Error:

  File "/home/flask/digimat/app/__init__.py", line 12, in <module>
    from flask_moment import Moment
ModuleNotFoundError: No module named 'flask_moment'

I tested upgrading Flask-Moment in other environments all with the same effect

How do I use format with refresh?

I'm add {{ moment().format('LLL', refresh = True) }} to my template,but it can't work.
BTW,I use fromNow(no_suffix=False, refresh = True) to be successful.

no seconds or real time update?

hey was just curious whats the actual point of flask-moment if it cant display seconds and cant update in real time (have to refresh page)? if it had these features and jquery countdown it could be much more useful.

Factor out loading moment from downloading

I use bower to manage the dependencies of my project, and don't want to use the CDN version.

I can bypass this by not using moment.include_moment(), but that means the javascript that does all the work also isn't included.

Is it possible to separate these out into two functions?

Blocked by CORS policy

When using the {{ moment.include_moment() }} in chrome i get the below error message. Any idea how i can solve it?

Importing moment through the <script src"..."></script> works fine, but then i can only use javascript-moment and not flask-moment.

Access to script at 'http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js' from origin 'http://127.0.0.1:5000' has been blocked by CORS policy: The response is invalid.

Javascript errors

End of Chapter 3 in your book, following directions, something is broken in the javascript. Using version 0.4.0

screenshot from 2014-12-08 22 14 34

Add strftime formatting support

Is there any way you could add support for formatting using the strtime format (e.g moment.strftime()), for example by including benjaminoakes/moment-strftime?

This is what the [http://momentjs.com/docs/#other-tokens](moment.js documentation) suggests.

Problem using Flask-Moment in IE11 and Edge

Hi -

I'm learning Python Flask and I've built my first simple website. In one of the HTML templates I've included the line:
<p>The current date and time is: {{ moment().format('MMMM Do YYYY, h:mm:ss a') }}.</p>

My init.py file contains the lines:
from flask_moment import Moment

moment = Moment(app)

My base.html file contains:
{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{{ moment.locale(auto_detect=True) }}
{% endblock %}

This works fine in Firefox and Chrome, but returns no datetime information in IE11 or Edge.

I'm running the Flask app on localhost:5000.

I've attached screenshots from the four browsers to illustrate the problem.

I'm running MS Windows 10 Home (64-bit) on a Lenovo ThinkPad laptop with Python 3.8.2 (32-bit) and Flask 1.1.2. I'm using Flask_Bootstrap4 4.0.2.

Apologies if this isn't the right place to raise this question, but I've searched extensively online (stackoverflow, etc) and I haven't been able to find any information that has helped me to resolve it.

Please let me know if you need any further information.

Many thanks

Firefox
Firefox
Chrome
Chrome
IE11
IE11
Edge
Edge

can't call moment.include_moment() from within Python code

If I call moment.include_moment() inside a Jinja template, it works fine, but if I try to call it directly from Python code, I get AttributeError: 'Moment' object has no attribute 'include_moment'

I am experimenting with Dominate as a possible replacement for Jinja.

How to customize fromNow output ?

I am displaying time data was received using flask Moment.fromNow. Typically it outputs 'a few seconds ago' but sometimes the sender's clock is a little off and it displays ' in a few seconds' - which makes no sense to the user.
To fix this I want to change ' in a few seconds' to 'current' but this does not seem easy using Moment customization so I thought I could simply change the output in jinja2 but cannot see how to capture the output string to change it:
Code:
{% set moment_text = moment(value.lastupdated).fromNow(no_suffix = False) %}

    {% if moment_text == "in a few seconds"  %}
        {% set moment_text = "current" %}
    {% endif %}

This never fires because moment_text is still a date and not a string.
How can I get the output string of Flask Moment so I can test it and change it?
Thanks
Bill

Eval() is Evil ;) (unsafe Content-Security-Policy)

When activating Content-Security-Policy (CSP) with script-src to allow for local scripts and cdnjs.cloudflare.com where the moment.js gets downloaded from by Flask-Moment, the following error gets triggered and further execution of moment.js gets blocked:

image

This is the line in question:

$(elem).text(eval('moment("' + $(elem).data('timestamp') + '").' + $(elem).data('format') + ';'));

One way to get around this would be to allow for unsafe-eval in the CSP, but that is not a good idea since that means that any script used on the website can use eval (and thus any potential malicious script). The right way would be to replace the eval() call in the code.

(in case the reference needs explaining: the title of the issue comes from Douglas Crockford's JavaScript: The Good Parts. Another bit about why Eval is Evil: https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/ )

Momentjs version

Before I started adding anything: you mentioned you want to Flask-Moment to reflect Momentjs as much as possible, without too many changes. It seems moment received some new functions in its version 2, that are not in Flask-Moment yet (like toNow()). Would it be OK to wrappers for those functions? Seems default_moment_version is already at the right version for this.

Safari (13.0.2) doesn't seem to like sri=True

I'm not sure whether this is properly an error in flask-moment. Apologies if this is the wrong place.

Using an extremely simple app, I can't seem to get dates to display properly in Safari (13.0.2) with flask-moment (0.9.0) unless I set sri to False in include_moment(). Otherwise, moment.js fails to load and no dates display. In the JavaScript console I see errors related to Access-Control-Allow-Origin, but setting that header manually doesn't have any impact.

The errors I see:

[Error] Cross-origin redirection to http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js denied by Cross-Origin Resource Sharing policy: Origin http://localhost:5000 is not allowed by Access-Control-Allow-Origin.
[Error] Failed to load resource: Cross-origin redirection to http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js denied by Cross-Origin Resource Sharing policy: Origin http://localhost:5000 is not allowed by Access-Control-Allow-Origin. (moment-with-locales.min.js, line 0)
[Error] Cross-origin script load denied by Cross-Origin Resource Sharing policy.
[Error] ReferenceError: Can't find variable: moment
Global Code (localhost:15)
[Error] Cross-origin script load denied by Cross-Origin Resource Sharing policy.
[Error] ReferenceError: Can't find variable: moment
Global Code (localhost:49)

The code I used:

main.py:

from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask import Flask, render_template, make_response
from datetime import datetime

app = Flask(__name__)
bootstrap = Bootstrap(app)
moment = Moment(app)

@app.route("/")
def index():
    return render_template('index.html', current_time=datetime.utcnow())

if __name__ == '__main__':
    app.run()

base.html:

{% extends "bootstrap/base.html" %}
{% block head %}
{{ super() }}
  {% block scripts %}
  {{ super() }}
  {{ moment.include_moment() }}
  {% endblock %}
{% endblock %}

{% block content %}
  {% block page_content %}
  {% endblock %}
{% endblock %}

index.html:

{% extends 'base.html' %}

{% block page_content %}
Current time: {{ moment(current_time).format('LLL') }}.
{% endblock %}

MIT or BSD?

I saw MIT in the LICENSE file while BSD in setup.py. Which is correct?
If BSD is the choice, which kind? (e.g. 2-Clause BSD ~= MIT, or maybe 3-BSD)

AttributeError: 'str' object has no attribute '

This works
<td>{{moment().format('MMMM Do YYYY, h:mm:ss a')}}</td>
But this don't work
<td>{{ moment('1/1/2020').format('L') }}</td>
And can I ask other question?
Is result returned from executing raw sql query db.engine.execute(sql) and result from User.query.all() ?
Thanks

AttributeError: 'unicode' object has no attribute 'strftime'

Hello,

I got registered_at value for members in db. It is string in db. Moment can't replace it.

When i type dump() to console, it shows:
timestamp = u'2014-10-14 23:51:31.297440'
and "AttributeError: 'unicode' object has no attribute 'strftime'

flask-moment doesn't seem to be rendering my time if I use jinja-partials

I'm using jinja partials (from Mike Kennedy) and htmx to create this app for myself: https://github.com/djotaku/taskwarrior_web/tree/main

I'm specifically using it here: https://github.com/djotaku/taskwarrior_web/blob/cd2c95ff7f15a7a422934fa40f37f7f3332d8560/taskwarrior_web/templates/partials/task_table.html

With the flask-moment in the header of https://github.com/djotaku/taskwarrior_web/blob/cd2c95ff7f15a7a422934fa40f37f7f3332d8560/taskwarrior_web/templates/layout.html

When I first load my page, it looks correct:

moment_works_on_first_load

but after I click one of the buttons which uses the jinja_partial to render a new table, it no longer does the moment conversion.

moment_no_longer_works

Is there something extra I need to do so that it works together with jinja-partials?

Moment JS is linked over HTTP when running behind HTTPS proxy

My Flask application is running behind Gunicorn and Nginx, with nginx terminating the HTTPS connection and talking to Gunicorn via regular HTTP. In this case, using 'include_moment()' (Flask-Moment v0.2.1) in my Flask application ends up with

<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/%s/moment-with-langs.min.js"></script> 

where %s is the version (Due to line 14 in flask_moment.py). This is because request.is_secure always seems to be False in this type of setup.

This causes the js not to get loaded since the browser is being asked to load the js over HTTP while the main site is served via HTTPS. I have seen that it is possible to use ProxyFix to get around this, but is there any way to resolve this just within Flask-Moment without manually editing flask_moment.py to always link to the script using HTTPS?

Understand if this might not get considered an actual bug but rather a deployment issue, but any insight would be appreciated.

High CPU load without refresh

When refresh is left disabled, flask_moment_render is constantly called by the setInterval call.
This is due to the following sequence of events:

Request the js files to be retrieved over https from the CDN

When running my app locally in development, it's running under http. This means the js files referenced by Flask-Moment are retrieved over http. This is causing problems when I run some checks with the Lighthouse tool in Chrome Dev Tools. I'd like to be able to force the js references to be via https and not via http.

I propose making a change to include_moment with an optional variable of force_https. The default will be false and the function will work as at present and use whatever the application is running under. If it's set to true then it will use https irrespective of what the application is running.

Using ES6 intead of JQuery

I think we should use ES6 instead of JQuery in the markup for now, what do you think? and I could submit a PR for this.

Correct way to disable auto-refresh

My tests show me that taking out the data-refresh attribute with jquery works, are there secondary problems when doing it that way or is is correct?

Question: is the moment object in the template not the same as the one created with the Flask app?

According to the documentation, a moment instance can be created as follows:

from flask_moment import Moment
moment = Moment(app)

And is then further initialized in the template:

{{ moment.include_moment() }}

I notice that if I rename or remove the moment variable in the python code, for example:

moment2 = Moment(app)

or simply just

Moment(app)

it still works. Are these moment objects not the same thing?

Apparently the CDN is giving 404 for the moment.js version in the package

Hi! I'm getting

DevTools failed to load SourceMap: Could not load content for http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment-with-locales.min.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE

on the browser console with latest Flask-Moment installed (0.10). The latest version on cdnjs for moment.js is 2.29.1.
Cheers!

I keep getting errors trying to format a duration

I'd like to format a number of seconds e.g. 150 seconds -> 00:02:30 using Flask-Moment

I think this should work:

{{ moment().startOf('day').seconds(s).format('H:mm:ss'); }}

but I get an error jinja2.exceptions.UndefinedError: 'flask_moment._moment object' has no attribute 'startOf'

How to use moment in macro?

I have {{ moment.include_moment() }} in base.html, but when I use moment in a macro, I get this error: UndefinedError: 'moment' is undefined.

moment(from strptime) is off by 2 hrs

When I pass a datetime.strptime(date) date to moment, it adds 2 hours. I suspect a timezone issue, as it also says I'm UTC+02:00.
{{ moment(message.sent_at).format('LLL') }} is rendered as May 15, 2017 12:10 AM
while the same {{ message.sent_at }} becomes 2017-05-14 22:10:00.

Is there a timezone setting I'm missing?

Add SRI for better security

It shouldn't be too complicated to add SRI to ensure that resources hosted on third-party servers have not been tampered with. Or am I missing something?

Greetings

Need configuration options to load JS locally

It would be great if there was an option or flag to the moment-with-langs.min.js library is loading locally, like @stynr said. For exapmle:
app.config['MOMENTJS_SERVE_LOCAL'] = True

Also, when I'm using Flask-Bootstrap I think It is not necessary to load jquery-<version>.min.js again.

ModuleNotFoundError: No module named 'packaging'

I got the following error when importing flask_moment

$ flask run                    
 * Serving Flask app 'microblog.py' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
Usage: flask run [OPTIONS]
Try 'flask run --help' for help.

Error: While importing 'microblog', an ImportError was raised:

Traceback (most recent call last):
  File "/Users/fengchuxiao/Desktop/microblog/venv/lib/python3.8/site-packages/flask/cli.py", line 214, in locate_app
    __import__(module_name)
  File "/Users/fengchuxiao/Desktop/microblog/microblog.py", line 1, in <module>
    from app import app, db
  File "/Users/fengchuxiao/Desktop/microblog/app/__init__.py", line 8, in <module>
    from flask_moment import Moment
  File "/Users/fengchuxiao/Desktop/microblog/venv/lib/python3.8/site-packages/flask_moment/__init__.py", line 2, in <module>
    from packaging.version import parse as version_parse
ModuleNotFoundError: No module named 'packaging'

I worked around the issue by manually pip install packaging. I assume you forgot to specify packaging as a dependency? I am using Flask-Moment==1.0.3.

option to load moment.js locally

rather than loading from //cdnjs.cloudflare.com/ajax/libs/moment.js/%s/moment-with-langs.min.js all the time, is there a flag for loading it locally?

Substract and add integration

Hey is it possible to add the support for using moment().substraction(7, 'days') and add? Like in the official module?

Thanks a lot and kr
flow

CSP

I added Talisman to my Flask project and tried to properly configure TALISMAN_SECURITY_POLICY but I can't figure out how to get Moment scripts accepted.

I got the following message(s): Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' cdnjs.cloudflare.com maxcdn.bootstrapcdn.com code.jquery.com 'nonce-gOu5h3Vkvkid_uTOnxjYsw'". Note that 'unsafe-inline' is ignored if either a hash or nonce value is present in the source list.

I tried to investigate things a bit further and it looks like it comes from moment.include_jquery() and moment.include_moment(). I wonder if someone (@miguelgrinberg ?) could add an option to include a SHA or a nonce to the script tag (if that's the proper way to do it) or let me know how to circumvent the issue(s).

Manually reload flask_moment_render_all when new content is loaded

I am using htmx to async load some components onto my page. The components gets loaded when in view, so it may be some time after the actual pageload. These components includes dates that I would like to render with moment. Is there any way I can re-run the flask_moment_render_all function so that these dates are being caught as well?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.