1
votes

I used flask-sqlalchemy with PostgreSQL. Now, I switched to RDS MySQL, so I changed SQLALCHEMY_DATABASE_URI form

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://**************'

to

app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://{username}:{password}@{endpoint}:{port}?charset=utf8"

after this, I initialize app like this

from flask import Flask, render_template, request, logging, Response, redirect, flash, jsonify
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

app = Flask(__name__)

db = SQLAlchemy(app)
ma = Marshmallow(app)

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.String(8),  primary_key=True)
    name = db.Column(db.String, unique=False)
    email = db.Column(db.String, unique=False)

    def __init__(self,params):
        self.id = params['id']
        self.name = params['name']
        self.email = params['email']

class UserSchema(ma.ModelSchema):
    class Meta:
        model = User

@app.route('/get_user', methods=['GET'])
def get_user():
    userid = request.args['id']
    user = User.query.get(userid)
    return user

if __name__ == '__main__':
    app.run()

But the app cannot connect to server. (I confirmed username, password, endpoint, port, is correct and connected from mysql workbench)

I read this question. Switching from SQLite to MySQL with Flask SQLAlchemy so I installed pymysql, but it didn't work.

When my app tried to connect db, this error message is shown. it seems that psycopg2 is called although I'm using mysql.

Could you please give me some advise?

psycopg2.ProgrammingError: invalid dsn: invalid connection option "mysql+pymysql://mysql+pymysql://{username}:{password}{endpoint}:{port}?charset"
2
Probably your connection string is missing '@' b/w password and endpoint..Conn = "mysql+pymysql://{username}:{password}@{endpoint}:{port}/{database}?charset=utf8"Tech at The Sparks Foundation
Thank you for your suggestion sorry, I missed '@' in my question, I corrected questionkaz0621
When u create the engine. Are you doing engine.connect() ? And can you put full stacktrace?Tech at The Sparks Foundation
Can you put the full stack trace in your questionTech at The Sparks Foundation
Yes i wanted to see the whole error log.Tech at The Sparks Foundation

2 Answers

0
votes

The error message suggests to check your connection string with a debugger breakpoint, or just by printing.

print(app.config['SQLALCHEMY_DATABASE_URI'])
0
votes

it could be the uri format: "dialect+driver://username:password@host:port/database" in MySQL "mysql://username:password@localhost:####/mydatabase" https://flask-sqlalchemy.palletsprojects.com/en/2.x/config/#connection-uri-format