1

I have Docker Containers application with Flask and Django containers. It is possible share Database between Django container and Flask Container?

 django: &django
  ...
  depends_on:
  - postgres

 flask:
  ...
  ports:
    - "5090:5090"
  ...
  - postgres
  links:
  - postgres

 postgres:
   build:
   ...
   env_file:
  - ./.envs/.local/.postgres

Models are in Django application. So, I need to do a Login in Flask Application using Postgres Database. The problem is, I only want to use the connection to Database, I do not need to do models in Flask.

I used Sqlalchemy method:

  if form.validate_on_submit():
    query = session.query(User)
    login = User.query.filter(username=form.username.data).first()
    if login is not None:
        print(login)
        return redirect(url_for('index'))
   return render_template('login.html', form=form)

And I tried with Panda method:

     if form.validate_on_submit():
    sql = "SELECT * from users WHERE username = '{0}'".format(form.username.data)
    login = pd.read_sql_query(sql,SQLALCHEMY_DATABASE_URI)
    if login is not None:
        print(login)
        return redirect(url_for('index'))

But the error is the same in both cases, I need to do a relation, so, it is a Migration, in Flask.

   **sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "users"** 

It is my database.py:

     ...
     SQLALCHEMY_DATABASE_URI = 'postgres://%s:%s@%s:%s/%s' % (user, pwd, host, port, db)
     SQLALCHEMY_TRACK_MODIFICATIONS = os.environ.get('SQLALCHEMY_TRACK_MODIFICATIONS')

     db_session = scoped_session(sessionmaker(autocommit=False,
                                     autoflush=False,
                                     bind=engine))
     def init_db():
     ...

1 Answer 1

1

It's certainly possible to share the database between multiple containers. I wouldn't, but it's possible, nonetheless.

The error I see above seems to be that the user table doesn't have the name you'd expect. You can verify using some database gui or the psql cli tool. Unless you explicitly named it users it will be named using the <app_name>_<model_name> convention. If you're using the default django User model then the actual db table will be named auth_user.

Side note: you could definitely continue this way, but, if you have some time to invest on the problem: I'd highly suggest you look into OAUTH+OIDC, JWTs, and how to accomplish SSO using them.

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

1 Comment

Yes, to be honest, finally I leaved this way and I am trying to do it connecting Flask templates with DRF. Thanks for the advise.

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.