adding sqlalchemy models
parent
804dda48ea
commit
a5d58dfb18
@ -0,0 +1,58 @@
|
||||
from sqlalchemy import (
|
||||
Column,
|
||||
Identity, # Identity replaced Serial
|
||||
Integer,
|
||||
BigInteger,
|
||||
Numeric,
|
||||
String,
|
||||
ForeignKey,
|
||||
DateTime,
|
||||
Boolean,
|
||||
Enum,
|
||||
)
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import expression
|
||||
from sqlalchemy.ext.compiler import compiles
|
||||
from sqlalchemy.types import DateTime as DatetimeType
|
||||
|
||||
from . import db
|
||||
|
||||
|
||||
class utcnow(expression.FunctionElement):
|
||||
type = DatetimeType()
|
||||
|
||||
|
||||
@compiles(utcnow, "postgresql")
|
||||
def pg_utcnow(element, compiler, **kw):
|
||||
return "TIMEZONE('utc', CURRENT_TIMESTAMP)"
|
||||
|
||||
|
||||
def ReferenceCol(tablename, nullable=False, **kw):
|
||||
"""A utility function for declaring foreign key relationships."""
|
||||
return Column(ForeignKey("{}.id".format(tablename)), nullable=nullable, **kw)
|
||||
|
||||
|
||||
class DBMixin:
|
||||
id = Column(BigInteger, Identity(start=100000), primary_key=True)
|
||||
created_date = Column(DateTime(timezone=True), server_default=utcnow())
|
||||
modified_date = Column(
|
||||
DateTime(timezone=True), server_default=utcnow(), onupdate=utcnow()
|
||||
)
|
||||
|
||||
def to_dict(self):
|
||||
d = self.__dict__.copy()
|
||||
if "_sa_instance_state" in d:
|
||||
d.pop("_sa_instance_state")
|
||||
return d
|
||||
|
||||
|
||||
class Cookie(DBMixin, db.Model):
|
||||
"""A Cookie Class"""
|
||||
|
||||
__tablename__ = "cookies"
|
||||
|
||||
name = Column(String(50), index=True)
|
||||
recipe_url = Column(String(255))
|
||||
sku = Column(String(55))
|
||||
qoh = Column(Integer)
|
||||
unit_cost = Column(Numeric(12, 2))
|
@ -0,0 +1,19 @@
|
||||
import datetime as dt
|
||||
from decimal import Decimal
|
||||
|
||||
from flask.json import JSONEncoder
|
||||
|
||||
|
||||
class CustomJSONEncoder(JSONEncoder):
|
||||
def default(self, obj):
|
||||
try:
|
||||
if isinstance(obj, dt.datetime):
|
||||
return obj.isoformat()
|
||||
if isinstance(obj, Decimal):
|
||||
return float(obj)
|
||||
iterable = iter(obj)
|
||||
except TypeError:
|
||||
pass
|
||||
else:
|
||||
return list(iterable)
|
||||
return JSONEncoder.default(self, obj)
|
Loading…
Reference in New Issue