Skip to content

Commit

Permalink
Add aiocache with gunicorn example
Browse files Browse the repository at this point in the history
  • Loading branch information
drgarcia1986 committed Aug 12, 2020
1 parent 81b40b4 commit f18034e
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
21 changes: 21 additions & 0 deletions examples/gunicorn-aiocache-api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Gunicorn + AioHTTP + AioCache + SharedMemoryDict

## Requirements:
- SharedMemoryDict + AioCache (`pip install shared-memory-cache[aiocache]`)
- AioHTTP
- Gunicorn

## To Run:
```
$ gunicorn main:app --config gunicorn_config.py -w 3 --worker-class aiohttp.GunicornWebWorker
```

## Write on cache
```
$ curl -d "key=foo&value=bar" localhost:8000/
```

## Read from cache
```
$ curl localhost:8000/?key=foo
```
9 changes: 9 additions & 0 deletions examples/gunicorn-aiocache-api/gunicorn_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from shared_memory_dict.hooks import create_shared_memory, free_shared_memory


def on_starting(server):
create_shared_memory(name='sm', size=1024)


def on_exit(server):
free_shared_memory(name='sm')
38 changes: 38 additions & 0 deletions examples/gunicorn-aiocache-api/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from aiocache import caches
from aiohttp import web


caches.set_config({
'default': {
'cache': 'shared_memory_dict.caches.aiocache.SharedMemoryCache',
'name': 'sm'
}
})


class Handler(web.View):

async def get(self):
key = self.request.query.get('key', '')
text = await self.request.app['cache'].get(key)
return web.Response(text=text)

async def post(self):
data = await self.request.post()
await self.request.app['cache'].set(data['key'], data['value'])
return web.Response(text='OK!')


async def app_shutdown(app):
await app['cache'].close()


app = web.Application()
app.router.add_view('/', Handler)

app['cache'] = caches.get('default')
app.on_shutdown.append(app_shutdown)


if __name__ == '__main__':
web.run_app(app)

0 comments on commit f18034e

Please sign in to comment.