组织Flask项目

时间:2018-03-25 12:40:26

标签: python flask

这是我第一次使用python和flask创建项目。我打算也使用SQLAlchemy模型。这是一个相当大的项目。截至目前,我已将该项目分为2个蓝图:网站和api。在组织项目之后,我很困惑如何将这些模型与数据库联系起来,我是否需要重新组织结构,因为我并不完全了解烧瓶的性质。

所以这是我的基础存储库中的目录app/的目录结构:

`

.
├── Blueprints
│   ├── __init__.py
│   ├── __pycache__
│   │   └── __init__.cpython-36.pyc
│   ├── api
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-36.pyc
│   │   │   └── routes.cpython-36.pyc
│   │   └── routes.py
│   ├── config.py
│   └── site
│       ├── __init__.py
│       ├── __pycache__
│       │   ├── __init__.cpython-36.pyc
│       │   └── routes.cpython-36.pyc
│       ├── operations.py
│       ├── routes.py
│       ├── static
│       └── templates
│           ├── about.html
│           ├── contact.html
│           ├── home.html
│           ├── login.html
│           ├── services.html
│           └── stories.html
├── __main__.py
├── __pycache__
│   └── __main__.cpython-36.pyc
└── models
    ├── Attendance.py
    ├── Batch.py
    ├── Course.py
    ├── Module.py
    ├── Student.py
    ├── Test.py
    └── __init__.py

`

请忽略Pycache,因为这是自动生成的。

现在我无法找到如何在api和site中导入和使用这些模型的方法,我也无法理解我应该如何将/Blueprints/__init__.py中创建的db对象提取到所有模型

据我所知,这个问题不符合堆栈溢出问题的标准,但我个人认为组织一个烧瓶项目本身对我看到的每个教程或论坛都很困惑,有自己的组织观点。

1 个答案:

答案 0 :(得分:2)

There's several ways to organize a project, but the __init__.py file contained inside the app/ folder is what links a lot of it together. Here's the contents of one of my project's __init__.py file:

from werkzeug.contrib.fixers import ProxyFix
from flask import Flask, session
from app.config import (PERMANENT_SESSION_LIFETIME_MS, Time_Before_Warning,
                        Min_Ping_Interval)
import datetime

app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)

# Setup the app with the config.py file
app.config.from_pyfile('config.py')

# Setup the logger
from app.logger_setup import logger, log_view

# Setup the database
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)

#setup zipcode database
from pyzipcode import ZipCodeDatabase
zdb = ZipCodeDatabase()

# Setup the mail server
from flask.ext.mail import Mail
mail = Mail(app)

# Setup the debug toolbar
#from flask_debugtoolbar import DebugToolbarExtension
#app.config['DEBUG_TB_TEMPLATE_EDITOR_ENABLED'] = False
#app.config['DEBUG_TB_PROFILER_ENABLED'] = False
#toolbar = DebugToolbarExtension(app)

# Setup the password crypting
from flask.ext.bcrypt import Bcrypt
bcrypt = Bcrypt(app)

# Import the views
from app.views import (main, user, error, request, upload, dashboard, org,
                        msgs, notifications, download, reports,
                        direct_send,provider,utils)
app.register_blueprint(user.userbp)
app.register_blueprint(request.requestbp)
app.register_blueprint(upload.uploadbp)
app.register_blueprint(dashboard.dashboardbp)
app.register_blueprint(org.orgbp)
app.register_blueprint(msgs.msgbp)
app.register_blueprint(notifications.notificationsbp)
app.register_blueprint(download.downloadbp)
app.register_blueprint(reports.reportsbp)
app.register_blueprint(direct_send.directsendbp)
app.register_blueprint(provider.providerbp)
app.register_blueprint(utils.utilsbp)

# Setup the user login process
from flask.ext.login import LoginManager, current_user
from app.models import User, View

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'userbp.signin'


@login_manager.user_loader
def load_user(email):
    return User.query.filter(User.email == email).first()

from flask.ext.principal import identity_loaded, RoleNeed, UserNeed
@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):

    # Set the identity user object
    identity.user = current_user

    # Add the UserNeed to the identity
    if hasattr(current_user, 'id'):
        identity.provides.add(UserNeed(current_user.id))

    # Assuming the User model has a list of roles, update the
    # identity with the roles that the user provides
    if hasattr(current_user, 'roles'):
        identity.provides.add(RoleNeed(current_user.roles.type))

from flask.ext.principal import Principal

# load the extension
principals = Principal(app)

# Create a permission with a single Need, in this case a RoleNeed.

#from app import admin

@app.before_request
def make_session_permanent():
    session.permanent = True
    lt = PERMANENT_SESSION_LIFETIME_MS / (60*1000)
    app.permanent_session_lifetime = datetime.timedelta(minutes=lt)

@app.context_processor
def add_session_config():
    """
    Add current_app.permanent_session_lifetime converted to milliseconds
    to context.
    """
    return {
        'PERMANENT_SESSION_LIFETIME_MS': PERMANENT_SESSION_LIFETIME_MS,
        'Time_Before_Warning': Time_Before_Warning,
        'Min_Ping_Interval': Min_Ping_Interval,
    }

And then inside one of the blueprints:

from flask import (Blueprint, render_template, redirect, url_for,
                   abort, flash, request)
from flask.ext.login import login_required, current_user
from app import app, models, db, log_view, config
from app.models import (Groups, Organizations, OrgHasOwner, UserHasGroups,
                        GroupHasOwner, User, Fax, FavoriteGroups)
from app.forms import org as org_forms
from app.toolbox import email, misc, s3, fax
from sqlalchemy.sql import func
from werkzeug import secure_filename
from uuid import uuid4
import datetime
import string
import os

# Create a user blueprint
orgbp = Blueprint('orgbp', __name__, url_prefix='/org')

@orgbp.route('/invite_user', methods=['GET','POST'])
@login_required
def invite_user():
    [stuff goes here]