Flask-Caching 소개
Flask-Caching 자료에 대해 소개한다.
cache는 일단 요청되었던 기록이 있는지를 확인하고 이미 요청 기록이 있을 경우에 반환했던 값을 내뱉어 대기시간을 줄이는 기법으로 보면 된다.
이 자료는 https://flask-caching.readthedocs.io/en/latest/
참고하여 작성하였다.
1. Installation
설치는 간단한 명령어로 실행
Install the extension with one of the following commands:
$ easy_install Flask-Caching
or alternatively if you have pip installed:
$ pip install Flask-Caching
2. Set Up
cache는 instance 객체를 만들어 사용한다.
Flask에 객체를 만들고, cache 객체에 flask 객체를 입혀서 처리하는 방식
from flask import Flask
from flask_caching import Cache
config = {
"DEBUG": True, # some Flask specific configs
"CACHE_TYPE": "simple", # Flask-Caching related configs
"CACHE_DEFAULT_TIMEOUT": 300
}
app = Flask(__name__)
# tell Flask to use the above defined config
app.config.from_mapping(config)
cache = Cache(app)
## OR
cache = Cache(config={'CACHE_TYPE': 'simple'})
app = Flask(__name__)
cache.init_app(app)
## OR
#: Method A: During instantiation of class
cache = Cache(config={'CACHE_TYPE': 'simple'})
#: Method B: During init_app call
cache.init_app(app, config={'CACHE_TYPE': 'simple'})
3. Caching View Functions
cache를 함수에 적용하기 위해서는 cached라는 데커레이터를 이용하여 적용한다.
이 데커레이터는 flask의 app.route 와 함수 사이에 넣어줘야 한다.
(만약 위치가 route 위로 올라오게 되면 cached는 route 데커레이터에 대한 결과만 cached 한다)
@app.route("/")
@cache.cached(timeout=50)
def index():
return render_template('index.html')
위의 cached 데커레이터는 unless라는 argument를 받을 수 있는데 이것은 True, False를 반환하는 것으로 True일 경우에는 it will bypass the caching mechanism entirely 요렇게 되어있는데 아마 cache하는 메커니즘 전체를 건너띄는 듯하다..이 부분은 잘 이해가 안되는 군
4. Caching Other Functions
cached는 flask의 app.route로 씌여진 함수외에 일반적인 함수도 cached로 받을 수 있다.
@cache.cached(timeout=50, key_prefix='all_comments')
def get_all_comments():
comments = do_serious_dbio()
return [x.author for x in comments]
cached_comments = get_all_comments()
5. Memoization
Memoization은 함수가 받은 인자를 대상으로 기억한다. 즉 function안에 받는 인자 요청이 왔을때 이전에 받았던 인자인지 아닌지를 판단하여 결과를 리턴한다.
class Person(db.Model):
@cache.memoize(50)
def has_membership(self, role_id):
return Group.query.filter_by(user=self, role_id=role_id).count() >= 1
6. Deleting memoize cache
이것은 memoize 되어 있는 정보를 삭제하는데 접근 유저별로 관리할 수 있다.
user_has_membership('demo', 'admin')
user_has_membership('demo', 'user')
cache.delete_memoized(user_has_membership, 'demo', 'user')
7. Clearing Cache
가지고 있던 cache 정보를 클리어, 삭제한다.
from flask_caching import Cache
from yourapp import app, your_cache_config
cache = Cache()
def main():
cache.init_app(app, config=your_cache_config)
with app.app_context():
cache.clear()
if __name__ == '__main__':
main()
8. Explicitly Caching Data
함수가 아닌 data 자체를 cache로 가질 수 있다.
cache.set("명칭", data) 의 형태로 받는데 이부분이 마치 딕셔너리처럼 저장하고 있다고 생각하면 된다.
@app.route("/html")
@app.route("/html/<foo>")
def html(foo=None):
if foo is not None:
cache.set("foo", foo)
bar = cache.get("foo")
return render_template_string(
"<html><body>foo cache: {{bar}}</body></html>", bar=bar
)
9. Built-in Cache Backends
Cache Type은 여러가지 종류가 있다. 기본적으로 내장되어 있는 cache 타입들이 있는데 필요에 따라 cache 타입을 선택하여 적용할 수 있다.
NullCache, SimpleCache, FileSystemCache, RedisCache, RedisSentinelCache,
MemcachedCache, SASLMemcachedCache, SpreadSASLMemcachedCache
10. Custom Cache Backends
cache를 custom하게 만들어 사용할 수 있다.
####
Your custom cache object must also subclass the flask_caching.backends.cache.BaseCache class.
Flask-Caching will make sure that threshold is already included in the kwargs options dictionary
since it is common to all BaseCache classes.
#: the_app/custom.py
class RedisCache(BaseCache):
def __init__(self, servers, default_timeout=500):
pass
def redis(app, config, args, kwargs):
args.append(app.config['REDIS_SERVERS'])
return RedisCache(*args, **kwargs)
####
An example PylibMC cache implementation to change binary setting and provide username/password
if SASL is enabled on the library
#: the_app/custom.py
def pylibmccache(app, config, args, kwargs):
return pylibmc.Client(servers=config['CACHE_MEMCACHED_SERVERS'],
username=config['CACHE_MEMCACHED_USERNAME'],
password=config['CACHE_MEMCACHED_PASSWORD'],
binary=True)
이상...아주..유용한 cache 기능 정리...
flask로 web을 개발한다면 반복적으로 일어날 수 있는 부분에 대해 빠른 반응이 가능하도록 적용하면 아주 유용할 것이다.