| 1 |
import random |
| 2 |
from datetime import datetime |
| 3 |
|
| 4 |
from flask import Flask |
| 5 |
from flask import jsonify |
| 6 |
from flask import render_template_string |
| 7 |
|
| 8 |
from flask_caching import Cache |
| 9 |
|
| 10 |
app = Flask(__name__) |
| 11 |
app.config.from_pyfile("hello.cfg") |
| 12 |
cache = Cache(app) |
| 13 |
|
| 14 |
|
| 15 |
#: This is an example of a cached view |
| 16 |
@app.route("/api/now") |
| 17 |
@cache.cached(50) |
| 18 |
def current_time(): |
| 19 |
return str(datetime.now()) |
| 20 |
|
| 21 |
|
| 22 |
#: This is an example of a cached function |
| 23 |
@cache.cached(key_prefix="binary") |
| 24 |
def random_binary(): |
| 25 |
return [random.randrange(0, 2) for i in range(500)] |
| 26 |
|
| 27 |
|
| 28 |
@app.route("/api/get/binary") |
| 29 |
def get_binary(): |
| 30 |
return jsonify({"data": random_binary()}) |
| 31 |
|
| 32 |
|
| 33 |
#: This is an example of a memoized function |
| 34 |
@cache.memoize(60) |
| 35 |
def _add(a, b): |
| 36 |
return a + b + random.randrange(0, 1000) |
| 37 |
|
| 38 |
|
| 39 |
@cache.memoize(60) |
| 40 |
def _sub(a, b): |
| 41 |
return a - b - random.randrange(0, 1000) |
| 42 |
|
| 43 |
|
| 44 |
@app.route("/api/add/<int:a>/<int:b>") |
| 45 |
def add(a, b): |
| 46 |
return str(_add(a, b)) |
| 47 |
|
| 48 |
|
| 49 |
@app.route("/api/sub/<int:a>/<int:b>") |
| 50 |
def sub(a, b): |
| 51 |
return str(_sub(a, b)) |
| 52 |
|
| 53 |
|
| 54 |
@app.route("/api/cache/delete") |
| 55 |
def delete_cache(): |
| 56 |
cache.delete_memoized("_add", "_sub") |
| 57 |
return "OK" |
| 58 |
|
| 59 |
|
| 60 |
@app.route("/html") |
| 61 |
@app.route("/html/<foo>") |
| 62 |
def html(foo=None): |
| 63 |
if foo is not None: |
| 64 |
cache.set("foo", foo) |
| 65 |
return render_template_string( |
| 66 |
"<html><body>foo cache: {{foo}}</body></html>", foo=cache.get("foo") |
| 67 |
) |
| 68 |
|
| 69 |
|
| 70 |
@app.route("/template") |
| 71 |
def template(): |
| 72 |
return render_template_string( |
| 73 |
"""<html><body>foo cache: |
| 74 |
{% cache 60, "random" %} |
| 75 |
{{ range(1, 42) | random }} |
| 76 |
{% endcache %} |
| 77 |
</body></html>""" |
| 78 |
) |
| 79 |
|
| 80 |
|
| 81 |
if __name__ == "__main__": |
| 82 |
app.run() |