一、单模块结构
myapp/app.py
from flask import Flask,render_template
import settings
app = Flask(__name__)
app.config.from_object(settings.BaseConfig)
@app.route('/index')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run()
settings.py
class BaseConfig():
DEBUG = True
SECRET_KEY = 'base'
class testConfig(BaseConfig):
SECRET_KEY = 'test'
class preConfig(BaseConfig):
DEBUG = False
SECRET_KEY = 'pre'
二、简单项目结构(使用蓝图进行目录结构划分——常用)
myapp/__init__.py
from flask import Flask
from . import settings
from .views import index, login
app = Flask(__name__)
# 导入配置
app.config.from_object(settings.BaseConfig)
# 蓝图注册
app.register_blueprint(login.lg)
app.register_blueprint(index.ide)
myapp/views/index.py
from flask import Blueprint,redirect,url_for
ide = Blueprint('index',__name__)
@ide.route('/index')
def index():
return '首页'
@ide.route('/x1')
def x1():
return redirect(url_for('lg.x2'))
myapp/views/login.py
from flask import Blueprint,render_template
lg = Blueprint('lg',__name__)
@lg.route('/login')
def login():
return render_template('login')
@lg.route('/logout')
def logout():
return '登出'
@lg.route('/x2')
def x2():
return '跳转成功'
manage.py
from myapp import app
if __name__ == '__main__':
app.run()
三、官网项目结构
myapp/__init__.py
import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, World!'
return app