def _create_storage(self):
     temp_dir = tempfile.gettempdir()
     self._dbfile = os.path.join(temp_dir, "temp.db")
     conn_string = 'sqlite:///' + self._dbfile
     engine = create_engine(conn_string)
     meta = MetaData()
     self.storage = SQLAStorage(engine, metadata=meta)
     meta.create_all(bind=engine)
Пример #2
0
 def _create_storage(self):
     temp_dir = tempfile.gettempdir()
     self._dbfile = os.path.join(temp_dir, "temp.db")
     conn_string = 'sqlite:///'+self._dbfile
     engine = create_engine(conn_string)
     meta = MetaData()
     self.storage = SQLAStorage(engine, metadata=meta)
     meta.create_all(bind=engine)
Пример #3
0
    def __repr__(self):
        return '<User %r>' % self.username

    def get_name(self):
        return self.username


class LoginForm(FlaskForm):
    username = StringField('User Name', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember_me = BooleanField('remember me', default=False)


with app.app_context():

    blog_sql_storage = SQLAStorage(db=db)
    blog_login_manager = LoginManager(app)
    blog_login_manager.session_protection = 'strong'
    blog_login_manager.login_view = 'login'
    blog_login_manager.login_message = 'Please enter your account'
    blog_login_manager.init_app(app)
    db.create_all()

blog_extns = [
    'markdown.extensions.extra', 'markdown.extensions.codehilite',
    'markdown.extensions.tables', 'markdown.extensions.toc'
]
blog_engine = BloggingEngine(app, blog_sql_storage, extensions=blog_extns)

from flask_blogging.sqlastorage import Post, Tag
Пример #4
0
from flask_principal import identity_changed, Identity, AnonymousIdentity, identity_loaded, \
    UserNeed, RoleNeed


app = Flask(__name__)
app.config["SECRET_KEY"] = "secret"  # for WTF-forms and login
app.config["BLOGGING_URL_PREFIX"] = "/blog"
app.config["BLOGGING_DISQUS_SITENAME"] = "test"
app.config["BLOGGING_SITEURL"] = "http://localhost:8000"
app.config["BLOGGING_SITENAME"] = "My Site"
app.config["BLOGGING_PERMISSIONS"] = False  # Enable blogger permissions

# extensions
engine = create_engine('sqlite:////tmp/blog.db')
meta = MetaData()
sql_storage = SQLAStorage(engine, metadata=meta)
blog_engine = BloggingEngine(app, sql_storage)
login_manager = LoginManager(app)
meta.create_all(bind=engine)

class User(UserMixin):
    def __init__(self, user_id):
        self.id = user_id

    def get_name(self):
        return "Paul Dirac"  # typically the user's name


@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
    identity.user = current_user
class TestSignals(FlaskBloggingTestCase):
    def _create_storage(self):
        temp_dir = tempfile.gettempdir()
        self._dbfile = os.path.join(temp_dir, "temp.db")
        conn_string = 'sqlite:///' + self._dbfile
        engine = create_engine(conn_string)
        meta = MetaData()
        self.storage = SQLAStorage(engine, metadata=meta)
        meta.create_all(bind=engine)

    def _create_blogging_engine(self):
        return SignalCountingBloggingEngine(self.app, self.storage)

    def tearDown(self):
        disconnect_receivers(self.app)

    def setUp(self):
        FlaskBloggingTestCase.setUp(self)
        self._create_storage()
        self.app.config["BLOGGING_URL_PREFIX"] = "/blog"
        self.app.config["BLOGGING_PLUGINS"] = ["test.plugin"]
        self.engine = self._create_blogging_engine()
        self.login_manager = LoginManager(self.app)

        @self.login_manager.user_loader
        @self.engine.user_loader
        def load_user(user_id):
            return TestUser(user_id)

        @self.app.route("/login/<username>/",
                        methods=["POST"],
                        defaults={"blogger": 0})
        @self.app.route("/login/<username>/<int:blogger>/", methods=["POST"])
        def login(username, blogger):
            this_user = TestUser(username)
            login_user(this_user)
            if blogger:
                identity_changed.send(current_app._get_current_object(),
                                      identity=Identity(username))
            return redirect("/")

        @self.app.route("/logout/")
        def logout():
            logout_user()
            identity_changed.send(current_app._get_current_object(),
                                  identity=AnonymousIdentity())
            return redirect("/")

        for i in range(20):
            tags = ["hello"] if i < 10 else ["world"]
            user = "******" if i < 10 else "newuser"
            self.storage.save_post(title="Sample Title%d" % i,
                                   text="Sample Text%d" % i,
                                   user_id=user,
                                   tags=tags)

    def test_blueprint_created_signal(self):
        with self.client:
            self.assertEqual(self.engine.ctr_blueprint_created, 1)

    def test_sitemap_signals(self):
        with self.client:
            response = self.client.get("/blog/sitemap.xml")
            self.assertEqual(response.status_code, 200)
            self.assertEqual(self.engine.ctr_sitemap_posts, 2)

    def test_feed_signals(self):
        with self.client:
            response = self.client.get("/blog/feeds/all.atom.xml")
            self.assertEqual(response.status_code, 200)
            self.assertEqual(self.engine.ctr_feed_posts_fetched, 1)
            self.assertEqual(self.engine.ctr_feed_posts_processed, 1)

    def test_index_posts_signals(self):
        with self.client:
            response = self.client.get("/blog/")
            self.assertEqual(response.status_code, 200)
            self.assertEqual(self.engine.ctr_index_posts, 2)

    def test_page_by_id_signals(self):
        with self.client:
            response = self.client.get("/blog/page/1/")
            self.assertEqual(response.status_code, 200)
            self.assertEqual(self.engine.ctr_page_by_id, 2)

    def test_posts_by_tag_signals(self):
        with self.client:
            response = self.client.get("/blog/tag/hello/")
            self.assertEqual(response.status_code, 200)
            self.assertEqual(self.engine.ctr_posts_by_tag, 2)

    def test_posts_by_author_signals(self):
        with self.client:
            response = self.client.get("/blog/author/testuser/")
            self.assertEqual(response.status_code, 200)
            self.assertEqual(self.engine.ctr_posts_by_author, 2)
Пример #6
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    SSLify(app)

    db.init_app(app)

    migrate.init_app(app, db)

    login_manager.session_protection = 'strong'
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    principal.init_app(app)

    mail.init_app(app)

    # Flask-Blogging database config
    with app.app_context():
        storage = SQLAStorage(db=db)
        db.create_all()
    blog_engine.init_app(app, storage)
    Post = storage.post_model  # the Post model class
    Tag = storage.tag_model  # the Tag model class

    misaka.init_app(app)

    def is_hidden_field_filter(field):
        return isinstance(field, HiddenField)

    app.jinja_env.globals['bootstrap_is_hidden_field'] = \
        is_hidden_field_filter

    # TODO: Move these auth handlers out of __init__.py
    @login_manager.user_loader
    @blog_engine.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))

    @login_manager.unauthorized_handler
    def handle_unauthorized():
        if session.get('_id'):
            return redirect(url_for('auth.login'))
        else:
            login_user(User().save())
            return redirect(request.url)

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        identity.user = current_user

        if hasattr(current_user, "id"):
            identity.provides.add(UserNeed(current_user.id))

        # TODO: Fully implement roles
        # # Assuming the User model has a list of roles, update the
        # # identity with the roles that the user provides
        # if hasattr(current_user, 'roles'):
        #     for role in current_user.roles:
        #         identity.provides.add(RoleNeed(role.rolename))

        # Shortcut to the above: give admins "blogger" role.
        if hasattr(current_user, "is_admin"):
            if current_user.is_admin:
                identity.provides.add(RoleNeed("blogger"))

    from .quiz import quiz as quiz_blueprint
    app.register_blueprint(quiz_blueprint)

    from .dashboard import dashboard as dashboard_blueprint
    app.register_blueprint(dashboard_blueprint)

    from .topic import topic as topic_blueprint
    app.register_blueprint(topic_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')

    from .utils import utils as utils_blueprint
    app.register_blueprint(utils_blueprint)

    from .profile import profile as profile_blueprint
    app.register_blueprint(profile_blueprint)

    from .store import store as store_blueprint
    app.register_blueprint(store_blueprint)

    from .misc import misc as misc_blueprint
    app.register_blueprint(misc_blueprint)

    from .activity import activity as activity_blueprint
    app.register_blueprint(activity_blueprint)

    class AuthenticatedAdminIndex(AdminIndexView):
        @expose('/')
        def index(self):
            if not current_user.is_authenticated:
                return redirect(url_for('auth.login', next=request.url))
            if not current_user.is_admin:
                return redirect(url_for('dashboard.dashboard'))
            return super(AuthenticatedAdminIndex, self).index()

    # Initialise flask-admin
    admin = Admin(
        app,
        name=app.config.get('SITE_NAME'),
        template_mode='bootstrap3',
        base_template='admin_base.html',
        index_view=AuthenticatedAdminIndex()
    )

    class AuthenticatedModelView(ModelView):
        def is_accessible(self):
            return current_user.is_authenticated and current_user.is_admin

        def inaccessible_callback(self, name, **kwargs):
            # redirect to login page if user doesn't have access
            return redirect(url_for('auth.login', next=request.url))

        column_exclude_list = ('password_hash')

    # Add administrative views here
    admin.add_view(AuthenticatedModelView(User, db.session))
    admin.add_view(AuthenticatedModelView(Topic, db.session, endpoint="admin_topic"))
    admin.add_view(AuthenticatedModelView(Quiz, db.session, endpoint="admin_quiz"))
    admin.add_view(AuthenticatedModelView(Sentence, db.session))
    admin.add_view(AuthenticatedModelView(Answer, db.session))
    admin.add_view(AuthenticatedModelView(Score, db.session))
    admin.add_view(AuthenticatedModelView(Product, db.session))
    admin.add_view(AuthenticatedModelView(Purchase, db.session))
    admin.add_view(AuthenticatedModelView(Post, db.session, name='Post'))
    admin.add_view(AuthenticatedModelView(Tag, db.session, name='Tag'))
    admin.add_view(AuthenticatedModelView(Comment, db.session))
    admin.add_view(AuthenticatedModelView(Activity, db.session, endpoint="admin_activity"))

    return app
Пример #7
0
def configure_blogging(app):
    app.config["SECRET_KEY"] = "secret"  # for WTF-forms and login
    app.config["BLOGGING_URL_PREFIX"] = "/blog"
    app.config["BLOGGING_DISQUS_SITENAME"] = "test"
    app.config["BLOGGING_SITEURL"] = "http://localhost:8989"
    app.config["BLOGGING_SITENAME"] = "BieFeNg"
    app.config["BLOGGING_KEYWORDS"] = ["blog", "meta", "keywords"]
    app.config["FILEUPLOAD_IMG_FOLDER"] = "fileupload"
    app.config["FILEUPLOAD_PREFIX"] = "/fileupload"
    app.config["FILEUPLOAD_ALLOWED_EXTENSIONS"] = ["png", "jpg", "jpeg", "gif"]

    with app.app_context():
        sql_storage = SQLAStorage(db=db)
    blog_engine = BloggingEngine(app=None, storage=sql_storage)
    login_manager = LoginManager(app)

    # blog_engine.init_app(app, sql_storage)

    class User(UserMixin):
        def __init__(self, user_id):
            self.id = user_id

        def get_name(self):
            return "Paul Dirac"  # typically the user's name

    @login_manager.user_loader
    @blog_engine.user_loader
    def load_user(user_id):
        return User(user_id)

    index_template = """
    <!DOCTYPE html>
    <html>
        <head> </head>
        <body>
            {% if current_user.is_authenticated %}
                <a href="/logout/"> Logout </a>
            {% else %}
                <a href="/login/"> Login </a>
            {% endif %}
            &nbsp&nbsp<a href="/blog/"> Blog </a>
            &nbsp&nbsp<a href="/blog/sitemap.xml">Sitemap</a>
            &nbsp&nbsp<a href="/blog/feeds/all.atom.xml">ATOM</a>
            &nbsp&nbsp<a href="/fileupload/">FileUpload</a>
        </body>
    </html>
    """

    @app.route("/")
    def index():
        return render_template_string(index_template)

    @app.route("/login/")
    def login():
        user = User("testuser")
        login_user(user)
        return redirect("/blog")

    @app.route("/logout/")
    def logout():
        logout_user()
        return redirect("/")
Пример #8
0
class TestSignals(FlaskBloggingTestCase):

    def _create_storage(self):
        temp_dir = tempfile.gettempdir()
        self._dbfile = os.path.join(temp_dir, "temp.db")
        conn_string = 'sqlite:///'+self._dbfile
        engine = create_engine(conn_string)
        meta = MetaData()
        self.storage = SQLAStorage(engine, metadata=meta)
        meta.create_all(bind=engine)

    def _create_blogging_engine(self):
        return SignalCountingBloggingEngine(self.app, self.storage)

    def tearDown(self):
        disconnect_receivers(self.app)

    def setUp(self):
        FlaskBloggingTestCase.setUp(self)
        self._create_storage()
        self.app.config["BLOGGING_URL_PREFIX"] = "/blog"
        self.app.config["BLOGGING_PLUGINS"] = ["test.plugin"]
        self.engine = self._create_blogging_engine()
        self.login_manager = LoginManager(self.app)

        @self.login_manager.user_loader
        @self.engine.user_loader
        def load_user(user_id):
            return TestUser(user_id)

        @self.app.route("/login/<username>/", methods=["POST"],
                        defaults={"blogger": 0})
        @self.app.route("/login/<username>/<int:blogger>/", methods=["POST"])
        def login(username, blogger):
            this_user = TestUser(username)
            login_user(this_user)
            if blogger:
                identity_changed.send(current_app._get_current_object(),
                                      identity=Identity(username))
            return redirect("/")

        @self.app.route("/logout/")
        def logout():
            logout_user()
            identity_changed.send(current_app._get_current_object(),
                                  identity=AnonymousIdentity())
            return redirect("/")

        for i in range(20):
            tags = ["hello"] if i < 10 else ["world"]
            user = "******" if i < 10 else "newuser"
            self.storage.save_post(title="Sample Title%d" % i,
                                   text="Sample Text%d" % i,
                                   user_id=user, tags=tags)

    def test_blueprint_created_signal(self):
        with self.client:
            self.assertEqual(self.engine.ctr_blueprint_created, 1)

    def test_sitemap_signals(self):
        with self.client:
            response = self.client.get("/blog/sitemap.xml")
            self.assertEqual(response.status_code, 200)
            self.assertEqual(self.engine.ctr_sitemap_posts, 2)

    def test_feed_signals(self):
        with self.client:
            response = self.client.get("/blog/feeds/all.atom.xml")
            self.assertEqual(response.status_code, 200)
            self.assertEqual(self.engine.ctr_feed_posts_fetched, 1)
            self.assertEqual(self.engine.ctr_feed_posts_processed, 1)

    def test_index_posts_signals(self):
        with self.client:
            response = self.client.get("/blog/")
            self.assertEqual(response.status_code, 200)
            self.assertEqual(self.engine.ctr_index_posts, 2)

    def test_page_by_id_signals(self):
        with self.client:
            response = self.client.get("/blog/page/1/")
            self.assertEqual(response.status_code, 200)
            self.assertEqual(self.engine.ctr_page_by_id, 2)

    def test_posts_by_tag_signals(self):
        with self.client:
            response = self.client.get("/blog/tag/hello/")
            self.assertEqual(response.status_code, 200)
            self.assertEqual(self.engine.ctr_posts_by_tag, 2)

    def test_posts_by_author_signals(self):
        with self.client:
            response = self.client.get("/blog/author/testuser/")
            self.assertEqual(response.status_code, 200)
            self.assertEqual(self.engine.ctr_posts_by_author, 2)
Пример #9
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)

    migrate = Migrate()
    migrate.init_app(app, db=db)

    login_manager.session_protection = 'strong'
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    principal = Principal()
    principal.init_app(app)

    from app.models import User, Sentence, Quiz, Answer

    # Flask-Blogging database config
    with app.app_context():
        storage = SQLAStorage(db=db)
        db.create_all()
        blog_engine = BloggingEngine()
        blog_engine.init_app(app, storage)

    misaka = Misaka(app=None,
                    renderer=None,
                    strikethrough=True,
                    underline=True,
                    tables=True,
                    wrap=True)
    misaka.init_app(app)

    from wtforms.fields import HiddenField

    def is_hidden_field_filter(field):
        return isinstance(field, HiddenField)

    app.jinja_env.globals['bootstrap_is_hidden_field'] = \
        is_hidden_field_filter

    # TODO: Move these auth handlers out of __init__.py
    @login_manager.user_loader
    # @blog_engine.user_loader
    def load_user(user_id):
        print "ID: ", user_id
        return User.query.get(int(user_id))

    @login_manager.unauthorized_handler
    def handle_unauthorized():
        if session.get('_id'):
            return redirect(url_for('auth.login'))
        else:
            login_user(User().save())
            return redirect(request.url)

    @identity_loaded.connect_via(app)
    def on_identity_loaded(sender, identity):
        identity.user = current_user

        if hasattr(current_user, "id"):
            identity.provides.add(UserNeed(current_user.id))

        # Shortcut to the give admins "blogger" role.
        if hasattr(current_user, "is_admin"):
            if current_user.is_admin:
                identity.provides.add(RoleNeed("blogger"))

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    # Initialise flask-admin
    admin = Admin(app, template_mode='bootstrap3', index_view=AdminIndexView())
    Post = storage.post_model
    # Add administrative views here
    admin.add_view(ModelView(User, db.session))
    admin.add_view(ModelView(Post, db.session))

    return app
