Merge branch 'dev/apiCaching' into devel

# Conflicts:
#	src/octoprint/filemanager/storage.py
#	src/octoprint/static/js/app/viewmodels/files.js
This commit is contained in:
Gina Häußge committed 2016-09-16 17:11:14 +02:00
commit d2ed80baca
31 files changed
+763 -211

No files matched your search

+2 -2
View File
@@ -19,7 +19,7 @@ import octoprint.server
import octoprint.plugin
from octoprint.server import admin_permission, NO_CONTENT
from octoprint.settings import settings as s, valid_boolean_trues
from octoprint.server.util import noCachingResponseHandler, apiKeyRequestHandler, corsResponseHandler
from octoprint.server.util import noCachingExceptGetResponseHandler, apiKeyRequestHandler, corsResponseHandler
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, passive_login
@@ -43,7 +43,7 @@ from . import system as api_system
VERSION = "0.1"
api.after_request(noCachingResponseHandler)
api.after_request(noCachingExceptGetResponseHandler)
api.before_request(apiKeyRequestHandler)
api.after_request(corsResponseHandler)
+102 -20
View File
@@ -10,7 +10,7 @@ from flask import request, jsonify, make_response, url_for
from octoprint.filemanager.destinations import FileDestinations
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, with_revalidation_checking
from octoprint.server.api import api
from octoprint.events import Events
import octoprint.filemanager
@@ -19,15 +19,82 @@ import octoprint.filemanager.storage
import octoprint.slicing
import psutil
import hashlib
import logging
import threading
#~~ GCODE file handling
_file_cache = dict()
_file_cache_mutex = threading.RLock()
def _clear_file_cache():
with _file_cache_mutex:
_file_cache.clear()
def _create_lastmodified(path, recursive):
if path.endswith("/files"):
# all storages involved
lms = [0]
for storage in fileManager.registered_storages:
try:
lms.append(fileManager.last_modified(storage, recursive=recursive))
except:
logging.getLogger(__name__).exception("There was an error retrieving the last modified data from storage {}".format(storage))
lms.append(None)
if filter(lambda x: x is None, lms):
# we return None if ANY of the involved storages returned None
return None
# if we reach this point, we return the maximum of all dates
return max(lms)
elif path.endswith("/files/local"):
# only local storage involved
try:
return fileManager.last_modified(FileDestinations.LOCAL, recursive=recursive)
except:
logging.getLogger(__name__).exception("There was an error retrieving the last modified data from storage {}".format(FileDestinations.LOCAL))
return None
else:
return None
def _create_etag(path, recursive, lm=None):
if lm is None:
lm = _create_lastmodified(path, recursive)
if lm is None:
return None
hash = hashlib.sha1()
hash.update(str(lm))
hash.update(str(recursive))
if path.endswith("/files") or path.endswith("/files/sdcard"):
# include sd data in etag
hash.update(repr(sorted(printer.get_sd_files(), key=lambda x: x[0])))
return hash.hexdigest()
@api.route("/files", methods=["GET"])
@with_revalidation_checking(etag_factory=lambda lm=None: _create_etag(request.path,
request.values.get("recursive", False),
lm=lm),
lastmodified_factory=lambda: _create_lastmodified(request.path,
request.values.get("recursive", False)),
unless=lambda: request.values.get("force", False) or request.values.get("_refresh", False))
def readGcodeFiles():
filter = "filter" in request.values and request.values["recursive"] in valid_boolean_trues
recursive = "recursive" in request.values and request.values["recursive"] in valid_boolean_trues
filter = request.values.get("filter", "false") in valid_boolean_trues
recursive = request.values.get("recursive", "false") in valid_boolean_trues
force = request.values.get("force", "false") in valid_boolean_trues
if force:
_clear_file_cache()
files = _getFileList(FileDestinations.LOCAL, filter=filter, recursive=recursive)
files.extend(_getFileList(FileDestinations.SDCARD))
@@ -37,13 +104,25 @@ def readGcodeFiles():
@api.route("/files/<string:origin>", methods=["GET"])
@with_revalidation_checking(etag_factory=lambda lm=None: _create_etag(request.path,
request.values.get("recursive", False),
lm=lm),
lastmodified_factory=lambda: _create_lastmodified(request.path,
request.values.get("recursive", False)),
unless=lambda: request.values.get("force", False) or request.values.get("_refresh", False))
def readGcodeFilesForOrigin(origin):
if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown origin: %s" % origin, 404)
recursive = False
if "recursive" in request.values:
recursive = request.values["recursive"] in valid_boolean_trues
recursive = request.values.get("recursive", "false") in valid_boolean_trues
force = request.values.get("force", "false") in valid_boolean_trues
if force:
with _file_cache_mutex:
try:
del _file_cache[origin]
except KeyError:
pass
files = _getFileList(origin, recursive=recursive)
@@ -89,24 +168,29 @@ def _getFileList(origin, path=None, filter=None, recursive=False):
if filter:
filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(entry, type=filter)
files = fileManager.list_files(origin, path=path, filter=filter_func, recursive=recursive)[origin].values()
with _file_cache_mutex:
files, lastmodified = _file_cache.get("{}:{}:{}:{}".format(origin, path, recursive, filter), ([], None))
if lastmodified is None or lastmodified < fileManager.last_modified(origin, path=path, recursive=recursive):
files = fileManager.list_files(origin, path=path, filter=filter_func, recursive=recursive)[origin].values()
lastmodified = fileManager.last_modified(origin, path=path, recursive=recursive)
_file_cache["{}:{}:{}:{}".format(origin, path, recursive, filter)] = (files, lastmodified)
def analyse_recursively(files, path=None):
if path is None:
path = ""
result = []
for file_or_folder in files:
# make a shallow copy in order to not accidentally modify the cached data
file_or_folder = dict(file_or_folder)
file_or_folder["origin"] = FileDestinations.LOCAL
if file_or_folder["type"] == "folder":
if "children" in file_or_folder:
file_or_folder["children"] = analyse_recursively(file_or_folder["children"].values(), path + file_or_folder["name"] + "/")
file_or_folder.update({
"refs": {
"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=path + file_or_folder["name"], _external=True)
}
})
file_or_folder["refs"] = dict(resource=url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=path + file_or_folder["name"], _external=True))
else:
if "analysis" in file_or_folder and octoprint.filemanager.valid_file_type(file_or_folder["name"], type="gcode"):
file_or_folder["gcodeAnalysis"] = file_or_folder["analysis"]
@@ -137,16 +221,14 @@ def _getFileList(origin, path=None, filter=None, recursive=False):
prints["last"]["printTime"] = last["printTime"]
file_or_folder["prints"] = prints
file_or_folder.update({
"refs": {
"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file_or_folder["path"], _external=True),
"download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + file_or_folder["path"]
}
})
file_or_folder["refs"] = dict(resource=url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file_or_folder["path"], _external=True),
download=url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + file_or_folder["path"])
return files
result.append(file_or_folder)
analyse_recursively(files)
return result
files = analyse_recursively(files)
return files
+17 -15
View File
@@ -9,6 +9,11 @@ import os
import tarfile
import zipfile
try:
from os import scandir
except ImportError:
from scandir import scandir
from collections import defaultdict
from flask import request, jsonify, make_response
@@ -33,10 +38,8 @@ def getInstalledLanguagePacks():
core_packs = []
plugin_packs = defaultdict(lambda: dict(identifier=None, display=None, languages=[]))
for folder in os.listdir(translation_folder):
path = os.path.join(translation_folder, folder)
if not os.path.isdir(path):
for entry in scandir(translation_folder):
if not entry.is_dir():
continue
def load_meta(path, locale):
@@ -61,24 +64,23 @@ def getInstalledLanguagePacks():
meta["locale_english"] = l.english_name
return meta
if folder == "_plugins":
for plugin_folder in os.listdir(path):
plugin_path = os.path.join(path, plugin_folder)
if not os.path.isdir(plugin_path):
if entry.name == "_plugins":
for plugin_entry in scandir(entry.path):
if not plugin_entry.is_dir():
continue
if not plugin_folder in plugin_manager().plugins:
if not plugin_entry.name in plugin_manager().plugins:
continue
plugin_info = plugin_manager().plugins[plugin_folder]
plugin_info = plugin_manager().plugins[plugin_entry.name]
plugin_packs[plugin_folder]["identifier"] = plugin_folder
plugin_packs[plugin_folder]["display"] = plugin_info.name
plugin_packs[plugin_entry.name]["identifier"] = plugin_entry.name
plugin_packs[plugin_entry.name]["display"] = plugin_info.name
for language_folder in os.listdir(plugin_path):
plugin_packs[plugin_folder]["languages"].append(load_meta(os.path.join(plugin_path, language_folder), language_folder))
for language_entry in scandir(plugin_entry.path):
plugin_packs[plugin_entry.name]["languages"].append(load_meta(language_entry.path, language_entry.name))
else:
core_packs.append(load_meta(os.path.join(translation_folder, folder), folder))
core_packs.append(load_meta(entry.path, entry.name))
result = dict(_core=dict(identifier="_core", display="Core", languages=core_packs))
result.update(plugin_packs)
+11 -7
View File
@@ -5,7 +5,12 @@ __author__ = "Marc Hannappel Salandora"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
try:
from os import scandir
except ImportError:
from scandir import scandir
from flask import request, jsonify, url_for, make_response
from werkzeug.utils import secure_filename
@@ -52,15 +57,14 @@ def deleteLog(filename):
def _getLogFiles():
files = []
basedir = settings().getBaseFolder("logs")
for osFile in os.listdir(basedir):
statResult = os.stat(os.path.join(basedir, osFile))
for entry in scandir(basedir):
files.append({
"name": osFile,
"date": int(statResult.st_mtime),
"size": statResult.st_size,
"name": entry.name,
"date": int(entry.stat().st_mtime),
"size": entry.stat().st_size,
"refs": {
"resource": url_for(".downloadLog", filename=osFile, _external=True),
"download": url_for("index", _external=True) + "downloads/logs/" + osFile
"resource": url_for(".downloadLog", filename=entry.name, _external=True),
"download": url_for("index", _external=True) + "downloads/logs/" + entry.name
}
})
+20 -2
View File
@@ -11,15 +11,33 @@ import copy
from flask import jsonify, make_response, request, url_for
from werkzeug.exceptions import BadRequest
from octoprint.server.api import api, NO_CONTENT
from octoprint.server.util.flask import restricted_access
from octoprint.server.api import api, NO_CONTENT, valid_boolean_trues
from octoprint.server.util.flask import restricted_access, with_revalidation_checking
from octoprint.util import dict_merge
from octoprint.server import printerProfileManager
from octoprint.printer.profile import InvalidProfileError, CouldNotOverwriteError, SaveError
def _lastmodified():
return printerProfileManager.last_modified
def _etag(lm=None):
if lm is None:
lm = _lastmodified()
import hashlib
hash = hashlib.sha1()
hash.update(str(lm))
hash.update(repr(printerProfileManager.get_default()))
return hash.hexdigest()
@api.route("/printerprofiles", methods=["GET"])
@with_revalidation_checking(etag_factory=_etag,
lastmodified_factory=_lastmodified,
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
def printerProfilesList():
all_profiles = printerProfileManager.get_all()
return jsonify(dict(profiles=_convert_profiles(all_profiles)))
+19 -2
View File
@@ -11,19 +11,36 @@ from flask import request, jsonify, make_response
from werkzeug.exceptions import BadRequest
from octoprint.events import eventManager, Events
from octoprint.settings import settings
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import admin_permission, printer
from octoprint.server.api import api
from octoprint.server.util.flask import restricted_access
from octoprint.server.util.flask import restricted_access, with_revalidation_checking
import octoprint.plugin
import octoprint.util
#~~ settings
def _lastmodified():
return settings().last_modified
def _etag(lm=None):
if lm is None:
lm = _lastmodified()
connection_options = printer.__class__.get_connection_options()
import hashlib
hash = hashlib.sha1()
hash.update(str(lm))
hash.update(repr(connection_options))
return hash.hexdigest()
@api.route("/settings", methods=["GET"])
@with_revalidation_checking(etag_factory=_etag,
lastmodified_factory=_lastmodified,
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
def getSettings():
logger = logging.getLogger(__name__)
+33 -1
View File
@@ -9,7 +9,7 @@ from flask import request, jsonify, make_response, url_for
from werkzeug.exceptions import BadRequest
from octoprint.server import slicingManager
from octoprint.server.util.flask import restricted_access
from octoprint.server.util.flask import restricted_access, with_revalidation_checking
from octoprint.server.api import api, NO_CONTENT
from octoprint.settings import settings as s, valid_boolean_trues
@@ -17,7 +17,39 @@ from octoprint.settings import settings as s, valid_boolean_trues
from octoprint.slicing import UnknownSlicer, SlicerNotConfigured, ProfileAlreadyExists, UnknownProfile, CouldNotDeleteProfile
def _lastmodified(configured):
if configured:
slicers = slicingManager.configured_slicers
else:
slicers = slicingManager.registered_slicers
lms = [0]
for slicer in slicers:
lms.append(slicingManager.profiles_last_modified(slicer))
return max(lms)
def _etag(configured, lm=None):
if lm is None:
lm = _lastmodified(configured)
import hashlib
hash = hashlib.sha1()
hash.update(str(lm))
if configured:
hash.update(repr(sorted(slicingManager.configured_slicers)))
else:
hash.update(repr(sorted(slicingManager.registered_slicers)))
return hash.hexdigest()
@api.route("/slicing", methods=["GET"])
@with_revalidation_checking(etag_factory=lambda lm=None: _etag(request.values.get("configured", "false") in valid_boolean_trues, lm=lm),
lastmodified_factory=lambda: _lastmodified(request.values.get("configured", "false") in valid_boolean_trues),
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
def slicingListAll():
from octoprint.filemanager import get_extensions
+61 -6
View File
@@ -6,6 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
import threading
from flask import request, jsonify, url_for, make_response
from werkzeug.utils import secure_filename
@@ -15,7 +16,7 @@ import octoprint.util as util
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import admin_permission, printer
from octoprint.server.util.flask import redirect_to_tornado, restricted_access, get_json_command_from_request
from octoprint.server.util.flask import redirect_to_tornado, restricted_access, get_json_command_from_request, with_revalidation_checking
from octoprint.server.api import api
from octoprint.server import NO_CONTENT
@@ -23,8 +24,36 @@ from octoprint.server import NO_CONTENT
#~~ timelapse handling
_timelapse_cache_finished = []
_timelapse_cache_finished_lastmodified = None
_timelapse_cache_unrendered = []
_timelapse_cache_unrendered_lastmodified = None
_timelapse_cache_mutex = threading.RLock()
def _lastmodified(unrendered):
lm_finished = octoprint.timelapse.last_modified_finished()
if unrendered:
lm_unrendered = octoprint.timelapse.last_modified_unrendered()
if lm_finished is None or lm_unrendered is None:
return None
return max(lm_finished, lm_unrendered)
return lm_finished
def _etag(unrendered, lm=None):
if lm is None:
lm = _lastmodified(unrendered)
import hashlib
hash = hashlib.sha1()
hash.update(str(lm))
return hash.hexdigest()
@api.route("/timelapse", methods=["GET"])
@with_revalidation_checking(etag_factory=lambda lm=None: _etag(request.values.get("unrendered", "false") in valid_boolean_trues, lm=lm),
lastmodified_factory=lambda: _lastmodified(request.values.get("unrendered", "false") in valid_boolean_trues),
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
def getTimelapseData():
timelapse = octoprint.timelapse.current
@@ -41,15 +70,41 @@ def getTimelapseData():
else:
config = dict(type="off")
files = octoprint.timelapse.get_finished_timelapses()
force = request.values.get("force", "false") in valid_boolean_trues
unrendered = request.values.get("unrendered", "false") in valid_boolean_trues
global _timelapse_cache_finished_lastmodified, _timelapse_cache_finished, _timelapse_cache_unrendered_lastmodified, _timelapse_cache_unrendered
with _timelapse_cache_mutex:
current_lastmodified_finished = octoprint.timelapse.last_modified_finished()
current_lastmodified_unrendered = octoprint.timelapse.last_modified_unrendered()
if not force and _timelapse_cache_finished_lastmodified == current_lastmodified_finished:
files = _timelapse_cache_finished
else:
files = octoprint.timelapse.get_finished_timelapses()
_timelapse_cache_finished = files
_timelapse_cache_finished_lastmodified = current_lastmodified_finished
unrendered_files = []
if unrendered:
if not force and _timelapse_cache_unrendered_lastmodified == current_lastmodified_unrendered:
unrendered_files = _timelapse_cache_unrendered
else:
unrendered_files = octoprint.timelapse.get_unrendered_timelapses()
_timelapse_cache_unrendered = unrendered_files
_timelapse_cache_unrendered_lastmodified = current_lastmodified_unrendered
finished_list = []
for f in files:
f["url"] = url_for("index") + "downloads/timelapse/" + f["name"]
output = dict(f)
output["url"] = url_for("index") + "downloads/timelapse/" + f["name"]
finished_list.append(output)
result = dict(config=config,
files=files)
files=finished_list)
if "unrendered" in request.values and request.values["unrendered"] in valid_boolean_trues:
result.update(unrendered=octoprint.timelapse.get_unrendered_timelapses())
if unrendered:
result.update(unrendered=unrendered_files)
return jsonify(result)