Skip to content

Commit

Permalink
Merge pull request #169 from cuappdev/migrate-dev-server
Browse files Browse the repository at this point in the history
Migrate dev server
  • Loading branch information
JoshD94 authored Nov 6, 2024
2 parents d3b53e1 + d94a98f commit 5715f8a
Show file tree
Hide file tree
Showing 10 changed files with 480 additions and 112 deletions.
18 changes: 16 additions & 2 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from graphene import Schema
from graphql.utils import schema_printer
from src.database import db_session, init_db
from src.database import Base as db
from flask_migrate import Migrate
from src.schema import Query, Mutation
from src.scrapers.capacities_scraper import fetch_capacities
from src.scrapers.reg_hours_scraper import fetch_reg_building, fetch_reg_facility
Expand All @@ -16,9 +18,9 @@
from src.scrapers.activities_scraper import fetch_activity
from src.utils.utils import create_gym_table
from src.models.openhours import OpenHours
from src.database import db_url, db_user, db_password, db_name, db_host, db_port
from flasgger import Swagger


sentry_sdk.init(
dsn="https://2a96f65cca45d8a7c3ffc3b878d4346b@o4507365244010496.ingest.us.sentry.io/4507850536386560",
# Set traces_sample_rate to 1.0 to capture 100%
Expand All @@ -32,6 +34,17 @@

app = Flask(__name__)
app.debug = True

# Verify all required variables are present
if not all([db_user, db_password, db_name, db_host, db_port]):
raise ValueError(
"Missing required database configuration. "
"Please ensure all database environment variables are set."
)

app.config['SQLALCHEMY_DATABASE_URI'] = db_url
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

schema = Schema(query=Query, mutation=Mutation)
swagger = Swagger(app)

Expand Down Expand Up @@ -84,20 +97,21 @@ def scrape_capacities():
def scrape_classes():
logging.info("Scraping classes from group-fitness-classes...")


fetch_classes(10)


# Create database and fill it with data
init_db()
create_gym_table()

scrape_classes()
scrape_hours()
scrape_capacities()
scrape_equipment()

logging.info("Scraping activities from sheets...")
fetch_activity()

# Create schema.graphql
with open("schema.graphql", "w+") as schema_file:
schema_file.write(schema_printer.print_schema(schema))
Expand Down
8 changes: 4 additions & 4 deletions manager.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from flask_script import Manager
from flask_migrate import MigrateCommand
from app import app # , db
from flask_migrate import Migrate, MigrateCommand
from app import app
from src.database import Base as db

# Build manager
# migrate = Migrate(app, db)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command("db", MigrateCommand)

Expand Down
46 changes: 26 additions & 20 deletions schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -65,18 +65,10 @@ enum CourtType {
BADMINTON
}

type CreateGiveaway {
giveaway: Giveaway
}

type CreateReport {
report: Report
}

type CreateUser {
user: User
}

scalar DateTime

enum DayOfWeekEnum {
Expand All @@ -92,22 +84,13 @@ enum DayOfWeekEnum {
type Equipment {
id: ID!
name: String!
equipmentType: EquipmentType!
muscleGroups: [MuscleGroup]!
cleanName: String!
facilityId: Int!
quantity: Int
accessibility: AccessibilityType
}

enum EquipmentType {
CARDIO
RACKS_AND_BENCHES
SELECTORIZED
MULTI_CABLE
FREE_WEIGHTS
MISCELLANEOUS
PLATE_LOADED
}

type Facility {
id: ID!
facilityType: FacilityType!
Expand Down Expand Up @@ -154,12 +137,34 @@ type Gym {
reports: [Report]
}

enum MuscleGroup {
ABDOMINALS
CHEST
BACK
SHOULDERS
BICEPS
TRICEPS
HAMSTRINGS
QUADS
GLUTES
CALVES
MISCELLANEOUS
CARDIO
}

type Mutation {
createGiveaway(name: String!): Giveaway
createUser(email: String!, name: String!, netId: String!): User
enterGiveaway(giveawayId: Int!, userNetId: String!): GiveawayInstance
setWorkoutGoals(userId: Int!, workoutGoal: [String]!): User
logWorkout(userId: Int!, workoutTime: DateTime!): Workout
createReport(
createdAt: DateTime!
description: String!
gymId: Int!
issue: String!
userId: Int!
): CreateReport
}

type OpenHours {
Expand Down Expand Up @@ -194,6 +199,7 @@ type Query {
getWeeklyWorkoutDays(id: Int): [String]
getWorkoutsById(id: Int): [Workout]
activities: [Activity]
getAllReports: [Report]
}

type Report {
Expand All @@ -217,7 +223,7 @@ enum ReportType {

type User {
id: ID!
email: String!
email: String
netId: String!
name: String!
workoutGoal: [DayOfWeekEnum]
Expand Down
18 changes: 10 additions & 8 deletions src/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,29 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
# import dotenv

db_user = os.environ.get("DB_USERNAME")
db_password = os.environ.get("DB_PASSWORD")
db_name = os.environ.get("DB_NAME")
db_host = os.environ.get("DB_HOST")
db_port = os.environ.get("DB_PORT")
# dotenv.load_dotenv()

# Get database credentials with logging
db_user = os.getenv("DB_USERNAME")
db_password = os.getenv("DB_PASSWORD")
db_name = os.getenv("DB_NAME")
db_host = os.getenv("DB_HOST")
db_port = os.getenv("DB_PORT", "5432") # Add default port
db_url = f"postgresql://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}"


engine = create_engine(db_url)
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))

Base = declarative_base()
Base.query = db_session.query_property()


def init_db():
"""
Initialize database for Uplift.
"""
logging.info("Initializing database")

# Load initial data
Base.metadata.create_all(bind=engine)
db_session.commit()
43 changes: 24 additions & 19 deletions src/models/equipment.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,44 @@
import enum
from sqlalchemy import Column, String, Enum, Integer, ForeignKey
from sqlalchemy import Column, String, Enum, Integer, ForeignKey, ARRAY
from sqlalchemy.orm import relationship
from src.database import Base


class EquipmentType(enum.Enum):

cardio = 0
racks_and_benches = 1
selectorized = 2
multi_cable = 3
free_weights = 4
miscellaneous = 5
plate_loaded = 6
class MuscleGroup(enum.Enum):
ABDOMINALS = 1 # Core/Ab exercises
CHEST = 2 # Chest exercises
BACK = 3 # Back exercises
SHOULDERS = 4 # Shoulder exercises
BICEPS = 5 # Bicep exercises
TRICEPS = 6 # Tricep exercises
HAMSTRINGS = 7 # Hamstring exercises
QUADS = 8 # Quad exercises
GLUTES = 9 # Glute exercises
CALVES = 10 # Calf exercises
MISCELLANEOUS = 11 # General equipment, accessories, and multi-purpose items
CARDIO = 12 # Cardiovascular equipment


class AccessibilityType(enum.Enum):

wheelchair = 0


class Equipment(Base):

__tablename__ = "equipment"

id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
equipment_type = Column(Enum(EquipmentType), nullable=False)
muscle_groups = Column(ARRAY(Enum(MuscleGroup)), nullable=False)
clean_name = Column(String, nullable=False)
facility_id = Column(Integer, ForeignKey("facility.id"), nullable=False)
quantity = Column(Integer, nullable=True)
accessibility = Column(Enum(AccessibilityType), nullable=True)

def __init__(self, **kwargs):
self.id = kwargs.get("id")
self.name = kwargs.get("name")
self.equipment_type = kwargs.get("equipment_type")
self.facility_id = kwargs.get("facility_id")
self.quantity = kwargs.get("quantity")
self.accessibility = kwargs.get("accessibility")
def __init__(self, **kwargs):
self.id = kwargs.get("id")
self.name = kwargs.get("name")
self.muscle_groups = kwargs.get("muscle_groups")
self.facility_id = kwargs.get("facility_id")
self.quantity = kwargs.get("quantity")
self.accessibility = kwargs.get("accessibility")
2 changes: 1 addition & 1 deletion src/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class User(Base):
__tablename__ = "users"

id = Column(Integer, primary_key=True)
email = Column(String, nullable=False)
email = Column(String, nullable=True)
giveaways = relationship("Giveaway", secondary="giveaway_instance", back_populates="users")
reports = relationship("Report", back_populates="user")
net_id = Column(String, nullable=False)
Expand Down
35 changes: 19 additions & 16 deletions src/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,22 @@ class Workout(SQLAlchemyObjectType):
class Meta:
model = WorkoutModel

# MARK: - Report

class Report(SQLAlchemyObjectType):
class Meta:
model = ReportModel

gym = graphene.Field(lambda: Gym)
user = graphene.Field(lambda: User)

def resolve_gym(self, info):
query = Gym.get_query(info).filter(GymModel.id == self.gym_id).first()
return query

def resolve_user(self, info):
query = User.get_query(info).filter(UserModel.id == self.user_id).first()
return query

# MARK: - Query

Expand All @@ -218,6 +234,7 @@ class Query(graphene.ObjectType):
)
get_workouts_by_id = graphene.List(Workout, id=graphene.Int(), description="Get all of a user's workouts by ID.")
activities = graphene.List(Activity)
get_all_reports = graphene.List(Report, description="Get all reports.")

def resolve_get_all_gyms(self, info):
query = Gym.get_query(info)
Expand Down Expand Up @@ -261,24 +278,10 @@ def resolve_get_weekly_workout_days(self, info, id):

return list(workout_days_set)


# MARK: - Report

class Report(SQLAlchemyObjectType):
class Meta:
model = ReportModel

gym = graphene.Field(lambda: Gym)
user = graphene.Field(lambda: User)

def resolve_gym(self, info):
query = Gym.get_query(info).filter(GymModel.id == self.gym_id).first()
def resolve_get_all_reports(self, info):
query = ReportModel.query.all()
return query

def resolve_user(self, info):
query = User.get_query(info).filter(UserModel.id == self.user_id).first()
return query


# MARK: - Mutation

Expand Down
4 changes: 2 additions & 2 deletions src/scrapers/class_scraper.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ def fetch_classes(num_pages):
gym_class = create_group_class(class_href)

if gym_class is None or not gym_class.id:
raise Exception(f"Failed to create or retrieve gym class from {BASE_URL + class_href}")
raise Exception(f"Failed to create or retrieve gym class from {BASE_URL + class_href}")

class_instance.class_id = gym_class.id
date_string = row_elems[1].text.strip()
if "Today" in date_string:
Expand Down
Loading

0 comments on commit 5715f8a

Please sign in to comment.