首页 > 其他 > 详细

目前flask程序结构

时间:2019-11-01 23:49:02      阅读:99      评论:0      收藏:0      [点我收藏+]

1、程序目录结构

技术分享图片

 

 

2、hello.py

from flask import Flask,request,make_response,redirect,render_template,session,url_for,flash,abort
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField,validators
#from wtforms.validators import Required
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager,Shell
from flask_migrate import Migrate, MigrateCommand
import os
from flask_mail import Mail,Message
from threading import Thread


app = Flask(__name__)
app.config[SQLALCHEMY_DATABASE_URI] = sqlite:///data.sqlite
app.config[SQLALCHEMY_COMMIT_ON_TEARDOWN] = True
app.config["SECRET_KEY"] = "123456"
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command(db, MigrateCommand)

app.config[MAIL_SERVER] = smtp.qq.com
app.config[MAIL_PORT] = 465
app.config[MAIL_USE_TLS] = False
app.config[MAIL_USE_SSL] = True
app.config[MAIL_USERNAME] = ******@qq.com
app.config[MAIL_PASSWORD] = *******
mail = Mail(app)

app.config[FLASKY_MAIL_SUBJECT_PREFIX] = [Flasky]
app.config[FLASKY_MAIL_SENDER] = ‘*****@qq.com
app.config[FLASKY_ADMIN] = ******@qq.com

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

def send_mail(to, subject, template, **kwargs):
    msg = Message(app.config[FLASKY_MAIL_SUBJECT_PREFIX] + subject, sender=app.config[FLASKY_MAIL_SENDER], recipients=[to])
    msg.body = render_template(template + .txt, **kwargs)
    msg.html = render_template(template + .html, **kwargs)
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr

#为shell命令添加一个上下文
def make_shell_context():
    return dict(app=app, db=db, User=User, Role=Role)
manager.add_command("shell", Shell(make_context=make_shell_context))


#定义数据库模型
class Role(db.Model):
    __tablename__ = roles
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    users = db.relationship(User, backref=role)

    def __repr__(self):
        return <Role %r> %self.name


class User(db.Model):
    __tablename__ = users
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    role_id = db.Column(db.Integer, db.ForeignKey(roles.id))

    def __repr__(self):
        return <User %r> %self.username

class NameForm(FlaskForm):
    name = StringField(what is your name?, validators=[validators.input_required()])
    submit = SubmitField(Submit)



@app.route(/, methods=[GET, POST])
def index():
    form = NameForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.name.data).first()
        if user is None:
            user = User(username=form.name.data)
            db.session.add(user)
            session[known] = False
            if app.config[FLASKY_ADMIN]:
                send_mail(app.config[FLASKY_ADMIN], New User, mail/new_user, user=user)
        else:
            session[known] = True
        session[name] = form.name.data
        form.name.data = ‘‘
        return redirect(url_for(index))
    return render_template(index.html, form = form, name = session.get(name), known = session.get(known, False))


@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(/user/<name>)
def user(name):
    return render_template(user.html, name=name)


@app.route(/user/<id>)
def get_user(id):
    user = load_user(id)
    if not user:
        abort(404)
    return <h1>Hello, %s</h1> % user.name


if __name__ == __main__:
    bootstrap.run()
    manager.run()

 

2、base.html

{% extends "bootstrap/base.html" %}

{% block title %}Flasky{% 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">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">Flask</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">
    {% for message in get_flashed_messages() %}
    <div class="alert alert-warning">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        {{ message }}
    </div>
    {% endfor %}

    {% block page_content %}{% endblock %}
    </div>
{% endblock %}

 

3、index.html

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf%}

{% block title %}Flasky{% endblock %}

{% block page_content %}
<div class="page-header">
    <h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}</h1>
    {% if not known %}
    <p>Pleased to meet you!</p>
    {% else %}
    <p>Happy to see you again!</p>
    {% endif %}
</div>
{{ wtf.quick_form(form)}}
{% endblock %}

 

4、user.html

{% extends "base.html" %}

{% block title %}Flasky{% endblock %}

{ % block page_content %}
<div class="page-header">
    <h1>Hello, {{ name }}!</h1>
</div>
{% endblock %}

 

5、404.html

{% extends "base.html" %}

{% block tittle %}Flasky - Page Not Found{% endblock %}

{% block page_content %}
<div class="page-header">
    <h1>Not Found</h1>
</div>
{% endblock %}

 

6、500.html

{% extends "base.html" %}

{% block tittle %}Flasky - Internal Server Error{% endblock %}

{% block page_content %}
<div class="page-header">
    <h1>Internal Server Error</h1>
</div>
{% endblock %}

 

7、new_user.html

User <b>{{ user.username }}</b> has joined.

 

8、new_user.txt

User {{ user.username }} has joined.

 

目前flask程序结构

原文:https://www.cnblogs.com/lw-monster/p/11779959.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!