之前我们为了方便将几乎所有的内容都放进了app.py中,这就导致了,我们的代码乱七八糟的,导入包,视图,配置,模型类等全部在一个文件中,很不方便,于是乎,为了统一化管理,我们对该项目进行重构。
项目目录结构
目录结构:
|-1级目录
|-二级目录
|-三级目录
|-四级目录
目录如下:
|-Sample
| |-app
| | |-static
| | | |-css
| | | |-fonts
| | | |-js
| | | |-jquery.js
| | | |-jquery.min.map
| | |-templates
| | | |-includes
| | | |-base.html
| | | |-http-404.html
| | | |-index.html
| | | |-login.html
| | | |-upload.html
| | |-__init__.py
| | |-config.txt
| | |-forms.py
| | |-models.py
| | |-views.py
| |-doc
| |-test
| |-venv
| |-manager.py
| |-requirements.txt
详细内容
init.py:
# -*- coding:utf-8 -*-
from flask import Flask,render_template, redirect, flash
from werkzeug.routing import BaseConverter
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import *
from os import path
from flask_sqlalchemy import SQLAlchemy
from .views import init_views
class RegexConver(BaseConverter):
def __init__(self,url_map,*items):
super(RegexConver,self).__init__(url_map)
self.regex = items[0]
#获取绝对路径
basedir = path.abspath(path.dirname(__file__))
bootstrap = Bootstrap()
nav = Nav()
#创建数据库实体
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.url_map.converters['regex'] = RegexConver
app.config.from_pyfile('config')
app.config['BOOTSTRAP_SERVE_LOCAL'] = True
nav.register_element('top', Navbar(u"Flask入门",
View(u'主页', 'index'),
View(u'关于', 'about'),
View(u'服务', 'services'),
View(u'登录', 'login')
))
bootstrap.init_app(app)
nav.init_app(app)
db.init_app(app)
init_views(app)
# 配置数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + path.join(basedir, 'data.sqlite')
# 打开提交
app.config['SQLALCHEMY_COMMIT-OD-TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']= True
app.config['SQLALCHEMY_COMMIT_TEARDOWN '] = True
return app
config.txt:
SECRET_KEY = 'hard to guess string'
forms.py:
# -*- coding:utf-8 -*-
#导入 form类
from flask_wtf import Form
#导入字段类型
from wtforms import StringField, PasswordField,SubmitField
#导入校验器
from wtforms.validators import DataRequired
#定义表单类:LoginForm
class LoginForm(Form):
username = StringField(label = u'用户名',validators=[DataRequired()]) #用户名,不能为空
password = PasswordField(label = u'密码',validators=[DataRequired()]) #密码,不能为空
submit = SubmitField(label = u'提交')
models.py:
# -*- coding:utf-8 -*-
from . import db
#定义用户角色模型类
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String,nullable=True)
#定义实体关系
users = db.relationship('User',backref='roles')
#定义用户类
class User(db.Model):
__tabelename__ = 'users'
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String,nullable=True)
password = db.Column(db.String,nullable=True)
#定义实体关系
role_id = db.Column(db.Integer,db.ForeignKey('roles.id'))
views.py:
# -*- coding:utf-8 -*-
from flask import render_template, redirect, url_for, flash,request
from werkzeug.utils import secure_filename
from os import path
def init_views(app):
@app.route('/')
def index():
return render_template('index.html',
title='index',
data1='<div><h1>welcome to ShangHai</h1></div>',
data2="<div><h1>welcome to BeiJing</h1></div>",
data3="## markdown content")
@app.route('/services')
def services():
return 'service!'
@app.route('/about')
def about():
return 'about!'
# @app.errorhandler(404)
# def page_not_found(e):
# return render_template('http-404.html'), 404
#
# @app.errorhandler(500)
# def internal_server_error(e):
# return render_template('http-500.html'), 500
'''The parameter length must be three characters'''
@app.route('/user/<regex("[a-z]{3}"):username>')
def user(username):
return 'Username is %s' % username
@app.route('/login', methods=["GET", "POST"])
def login():
# 导入表单类
from app.forms import LoginForm
# 实例化
form = LoginForm()
flash(u"登录成功")
return render_template('login.html', title=u'登录', form=form)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
f = request.files['file']
basepath = path.abspath(path.dirname(__file__))
filename = secure_filename(f.filename)
upload_path = path.join(basepath, 'static', 'uploads', filename)
f.save(upload_path)
return redirect(url_for('upload'))
return render_template('upload.html')
@app.template_filter('md')
def markdown_to_html(txt):
from markdown import markdown
return markdown(txt)
def read_md(filename):
with open(filename) as md_file:
content = reduce(lambda x, y: x + y, md_file.readlines())
return content.decode('utf-8')
@app.context_processor
def inject_mothods():
return dict(read_md=read_md)
至此,项目重构已经基本完成