I learn fastAPI framework, and need to change sqlite engine to mysql engine, what I've done:
database.py:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
DB_USER = 'user'
DB_PASSWORD = ''
DB_HOST = 'host'
DB_PORT = 'port'
DB_NAME = 'name'
SQLALCHEMY_DATABASE_URL = f"mysql+mysqlconnector://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
engine = create_engine(
SQLALCHEMY_DATABASE_URL
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
PS I used variables (DB_USER, DB_PASSWORD, etc) as my password is empty string, and there was an error when I directly was writing everything in url without variables.
models.py:
from sqlalchemy import Column, Integer, String, DateTime
from ..database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True)
address = Column(String)
password = Column(String)
# createdAt = Column(DateTime)
The problem is that I have to manually create tables of db and respectfully the columns too (through phpmyadmin). Is there a way so that the tables are created automatically when I run the program as there are already created necessary models in models.py with all the necessary information.
Thank you in advance.