Created
April 22, 2020 03:28
-
-
Save HamdyTawfeek/0435dc63e1300978a64e9781f64c4d6a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Init the engine | |
| import os | |
| from sqlalchemy import create_engine, Column, String, Integer | |
| database_filename = "test.db" | |
| project_dir = os.path.dirname(os.path.abspath('')) | |
| database_path = "sqlite:///{}".format(os.path.join(project_dir, database_filename)) | |
| engine = create_engine(database_path) | |
| # Define a model class | |
| from sqlalchemy.ext.declarative import declarative_base | |
| Base = declarative_base() | |
| class User(Base): | |
| __tablename__ = 'users' | |
| # Autoincrementing, unique primary key | |
| id = Column(Integer().with_variant(Integer, "sqlite"), primary_key=True) | |
| # String Title | |
| username = Column(String(80), unique=True) | |
| password = Column(String(180), nullable=False) | |
| def __repr__(self): | |
| return self.username +": "+self.password | |
| User.metadata.create_all(engine) | |
| # Init a session | |
| from sqlalchemy.orm import sessionmaker | |
| Session = sessionmaker(bind=engine) | |
| Session.configure(bind=engine) | |
| session = Session() | |
| # Add a new user | |
| new_user = User(username='James', password='superstrongpassword') | |
| session.add(new_user) | |
| session.commit() | |
| # Fetch a user from the database | |
| db_user = session.query(User).filter_by(username='James').first() | |
| print(db_user) | |
| # > TIP: If you get stuck with errors, try executing this block: | |
| #vsession.rollback() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment