Event-CRUD-Flask-python3-API/models.py
2024-01-09 11:01:39 +02:00

57 lines
2.1 KiB
Python

from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from sqlalchemy import Column, Integer, ForeignKey, String, Boolean
import uuid
db = SQLAlchemy()
bcrypt = Bcrypt()
class UserEventAssociation(db.Model):
__tablename__ = 'user_event'
user_id = Column(String(36), ForeignKey('user.id'), primary_key=True)
event_id = Column(Integer, ForeignKey('event.id'), primary_key=True)
class Event(db.Model):
id = Column(db.Integer, primary_key=True)
title = Column(db.String(100), nullable=False)
description = Column(db.String(200), nullable=False)
location = Column(db.String(100), nullable=False)
deleted = Column(Boolean, default=False)
duedate = Column(db.DateTime, nullable=False)
created_at = Column(db.DateTime, default=db.func.now())
user_id = Column(String(36), db.ForeignKey('user.id'), nullable=False)
users = db.relationship('User', secondary='user_event', back_populates='events')
def to_dict(self):
return {
'id': self.id,
'title': self.title,
'description': self.description,
'location': self.location,
'duedate': self.duedate.isoformat() if self.duedate else None,
'created_at': self.created_at.isoformat(),
'user_id': self.user_id
}
class User(db.Model):
id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
name = Column(db.String(100), nullable=False)
email = Column(db.String(120), unique=True, nullable=False)
password_hash = Column(db.String(128), nullable=False)
location = Column(db.String(100), nullable=False)
events = db.relationship('Event', secondary='user_event', back_populates='users')
def set_password(self, password):
self.password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
def check_password(self, password):
return bcrypt.check_password_hash(self.password_hash, password)
def to_dict(self):
return {
'id': self.id,
'name': self.name,
'email': self.email,
'location': self.location
}