table 'roles_users' is already defined for this MetaData instance

前端 未结 11 978
执笔经年
执笔经年 2021-02-05 01:40

hello iam trying to get a currnet_user information in my views

and i include from users.models import *

then in my code return return current_user;

<         


        
相关标签:
11条回答
  • 2021-02-05 02:17

    Most likely a bug in imports.

    It's just that the roles_users model is imported multiple times in one of your components.

    This can happen if you imported into several components in which there is already an import of the required model

    Examle:

    from schemas.user import UserSchema # have `from models.user import User` inside
    from blocs.users import UsersBLOC # have `from models.user import User` inside
    
    0 讨论(0)
  • 2021-02-05 02:18

    My name is Jacob. I had the same situation.

    The issue is this: this occurs when you are importing parent and child tables in the same code. Then you import CHILD table, the CHILD table brings the parent table's structure also into the metadata. So you don't need to import PARENT table again.

    The solution is this: you would need to rearrange the order of importing the ORM structures in your code. The order is based on parent + child relation.

    Example: The following yields an error:

    import CHILD_ORM
    import PARENT_ORM   
    

    Rearrange the order as follows, to prevent the error:

    import PARENT_ORM   
    import CHILD_ORM
    
    0 讨论(0)
  • 2021-02-05 02:24

    I had a similar error. My problem was importing the class that inherits db.Model from two different files using a relative import. Flask-SQLAlchemy mapped the two imports as two different table definitions and tried to create two tables. I fixed this issue by using the absolute import path in both files.

    0 讨论(0)
  • 2021-02-05 02:26

    I'm getting this error while running the flask app in development mode:

    FLASK_ENV=development flask run
    

    The dynamic reloading feature from flask apparently does reload the metadata instances as you might expect. Restarting the app as suggested by "Spcogg the second" resolves this issue for me!

    0 讨论(0)
  • 2021-02-05 02:28

    TL;DR

    • If you encounter this error when trying to register flask blueprint to application, check if Model importing path is consistent across all blueprints where imports the Model

    For example

    • Blueprint 1: from A.B.C import Model A
    • Blueprint 2: from .B.C import Model A (This raises error, importing path should be consistent across all blueprints that imports the same model. So it should be from A.B.C import Model A)

    I haven't dig this issue to find out what is the cause, but I guess that SQLAlchemy manages Model with its imported namespace and raise error when different namespace is defined but the models are same.

    0 讨论(0)
提交回复
热议问题