Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

@api.get('/api/weather/{city}')
async def weather(city: str):
redis = await aioredis.create_redis(address=('redis', 6379))
redis = await aioredis.from_url('redis://@redis:6379/0')

# get cache from memory
cache = await redis.get(city)
Expand All @@ -27,7 +27,7 @@ async def weather(city: str):
t = selector.xpath('//div[@class="information__content__temperature"]/text()').getall()[1].strip()

# save cache in memory for 1 hour
await redis.set(city, t, expire=3600)
await redis.set(city, t, ex=3600)

return {'city':city, 'temperature':t, 'source':'pogoda.mail.ru'}

Expand Down
24 changes: 24 additions & 0 deletions 5-cache-few-threads-microservice/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
version: '3.7'

services:
microservice:
build:
context: ./microservice
image: cache-few-threads-microservice
container_name: cache-few-threads-microservice
restart: unless-stopped
ports:
- "8000:8000"
# work in few threads
command: gunicorn --workers=3 -b 0.0.0.0:8000 -k uvicorn.workers.UvicornWorker cache-few-threads-microservice:api

redis:
image: redis
container_name: cache-few-threads-microservice-redis
restart: unless-stopped
volumes:
- ./redis/data:/data
- ./redis/redis.conf:/usr/local/etc/redis/redis.conf
expose:
- 6379
command: redis-server /usr/local/etc/redis/redis.conf
7 changes: 7 additions & 0 deletions 5-cache-few-threads-microservice/microservice/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
FROM python:3.7

RUN python -m pip install fastapi httpx scrapy gunicorn uvicorn uvloop httptools redis

WORKDIR /app

ADD cache-few-threads-microservice.py cache-few-threads-microservice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import fastapi
import httpx
from scrapy.selector import Selector
import redis

api = fastapi.FastAPI()
redis = redis.Redis(host='redis', port=6379, db=0)

@api.get('/api/weather/{city}')
def weather(city: str) -> dict:
# get cache from memory
cache = redis.get(city)

# check value from cache, if exists return it
if cache is not None:
return {'city':city, 'temperature':cache, 'source':'cache'}

url = f'https://pogoda.mail.ru/prognoz/{city}/'

with httpx.Client() as client:
response = client.get(url)
response.raise_for_status()

selector = Selector(text=response.text)
t = selector.xpath('//div[@class="information__content__temperature"]/text()').getall()[1].strip()

# save cache in memory for 1 hour
redis.set(city, t, ex=3600)

return {'city':city, 'temperature':t, 'source':'pogoda.mail.ru'}
Loading