Пример #10
0
app = Flask(__name__)
app.config["SECRET_KEY"] = "secret"  # for WTF-forms and login
app.config["BLOGGING_URL_PREFIX"] = "/blog"
app.config["BLOGGING_DISQUS_SITENAME"] = "test"
app.config["BLOGGING_SITEURL"] = "http://localhost:8000"
app.config["BLOGGING_SITENAME"] = "Krishna Kumar"
app.config["FILEUPLOAD_IMG_FOLDER"] = "fileupload"
app.config["FILEUPLOAD_PREFIX"] = "/fileupload"
app.config["FILEUPLOAD_ALLOWED_EXTENSIONS"] = ["png", "jpg", "jpeg", "gif"]
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ['DATABASE_URL']

#export DATABASE_URL="postgresql://localhost/blog"

db = SQLAlchemy(app)
storage = SQLAStorage(db=db)
#db.create_all()

blog_engine = BloggingEngine(app, storage)
login_manager = LoginManager(app)


class User(UserMixin):
    def __init__(self, user_id):
        self.id = user_id

    def get_name(self):
        return "Krishna Kumar"  # typically the user's name


def get_quotes():
def create_app(config=None):
    """Create a Flask applicationlicaction.
    """
    # Instantiate Flask
    application = Flask(__name__)

    # Load application Config settings
    if config is not None:
        application.config.from_object('config.Config')

    # Setup Flask-SQLAlchemy
    db.init_app(application)

    # Setup Flask-Migrate
    migrate.init_app(application, db)
    
    # Setup Heroku
    heroku = Heroku(application)

    # Setup Flask-Mail
    mail.init_app(application)
    
    # Setup Flask-Principal
    principal.init_app(application)
    
    # Setup WTForms CSRFProtect
    csrf_protect.init_app(application)
        
    # Setup Flask-Blogging
    with application.app_context():
        storage = SQLAStorage(db=db)
        db.create_all()
        blog_engine.init_app(application, storage)
        
    from application.models.user_models import User
    @blog_engine.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))       

    @identity_loaded.connect_via(application)
    def on_identity_loaded(sender, identity):
        identity.user = current_user
        if hasattr(current_user, "id"):
            identity.provides.add(UserNeed(current_user.id))
        # Shortcut to the give admins "blogger" role.
        #if hasattr(current_user, "is_admin"):
            #if current_user.is_admin:
                #identity.provides.add(RoleNeed("blogger"))
        if hasattr(current_user, 'roles'):
            for role in current_user.roles:
                identity.provides.add(RoleNeed(role.name))
    # Register blueprints
    from application.views.misc_views import main_blueprint
    application.register_blueprint(main_blueprint)

    # Define bootstrap_is_hidden_field for flask-bootstrap's bootstrap_wtf.html
    from wtforms.fields import HiddenField

    def is_hidden_field_filter(field):
        return isinstance(field, HiddenField)

    application.jinja_env.globals['bootstrap_is_hidden_field'] = is_hidden_field_filter

    # Setup an error-logger to send emails to application.config.ADMINS
    init_email_error_handler(application)

    # Setup Flask-User to handle user account related forms
    from .models.user_models import User, Role, MyRegisterForm

    db_adapter = SQLAlchemyAdapter(db, User)  # Setup the SQLAlchemy DB Adapter
    user_manager = UserManager(db_adapter, application,  # Init Flask-User and bind to application
                               register_form=MyRegisterForm)
    # Create admin
    global admin
    admin = flask_admin.Admin(application, 'Admin manager', template_mode='bootstrap3',)
    from .models.user_models import UserModelView,PostModelView, RoleModelView
    Post = storage.post_model
    admin.add_view(UserModelView(User, db.session))
    #admin.add_view(RoleModelView(Role, db.session))
    #admin.add_view(sqla.ModelView(Role, db.session))
    admin.add_view(PostModelView(Post, db.session))  
    admin.add_link(MenuLink(name='Index', category='Index', url='../'))  
    
    return application