FastAPI - Redis ์—ฐ๋™

2023. 7. 31. 09:44ใ†๊ฐœ๋ฐœ/Python

728x90
๋ฐ˜์‘ํ˜•
๐Ÿ’ก ์ถœ์ฒ˜ : https://phsun102.tistory.com/62?category=891189
 

Python - FastAPI ํ”„๋ ˆ์ž„์›Œํฌ๋ž€?

FastAPI๋ž€? ํŒŒ์ด์ฌ 3.6 ๋ฒ„์ „๋ถ€ํ„ฐ ์ œ๊ณต๋˜๋Š” ํŠธ๋žœ๋””ํ•˜๊ณ  ๋†’์€ ์„ฑ๋Šฅ์„ ๊ฐ€์ง„ ํŒŒ์ด์ฌ ํ”„๋ ˆ์ž„์›Œํฌ. FastAPI๋ผ๋Š” ์ด๋ฆ„์ฒ˜๋Ÿผ ๋น ๋ฅด๊ฒŒ ๊ฐœ๋ฐœ์„ ์ง„ํ–‰ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋ณ„๋„์˜ ๊ตฌ์„ฑ์ด๋‚˜ ์„ค์น˜์˜ ํ•„์š”์—†์ด ๋ฐ”๋กœ ์‚ฌ์šฉํ•  ์ˆ˜

phsun102.tistory.com

 

์„ค์น˜

ํ•„์ˆ˜ ์„ค์น˜ ์š”์†Œ

  • redis ์˜์กด์„ฑ ์„ค์น˜
pip3 install redis # redis ์˜์กด์„ฑ ์„ค์น˜

routes ์„ค์ •

# core/redis_config.py
# core ๋””๋ ‰ํ„ฐ๋ฆฌ์— redis_config.py๋ผ๋Š” ํŒŒ์ผ์„ ์ƒˆ๋กœ ๋งŒ๋“ ๋‹ค.

import os
from dotenv import load_dotenv
import redis

load_dotenv()

def redis_config() :
	
    try:
        REDIS_HOST = str = os.getenv("REDIS_HOST")
        REDIS_PORT = integer = os.getenv("REDIS_PORT")
        REDIS_DATABASE = integer = os.getenv("REDIS_DATABASE")
        rd = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DATABASE)
        # redis.StrictRedis( ... ) ๋ผ๊ณ ๋„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค
        # Python์˜ ๋ฒ„์ „์ด 3์œผ๋กœ ์—…๋ฐ์ดํŠธ ๋˜๋ฉด์„œ ํ•จ์ˆ˜๋ช…์ด ๋ณ€๊ฒฝ๋˜์—ˆ๋‹ค
        # ํ•˜์ง€๋งŒ ๋ฒ„์ „ ํ˜ธํ™˜์„ ์œ„ํ•ด StrictRedis๋กœ๋„ ์—ฐ๊ฒฐ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค
        # ์ฆ‰, Redis = StrictRedis๋กœ ๋™์ผํ•œ ๊ธฐ๋Šฅ์„ ํ•˜๋Š” ํ•จ์ˆ˜์ด๋‹ค
		
    except:
        print("redis connection failure")
# .env

REDIS_HOST = localhost # redis ํ˜ธ์ŠคํŠธ
REDIS_PORT = 6379      # redis ํฌํŠธ
REDIS_DATABASE = 0     # redis ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋ฒˆํ˜ธ

Api ํ•จ์ˆ˜ ์ˆ˜์ •

from core.redis_config import redis_config
# url์ด /items/redis_test์ผ ๊ฒฝ์šฐ ์‹คํ–‰๋˜๋Š” ํ•จ์ˆ˜
async def redis_test():
	rd = redis_config()
	rd.set("A", "B") # set
	
	return {
	    "data": rd.get("A") # get
	}

ํ…Œ์ŠคํŠธ

  • Redis key ํ˜ธ์ถœ ์ •์ƒ

728x90
๋ฐ˜์‘ํ˜•

'๊ฐœ๋ฐœ > Python' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

Python - Faust  (0) 2023.09.04
Python - Puppeteer vs Selenium vs Playwright  (0) 2023.08.01
FastAPI - DB ์—ฐ๋™  (0) 2023.07.31
FastAPI - ์„ค์น˜  (0) 2023.07.31
Python - Uvicorn  (0) 2023.07.31