vlambda博客
学习文章列表

flask-moment显示本地时间

首先,来几句废话:能把砖烧好的人,买砖时很容易买到好砖;能把房子盖好的人,买房时也很容易买到好房;假如对编程语言的原理已经有所了解,想要快速编码,可以试试打开浏览器,搜索官方文档,然后Ctrl+C,Ctrl+V;想要找点乐子,可以关掉电脑,一个人,一本书,一把青轴键盘,乱敲一通。

下面上代码

一、moment.py

from datetime import datetimefrom flask import Flask, render_template# from flask_script import Managerfrom flask_bootstrap import Bootstrapfrom flask_moment import Momentapp = Flask(__name__)# manager = Manager(app)bootstrap = Bootstrap(app)moment = Moment(app) 
@app.errorhandler(404)def page_not_found(e): return render_template('404.html'), 404
@app.errorhandler(500)def internal_server_error(e): return render_template('500.html'), 500
@app.route('/')def index(): return render_template('index.html', current_time=datetime.utcnow())
@app.route('/user/<name>')def user(name): return render_template('user.html', name=name)
if __name__ == '__main__': app.run(debug=True)

二、index.html

{% extends "base.html" %}
{% block title %}金馆长Flask学习{% endblock %}
{% block page_content %}<div class="page-header"> <h1>欢迎来到金馆长的世界!</h1></div><p>当前时间是:{{ moment(current_time).format('LLL') }}。</p><p>这是:{{ moment(current_time).fromNow(refresh=True) }}。</p>{% endblock %}

三、user.html

{% extends "base.html" %}
{% block title %}金馆长Flasky{% endblock %}
{% block page_content %}<div class="page-header"> <h1>你好, {{ name }}!</h1></div>{% endblock %

四、base.html

{% extends "bootstrap/base.html" %}
{% block title %}金馆长{% endblock %}
{% block head %}{{ super() }}<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon"><link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">{% endblock %}
{% block navbar %}<div class="navbar navbar-inverse" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">馆内人员</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">金馆长</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="/">Home</a></li> </ul> </div> </div></div>{% endblock %}
{% block content %}<div class="container"> {% block page_content %}{% endblock %}</div>{% endblock %}
{% block scripts %}{{ super() }}{{ moment.include_moment() }}{{ moment.lang("zh-CN")}}{% endblock %}

五、404.html

{% extends "base.html" %}
{% block title %}Flasky - Page Not Found{% endblock %}
{% block page_content %}<div class="page-header"> <h1>Not Found</h1></div>{% endblock %}

六、500.html

{% extends "base.html" %}
{% block title %}Flasky - Internal Server Error{% endblock %}
{% block page_content %}<div class="page-header"> <h1>Internal Server Error</h1></div>{% endblock %}

输入http://127.0.0.1:5000/,效果如下图:

输入http://127.0.0.1:5000/user/蘑菇头,效果如下图: