Self hosted FLOSS fitness/workout, nutrition and weight tracker
Move further functions to invoke's task file
Roland Geider0a585eb7f376
diff --git a/tasks.py b/tasks.pyindex 9f611cdf2..24e702951 100644--- a/tasks.py+++ b/tasks.py@@ -15,21 +15,166 @@# You should have received a copy of the GNU Affero General Public Licenseimport os-import inspect-import django+import sysimport time-import webbrowser+import django+import base64+import inspectimport threading+import webbrowserfrom invoke import run, taskfrom django.core.management import call_command-+from wger.utils.main import (+ get_user_data_path,+ get_user_config_path,+ detect_listen_opts,+ setup_django_environment+)os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')django.setup()+@task+def bootstrap_app(settings=None, address='localhost', port=8000, no_browser=False, upgrade_db=False, reset_admin=False):+ '''+ Performs all steps necessary to bootstrap the application+ '''++ # Find the path to the settings+ settings_path = settings+ # if settings_path is None:+ # settings_path = get_user_config_path('wger', 'settings.py')++ # Override URL if no browser should be started+ addr, port = detect_listen_opts(address, port)+ if no_browser:+ url = None+ else:+ # Find url to wger+ if port == 80:+ url = "http://{0}".format(addr)+ else:+ url = "http://{0}:{1}".format(addr, port)++ # print(settings_path)+ # print(port)+ # print(url)+ # sys.exit()+++ # Create settings if necessary+ if not os.path.exists(settings_path):+ create_settings(settings_path, url=url)++ # Set the django environment to the settings+ setup_django_environment(settings_path)++ # Create Database if necessary+ if not database_exists() or upgrade_db:+ migrate_db()+ create_or_reset_admin()++ # Only run the south migrations+ elif upgrade_db:+ migrate_db()++ # Reset Admin+ elif reset_admin:+ create_or_reset_admin()++ # Start wger+ # if opts.no_reload:+ # extra_args = ['--noreload']+ # else:+ # extra_args = []+ #+ # start_wger(addr, port, start_browser_url=url, extra_args=extra_args)+++@task+def database_exists():+ """Detect if the database exists"""++ # can't be imported in global scope as they already require+ # the settings module during import+ from django.db import DatabaseError+ from django.core.exceptions import ImproperlyConfigured+ from wger.manager.models import User++ try:+ # TODO: Use another model, the User could be deactivated+ User.objects.count()+ except DatabaseError:+ return False+ except ImproperlyConfigured:+ print("Your settings file seems broken")+ sys.exit(0)+ else:+ return True++++@task+def create_settings(settings_path=None, database_path=None, url=None, database_type='sqlite3', key_length=30):+ if settings_path is None:+ settings_path = get_user_config_path('wger', 'settings.py')+ settings_module = os.path.dirname(settings_path)+ print("* Creating settings file at {0}".format(settings_module))++ if database_path is None:+ database_path = get_user_data_path('wger', 'database.sqlite')+ dbpath_value = repr(database_path)++ media_folder_path = get_user_data_path('wger', 'media')+ print("Please edit your settings file and enter the values for the reCaptcha keys ")+ print("You can leave this empty, but won't be able to register new users")++ # Fill in the config file template++ # os.chdir(os.path.dirname(inspect.stack()[0][1]))+ settings_template = os.path.join(os.getcwd(), 'wger', 'settings.tpl')+ with open(settings_template, 'r') as settings_file:+ settings_content = settings_file.read()+ # The environment variable is set by travis during testing+ if database_type == 'postgresql':+ dbengine = 'postgresql_psycopg2'+ dbname = "'test_wger'"+ dbuser = 'postgres'+ dbpassword = ''+ dbhost = '127.0.0.1'+ dbport = ''+ elif database_type == 'sqlite3':+ dbengine = 'sqlite3'+ dbname = dbpath_value+ dbuser = ''+ dbpassword = ''+ dbhost = ''+ dbport = ''++ settings_content = settings_content.format(dbname=dbname,+ dbpath=dbpath_value,+ dbengine=dbengine,+ dbuser=dbuser,+ dbpassword=dbpassword,+ dbhost=dbhost,+ dbport=dbport,+ default_key=base64.b64encode(os.urandom(key_length)),+ siteurl=url,+ media_folder_path=media_folder_path)++ if not os.path.exists(settings_module):+ os.makedirs(settings_module)++ if not os.path.exists(os.path.dirname(database_path)):+ os.makedirs(os.path.dirname(database_path))++ with open(settings_path, 'w') as settings_file:+ settings_file.write(settings_content)++@taskdef create_or_reset_admin():# can't be imported in global scope as it already requiresdiff --git a/wger/settings.tpl b/wger/settings.tplnew file mode 100644index 000000000..0f87ca3f2--- /dev/null+++ b/wger/settings.tpl@@ -0,0 +1,50 @@+#!/usr/bin/env python+# -*- coding: utf-8 -*-++from wger.settings_global import *++# Use 'DEBUG = True' to get more details for server errors+DEBUG = True+TEMPLATE_DEBUG = DEBUG++ADMINS = (+ ('Your name', '[email protected]'),+)+MANAGERS = ADMINS+++DATABASES = {{+ 'default': {{+ 'ENGINE': 'django.db.backends.{dbengine}',+ 'NAME': {dbname},+ 'USER': '{dbuser}',+ 'PASSWORD': '{dbpassword}',+ 'HOST': '{dbhost}',+ 'PORT': '{dbport}',+ }}+}}++# Make this unique, and don't share it with anybody.+SECRET_KEY = {default_key}++# Your reCaptcha keys+RECAPTCHA_PUBLIC_KEY = ''+RECAPTCHA_PRIVATE_KEY = ''+NOCAPTCHA = True++# The site's URL (e.g. http://www.my-local-gym.com or http://localhost:8000)+# This is needed for Mozilla's BrowserID to work+SITE_URL = '{siteurl}'+BROWSERID_AUDIENCES = [SITE_URL]++# This might be a good idea if you setup memcached+#SESSION_ENGINE = "django.contrib.sessions.backends.cache"+++# Path to uploaded files+# Absolute filesystem path to the directory that will hold user-uploaded files.+MEDIA_ROOT = '{media_folder_path}'+MEDIA_URL = SITE_URL + '/static/'+if DEBUG:+ # Serve the uploaded files like this only during development+ STATICFILES_DIRS = (MEDIA_ROOT, )\ No newline at end of filediff --git a/wger/utils/main.py b/wger/utils/main.pynew file mode 100644index 000000000..2ebab5929--- /dev/null+++ b/wger/utils/main.py@@ -0,0 +1,97 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++import logging+import sys+import os+import ctypes+import socket++import django++logger = logging.getLogger(__name__)+++def get_user_data_path(*args):+ if sys.platform == "win32":+ return win32_get_app_data_path(*args)++ data_home = os.environ.get(+ 'XDG_DATA_HOME', os.path.join(+ os.path.expanduser('~'), '.local', 'share'))++ return os.path.join(data_home, *args)+++def get_user_config_path(*args):+ if sys.platform == "win32":+ return win32_get_app_data_path(*args)++ config_home = os.environ.get(+ 'XDG_CONFIG_HOME', os.path.join(os.path.expanduser('~'), '.config'))++ return os.path.join(config_home, *args)++++def win32_get_app_data_path(*args):+ shell32 = ctypes.WinDLL("shell32.dll")+ SHGetFolderPath = shell32.SHGetFolderPathW+ SHGetFolderPath.argtypes = (+ ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32,+ ctypes.c_wchar_p)+ SHGetFolderPath.restype = ctypes.c_uint32++ CSIDL_LOCAL_APPDATA = 0x001c+ MAX_PATH = 260++ buf = ctypes.create_unicode_buffer(MAX_PATH)+ res = SHGetFolderPath(0, CSIDL_LOCAL_APPDATA, 0, 0, buf)+ if res != 0:+ raise Exception("Could not deterime APPDATA path")++ return os.path.join(buf.value, *args)+++def detect_listen_opts(address, port):+ if address is None:+ try:+ address = socket.gethostbyname(socket.gethostname())+ except socket.error:+ address = "127.0.0.1"++ if port is None:+ # test if we can use port 80+ s = socket.socket()+ port = 80+ try:+ s.bind((address, port))+ s.listen(-1)+ except socket.error:+ port = 8000+ finally:+ s.close()++ return address, port+++def setup_django_environment(settings_path):+ settings_file = os.path.basename(settings_path)+ settings_module_name = "".join(settings_file.split('.')[:-1])+ if '.' in settings_module_name:+ print("'.' is not an allowed character in the settings-file")+ sys.exit(1)+ settings_module_dir = os.path.dirname(settings_path)+ sys.path.append(settings_module_dir)+ os.environ[django.conf.ENVIRONMENT_VARIABLE] = '%s' % settings_module_name