Initial commit
This commit is contained in:
43
fc-example
Executable file
43
fc-example
Executable file
@@ -0,0 +1,43 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
|
||||||
|
from flask import Flask, escape, request
|
||||||
|
from time import sleep, time, ctime
|
||||||
|
from flaskcache import FlaskCache
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
fc = FlaskCache()
|
||||||
|
|
||||||
|
def page(name, count, delta=0.2):
|
||||||
|
page= (
|
||||||
|
"<!DOCTYPE html>\n"
|
||||||
|
"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
|
||||||
|
"<head>\n"
|
||||||
|
" <meta name=\"generator\" content=\"flask\">\n"
|
||||||
|
" <title>%s<title/>\n"
|
||||||
|
"</head>\n"
|
||||||
|
"<body>\n"
|
||||||
|
"<h1>%s<s/h1>\n"
|
||||||
|
"<h2>time</h2>\n"
|
||||||
|
" %f<br />\n"
|
||||||
|
" %s<br />\n"
|
||||||
|
"<h2>data</h2>\n"
|
||||||
|
) % (name, name, time(), ctime())
|
||||||
|
for i in range(1, count+1):
|
||||||
|
page += " %i<br />\n" % i
|
||||||
|
sleep(delta)
|
||||||
|
page += (
|
||||||
|
"</body>\n"
|
||||||
|
"</html>\n"
|
||||||
|
)
|
||||||
|
return(page)
|
||||||
|
|
||||||
|
@app.route('/p1')
|
||||||
|
def p1():
|
||||||
|
return(fc.getpage("/p1", page, "p1", 5))
|
||||||
|
|
||||||
|
@app.route('/p2')
|
||||||
|
def p2():
|
||||||
|
return(fc.getpage("/p2", page, "p2", 10, 0.5))
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
app.run()
|
38
flaskcache.py
Normal file
38
flaskcache.py
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
from time import time
|
||||||
|
from threading import Lock
|
||||||
|
|
||||||
|
class FlaskCache:
|
||||||
|
def __init__(self, timeout=20):
|
||||||
|
self.timeout = timeout
|
||||||
|
self.cache = {}
|
||||||
|
self.lock = {}
|
||||||
|
|
||||||
|
def genpage(self, pagefunc, *args):
|
||||||
|
page = {}
|
||||||
|
try:
|
||||||
|
page["page"] = pagefunc(*args)
|
||||||
|
page["code"] = 200
|
||||||
|
except Exception as e:
|
||||||
|
page["page"] = "ERROR\n"
|
||||||
|
page["code"] = 500
|
||||||
|
page["time"] = time()
|
||||||
|
return(page)
|
||||||
|
|
||||||
|
def cachetime(self, pagename):
|
||||||
|
try:
|
||||||
|
delta = self.cache[pagename]["time"] + self.timeout - time()
|
||||||
|
except Exception as e:
|
||||||
|
delta = -1
|
||||||
|
return(delta)
|
||||||
|
|
||||||
|
def getpage(self, pagename, pagefunc, *args):
|
||||||
|
if pagename not in self.cache:
|
||||||
|
self.cache[pagename] = {}
|
||||||
|
if pagename not in self.lock:
|
||||||
|
self.lock[pagename] = Lock()
|
||||||
|
if (self.cachetime(pagename) <= 0):
|
||||||
|
self.lock[pagename].acquire()
|
||||||
|
if (self.cachetime(pagename) <= 0):
|
||||||
|
self.cache[pagename] = self.genpage(pagefunc, *args)
|
||||||
|
self.lock[pagename].release()
|
||||||
|
return(self.cache[pagename]["page"], self.cache[pagename]["code"])
|
Reference in New Issue
Block a user