本文整理汇总了Python中fle_utils.config.models.Settings.get方法的典型用法代码示例。如果您正苦于以下问题:Python Settings.get方法的具体用法?Python Settings.get怎么用?Python Settings.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类fle_utils.config.models.Settings
的用法示例。
在下文中一共展示了Settings.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_keys
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def load_keys():
private_key_string = Settings.get("private_key")
public_key_string = Settings.get("public_key")
if private_key_string and public_key_string:
sys.modules[__name__]._own_key = Key(
public_key_string=public_key_string,
private_key_string=private_key_string)
else:
reset_keys()
示例2: setup_server_if_needed
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def setup_server_if_needed(self):
"""Run the setup command, if necessary."""
try: # Ensure that the database has been synced and a Device has been created
assert Settings.get("private_key") and Device.objects.count()
except (DatabaseError, AssertionError): # Otherwise, run the setup command
self.stdout.write("Setting up KA Lite; this may take a few minutes; please wait!\n")
call_command("setup", interactive=False)
# Double check that the setup process successfully created a Device
assert Settings.get("private_key") and Device.objects.count(), "There was an error configuring the server. Please report the output of this command to Learning Equality."
示例3: setup_server_if_needed
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def setup_server_if_needed(self):
"""Run the setup command, if necessary.
It's necessary if the Settings model doesn't have a "database_version" or if that version doesn't match
kalite.version.VERSION, indicating the source has been changed. Then setup is run to create/migrate the db.
"""
try:
from kalite.version import VERSION
assert Settings.get("database_version") == VERSION
except (DatabaseError, AssertionError):
logging.info("Setting up KA Lite; this may take a few minutes; please wait!\n")
call_command("setup", interactive=False)
# Double check the setup process worked ok.
assert Settings.get("database_version") == VERSION, "There was an error configuring the server. Please report the output of this command to Learning Equality."
示例4: set_default_language
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def set_default_language(request, lang_code, global_set=False):
"""
global_set has different meanings for different users.
For students, it means their personal default language
For teachers, it means their personal default language
For django users, it means the server language.
"""
# Get lang packs directly, to force reloading, as they may have changed.
lang_packs = get_installed_language_packs(force=True).keys()
lang_code = select_best_available_language(lang_code, available_codes=lang_packs) # Make sure to reload available languages; output is in django_lang format
if lang_code != request.session.get("default_language"):
logging.debug("setting session language to %s" % lang_code)
request.session["default_language"] = lang_code
if global_set:
if request.is_django_user and lang_code != Settings.get("default_language"):
logging.debug("setting server default language to %s" % lang_code)
Settings.set("default_language", lang_code)
elif not request.is_django_user and request.is_logged_in and lang_code != request.session["facility_user"].default_language:
logging.debug("setting user default language to %s" % lang_code)
request.session["facility_user"].default_language = lang_code
request.session["facility_user"].save()
set_request_language(request, lang_code)
示例5: handle
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def handle(self, *args, **options):
if Settings.get("private_key"):
self.stderr.write("Error: This device already has an encryption key generated for it; aborting.\n")
return
self.stdout.write("Generating 2048-bit RSA encryption key (may take a few minutes; please wait)...\n")
reset_keys()
self.stdout.write("Done!\n")
示例6: facility_from_request_wrapper_fn
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def facility_from_request_wrapper_fn(request, *args, **kwargs):
facility = None
if kwargs.get("facility_id", None): # avoid using blank
# Facility passed in directly
facility = get_object_or_None(Facility, pk=kwargs["facility_id"])
del kwargs["facility_id"]
if not facility and "facility" in request.GET:
# Facility from querystring
facility = get_object_or_None(Facility, pk=request.GET["facility"])
if facility:
pass
elif settings.CENTRAL_SERVER: # following options are distributed-only
facility = None
elif "facility_user" in request.session:
# Facility from currently logged-in facility user
facility = request.session["facility_user"].facility
elif request.session["facility_count"] == 1:
# There's only one facility
facility = Facility.objects.all()[0]
elif request.session["facility_count"] > 0:
if Settings.get("default_facility"):
# There are multiple facilities--try to grab the default
facility = get_object_or_None(Facility, pk=Settings.get("default_facility"))
elif Facility.objects.filter(Q(signed_by__isnull=True) | Q(signed_by=Device.get_own_device())).count() == 1:
# Default to a locally created facility (if there are multiple, and none are specified)
facility = Facility.objects.filter(Q(signed_by__isnull=True) | Q(signed_by=Device.get_own_device()))[0]
else:
facility = None
else:
# There's nothing; don't bother even hitting the DB
facility = None
if "set_default" in request.GET and request.is_admin and facility:
Settings.set("default_facility", facility.id)
if facility or "facility" not in kwargs: # this syntax allows passed in facility param to work.
kwargs["facility"] = facility
return handler(request, *args, **kwargs)
示例7: setup_server_if_needed
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def setup_server_if_needed(self):
"""Run the setup command, if necessary."""
try: # Ensure that the database has been synced and a Device has been created
assert Settings.get("private_key") and Device.objects.count()
except (DatabaseError, AssertionError): # Otherwise, run the setup command
self.stdout.write("Setting up KA Lite; this may take a few minutes; please wait!\n")
call_command("setup", interactive=False)
示例8: get_current_unit_settings_value
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def get_current_unit_settings_value(facility_id):
"""
Get value of current unit based on facility id. If none, defaults to 1 and creates an
entry on the Settings.
"""
name = get_current_unit_settings_name(facility_id)
value = Settings.get(name, UNITS[0])
if value == 0:
# This may be the first time this facility`s current unit is queried so
# make sure it has a value at Settings so we can either change it on
# the admin page or at front-end code later.
value = 1
Settings.set(name, value)
return value
示例9: initialize_default_facility
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def initialize_default_facility(cls, facility_name=None):
facility_name = facility_name or getattr(settings, "INSTALL_FACILITY_NAME", None) or unicode(_("Default Facility"))
# Finally, install a facility--would help users get off the ground
facilities = Facility.objects.filter(name=facility_name)
if facilities.count() == 0:
# Create a facility, set it as the default.
facility = Facility(name=facility_name)
facility.save()
Settings.set("default_facility", facility.id)
elif Settings.get("default_facility") not in [fac.id for fac in facilities.all()]:
# Use an existing facility as the default, if one of them isn't the default already.
Settings.set("default_facility", facilities[0].id)
示例10: set_language_data
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def set_language_data(request):
"""
Process requests to set language, redirect to the same URL to continue processing
without leaving the "set" in the browser history.
"""
if "set_server_language" in request.GET:
# Set the current server default language, and redirect (to clean browser history)
if not request.is_admin:
raise PermissionDenied(_("You don't have permissions to set the server's default language."))
set_default_language(request, lang_code=request.GET["set_server_language"], global_set=True)
# Redirect to the same URL, but without the GET param,
# to remove the language setting from the browser history.
redirect_url = set_query_params(request.get_full_path(), {"set_server_language": None})
return HttpResponseRedirect(redirect_url)
elif "set_user_language" in request.GET:
# Set the current user's session language, and redirect (to clean browser history)
set_default_language(request, request.GET["set_user_language"], global_set=(request.is_logged_in and not request.is_django_user))
# Redirect to the same URL, but without the GET param,
# to remove the language setting from the browser history.
redirect_url = set_query_params(request.get_full_path(), {"set_user_language": None})
return HttpResponseRedirect(redirect_url)
if not "default_language" in request.session:
# default_language has the following priority:
# facility user's individual setting
# config.Settings object's value
# settings' value
request.session["default_language"] = select_best_available_language( \
getattr(request.session.get("facility_user"), "default_language", None) \
or Settings.get("default_language") \
or settings.LANGUAGE_CODE
)
# Set this request's language based on the listed priority
cur_lang = request.GET.get("lang") \
or request.session.get("default_language")
set_request_language(request, lang_code=cur_lang)
示例11: setup_server_if_needed
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def setup_server_if_needed(self):
"""Run the setup command, if necessary."""
# Now, validate the server.
try:
if Settings.get("private_key") and Device.objects.count():
# The only success case
pass
elif not Device.objects.count():
# Nothing we can do to recover
raise CommandError("You are screwed, buddy--you went through setup but you have no devices defined! Call for help!")
else:
# Force hitting recovery code, by raising a generic error
# that gets us to the "except" clause
raise DatabaseError
except DatabaseError:
self.stdout.write("Setting up KA Lite; this may take a few minutes; please wait!\n")
call_command("setup", interactive=False) # show output to the user
示例12: handle
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def handle(self, *args, **options):
if not options["interactive"]:
options["hostname"] = options["hostname"] or get_host_name()
# blank allows ansible scripts to dump errors cleanly.
print(" ")
print(" _ __ ___ _ _ _ ")
print(" | | / / / _ \ | | (_) | ")
print(" | |/ / / /_\ \ | | _| |_ ___ ")
print(" | \ | _ | | | | | __/ _ \ ")
print(" | |\ \| | | | | |___| | || __/ ")
print(" \_| \_/\_| |_/ \_____/_|\__\___| ")
print(" ")
print("http://kalite.learningequality.org")
print(" ")
print(" version %s" % VERSION)
print(" ")
if sys.version_info >= (2, 8) or sys.version_info < (2, 6):
raise CommandError(
"You must have Python version 2.6.x or 2.7.x installed. Your version is: %s\n" % str(sys.version_info))
if sys.version_info < (2, 7, 9):
logging.warning(
"It's recommended that you install Python version 2.7.9. Your version is: %s\n" % str(sys.version_info))
if options["interactive"]:
print(
"--------------------------------------------------------------------------------")
print(
"This script will configure the database and prepare it for use.")
print(
"--------------------------------------------------------------------------------")
raw_input("Press [enter] to continue...")
# Tried not to be os-specific, but ... hey. :-/
# benjaoming: This doesn't work, why is 502 hard coded!? Root is normally
# '0' And let's not care about stuff like this, people can be free to
# run this as root if they want :)
if not is_windows() and hasattr(os, "getuid") and os.getuid() == 502:
print(
"-------------------------------------------------------------------")
print("WARNING: You are installing KA-Lite as root user!")
print(
"\tInstalling as root may cause some permission problems while running")
print("\tas a normal user in the future.")
print(
"-------------------------------------------------------------------")
if options["interactive"]:
if not raw_input_yn("Do you wish to continue and install it as root?"):
raise CommandError("Aborting script.\n")
git_migrate_path = options["git_migrate_path"]
if git_migrate_path:
call_command("gitmigrate", path=git_migrate_path)
# TODO(benjaoming): This is used very loosely, what does it mean?
# Does it mean that the installation path is clean or does it mean
# that we should remove (clean) items from a previous installation?
install_clean = not kalite.is_installed()
database_kind = settings.DATABASES["default"]["ENGINE"]
database_file = (
"sqlite" in database_kind and settings.DATABASES["default"]["NAME"]) or None
if database_file and os.path.exists(database_file):
# We found an existing database file. By default,
# we will upgrade it; users really need to work hard
# to delete the file (but it's possible, which is nice).
print(
"-------------------------------------------------------------------")
print("WARNING: Database file already exists!")
print(
"-------------------------------------------------------------------")
if not options["interactive"] \
or raw_input_yn("Keep database file and upgrade to KA Lite version %s? " % VERSION) \
or not raw_input_yn("Remove database file '%s' now? " % database_file) \
or not raw_input_yn("WARNING: all data will be lost! Are you sure? "):
install_clean = False
print("Upgrading database to KA Lite version %s" % VERSION)
else:
install_clean = True
print("OK. We will run a clean install; ")
# After all, don't delete--just move.
print(
"the database file will be moved to a deletable location.")
if not install_clean and not database_file and not kalite.is_installed():
# Make sure that, for non-sqlite installs, the database exists.
raise Exception(
"For databases not using SQLite, you must set up your database before running setup.")
# Do all input at once, at the beginning
if install_clean and options["interactive"]:
if not options["username"] or not options["password"]:
print(
"Please choose a username and password for the admin account on this device.")
print(
"\tYou must remember this login information, as you will need")
print(
#.........这里部分代码省略.........
示例13: handle
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def handle(self, *args, **options):
if not options["interactive"]:
options["hostname"] = options["hostname"] or get_host_name()
# blank allows ansible scripts to dump errors cleanly.
logger.info(
" \n"
" _ __ ___ _ _ _ \n"
" | | / / / _ \ | | (_) | \n"
" | |/ / / /_\ \ | | _| |_ ___ \n"
" | \ | _ | | | | | __/ _ \ \n"
" | |\ \| | | | | |___| | || __/ \n"
" \_| \_/\_| |_/ \_____/_|\__\___| \n"
" \n"
"https://learningequality.org/ka-lite/\n"
" \n"
" version {version:s}\n"
" ".format(
version=VERSION
)
)
if sys.version_info < (2, 7):
raise CommandError(
"Support for Python version 2.6 and below had been discontinued, please upgrade.")
elif sys.version_info >= (2, 8):
raise CommandError(
"Your Python version is: %d.%d.%d -- which is not supported. Please use the Python 2.7 series or wait for Learning Equality to release Kolibri.\n" % sys.version_info[:3])
elif sys.version_info < (2, 7, 6):
logger.warning(
"It's recommended that you install Python version 2.7.6. Your version is: %d.%d.%d\n" % sys.version_info[:3])
if options["interactive"]:
logger.info(
"--------------------------------------------------------------------------------\n"
"This script will configure the database and prepare it for use.\n"
"--------------------------------------------------------------------------------\n"
)
raw_input("Press [enter] to continue...")
# Assuming uid '0' is always root
if not is_windows() and hasattr(os, "getuid") and os.getuid() == 0:
logger.info(
"-------------------------------------------------------------------\n"
"WARNING: You are installing KA-Lite as root user!\n"
" Installing as root may cause some permission problems while running\n"
" as a normal user in the future.\n"
"-------------------------------------------------------------------\n"
)
if options["interactive"]:
if not raw_input_yn("Do you wish to continue and install it as root?"):
raise CommandError("Aborting script.\n")
database_kind = settings.DATABASES["default"]["ENGINE"]
if "sqlite" in database_kind:
database_file = settings.DATABASES["default"]["NAME"]
else:
database_file = None
database_exists = database_file and os.path.isfile(database_file)
# An empty file is created automatically even when the database dosn't
# exist. But if it's empty, it's safe to overwrite.
database_exists = database_exists and os.path.getsize(
database_file) > 0
install_clean = not database_exists
if database_file:
if not database_exists:
install_clean = True
else:
# We found an existing database file. By default,
# we will upgrade it; users really need to work hard
# to delete the file (but it's possible, which is nice).
logger.info(
"-------------------------------------------------------------------\n"
"WARNING: Database file already exists!\n"
"-------------------------------------------------------------------"
)
if not options["interactive"] \
or raw_input_yn("Keep database file and upgrade to KA Lite version %s? " % VERSION) \
or not raw_input_yn("Remove database file '%s' now? " % database_file) \
or not raw_input_yn("WARNING: all data will be lost! Are you sure? "):
install_clean = False
logger.info("Upgrading database to KA Lite version %s" % VERSION)
else:
install_clean = True
logger.info("OK. We will run a clean install; ")
# After all, don't delete--just move.
logger.info(
"the database file will be moved to a deletable "
"location."
)
if not install_clean and not database_file:
# Make sure that, for non-sqlite installs, the database exists.
raise Exception(
"For databases not using SQLite, you must set up your database before running setup.")
#.........这里部分代码省略.........
示例14: get_default_language
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def get_default_language():
"""Returns: the default language (ietf-formatted language code)"""
return Settings.get("default_language") or settings.LANGUAGE_CODE or "en"
示例15: user_progress
# 需要导入模块: from fle_utils.config.models import Settings [as 别名]
# 或者: from fle_utils.config.models.Settings import get [as 别名]
def user_progress(cls, user_id, language=None):
"""
Return a list of PlaylistProgress objects associated with the user.
"""
if not language:
language = Settings.get("default_language") or settings.LANGUAGE_CODE
user = FacilityUser.objects.get(id=user_id)
# Retrieve video, exercise, and quiz logs that appear in this playlist
user_vid_logs, user_ex_logs = cls.get_user_logs(user)
exercise_ids = list(set([ex_log["exercise_id"] for ex_log in user_ex_logs]))
video_ids = list(set([vid_log["video_id"] for vid_log in user_vid_logs]))
# Build a list of playlists for which the user has at least one data point
user_playlists = get_content_parents(ids=exercise_ids+video_ids, language=language)
# Store stats for each playlist
user_progress = list()
for i, p in enumerate(user_playlists):
# Playlist entry totals
pl_video_ids, pl_exercise_ids = cls.get_playlist_entry_ids(p)
n_pl_videos = float(len(pl_video_ids))
n_pl_exercises = float(len(pl_exercise_ids))
# Vid & exercise logs in this playlist
pl_ex_logs = [ex_log for ex_log in user_ex_logs if ex_log["exercise_id"] in pl_exercise_ids]
pl_vid_logs = [vid_log for vid_log in user_vid_logs if vid_log["video_id"] in pl_video_ids]
# Compute video stats
n_vid_complete = len([vid for vid in pl_vid_logs if vid["complete"]])
n_vid_started = len([vid for vid in pl_vid_logs if (vid["total_seconds_watched"] > 0) and (not vid["complete"])])
vid_pct_complete = int(float(n_vid_complete) / n_pl_videos * 100) if n_pl_videos else 0
vid_pct_started = int(float(n_vid_started) / n_pl_videos * 100) if n_pl_videos else 0
if vid_pct_complete == 100:
vid_status = "complete"
elif n_vid_started > 0:
vid_status = "inprogress"
else:
vid_status = "notstarted"
# Compute exercise stats
n_ex_mastered = len([ex for ex in pl_ex_logs if ex["complete"]])
n_ex_started = len([ex for ex in pl_ex_logs if ex["attempts"] > 0])
n_ex_incomplete = len([ex for ex in pl_ex_logs if (ex["attempts"] > 0 and not ex["complete"])])
n_ex_struggling = len([ex for ex in pl_ex_logs if ex["struggling"]])
ex_pct_mastered = int(float(n_ex_mastered) / (n_pl_exercises or 1) * 100)
ex_pct_incomplete = int(float(n_ex_incomplete) / (n_pl_exercises or 1) * 100)
ex_pct_struggling = int(float(n_ex_struggling) / (n_pl_exercises or 1) * 100)
if not n_ex_started:
ex_status = "notstarted"
elif ex_pct_struggling > 0:
# note: we want to help students prioritize areas they need to focus on
# therefore if they are struggling in this exercise group, we highlight it for them
ex_status = "struggling"
elif ex_pct_mastered < 99:
ex_status = "inprogress"
else:
ex_status = "complete"
progress = {
"title": p.get("title"),
"id": p.get("id"),
"tag": p.get("tag"),
"vid_pct_complete": vid_pct_complete,
"vid_pct_started": vid_pct_started,
"vid_status": vid_status,
"ex_pct_mastered": ex_pct_mastered,
"ex_pct_incomplete": ex_pct_incomplete,
"ex_pct_struggling": ex_pct_struggling,
"ex_status": ex_status,
"n_pl_videos": n_pl_videos,
"n_pl_exercises": n_pl_exercises,
}
try:
progress["url"] = reverse("view_playlist", kwargs={"playlist_id": p.get("id")})
except NoReverseMatch:
progress["url"] = reverse("learn") + p.get("path")
user_progress.append(cls(**progress))
return user_progress