Skip to content Skip to sidebar Skip to footer

How To Use Flask_mysqldb With Blueprint

I´m using flask_mysqldb with a blueprint and I want to initialize MySQL but I have an error: app.config.setdefault('MYSQL_HOST', 'localhost') AttributeError: 'Blueprint' object

Solution 1:

This library looks pretty much dead to me. There's barely any any activity on the github repo and all of this would be covered by flask-sqlalchemy anyway.


You don't want to initialise the db connection inside the blueprint. You want it in your application factory.

from flask import Flask
from flask_cors import CORS
from .bodega import bodega

from flask_mysqldb import MySQL # Add the import in __init__

db = MySQL()


defcreate_app():
    app = Flask(__name__)
    cors = CORS(app, resources=r'/*')

    app.config['MYSQL_HOST'] = "localhost"
    app.config['MYSQL_USER'] = "root"
    app.config['MYSQL_PASSWORD'] = ""
    app.config['MYSQL_DB'] = "inventario_bodega"
    app.config['SECRET_KEY'] = 'thisisthesecrectkey_de_uepc_2019'

    db.init_app(app) # Initialise with the new app

    app.register_blueprint(bodega)

    return app

Then import the database (db) into your blueprint

from flask import jsonify
from datetime import datetime

from . import bodega
from flask_mysqldb import MySQL

from app import db # Import from app here@bodega.route('/show', methods=['GET'])defshow_bodega():
    try:
        cur = db.connection.cursor() # create a cursor
        cur.execute(
            """SELECT * FROM bodega 
            join item on bodega.id_item = item.id_item 
            join usuarios on bodega.id_usuario = usuarios.id_usuario 
            join images on bodega.id_image = images.id_image"""
        )
        data = cur.fetchall()
        cur.close()
        return jsonify(data), 202except:
        return"Error al extraer datos", 500

Solution 2:

The issue is on the following line

mysql = MySQL(bodega)

instead, you should pass app to MySQL

app = create_app()
mysql = MySQL(app)

for more consider, reading docs: https://flask-mysqldb.readthedocs.io/en/latest/

Post a Comment for "How To Use Flask_mysqldb With Blueprint"