V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
holinhot
V2EX  ›  Python

sqlalchemy+postgresql 建表不成功换 mysql 是可以

  •  
  •   holinhot · May 5, 2020 · 2448 views
    This topic created in 2194 days ago, the information mentioned may be changed or developed.
    database.py

    from sqlalchemy import create_engine
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker


    SQLALCHEMY_DATABASE_URL = "postgresql+psycopg2://postgres:123@localhost/cms"
    #SQLALCHEMY_DATABASE_URL = "mysql://root@localhost/cms"



    engine = create_engine(SQLALCHEMY_DATABASE_URL)
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

    Base = declarative_base()

    models.py

    from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
    from sqlalchemy.orm import relationship

    from .database import Base


    class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    email = Column(String(15), unique=True, index=True)
    hashed_password = Column(String(15))
    is_active = Column(Boolean, default=True)

    items = relationship("Item", back_populates="owner")


    class Item(Base):
    __tablename__ = "items"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String(15), index=True)
    description = Column(String(15), index=True)
    owner_id = Column(Integer, ForeignKey("users.id"))

    owner = relationship("User", back_populates="items")


    db.py
    from sql_app import models
    from sql_app.database import engine


    def init_db():
    models.Base.metadata.create_all(bind=engine)

    init_db()
    holinhot
        1
    holinhot  
    OP
       May 5, 2020
    真是奇怪了,执行了很多遍我看 postgresql 里根本没有表啊,同样的代码换成 mysql 是可以建表成功
    holinhot
        2
    holinhot  
    OP
       May 5, 2020
    结贴,navicat 的锅,不知为何在 navicat 中不管怎么刷新,还是重连都不显示 postgresql 里的表。pgAdmin 没问题
    zzl22100048
        4
    zzl22100048  
       May 5, 2020 via iPhone
    navicat 版本低了吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4454 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 10:13 · PVG 18:13 · LAX 03:13 · JFK 06:13
    ♥ Do have faith in what you're doing.