DEV Community

InterSystems Developer for InterSystems

Posted on • Originally published at community.intersystems.com

InterSystems IRIS Flask Blog application

main

 

 

Hi Community

In this article, I will introduce my application IRIS-FlaskBlog.

IRIS-FlaskBlog Application is a real-world application that leverages the functionality of Flask web framework, SQLALchemy ORM, and InterSystems IRIS. The application contains user registration and authentication with the help of Flask-Login python library, a responsive user interface to create and edit posts.

 

Application Features

  • User registration and authentication
  • Creation of a data structure with SQLALcemy model classes
  • Responsive user interface to create, edit, and delete posts
  • Like and add comments to the post
  • Search based on the user and based on the tags

Used Technologies

  • Flask: A micro web framework for Python that allows you to build web applications quickly and efficiently.Conduit
  • SQLAlchemy: An Object-Relational Mapping (ORM) library that provides a high-level, Pythonic interface for interacting with databases.
  • InterSystems IRIS: A high-performance, data platform that combines a powerful database with integration, analytics, and AI capabilities.

Installation

  1. Clone/git pull the repo into any local directory
git clone https://github.com/mwaseem75/IRIS-FlaskBlog.git
  1. Open a Docker terminal in this directory and run:
docker-compose build
  1. Run the IRIS container:
docker-compose up -d

Application Flow

In the docker, ENTRYPOINT [ "python", "app.py" ] is defined which will initiate the application  (The ENTRYPOINT instruction is used to configure the executables that will always run after the container is initiated)

# app.py
# import create_app from website package
from website import create_app
# import configuration parameters
from website.myconfig import *

if __name__ == "__main__":
    # Get db parameters and creating to create_app in order to create DB
    database_uri = f'iris://{DB_USER}:{DB_PASS}@{DB_URL}:{DB_PORT}/{DB_NAMESPACE}'
    app = create_app(database_uri)
    app.run('0.0.0.0', port="4040", debug=False)

The above code invokes create_app() function and then runs the application on port 4040

create_app() function is defined in \__init__.py file

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from .myconfig import *

db = SQLAlchemy()

def create_app(database_uri):
    #Import flask application
    app = Flask(__name__)
    app.config['SECRET_KEY'] = "iris-FlaskBlogKey"
    # assigning db parameters
    app.config['SQLALCHEMY_DATABASE_URI'] = database_uri
    #create and push an application context onto the application context stack
    app.app_context().push()

    from .views import views
    from .auth import auth
    from .models import User
    app.register_blueprint(views, url_prefix="/")
    app.register_blueprint(auth, url_prefix="/")

    db.init_app(app)

    with app.app_context():
        #Create database
        db.create_all()

    # Assign Login View
    login_manager = LoginManager()
    login_manager.login_view = "auth.login"
    login_manager.init_app(app)
    
    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    return app

The above code creates the database by invoking SQLAlchemy create_all() function which will create the database structure defined in the models.py file

from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func

#creates tags_accosication table
tags_table = db.Table(
    'tags_association',
    db.Column('post_id', db.ForeignKey('post.id'), primary_key=True),
    db.Column('tag_id', db.ForeignKey('tag.id'), primary_key=True),
)

#Users table
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(150), unique=True)
    username = db.Column(db.String(150), unique=True)
    password = db.Column(db.String(150))
    date_created = db.Column(db.DateTime(timezone=True), default=func.now())
    posts = db.relationship('Post', backref='user', passive_deletes=True)
    comments = db.relationship('Comment', backref='user', passive_deletes=True)
    likes = db.relationship('Like', backref='user', passive_deletes=True)

def __repr__(self):
        return f'{self.username}'
#Posts Table
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(250))
    content = db.Column(db.Text)
    date_created = db.Column(db.DateTime(timezone=True), default=func.now())
    author = db.Column(db.Integer, db.ForeignKey(
        'user.id', ondelete="CASCADE"), nullable=False)
    comments = db.relationship('Comment', backref='post', passive_deletes=True)
    likes = db.relationship('Like', backref='post', passive_deletes=True)
    tags = db.relationship('Tag', secondary=tags_table,
                           backref=db.backref('posts', lazy='dynamic'))


    def __repr__(self):
        user = User.query.filter_by(id=self.author).first()
        return f'{user.username}'
#Tags table
class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(150))

    def __repr__(self):
        return f'{self.name}'
#Comments table
class Comment(db.Model)&:
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.String(500), nullable=False)
    date_created = db.Column(db.DateTime(timezone=True), default=func.now())
    author = db.Column(db.Integer, db.ForeignKey(
        'user.id'&, ondelete=&"CASCADE"), nullable=False)
    post_id = db.Column(db.Integer, db.ForeignKey(
        'post.id', ondelete="CASCADE"), nullable=False)

#Like table
class Like(db.Model):
    id = db.Column(db.Integer, primary_key=True&)
    date_created = db.Column(db.DateTime(timezone=True), default=func.now())
    author = db.Column(db.Integer, db.ForeignKey(
        'user.id', ondelete="CASCADE"), nullable=False&)
    post_id = db.Column(db.Integer, db.ForeignKey(
        'post.id', ondelete="CASCADE"), nullable=False)

Application Database

SQLALchemy will create below tables:

  • user: To store User information
  • post: To store Posts related data
  • tags: To store Tags against the post
  • tags_association: To store links between Posts and Tags
  • comments: To save post comments by users
  • like: To store likes details by users

To view table details, navigate to http://localhost:52775/csp/sys/exp/%25CSP.UI.Portal.SQL.Home.zen?$NAMESPACE=USER#

image

For more details please visit IRIS-FlaskBlog application page


Thanks

Top comments (0)