Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask blueprints proper usage

Tags:

I have a question regarding blueprints. I have an app which is structured like this

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

this is the code http://pastebin.com/bsHsTGAP

run.py

from overwatch import app
app.run()

__init__.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)

Thing is, I seem to be importing a lot of stuff into a lot of stuff. Right now it works. if i go to the index paged, which is handled by general.py blueprint and secured with normal_permission it redirects to /login which is handled by crud.py blueprint and if logged in redirects to index. Again, right now it... works but .. it also feels realllllllllly dirty and unclean and .. bleac... so unlike some of the good code I read :)

Any suggestions are welcome please. If this is not the way to tackle it, I'm willing to learn. I dont want to have some code that .. just works.

Thank you for your time reading this and maybe answering it.

ps. if i pasted too much code here let me know and I'll edit it out.

like image 619
pocorschi Avatar asked Aug 16 '11 21:08

pocorschi


People also ask

What are flask blueprints used for?

Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications. Blueprints can greatly simplify how large applications work and provide a central means for Flask extensions to register operations on applications.

Should I use flask blueprints?

That's all you need to know about blueprints, they're really helpful when you want to refactor your flask application and split it into smaller parts. They help you to add extra routes and functions to your application without chunking the code into a single file.

What is blueprint in flask RESTful?

A blueprint in Flask is an object to structure a Flask application into subsets. This helps in organizing code and separating functionality. For Flask-RESTful this can be used to create an application subset for your api. So for example you have a core blueprint, an auth blueprint and besides that an api blueprint.


1 Answers

To access the current application from your blueprint's views, you should use the flask.current_app object, it is a proxy to the current application (and it's what's used in flask extensions for example).

Regarding your code, except the unused imports, it's well organised in my opinion, but i can't tell about the principal part, as i've never used it.

like image 162
mdeous Avatar answered Nov 09 '22 02:11

mdeous