0

I am beyond confused at this point. I have read so much documentation and there seems to be sparse examples of what to do for running raw SQL statements on my flask app using Flask_sqlalchemy or flask_mysqldb.

I have started by downloading XAMPP and creating a database on MySQL server through my localhost. I then created my flask application and created an initial database from the terminal using

>>> from yourapplication import db
>>> db.create_all()

The code from my flask app is as follows based on the documentation here

from flask import Flask, render_template, request, redirect, session
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

from werkzeug.security import check_password_hash, generate_password_hash


# Set up Flask instance 
app = Flask(__name__)

# Configure db
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root@localhost/hoook"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)

# Reload templates when changed (take down when in production)
app.config["TEMPLATES_AUTO_RELOAD"] = True

# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Create db model
class Users(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.Text, nullable=False)
    last_name = db.Column(db.Text, nullable=False)
    email = db.Column(db.Text, unique=True, nullable=False)
    password = db.Column(db.Text, nullable=False)
    date = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self):
        return "<Users %r>" % self.id

great, now I can see my table in myPhpAdmin. I then ran a test statement to see if information would be added as follows

db.engine.execute("INSERT INTO users (first_name, last_name, email, password) VALUES ('chris', 'blah', 'blah@gmail.com', 'something')")

works! but then looking at the previous stackoverflow answer and then the subsequent documentation I find this method is depreciated therefore I cant use this going forward. So I try to use session.execute instead (since connection.execute also shows its depreciated) as I see that for some reason there are three different methods all with the same function execute() that can be used...???? source. So using the following statement I try to add another row to my table but it failed.

db.session.execute("INSERT INTO users (first_name, last_name, email, password) VALUES ('jeremy', 'blah', 'something@gmail.com', 'whatever')")

there were no error messages, just when I check my database, nothing new was added. So if I got this right engine.execute didnt need a connection but session does? Does that mean this line

app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root@localhost/hoook"

is actually not connecting the session method to my database then? What about the pymysql connector in the URI? do I also need to import pymysql to be able to use this connector? What is the correct method for generating queries and being able to add tables etc from within your flask app... Please clarify as this is confusing and from my point of view, all this documentation and abstraction needs to be cleaned up.

Duke3e33
  • 151
  • 1
  • 3
  • 12
  • 1
    Usually, if you are using Flask-SQLAlchemy, you would add rows like this: `user = User(first_name='Jane', last_name='Doe',...); db.session.add(user)`. There's no need issue raw SQL statements directly. Conversely, if you want to work with raw SQL, why are you using an ORM? – snakecharmerb Mar 29 '22 at 15:42
  • so the use of an ORM is not to really have to write raw SQL but instead write built in functions in place of them? Then that being said is it better to use `Flask-MySQLdb` and create an instance of the `MySQL` class as laid out in this [documentation](https://flask-mysqldb.readthedocs.io/en/latest/). Then that being said I have to create a connection and cursor everytime executing a query? – Duke3e33 Mar 29 '22 at 15:50
  • Broadly speaking, yes; the ORM abstracts away SQL/database details and allows the programmer to deal with pure Python objects and code, at the cost of emitting not always optimal SQL. So if you prefer to write your own SQL, Flask-MySQLdb is probably a better fit. – snakecharmerb Mar 29 '22 at 15:58
  • "I have to create a connection and cursor everytime" - from the docs, I think Flask-MySQLdb maintains the connection (or a connection pool) as a global object, so you only need to create a cursor before executing SQL statements. – snakecharmerb Mar 29 '22 at 16:02
  • great, thank you! I will focus in that direction then. – Duke3e33 Mar 29 '22 at 16:07

0 Answers0