michael oska
michael oska

Reputation: 3

How to create User class to deal with flask-form and pymysql

I'm trying to build a flask app, normally I use SQ lite with sqlalchemy, but i use flask-login to handle all the login

now I m switching to using MySQL and for the database connecter I choose to use pymysql

my problem comes when i need to use the flask-login

in my current app to handle the user, i build a base SQL

db_connect.py

import pymysql
from my_app import app

def create_db():
    db = pymysql.connect(host=app.config['MYSQL_HOST'],
                         user=app.config['MYSQL_USER'],
                         passwd=app.config['MYSQL_PASSWORD'],
                         db=app.config['MYSQL_DB'],
                         port=app.config['MYSQL_PORT'])
    try:
        print("Creating database...")
        cur = db.cursor()
        cur.execute('''
            CREATE TABLE IF NOT EXISTS users (
                    id INT PRIMARY KEY AUTO_INCREMENT,
                    user_name VARCHAR(255) NOT NULL,
                    address VARCHAR(255) NOT NULL,
                    email VARCHAR(255) NOT NULL,
                    password VARCHAR(255) NOT NULL,
                    joined_at DATE DEFAULT (CURRENT_DATE),
                    last_update DATETIME DEFAULT NOW() ON UPDATE NOW())
                    ''')
        db.commit()
        cur.close()
        print("Database created")
        app.logger.info('Database created')
        db.close()
    except pymysql.Error as e:
        print(f'Error while creating table: {e.args[0]}, {e.args[1]}')
        app.logger.error(e)





class MySqlBase:
    def __init__(self, host, user, password, db, port):
        self.host = host
        self.user = user
        self.password = password
        self.db = db
        self.port=port

    def __connection(self):
        try:
            return pymysql.connect(host=self.host, user=self.user, passwd=self.password, db=self.db, port=self.port)
        except pymysql.Error as e:
            print(f"Error while opening sql connection: {str(e)}")

    def execute(self, sql: str, args: list=None): 
        with self.__connection() as connection:
            with connection.cursor() as cursor:
                cursor.execute(sql, args)
                connection.commit()
                return cursor


    def execute_many(self, sql: str, args: list[tuple]=None):
        with self.__connection() as connection:
            with connection.cursor() as cursor:
                cursor.executemany(sql, args)
                connection.commit()
                return cursor

    def select(self, sql: str, args: list = None):
        cursor = self.execute(sql, args)
        return cursor.fetchall()

    def select_many(self, sql: str, args: list[tuple]=None):
        cursor = self.execute(sql, args)
        return cursor.fetchall()

now for the user repository class

user.py

from my_app import app
from my_app.db_connect import MySqlBase



class UserRepository(MySqlBase):
    def __init__(self):
        MySqlBase.__init__(self, app.config['MYSQL_HOST'],
                         app.config['MYSQL_USER'],
                         app.config['MYSQL_PASSWORD'],
                         app.config['MYSQL_DB'],
                         app.config['MYSQL_PORT'])


    def get(self, id):
        query = 'SELECT * FROM users WHERE id = %s'
        return self.select(query, [id])

    def get_all(self):
        query = 'SELECT * FROM users'
        return self.select(query)

    def insert(self, user_name, address, email, password):
        query = 'INSERT INTO users(user_name, address, email, password) VALUES(%s, %s, %s, %s)'
        return self.execute(query, [user_name, address, email, password])


    def update(self, id, user_name, address, email, password):
        query = 'UPDATE users SET user_name = %s, address = %s, email = %s, password = %s WHERE id = %s'
        return self.execute(query, [user_name, address, email, password, id])

    def delete(self, id):
        query = 'DELETE FROM users WHERE id = %s'
        return self.execute(query, [id])

now for the login,

i dont want to use sqlalchemy, shall i build a User class to use it with flask-login or query the database directly using my UserRepository or not use flask-login at all and use session ?

Thank you in advance

I try to use session only without flask-login, it works fine but I have to build all the functions manual

normally with sqlalchemy we built user class like this

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    email = db.Column(db.String(120), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    about_me = db.Column(db.String(140))
    last_seen = db.Column(db.DateTime, default=datetime.utcnow)

Upvotes: 0

Views: 64

Answers (0)

Related Questions