Skip to content

Instantly share code, notes, and snippets.

@muindetuva
Created October 27, 2023 17:21
Show Gist options
  • Select an option

  • Save muindetuva/023d3b778dd4c461625a762931781779 to your computer and use it in GitHub Desktop.

Select an option

Save muindetuva/023d3b778dd4c461625a762931781779 to your computer and use it in GitHub Desktop.
Python ORMs
import cmd
import MySQLdb
# Define a Student class
class Student:
def __init__(self, name, email):
self.name = name
self.email = email
self.corrections = []
def add_correction(self, correction):
self.corrections.append(correction)
# Define a Correction class
class Correction:
def __init__(self, link):
self.link = link
# Define a DataManager class for abstracting data operations
class Storage:
def __init__(self):
self.conn = MySQLdb.connect(host='localhost',user='tuva',passwd='4321',db='adapter_corrections')
self.cursor = self.conn.cursor()
self.students = self.fetch_students()
def fetch_students(self):
students = []
fetch_students = """
SELECT students.name, students.email, corrections.link FROM students
LEFT JOIN corrections ON students.id = corrections.student_id
"""
self.cursor.execute(fetch_students)
current_student = None
for row in self.cursor.fetchall():
name, email, correction_link = row
if not current_student or current_student.email != email:
current_student = Student(name, email)
students.append(current_student)
if correction_link:
current_student.add_correction(Correction(correction_link))
return students
def add_student(self, name, email):
new_student = Student(name, email)
self.students.append(new_student)
# Placeholder: Add code to persist the student data
insert_student_query = "INSERT INTO students (name, email) VALUES (%s, %s)"
self.cursor.execute(insert_student_query, (name, email))
self.conn.commit()
def add_correction(self, student_email, link):
for student in self.students:
if student.email == student_email:
correction = Correction(link)
student.add_correction(correction)
# Placeholder: Add code to persist the correction data
get_student_id = "SELECT id FROM students WHERE email = %s"
self.cursor.execute(get_student_id, (student_email,))
student_id = self.cursor.fetchone()[0]
insert_correction = "INSERT INTO corrections (link, student_id) VALUES (%s, %s)"
self.cursor.execute(insert_correction, (link, student_id))
self.conn.commit()
def list_students(self):
for student in self.students:
print(f"Student: {student.name} ({student.email})")
for correction in student.corrections:
print(f" Correction: {correction.link}")
# Add methods for updating and removing data as needed
# Placeholder: Add corresponding database operations
# Define a command-line interface using the cmd module
class StudentAssignmentCLI(cmd.Cmd):
def __init__(self):
super().__init__()
self.prompt = ">> "
self.intro = "Student Corrections Management Tool"
def do_add_student(self, arg):
"""Add a student. Usage: add_student <student_name> <student_email>"""
args = arg.split()
if len(args) != 2:
print("Usage: add_student <student_name> <student_email>")
return
name, email = args
storage.add_student(name, email)
def do_add_correction(self, arg):
"""Add a correction to a student. Usage: add_correction <student_email> <correction_link>"""
args = arg.split()
if len(args) != 2:
print("Usage: add_correction <student_email> <correction_link>")
return
student_email, correction_link = args
storage.add_correction(student_email, correction_link)
def do_list_students(self, arg):
"""List all students and their corrections."""
storage.list_students()
def do_quit(self, arg):
"""Exit the program."""
print("Exiting...")
return True
if __name__ == "__main__":
storage = Storage()
cli = StudentAssignmentCLI()
cli.cmdloop()
import cmd
from sqlalchemy.orm import declarative_base, relationship, sessionmaker
from sqlalchemy import Column, Integer, String, create_engine, ForeignKey
# SQLAlchemy base class
Base = declarative_base()
# Define a Student class
class Student(Base):
__tablename__ = 'students'
id = Column(Integer, primary_key=True)
name = Column(String(50))
email = Column(String(100), unique=True)
corrections = relationship('Correction', back_populates='student')
#self.corrections = []
def add_correction(self, correction):
self.corrections.append(correction)
# Define a Correction class
class Correction(Base):
__tablename__ = 'corrections'
id = Column(Integer, primary_key=True)
link = Column(String(200))
student_id = Column(Integer, ForeignKey('students.id'))
student = relationship('Student', back_populates='corrections')
# Define a DataManager class for abstracting data operations
class Storage:
def __init__(self):
self.engine = create_engine('mysql+pymysql://tuva:4321@localhost/alchemy_corrections')
Base.metadata.create_all(self.engine)
self.Session = sessionmaker(bind=self.engine)
self.session = self.Session()
#self.students = []
def add_student(self, name, email):
new_student = Student(name=name, email=email)
#self.students.append(new_student)
# Placeholder: Add code to persist the student data
self.session.add(new_student)
self.session.commit()
def add_correction(self, student_email, link):
student = self.session.query(Student).filter_by(email=student_email).first()
if student:
new_correction = Correction(link=link, student=student)
self.session.add(new_correction)
self.session.commit()
#for student in self.students:
#if student.email == student_email:
#correction = Correction(link)
#student.add_correction(correction)
# Placeholder: Add code to persist the correction data
def list_students(self):
#for student in self.students:
for student in self.session.query(Student).all():
print(f"Student: {student.name} ({student.email})")
for correction in student.corrections:
print(f" Correction: {correction.link}")
# Add methods for updating and removing data as needed
# Placeholder: Add corresponding database operations
# Define a command-line interface using the cmd module
class StudentAssignmentCLI(cmd.Cmd):
def __init__(self):
super().__init__()
self.prompt = ">> "
self.intro = "Student Corrections Management Tool"
def do_add_student(self, arg):
"""Add a student. Usage: add_student <student_name> <student_email>"""
args = arg.split()
if len(args) != 2:
print("Usage: add_student <student_name> <student_email>")
return
name, email = args
storage.add_student(name, email)
def do_add_correction(self, arg):
"""Add a correction to a student. Usage: add_correction <student_email> <correction_link>"""
args = arg.split()
if len(args) != 2:
print("Usage: add_correction <student_email> <correction_link>")
return
student_email, correction_link = args
storage.add_correction(student_email, correction_link)
def do_list_students(self, arg):
"""List all students and their corrections."""
storage.list_students()
def do_quit(self, arg):
"""Exit the program."""
print("Exiting...")
return True
if __name__ == "__main__":
storage = Storage()
cli = StudentAssignmentCLI()
cli.cmdloop()
import cmd
# Define a Student class
class Student:
def __init__(self, name, email):
self.name = name
self.email = email
self.corrections = []
def add_correction(self, correction):
self.corrections.append(correction)
# Define a Correction class
class Correction:
def __init__(self, link):
self.link = link
# Define a DataManager class for abstracting data operations
class Storage:
def __init__(self):
self.students = []
def add_student(self, name, email):
new_student = Student(name, email)
self.students.append(new_student)
# Placeholder: Add code to persist the student data
def add_correction(self, student_email, link):
for student in self.students:
if student.email == student_email:
correction = Correction(link)
student.add_correction(correction)
# Placeholder: Add code to persist the correction data
def list_students(self):
for student in self.students:
print(f"Student: {student.name} ({student.email})")
for correction in student.corrections:
print(f" Correction: {correction.link}")
# Add methods for updating and removing data as needed
# Placeholder: Add corresponding database operations
# Define a command-line interface using the cmd module
class StudentAssignmentCLI(cmd.Cmd):
def __init__(self):
super().__init__()
self.prompt = ">> "
self.intro = "Student Corrections Management Tool"
def do_add_student(self, arg):
"""Add a student. Usage: add_student <student_name> <student_email>"""
args = arg.split()
if len(args) != 2:
print("Usage: add_student <student_name> <student_email>")
return
name, email = args
storage.add_student(name, email)
def do_add_correction(self, arg):
"""Add a correction to a student. Usage: add_correction <student_email> <correction_link>"""
args = arg.split()
if len(args) != 2:
print("Usage: add_correction <student_email> <correction_link>")
return
student_email, correction_link = args
storage.add_correction(student_email, correction_link)
def do_list_students(self, arg):
"""List all students and their corrections."""
storage.list_students()
def do_quit(self, arg):
"""Exit the program."""
print("Exiting...")
return True
if __name__ == "__main__":
storage = Storage()
cli = StudentAssignmentCLI()
cli.cmdloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment