Forums

I cannot get a data from second database using flask

I am unable to retrive data from a second database using flask. Here is my code.

from datetime import datetime, timedelta, timezone
from flask import Flask, redirect, render_template, request, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config["DEBUG"] = True

SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
username="SeiunProgram",
password="XXXXXX",
hostname="SeiunProgram.mysql.pythonanywhere-services.com",
databasename="SeiunProgram$comments"
)
SQLALCHEMY_BINDS = {
"nisi" : "mysql+mysqlconnector://SeiunProgram:XXXXX@SeiunProgram.mysql.pythonanywhere-services.com/SeiunProgram$nisi"
}
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_BINDS"] = SQLALCHEMY_BINDS
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)

class Comment(db.Model):
    __tablename__ = "comments"
    id = db.Column(db.Integer, primary_key=True)
    day = db.Column(db.String(20))
    content = db.Column(db.String(4096))
    log = db.Column(db.String(20))

class Nisi(db.Model):
__bind_key__ = "nisi"
id = db.Column(db.Integer, primary_key=True)
day = db.Column(db.String(20))
content = db.Column(db.String(4096))

print(Nisi.query.all())
print(Nisi.query.id)

I followed the steps in A beginner's guide to building a simple database-backed Flask website on PythonAnywhere, so there is only this python code. I ran this code but the "print(Nisi.query.all)" returns [None]. However the database Nisi properly has queries which contain data.

I checked error log. It said "AttributeError: 'BaseQuery' object has no attribute 'id'" This is the structure of Nisi.

I didnt know how to insert a picture

What shoud I do to get the data of Nisi, specifically in regards to setting binds?

[edit by admin: formatting, removed passwords]

First things first, please be careful about posting code here that contains passwords. I've removed the passwords from your code above and replaced them with XXXXX, but you should change it now from the "Databases" page and update your code with the new one, because someone could easily have seen your post before I did that, and they will now be able to access your database.

Regarding the problem you're having; I don't see anything obviously wrong with your code, but it does look a bit odd that you're not specifying the tablename for the Nisi model; perhaps adding that will help?

Thankyou very much, and sorry!

I tried that but it still doesnt work. I think the settings of id in database Nisi has some probrems, so I am tring it. I will ask in forum again if I found I cant. anyway, thanks!