Пример #1
0
def open_scenario(request, target, wrap_target=True):
    if wrap_target:
        target = workspace_path(target)
    print("Copying ", target, "to", db_path(), ". This could take several minutes...")
    close_old_connections()
    shutil.copy(target, db_path(name='scenario_db'))
    scenario_filename(os.path.basename(target))
    print('Sessions overwritten with ', target)
    update_db_version()
    unsaved_changes(False)  # File is now in sync
    SmSession.objects.all().update(iteration_text = '', simulation_has_started=outputs_exist())  # This is also reset from delete_all_outputs
    # else:
    #     print('File does not exist')
    return redirect('/setup/Scenario/1/')
Пример #2
0
    def handle(self, *args, **options):
        print("Preparing to migrate all Scenario Databases to the current state...")

        current_scenario = db_path(name='scenario_db')
        current_settings = db_path(name='default')
        moved_current = False
        try:
            shutil.move(current_scenario, current_scenario + '.tmp')
            shutil.move(current_settings, current_settings + '.tmp')
            moved_current = True
            print("Backed up current Active Session.")
        except:
            print("Failed to backup current Active Session! Note: it may just not exist which is fine.")

        graceful_startup()

        locations = [os.path.join(settings.BASE_DIR, 'ScenarioCreator', 'tests', 'population_fixtures'), os.path.join(settings.BASE_DIR, 'Sample Scenarios'), ]
        if not options['skip_workspace']:
            locations.append(workspace_path())
            print("\nIncluding User's Workspace folder.")
        else:
            print("\nExcluding User's Workspace folder.")

        connections['scenario_db'].close()
        close_old_connections()

        for location in locations:
            for root, dirs, files in os.walk(location):
                for file in files:
                    if file.endswith(".sqlite3") and file != "settings.sqlite3":
                        print("\nMigrating", file, "in", root + "...")
                        try:
                            open_test_scenario(request=None, target=os.path.join(root, file))
                            connections['scenario_db'].close()
                            close_old_connections()
                            shutil.move(db_path('scenario_db'), os.path.join(root, file))
                            print("\nDone.")
                        except Exception as e:
                            print("\nFailed to migrate", file + "!", e)
                            continue
        try:
            if moved_current:
                shutil.move(current_scenario + '.tmp', current_scenario)
                shutil.move(current_settings + '.tmp', current_settings)
                print("Reverted current Active Session.")
        except:
            print("Failed to revert current Active Session!")

        print("Completed migrating all Scenario Databases.")
Пример #3
0
    from django.conf import settings
    import django
    django.setup()

    from django.core import management

    from ADSMSettings.utils import db_path, workspace_path, scenario_filename
    from ADSMSettings.views import new_scenario, save_scenario
    from ADSMSettings.xml2sqlite import import_naadsm_xml
    from ScenarioCreator.models import DirectSpread


    if len(sys.argv) >= 4:  # single command line invocation
        print("""Usage: python3.4 ./xml2sqlite.py export_pop.xml parameters.xml debug.sqlite3 [--workspace]
        Include the flag '--workspace' as the fourth argument if you want to save the scenario to the ADSM Workspace""")
        shutil.copy(db_path(), workspace_path('activeSession.bak'))
        shutil.copy(db_path('default'), workspace_path('settings.bak'))
        
        popul_path = sys.argv[1]
        param_path = sys.argv[2]
        scenario_path = workspace_path(sys.argv[3]) if len(sys.argv) > 4 and sys.argv[4] == '--workspace' else sys.argv[3]
        scenario_name = os.path.basename(scenario_path)
        new_scenario()
        import_naadsm_xml(popul_path, param_path, saveIterationOutputsForUnits=False)
        scenario_filename(scenario_name, check_duplicates=True)
        save_scenario()
        count_model_entries()

        shutil.move(workspace_path(scenario_name), scenario_path)
        
        shutil.copy(workspace_path('activeSession.bak'), db_path())
Пример #4
-3
def save_scenario(request=None):
    """Save to the existing session of a new file name if target is provided
    """
    if request is not None and 'filename' in request.POST:
        target = request.POST['filename']
    else:
        target = scenario_filename()
    target = strip_tags(target)
    full_path = workspace_path(target) + ('.sqlite3' if not target.endswith('.sqlite3') else '')
    try:
        if '\\' in target or '/' in target:  # this validation has to be outside of scenario_filename in order for open_test_scenario to work
            raise ValueError("Slashes are not allowed: " + target)
        scenario_filename(target)
        print('Copying database to', target)

        shutil.copy(db_path(), full_path)
        unsaved_changes(False)  # File is now in sync
        print('Done Copying database to', full_path)
    except (IOError, AssertionError, ValueError) as err:
        if request is not None:
            save_error = 'Failed to save filename:' + str(err)
            print('Encountered an error while copying file', full_path)
            return render(request, 'ScenarioName.html', {"failure_message": save_error})

    if request is not None and request.is_ajax():
        return render(request, 'ScenarioName.html', {"success_message": "File saved to " + target,
                                                     "filename": scenario_filename(),
                                                     'unsaved_changes': unsaved_changes()})
    else:
        return redirect('/setup/Scenario/1/')