mirror of
https://github.com/Rainyy21/URL_shortener.git
synced 2026-10-11 00:00:13 -04:00
added redis
This commit is contained in:
Vendored
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import redis
|
||||
|
||||
redis_client = redis.Redis(host="localhost", port=6379, decode_responses=True)
|
||||
@@ -1,11 +1,15 @@
|
||||
from fastapi import FastAPI, HTTPException, Depends
|
||||
from fastapi.responses import RedirectResponse
|
||||
|
||||
# redis
|
||||
from cache.redis_client import redis_client
|
||||
|
||||
# the sqlalchemy
|
||||
from sqlalchemy.orm import Session
|
||||
import string
|
||||
import random
|
||||
|
||||
# the database
|
||||
from db.database import SessionLocal, engine
|
||||
from db import models, crud, schemas
|
||||
|
||||
@@ -33,13 +37,25 @@ def shorten_url(request: schemas.URLCreate, db: Session = Depends(get_db)):
|
||||
|
||||
crud.create_url(db, short_code, request.long_url)
|
||||
|
||||
# set it in cache for a hour
|
||||
redis_client.set(short_code, request.long_url, ex=3600)
|
||||
|
||||
return {"short_url": f"http://localhost:8000/{short_code}"}
|
||||
|
||||
|
||||
@app.get("/{short_code}")
|
||||
def redirect_url(short_code: str, db: Session = Depends(get_db)):
|
||||
db_url = crud.get_url(db, short_code)
|
||||
# check the redis
|
||||
check_url = redis_client.get(short_code)
|
||||
|
||||
if check_url:
|
||||
return RedirectResponse(url=check_url)
|
||||
|
||||
# get url from the db
|
||||
db_url = crud.get_url(db, short_code)
|
||||
# throw a error if url not in db
|
||||
if not db_url:
|
||||
raise HTTPException(status_code=404, detail="URL not found")
|
||||
|
||||
redis_client.set(short_code, db_url.long_url)
|
||||
return RedirectResponse(url=db_url.long_url)
|
||||
|
||||
Reference in New Issue
Block a user