Flask 的项目架构

(flask_env) fy@fy-Box:~/py_project/blog$ tree
.
├── app
│   ├── blog
│   │   ├── errors.py
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── errors.cpython-35.pyc
│   │   │   ├── __init__.cpython-35.pyc
│   │   │   └── views.cpython-35.pyc
│   │   └── views.py
│   ├── __init__.py
│   ├── __pycache__
│   │   └── __init__.cpython-35.pyc
│   ├── static
│   │   ├── css
│   │   ├── img
│   │   └── js
│   └── templates
│   ├── 404.html
│   ├── 500.html
│   ├── base.html
│   └── blog
│   └── index.html
├── config.py
├── manage.py
├── __pycache__
│   └── config.cpython-35.pyc
└── requirements.txt

11 directories, 16 files

app 目录

app 目录是Flask 的应用目录,里边包括templates\static和一些蓝图,蓝图可以有多个,但这里只有blog一个,蓝图里就是一些视图函数。

app/init.py
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy

# 导入配置文件
from config import config

bootstrap = Bootstrap()
db = SQLAlchemy()

def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)

bootstrap.init_app(app)
db.init_app(app)

# Bluerpint
from .blog import blog as blog_blueprint
app.register_blueprint(blog_blueprint)
return app

blog/config.py

import os

base_dir = os.path.abspath(os.path.dirname(__file__))

class Config(object):
'''
Base Config
'''
SECRET_KEY = 'ABCDEFG'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = True

@staticmethod
def init_app(app):
pass

class DevConfig(Config):
'''
Development Config
'''
DEBUG = True
HOST = '0.0.0.0'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(base_dir, 'data-dev.sqlite')

config = {
'development': DevConfig,
'default': DevConfig
}

blog/manage.py

import os
from app import create_app
from flask_script import Manager

app = create_app('default')
manage = Manager(app)

if __name__ == '__main__':
manage.run()

app/blog/init.py

from flask import Blueprint

blog = Blueprint('blog', __name__)

from . import views, errors

app/blog/errors.py

from flask import render_template
from . import blog

@blog.app_errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404

@blog.app_errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500

app/blog/views.py

from flask import render_template

from . import blog

@blog.route('/')
def index():
return render_template('blog/index.html')
templstes/base.html
{% extends "bootstrap/base.html" %}
{% block title %}疯影{% endblock %}

{% block content %}
<div class="container">
{% block page_content %}base.html{% endblock %}
</div>
{% endblock content %}

 

 

评论

  • 还没有任何评论,来说两句吧。

  • 0%