Skip to content

Commit

Permalink
Add api prefix to routes
Browse files Browse the repository at this point in the history
  • Loading branch information
thomashbrnrd committed Oct 10, 2023
1 parent 196d64e commit 3f6e4ae
Show file tree
Hide file tree
Showing 9 changed files with 30 additions and 35 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ jobs:

test-e2e:
name: Run E2E tests
needs: [tag-pr, build-backend]
needs: [build-backend, build-frontend]
uses: ./.github/workflows/test-on-kube.yml
secrets:
API_OVH_TOKEN: ${{ secrets.API_OVH_TOKEN }}
Expand Down
1 change: 0 additions & 1 deletion .github/workflows/test-on-kube.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ jobs:
--set-string backend.secret.values.AWS_SECRET_ACCESS_KEY="${{ secrets.AWS_SECRET_ACCESS_KEY }}" \
--set-string backend.secret.values.X_OVH_TOKEN="${{ secrets.X_OVH_TOKEN }}" \
--set-string backend.secret.values.API_OVH_TOKEN="${{ secrets.API_OVH_TOKEN }}"
for i in $(kubectl get deploy -o name); do kubectl rollout status $i -w --timeout=130s; done
- name: Display pod logs on failure
if: failure() && steps.tests.outcome == 'failure'
Expand Down
23 changes: 13 additions & 10 deletions backend/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@
from typing import Union

import boto3
from botocore.client import ClientError
from fastapi import BackgroundTasks, Cookie, FastAPI, File, Form, HTTPException, Request, Response, UploadFile
from fastapi import BackgroundTasks, Cookie, FastAPI, APIRouter, File, Form, HTTPException, Request, Response, UploadFile
from fastapi.responses import PlainTextResponse
from fastapi.middleware.cors import CORSMiddleware
from gelfformatter import GelfFormatter
Expand Down Expand Up @@ -139,6 +138,8 @@ def upload_image(content: bytes, image_key: str):

# FastAPI Setup
app = FastAPI()
router = APIRouter(prefix="/api")

