1

I'm totally beginner for use flask and Google Cloud SQL. I want to make Login and Registration in my app using Flask-Login and Flask-SQLAlchemy. But I can't connect to google cloud SQL using Flask-SQLAlchemy, this is my code.

SQLALCHEMY_DATABASE_URI = (
'mysql+pymysql://{db_user}:{db_password}@/{db_name}'
'?unix_socket=/cloudsql/{connection_name}').format(
    user=db_user, password=db_password,
    database=db_name, connection_name=connection_name)

app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI

I just got this error : (2003, "Can't connect to MySQL server on 'localhost' ([Errno 2] No such file or directory)")

But, when I try to make a connection using SQLAlchemy with this code, the connection is succeeded :

query_string = dict({"unix_socket": "/cloudsql/{}".format(connection_name)})
driver_name = 'mysql+pymysql'

db = sqlalchemy.create_engine(
sqlalchemy.engine.url.URL(
    drivername=driver_name,
    username=db_user,
    password=db_password,
    database=db_name, 
    query=query_string),
pool_size=5,
max_overflow=2,
pool_timeout=30,
pool_recycle=1800)

But when I tried to change the code like this :

app.config['SQLALCHEMY_DATABASE_URI'] = db

then, I got this error: 'Engine' object has no attribute 'drivername'.

Any suggestion for this problem? any advice, might be very helpful for me, Thank you.

1 Answer 1

1

This line right here actually assigns the "engine" object to your URI config:

app.config['SQLALCHEMY_DATABASE_URI'] = db

You can use the url object to create a URI instead:

uri = sqlalchemy.engine.url.URL(
    drivername=driver_name,
    username=db_user,
    password=db_password,
    database=db_name, 
    query=query_string)
app.config['SQLALCHEMY_DATABASE_URI'] = uri.render_as_string(hide_password=false)

You can compare the URI to the one you created and see where they differ. It's likely there is a typo, or that some value is escaped incorrectly.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @kurtisvg for your answer, but I got a new error: "Instance of 'URL' has no 'render_as_string' member"
@HikmahDwiyantiNasir - Perhaps make sure you are on a recent version - it's listed in the SQLAlchemy documentation here: docs.sqlalchemy.org/en/14/core/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.