flask 留言板(flask 39)

image.png

views.py

from flask import flash,render_template,redirect,url_for
from app import app,db
from models import Message
from forms import HelloForm

@app.route('/',methods=['GET','POST'])
def index():
messages=Message.query.order_by(Message.timestamp.desc()).all()
form=HelloForm()
if form.validate_on_submit():
name=form.name.data
body=form.body.data
message=Message(body=body,name=name)
db.session.add(message)
db.session.commit()
flash('Your message have been sent to the world!')
return redirect(url_for('index'))
return render_template('index.html',form=form,messages=messages)

settings.py

import os
import sys

from app import app

SQLite URI compatible

WIN = sys.platform.startswith('win')
if WIN:
prefix = 'sqlite:///'
else:
prefix = 'sqlite:////'

dev_db = prefix + os.path.join(os.path.dirname(app.root_path), 'data.db')

SECRET_KEY = os.getenv('SECRET_KEY', 'secret string')
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URI', dev_db)

models.py

from datetime import datetime
from app import db

class Message(db.Model):
id=db.Column(db.Integer,primary_key=True)
body=db.Column(db.String(200))
name=db.Column(db.String(20))
timestamp=db.Column(db.DateTime,default=datetime.now,index=True)

forms.py

from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField,TextAreaField
from wtforms.validators import DataRequired,Length

class HelloForm(FlaskForm):
name=StringField("Name",validators=[DataRequired(message="name must be not empty"),Length(1,20)])
body=TextAreaField("Message",validators=[DataRequired(message="message must be not empty"),Length(1,200)])
submit=SubmitField()

errors.py

from flask import render_template
from app import app

@app.errorhandler(404)
def page_not_found(e):
return render_template('errors/404.html'), 404

@app.errorhandler(500)
def internal_server_error(e):
return render_template('errors/500.html'), 500

commands.py

from app import db,manager
from faker import Faker
from models import Message

@manager.command
def hell():
print("hello")

@manager.option('-c','--count',dest='count',default=20,help='Quantity of messages,default is 20.')
def forge(count):
db.drop_all()
db.create_all()

faker=Faker()
print('Working...')

for i in range(int(count)):
    message=Message(name=faker.name(),body=faker.sentence(),
                    timestamp=faker.date_time_this_year())
    db.session.add(message)
db.session.commit()
print('Create %d fake messages' % int(count))

app.py

from flask import Flask
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager

app = Flask('sayhello')
app.config.from_pyfile('settings.py')
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True

db = SQLAlchemy(app)
bootstrap = Bootstrap(app)
moment = Moment(app)
manager=Manager(app)

import views, errors
from commands import *

if name == 'main':
manager.run()

.flaskenv

FLASK_APP=sayhello
FLASK_ENV=development

templates/index.html

{% extends "base.html" %}
{% from 'bootstrap/form.html' import render_form %}
{% block content %}
<div class="hello-form">
{{ render_form(form,action=request.full_path) }}
</div>
<h5>{{ messages|length }} messages
<small class="float-right">
<a href="#bottom" title="Go Bottom">↓</a>
</small>
</h5>
<div class="list-group">
{% for message in messages %}
<a class="list-group-item list-group-item-action flex-column">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1 text-success">{{ message.name }}
<small class="text-muted"> #{{ loop.revindex }}</small>
</h5>
<small data-toggle="tooltip" data-placement="top"
data-timestamp="{{ message.timestamp.strftime('%Y-%m-%dT%H:%M:%SZ') }}"
data-delay="500">
{{ moment(message.timestamp).fromNow(refresh=True) }}
</small>
</div>
<p class="mb-1">{{ message.body }}</p>
</a>
{% endfor %}
</div>
{% endblock %}

templates/base.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>{% block title %}Say Hello!{% endblock %}</title>
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}" type="text/css">
</head>
<body>
<main class="container">
<header>
<h1 class="text-center display-4">
<a href="{{ url_for('index') }}" class="text-success"><strong>Say Hello</strong></a>
<small class="text-muted sub-title">to the world</small>
</h1>
</header>
{% for message in get_flashed_messages() %}
<div class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ message }}
</div>
{% endfor %}
{% block content %}{% endblock %}
<footer class="text-center">
{% block footer %}
<small> © 2018 <a href="xxxxxxxxxx" title="xxxxxxxx">xxx</a> /
<a href="xxxxxxxxxxxxxxx" title="xxxxxxx">xxx</a> /
<a href="xxxxxxxx" title="xxxx">xxx</a>
</small>
<p><a id="bottom" href="#" title="Go Top">↑</a></p>
{% endblock %}
</footer>
</main>
<script type="text/javascript" src="{{ url_for('static', filename='js/jquery-3.2.1.slim.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/popper.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='js/script.js') }}"></script>
{{ moment.include_moment(local_js=url_for('static', filename='js/moment-with-locales.min.js')) }}
</body>
</html>

tempates/errors/404.html

{% extends "base.html" %}

{% block title %}404 Error{% endblock %}

{% block content %}
<p class="text-center">Page Not Found</p>
{% endblock %}

{% block footer %}
<a href="{{ url_for('index') }}">← Go Back</a>
{% endblock %}

templates/errors/500.html

{% extends "base.html" %}

{% block title %}500 Error{% endblock %}

{% block content %}
<p class="text-center">Internal Server Error</p>
{% endblock %}

{% block footer %}
<a href="{{ url_for('index') }}">← Go Back</a>
{% endblock %}

static

image.png

bootstrap 版本为4

转载自:https://github.com/greyli

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,099评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,473评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,229评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,570评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,427评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,335评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,737评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,392评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,693评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,730评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,512评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,349评论 3 314
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,750评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,017评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,290评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,706评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,904评论 2 335

推荐阅读更多精彩内容