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 %}


{{ render_form(form,action=request.full_path) }}

{{ messages|length }} messages





{% endblock %}

templates/base.html






{% block title %}Say Hello!{% endblock %}







Say Hello
to the world



{% for message in get_flashed_messages() %}


{{ message }}

{% endfor %}
{% block content %}{% endblock %}

{% block footer %}
© 2018 xxx /
xxx /
xxx


{% endblock %}






{{ moment.include_moment(local_js=url_for('static', filename='js/moment-with-locales.min.js')) }}

tempates/errors/404.html

{% extends "base.html" %}

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

{% block content %}

Page Not Found


{% endblock %}

{% block footer %}
← Go Back
{% endblock %}

templates/errors/500.html

{% extends "base.html" %}

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

{% block content %}

Internal Server Error


{% endblock %}

{% block footer %}
← Go Back
{% endblock %}

static

image.png

bootstrap 版本为4

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

你可能感兴趣的:(flask 留言板(flask 39))