Flask蓝图正确使用

时间:2011-08-16 21:45:34

标签: python flask

我对蓝图有疑问。我有一个像这样结构的应用程序

app
    /run.py
    /APP
        /__init__.py
        /VIEWS
            /__init__.py
            /general.py
            /crud.py

这是代码http://pastebin.com/bsHsTGAP

run.py

from overwatch import app
app.run()

__初始化__。PY

from flask import Flask, session, g, render_template, request, redirect, url_for, Response
import websiteconfig as config
from flaskext.principal import Identity, Principal, RoleNeed, UserNeed, \
            Permission, identity_changed, identity_loaded

app = Flask(__name__)
app.debug = config.DEBUG
app.secret_key = config.SECRET_KEY


principals = Principal(app)
principals._init_app(app)
@app.errorhandler(404)
def not_found(error):
    return render_template('404.html'), 404

@app.errorhandler(403)
def page_not_found(e):
    session['redirected_from'] = request.url
    return redirect(url_for('crud.login'))

# handle login failed
@app.errorhandler(401)
def page_not_found(e):
    return Response('<p>Login failed</p>')

from overwatch.views import general
from overwatch.views import crud


app.register_blueprint(general.mod)
app.register_blueprint(crud.mod)

general.py

from flask import Blueprint, render_template, session, redirect, url_for, \
     request, flash, g, Response, jsonify
from flaskext.principal import Identity, Principal, RoleNeed, UserNeed, \
            Permission, identity_changed, identity_loaded
from .. import principals

mod = Blueprint('general', __name__)

normal_role = RoleNeed('normal')
normal_permission = Permission(normal_role)

@mod.route('/')
@normal_permission.require(http_exception=403)
def index():
    return "YOU'RE IN"

crud.py

from flask import Blueprint, render_template, session, redirect, url_for, \
     request, flash, g, Response, jsonify, abort, Response
from mongokit import Connection, Document
from db import user_exists, email_exists, return_attribute, check_credentials
from forms import RegistrationForm, LoginForm
from .. import app
from flaskext.principal import Identity, Principal, RoleNeed, UserNeed, \
            Permission, identity_changed, identity_loaded
from general import normal_role, normal_permission

mod = Blueprint('crud', __name__)

@mod.route('/login/', methods=['GET', 'POST'])
def login():
    form = LoginForm(request.form)
    error = None
    if request.method == 'POST' and form.validate():
        if check_credentials(form.username.data,form.password.data):
            identity = Identity(form.username.data)
            identity_changed.send(app, identity=identity)
            return redirect(session['redirected_from'])
        else:
            return abort(401)
    return render_template('login.html', form=form, error=error)

@app.route("/logout/")
def logout():
    for key in ['identity.name', 'identity.auth_type', 'redirected_from']:
        try:
            del session[key]
        except:
            pass
    return Response('<p>Logged out</p>')

@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
    identity.provides.add(normal_role)

事情是,我似乎将很多东西导入很多东西。现在它有效。如果我转到索引分页,由general.py蓝图处理并用normal_permission保护,它会重定向到/ login,由crud.py蓝图处理,如果登录重定向到索引。再说一遍,现在它......工作但是......它也感觉真实,很脏,不干净......漂白......所以不像我读过的一些好代码:)

欢迎任何建议。如果这不是解决问题的方法,我愿意学习。我不想要一些代码......只是有效。

感谢您抽出时间阅读本文,也许还可以回答。

PS。如果我在这里粘贴太多代码,请告诉我,我会将其编辑出来。

1 个答案:

答案 0 :(得分:21)

要从蓝图的视图中访问当前应用程序,您应该使用flask.current_app对象,它是当前应用程序的代理(例如,它是在flask扩展中使用的内容)。

关于你的代码,除了未使用的导入之外,我认为它组织得很好,但我无法分辨principal部分,因为我从未使用它。