origins = [ # allow requests from front-end
"http://basegun.fr",
"https://basegun.fr",
Expand Down Expand Up @@ -198,17 +199,17 @@ def upload_image(content: bytes, image_key: str):
####################
# ROUTES #
####################
@app.get("/", response_class=PlainTextResponse)
@router.get("/", response_class=PlainTextResponse)
def home():
return "Basegun backend"


@app.get("/version", response_class=PlainTextResponse)
@router.get("/version", response_class=PlainTextResponse)
def version():
return APP_VERSION


@app.get("/logs")
@router.get("/logs")
def logs():
if "WORKSPACE" in os.environ and os.environ["WORKSPACE"] != "prod":
with open(os.path.join(PATH_LOGS, "log.json"), "r") as f:
Expand All @@ -220,7 +221,7 @@ def logs():
return PlainTextResponse("Forbidden")


@app.post("/upload")
@router.post("/upload")
async def imageupload(
request: Request,
response: Response,
Expand Down Expand Up @@ -279,7 +280,7 @@ async def imageupload(
raise HTTPException(status_code=500, detail=str(e))


@app.post("/identification-feedback")
@router.post("/identification-feedback")
async def log_feedback(request: Request, user_id: Union[str, None] = Cookie(None)):
res = await request.json()

Expand All @@ -294,7 +295,7 @@ async def log_feedback(request: Request, user_id: Union[str, None] = Cookie(None
return


@app.post("/tutorial-feedback")
@router.post("/tutorial-feedback")
async def log_tutorial_feedback(request: Request, user_id: Union[str, None] = Cookie(None)):
res = await request.json()

Expand All @@ -309,7 +310,7 @@ async def log_tutorial_feedback(request: Request, user_id: Union[str, None] = Co
return


@app.post("/identification-dummy")
@router.post("/identification-dummy")
async def log_identification_dummy(request: Request, user_id: Union[str, None] = Cookie(None)):
res = await request.json()

Expand All @@ -322,4 +323,6 @@ async def log_identification_dummy(request: Request, user_id: Union[str, None] =
extras_logging["bg_"+key] = res[key]

logger.info("Identification dummy", extra=extras_logging)
return
return

app.include_router(router)
12 changes: 6 additions & 6 deletions backend/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ def create_bucket():
class TestModel(unittest.TestCase):
def test_home(self):
"""Checks that the route / is alive"""
response = client.get("/")
response = client.get("/api/")
self.assertEqual(response.text, "Basegun backend")

def test_version(self):
"""Checks that the route /version sends a version"""
response = client.get("/version")
response = client.get("/api/version")
self.assertEqual(response.status_code, 200)

def check_log_base(self, log):
Expand All @@ -66,7 +66,7 @@ def test_upload(self):
geoloc = "12.666,7.666"

with open(path, 'rb') as f:
r = client.post("/upload",
r = client.post("/api/upload",
files={"image": f},
data={"date": time.time(), "geolocation": geoloc})
self.assertEqual(r.status_code, 200)
Expand All @@ -77,7 +77,7 @@ def test_upload(self):
self.assertAlmostEqual(res["confidence"], 98.43, places=1)
self.assertTrue(res["confidence_level"], "high")
# checks that the result is written in logs
r = client.get("/logs")
r = client.get("/api/logs")
self.assertEqual(r.status_code, 200)
# checks the latest log with validates upload to object storage
self.assertEqual(r.json()[0]["_bg_image_url"], r.json()[1]["_bg_image_url"])
Expand All @@ -98,11 +98,11 @@ def test_feedback_and_logs(self):
label = "revolver"
confidence_level = "high"
image_url = "https://storage.gra.cloud.ovh.net/v1/test"
r = client.post("/identification-feedback",
r = client.post("/api/identification-feedback",
json={"image_url": image_url, "feedback": True, "confidence": confidence, "label": label, "confidence_level": confidence_level})

self.assertEqual(r.status_code, 200)
r = client.get("/logs")
r = client.get("/api/logs")
self.assertEqual(r.status_code, 200)
log = r.json()[0]
self.check_log_base(log)
Expand Down
1 change: 1 addition & 0 deletions frontend/.env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_API_HOST=http://localhost:5000
1 change: 1 addition & 0 deletions frontend/.env.production
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_API_HOST=http://basegun.kubernetes.local
4 changes: 1 addition & 3 deletions frontend/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ COPY ./cert/. /etc/ssl/certs/
COPY ./package.json ./package-lock.json ./
RUN npm ci --legacy-peer-deps

COPY src ./src
COPY public ./public
COPY vite.config.js index.html ./
COPY . .

FROM base as dev

Expand Down
7 changes: 4 additions & 3 deletions frontend/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,11 @@ register()

const pinia = createPinia()

axios.defaults.withCredentials = true

// the FastAPI backend
axios.defaults.baseURL = '/api/'
axios.defaults.baseURL = "http://basegun.kubernetes.local/api"
// if (import.meta.env.VITE_API_HOST) {
// axios.defaults.baseURL = import.meta.env.VITE_API_HOST + "/api"
// }

const app = createApp(App)

Expand Down
14 changes: 3 additions & 11 deletions frontend/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import UnoCSS from 'unocss/vite'
import transformerDirectives from '@unocss/transformer-directives'
import transformerVariantGroup from '@unocss/transformer-variant-group'

const path = require('path')
const apiHost = process.env.API_HOST || 'basegun-backend'
const path = require("path");

// https://vitejs.dev/config/
export default defineConfig({
Expand Down Expand Up @@ -58,13 +57,6 @@ export default defineConfig({
},
},
server: {
host: true,
proxy: {
'^/api': {
target: `http://${apiHost}:5000`,
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
host: true
}
})

0 comments on commit 3f6e4ae

Please sign in to comment.