Skip to content

Commit

Permalink
Expose via api
Browse files Browse the repository at this point in the history
  • Loading branch information
kelvinn committed Oct 29, 2023
1 parent 69e3c1d commit 2636d1f
Show file tree
Hide file tree
Showing 11 changed files with 129 additions and 6 deletions.
Empty file added app/__init__.py
Empty file.
10 changes: 10 additions & 0 deletions app/crud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from sqlalchemy.orm import Session

import models
from app import schemas


def get_product(db: Session, product_gid: int):
product = db.query(models.Product).filter(models.Product.gid ==product_gid).first()

return product
27 changes: 27 additions & 0 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session

from app import crud, schemas
import models
from database import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)

app = FastAPI()


# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()


@app.get("/products/{product_gid}/", response_model=schemas.Product)
def read_product(product_gid: int, db: Session = Depends(get_db)):
db_product = crud.get_product(db, product_gid=product_gid)
if db_product is None:
raise HTTPException(status_code=404, detail="Product not found")
return db_product
24 changes: 24 additions & 0 deletions app/schemas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from typing import List
from pydantic import BaseModel, ConfigDict
from datetime import datetime


class Price(BaseModel):
model_config = ConfigDict(from_attributes=True)

gid: int
amount: float = None
product_gid: int
created: datetime


class Product(BaseModel):
model_config = ConfigDict(from_attributes=True)

gid: int
name: str = None
url: str = None
prices: List[Price]
created: datetime
last_updated: datetime

42 changes: 42 additions & 0 deletions app/test_main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from fastapi.testclient import TestClient
from fastapi import Depends
import models
from database import SessionLocal, engine
from sqlalchemy.orm import Session

models.Base.metadata.create_all(bind=engine)

from .main import app
from datetime import datetime

client = TestClient(app)


def test_read_main():

name = "Sample Shirt"
url = "https://www.outdoorstore.com"
amount = 123.45

db = SessionLocal()

product = db.query(models.Product).filter_by(name=name).one_or_none()
if not product:
# Add a test product
product = models.Product(name=name, url=url, created=datetime.now(), last_updated=datetime.now())
db.add(product)
db.commit()
db.refresh(product)

# Add a test price
price = models.Price(amount=amount, product=product, created=datetime.now())
db.add(price)
db.commit()

response = client.get(f'/products/{product.gid}/')
assert response.status_code == 200
data = response.json()

assert data['name'] == name
assert data['url'] == url
assert data['prices'][0]['amount'] == amount
13 changes: 13 additions & 0 deletions database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from os import getenv
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base

SQLALCHEMY_DATABASE_URL = getenv('DATABASE_URL', 'postgresql://postgres:postgres@localhost/changedetection')
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"

engine = create_engine(
SQLALCHEMY_DATABASE_URL
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()
8 changes: 8 additions & 0 deletions fly.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ primary_region = "syd"
release_command = "alembic upgrade head"

[processes]
app = "uvicorn main:app --host 0.0.0.0 --port 3000"
worker = "python main.py"

[[services]]
Expand All @@ -21,3 +22,10 @@ primary_region = "syd"
min_machines_running = 0
processes = ["worker"]

[http_service]
internal_port = 3000
force_https = true
auto_stop_machines = true
auto_start_machines = true
min_machines_running = 0
processes = ["app"]
4 changes: 2 additions & 2 deletions models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from sqlalchemy import Column, Integer, String, ForeignKey, Table, Float, DateTime
from sqlalchemy.orm import relationship, mapped_column

Base = declarative_base()
from database import Base


class Store(Base):
Expand All @@ -26,6 +26,6 @@ class Product(Base):
gid = Column(Integer, primary_key=True)
name = Column(String, unique=False)
url = Column(String, unique=True)
prices = relationship("Price", back_populates="product")
prices = relationship("Price", back_populates="product", lazy=False)
created = Column(DateTime)
last_updated = Column(DateTime)
File renamed without changes.
5 changes: 2 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ psycopg2
alembic
sentry-sdk



# This is for testing
pytest
pytest
httpx
2 changes: 1 addition & 1 deletion scripts/test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@
set -e

alembic upgrade head
pytest tests.py
pytest
scrapy check

0 comments on commit 2636d1f

Please sign in to comment.