Exemplo n.º 1
0
def updateSetting():
    form = SettingsForm()
    if not current_user.is_authenticated:
        return redirect(url_for('index'))

    try:
        if current_user.forgot_password:
            current_user.set_password(form.new_password.data)
            current_user.forgot_password = False
            db.session.commit()
            return "Your password was successfully changed!"

        validation = form.validate_password(current_user)
        print('validated password')
        if validation:
            print(form.new_password.data)
            current_user.set_password(form.new_password.data)
            db.session.commit()
            return "Your password was successfully changed!"
        else:
            print(validation)

    except ValidationError as e:
        print("Error is: " + str(e))
        return (str(e))
Exemplo n.º 2
0
def settings(request):
    if request.method == "GET":
        form = SettingsForm(initial={
            "username": request.user.username,
            "email": request.user.email
        })
    else:
        form = SettingsForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            user = request.user
            if form.cleaned_data["username"] != user.username:
                user.username = form.cleaned_data["username"]
            if form.cleaned_data["email"] != user.email:
                user.email = form.cleaned_data["email"]
            if form.cleaned_data["password"]:
                user.set_password(form.cleaned_data["password"])
            if form.cleaned_data["avatar"]:
                profile = Profile.objects.get(user=user)
                new_photo = upload_image(form.cleaned_data["avatar"], user.id)
                flag = False
                if profile.avatar == BASE_AVATAR:
                    flag = True
                profile.avatar = new_photo
                profile.save()
                if flag:
                    change_photos(user)
            user.save()

    return render(request, "settings.html", {
        "form": form,
        "avatar": Profile.objects.get(user=request.user).avatar,
    })
Exemplo n.º 3
0
def settings():
    sfo = SettingsForm()

    class Einstellungen:
        pass

    if conf.IPC_FLAG:
        msg = '{"cmd": "get-settings" }'
        queue_c_to_s.put(msg)
        result = queue_s_to_c.get()  # list of dict
        logger.info("/settings: {}".format(msg))

    einstellungen = Einstellungen()
    einstellungen.dauer_manuell = result[1]['val']  # int!

    if sfo.validate_on_submit():
        if isNotBlank(sfo.dauer_manuell.data):
            einstellungen.dauer_manuell = int(sfo.dauer_manuell.data)

        if conf.IPC_FLAG:
            D = {'type': 'manual_delay', 'val': int(sfo.dauer_manuell.data)}
            msg = json.dumps({"cmd": "set-settings", "manual_delay": D})
            logger.info("{}".format(msg))
            queue_c_to_s.put(msg)
            result = queue_s_to_c.get()

        return redirect(url_for('settings'))

    return render_template('settings.html',
                           title='Einstellungen',
                           sfo=sfo,
                           einstellungen=einstellungen)
Exemplo n.º 4
0
def admin_settings():
    form = SettingsForm()
    admin = db.session.query(Administrator).get(1)
    if request.method == "GET":
        form.username.data = admin.username
        form.first_name.data = admin.first_name
        form.last_name.data = admin.last_name
        form.email.data = admin.email

        form.jumbotron_header.data = admin.jumbotron_header
        form.jumbotron_subheader.data = admin.jumbotron_subheader

        form.desc_details.data = admin.desc_details
        form.desc_header.data = admin.desc_header

        form.about_details.data = admin.about_detail
        form.about_heading.data = admin.about_heading

        form.site_dominant_color.data = admin.site_dominant_color
        form.site_accent_color.data = admin.site_accent_color

        form.facebook.data = admin.facebook
        form.twitter.data = admin.twitter
        form.instagram.data = admin.instagram
        form.soundcloud.data = admin.soundcloud
        form.spotify.data = admin.spotify
        form.youtube.data = admin.youtube

    if form.validate_on_submit():
        admin = db.session.query(Administrator).get(1)
        admin.first_name = form.first_name.data
        admin.last_name = form.last_name.data
        admin.email = form.email.data

        admin.jumbotron_header = form.jumbotron_header.data
        admin.jumbotron_subheader = form.jumbotron_subheader.data
        admin.desc_header = form.desc_header.data
        admin.desc_details = form.desc_details.data

        admin.about_detail = form.about_details.data
        admin.about_heading = form.about_heading.data

        admin.site_dominant_color = form.site_dominant_color.data
        admin.site_accent_color = form.site_accent_color.data
        admin.facebook = form.facebook.data
        admin.twitter = form.twitter.data
        admin.soundcloud = form.soundcloud.data
        admin.spotify = form.spotify.data
        admin.youtube = form.youtube.data
        admin.instagram = form.instagram.data

        db.session.add(admin)
        db.session.commit()

        message = Markup(
            '<div class="alert alert-success alert-dismissible"><button type="button" class="close" data-dismiss="alert">&times;</button>Settings saved</div>'
        )
        flash(message)
        return redirect(url_for('admin_settings'))
    return render_template('admin/settings.html', form=form)
Exemplo n.º 5
0
def view_settings():
    form = SettingsForm()
    if form.validate_on_submit():
        print form.node_details_plot_back_period.data
        update_setting("NODE_DETAILS_PLOT_BACK_PERIOD",
                       form.node_details_plot_back_period.data,
                       int)
        update_setting("SERVER_TEMP_PLOT_BACK_PERIOD",
                       form.server_temp_plot_back_period.data,
                       int)
        update_setting("PROC_MAX_TEMP_LIMIT",
                       form.server_temp_proc_max_temp_limit.data,
                       float)
        update_setting("ENVIRONMENT_BACK_PLOT_PERIOD",
                       form.temperature_back_plot_period.data,
                       int)
        update_setting("ENVIRONMENT_SCAN_PERIOD",
                       form.temperature_scan_period.data,
                       float)
        flash("Settings successfully changed!")
    details_plot_back_period = get_setting("NODE_DETAILS_PLOT_BACK_PERIOD", int)
    server_temp_plot_back_period = get_setting("SERVER_TEMP_PLOT_BACK_PERIOD", int)
    server_temp_proc_max_temp_limit = get_setting("PROC_MAX_TEMP_LIMIT", float)
    temperature_plot_back_period = get_setting("ENVIRONMENT_BACK_PLOT_PERIOD", int)
    temperature_scan_period = get_setting("ENVIRONMENT_SCAN_PERIOD", float)

    form.node_details_plot_back_period.data = details_plot_back_period.value
    form.server_temp_plot_back_period.data = server_temp_plot_back_period.value
    form.server_temp_proc_max_temp_limit.data = server_temp_proc_max_temp_limit.value
    form.temperature_back_plot_period.data = temperature_plot_back_period.value
    form.temperature_scan_period.data = temperature_scan_period.value
    return render_template("settings.html",
                           form=form,
                           page_loc="settings")
Exemplo n.º 6
0
def settings():
	form = SettingsForm()
	if form.validate_on_submit():
		current_user.secret = form.secret.data
		db.session.commit()
		flash('Secret successfully stored.')
		return redirect(url_for('index'))
	return render_template('settings.html', title='Settings', form=form)
Exemplo n.º 7
0
def settings():
    form = SettingsForm(obj=current_user)
    if form.validate_on_submit():
        current_user.daily_email = form.daily_email.data
        db.session.commit()
        flash('Your preferences have been updated')
        return redirect(url_for('index'))
    return render_template('settings.html', title='Settings', form=form)
Exemplo n.º 8
0
def settings():
    form = SettingsForm()
    if form.validate_on_submit():
        flash('Settings saved!')
        session['cf_login'] = form.cf_login.data
    else:
        if 'cf_login' in session:
            form.cf_login.data = session['cf_login']
    return render_template('settings.html', form=form, title='Settings')
Exemplo n.º 9
0
def settings():
    form = SettingsForm(request.form)
    if form.validate_on_submit():
        if form.newpassword.data and form.oldpassword.data and form.repeat.data:
            current_user.set_password(form.newpassword.data)
            current_user.save()
            flash("Successfully set new password")
        return redirect(url_for('settings'))
    else:
        return render_template("settings.html", form=form)
Exemplo n.º 10
0
def settings():
    form = SettingsForm(current_user.username)
    if form.validate_on_submit():
        current_user.username = form.username.data
        db.session.commit()
        flash('Your changes have been saved.')
        return redirect(url_for('settings'))
    elif request.method == 'GET':
        form.username.data = current_user.username
    return render_template('settings.html', title='Edit Profile', form=form)
Exemplo n.º 11
0
def setSettings():
    form = SettingsForm()
    if form.validate_on_submit():
        if form.token.data != "":
            current_user.token = form.token.data
            db.session.commit()
            flash(f'New token has been successfully set {current_user.token}')
        if form.passphrase.data != "":
            current_user.grades_password = form.passphrase.data
            db.session.commit()
        return redirect(url_for('index'))
    return render_template('settings.html', title='Settings', form=form)
Exemplo n.º 12
0
def settings():
    form = None
    if current_user.service == 'local':
        form = SettingsForm(request.form, current_user)
    if request.method == 'POST' and form.validate():
        current_user.email = form.email.data
        current_user.name = form.name.data
        if form.password.data != None:
            current_user.set_password(form.password.data)
            flash("You updated your password.")
        current_user.save()
        flash("You updated your settings.")
    return render_template('settings.html', form=form)
Exemplo n.º 13
0
def user_settings_edit():
    form = SettingsForm()
    if request.method == 'POST' and form.validate():
        user = User.objects(email=current_user.email).first()
        user.default_alert_method = form.method.data
        user.default_currency = form.currency.data
        user.default_exchange = form.exchange.data
        user.save()
        flash("Your new settings have been saved!")
        return redirect(url_for('index'))

    flash_form_errors(form)
    return redirect(url_for('index'))
Exemplo n.º 14
0
def settings(request):
    if request.method == 'GET':
        form = SettingsForm(data={
            'login': request.user.username,
            'email': request.user.email
        })
    if request.POST:
        form = SettingsForm(data=request.POST, files=request.FILES,
                            instance=request.user.author)
        if form.is_valid():
            post = form.save(commit=False)
            username_field = form.cleaned_data.get('login')
            email_field = form.cleaned_data.get('email')
            author = request.user.author
            author.user_name = username_field
            author.avatar = request.FILES.get('avatar', request.user.author.avatar)
            author.save()

            user_ = request.user
            user_.username = username_field
            user_.email = email_field
            user_.save()

            form.save()
    return render(request, 'settings.html', {'form': form})
Exemplo n.º 15
0
def settings():
    """Изменение настроек пользователя"""
    form = SettingsForm(obj=current_user)
    next = request.args.get('next')
    if next is None or not is_safe_url(next):
        next = url_for('.settings')
    if form.validate_on_submit():
        current_user.phone = form.phone.data
        current_user.address = form.address.data
        db.session.add(current_user)
        db.session.commit()
        flash('Настройки успешно изменены.')
        return redirect(next)
    return render_template('auth_settings.html', form=form)
Exemplo n.º 16
0
def getUserSettings():
    if not current_user.is_authenticated:
        return redirect(url_for('index'))
    form = SettingsForm()
    return render_template("change_password.html",
                           user=current_user,
                           form=form)
def settings():
    user_record = db_base.get_user_record()
    mp.track(f"user_{current_user.id}", "settings visit")

    form = SettingsForm()

    if form.validate_on_submit():
        user_record.name = form.name.data
        user_record.time_zone = form.time_zone.data
        db.session.commit()
        flash("settings updated")
        return redirect(url_for("auth.settings"))

    return render_template("auth/settings.html",
                           form=form,
                           user_record=user_record)
Exemplo n.º 18
0
def settings():
    form = SettingsForm(request.form)
    if form.validate_on_submit():
        if form.newpassword.data and form.oldpassword.data and form.repeat.data:
            # Handling the decryption and re-encryption of the passwords in case of a password change
            new_pwdh = PasswordManager.generate_pwdh_from_password(form.newpassword.data)
            for device in Device.query.all():
                # Decrypts the password using the session pwdh and encrypts it with the new pwdh (not in session)
                device.password = PasswordManager.encrypt_string(device.decrypt_password(), new_pwdh)
                device.save(encrypt=False)  # The password is already encrypted
            PasswordManager.set_session_pwdh(form.newpassword.data)
            current_user.set_password(form.newpassword.data)
            current_user.save()
            flash("Successfully set new password", "info")
        return redirect(url_for('settings'))
    else:
        return render_template("settings.html", form=form, active_page="settings")
Exemplo n.º 19
0
def settings_profile():
    form = SettingsForm(obj=current_user)
    if form.validate_on_submit():
        user = User.query.filter_by(id=int(current_user.id)).first()
        if user is None:
            flash('Error! We could not update your settings.', 'error')
            return redirect(url_for('settings_profile'))

        user.firstname = form.firstname.data
        user.lastname = form.lastname.data
        user.email = form.email.data
        db.session.commit()
        return redirect(url_for('settings_profile'))

    return render_template('settings_profile.html',
                           title='Settings',
                           form=form)
Exemplo n.º 20
0
def form_with_settings(request):
    best_members = UserProfile.objects.best_members()
    popular_tags = Tag.objects.popular_tags()

    if request.method == 'GET':
        form = SettingsForm()
        avatar_form = AvatarForm()
        print('tut')
    else:
        print("регистрируемся")
        form = SettingsForm(data=request.POST)
        avatar_form = AvatarForm(data=request.POST,
                                 files=request.FILES,
                                 instance=request.user.userprofile)
        print(request.FILES)
        if form.is_valid():
            user = request.user
            print('валидный')
            if form.cleaned_data[
                    "login"] != user.username and form.cleaned_data[
                        "login"] != '':
                user.name = form.cleaned_data["login"]
            if form.cleaned_data[
                    "username"] != user.username and form.cleaned_data[
                        "username"] != '':
                user.username = form.cleaned_data["username"]
            if form.cleaned_data["email"] != user.email and form.cleaned_data[
                    "email"] != '':
                user.email = form.cleaned_data["email"]
            if form.cleaned_data["password"] != '':
                user.set_password(form.cleaned_data["password"])
            user.save()
            auth.login(request, user)
            # if avatar_form.get('image_profile', None) is not None:
            avatar_form.save()
            return redirect('main_page')

    return render(
        request, 'form_with_settings.html', {
            'form': form,
            'avatar_form': avatar_form,
            'popular_tags': popular_tags,
            'best_members': best_members,
            'settings': settings
        })
Exemplo n.º 21
0
def edit_settings(request):
    
    organizations = [membership.organization for membership in OrganizationMember.objects.filter(user=request.user, is_owner=True)]

    try:
        credentials = SlackCredentials.objects.get(user=request.user)
        slack_auth = None
    except SlackCredentials.DoesNotExist:
        slack_auth = {
            'auth_url': SlackCredentials.get_auth_url(request)
        }

    initial = {
        'name': request.user.name,
        'email': request.user.email,
        'bio': request.user.bio,
        'city': request.user.city,
        'country': request.user.country,
        'public_phone': request.user.public_phone,
        'public_email': request.user.public_email
    }

    form = SettingsForm(initial=initial)
    if request.method == 'POST':
        form = SettingsForm(request.POST, initial=initial)
        form.set_user(request.user)
        if form.is_valid():
            if request.FILES.get('userpic'):
                request.user.userpic =  request.FILES.get('userpic')
            request.user.name = form.cleaned_data.get('name')
            request.user.city = form.cleaned_data.get('city')
            request.user.country = form.cleaned_data.get('country')
            request.user.public_phone = form.cleaned_data.get('public_phone')
            request.user.public_email = form.cleaned_data.get('public_email')
            request.user.bio = form.cleaned_data.get('bio')
            request.user.save()
            # TODO: if email was updated -> mark user account is_active=False and send activation link
            password = form.cleaned_data.get('password')
            request.user.email = form.cleaned_data.get('email').lower()
            if password != '':
                request.user.set_password(password)
            request.user.save()
            messages.add_message(request, messages.SUCCESS, _('Your account was updated successfully'))
            return redirect(reverse('index'))
    return render(request, 'app/settings.html', locals())
Exemplo n.º 22
0
def settings():
    del_account_form = DeleteAccountForm()
    settings_form = SettingsForm()
    saved = ""
    if del_account_form.form_identifier.data and del_account_form.validate_on_submit(
    ):
        try:
            user_folder = app.config["UPLOAD_FOLDER"].joinpath(
                str(current_user.id))
            if user_folder.is_dir():
                target_path = app.config["UPLOAD_FOLDER"].joinpath(
                    "scheduled_delete",
                    f"{current_user.id} {int(time.time())}")
                user_folder.rename(target_path)
            db.session.delete(current_user)
            db.session.commit()
            try:
                delete_id_folder_else_log_path(str(current_user.id))
            except Exception as e:
                delete_account_logger.exception(
                    f"Delete folder error for user: {current_user.id} {e}")
            return redirect(url_for("logout"))
        except Exception as e:
            delete_account_logger.exception(f"Delete account error for user: "******"{current_user.id} {e}")
            flash(
                "An unexpected error occured. Please try again, or contact support."
            )
    if settings_form.settings_submit.data and settings_form.validate_on_submit(
    ):
        current_user.settings.preserve_photo_data = settings_form.photo_metadata.data
        try:
            db.session.commit()
            saved = "1"
        except Exception as e:
            flash(
                "An unexpected error occured. Please try again, or contact support."
            )
            general_logger.error(
                f"Problem changing settings for {current_user.id} {e}")
    return render_template('settings.html',
                           delete_account_form=del_account_form,
                           settings_form=settings_form,
                           title="Alienbook",
                           saved=saved)
def settings(request):
    if request.method == 'POST':
        form = SettingsForm(request.POST, instance=request.user)
        formAv = AvatarForm(request.user, request.POST, request.FILES)
        if formAv.is_valid():
            formAv.save()
        if form.is_valid():
            form.save()
            return redirect('/main/')
        tags = Tag.objects.best_tags()[0:10]
        users = Client.objects.best_members()[0:10]
        return render(request, 'settings_page.html', {
            'tags': tags,
            'users': users,
            'form': form,
            'formAv': formAv,
            'user': request.user,
            'errors': form.errors,
        })
    else:
        form = SettingsForm(instance=request.user)
        formAv = AvatarForm(request.user)
        tags = Tag.objects.best_tags()[0:10]
        users = Client.objects.best_members()[0:10]
        return render(request, 'settings_page.html', {
            'tags': tags,
            'users': users,
            'form': form,
            'formAv': formAv,
            'user': request.user,
            'errors': form.errors,
        })
Exemplo n.º 24
0
def profile(request):
    tags = Tag.objects.get_popular()
    if request.method == "GET":
        form = SettingsForm()
    else:
        form = SettingsForm(data=request.POST)
        if form.is_valid():
            user = request.user
            if form.cleaned_data["username"] != user.username:
                user.username = form.cleaned_data["username"]
            if form.cleaned_data["email"] != user.email:
                user.email = form.cleaned_data["email"]
            if form.cleaned_data["password"]:
                user.set_password(form.cleaned_data["password"])
            user.save()
    return render(request, 'profile.html', {
        'form': form,
        'user': request.user,
        'tags': tags,
    })
Exemplo n.º 25
0
def settings(request):

    initial = {'username': request.user.username}
    form = SettingsForm(initial=initial)

    if request.method == "POST":
        form = SettingsForm(request.POST, request.FILES)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            users = User.objects.filter(username=username)
            if len(users) == 0:
                request.user.username = username
            elif request.user.id != users[0].id:
                messages.add_message(request, messages.ERROR,
                                     'Sorry, this username is taken!')
            userpic = request.FILES.get('userpic')
            if userpic is not None:
                request.user.profile.userpic = userpic
                request.user.profile.save()
            password = form.cleaned_data.get('password')
            if password != '':
                if request.user.check_password(password):
                    new_password = form.cleaned_data.get('new_password')
                    confirm_password = form.cleaned_data.get(
                        'confirm_password')
                    if new_password != '':
                        if new_password == confirm_password:
                            request.user.set_password(new_password)
                            update_session_auth_hash(request, request.user)
                            messages.add_message(request, messages.SUCCESS,
                                                 'Password was updated')
                        else:
                            messages.add_message(request, messages.ERROR,
                                                 'Passwords do not match!')
                else:
                    messages.add_message(request, messages.ERROR,
                                         'Wrong password!')
            request.user.save()
            return redirect(request.path)

    return render(request, 'settings.html', locals())
Exemplo n.º 26
0
def settings():
    redirect_non_admins()

    form = SettingsForm()
    settings = GeneralSetting.query.get(1)

    if form.validate_on_submit():
        settings.title = form.title.data

        flash("Settings changed.")

        db.session.commit()
    else:
        form.title.data = settings.title

    categories = Category.query.all()

    return render_template("trivia/settings.html",
                           form=form,
                           categories=categories,
                           title=page_title("Categories"))
Exemplo n.º 27
0
def settings(request):
    if request.method == 'GET':
        form = SettingsForm(instance=request.user)
    elif request.method == 'POST':
        form = SettingsForm(data=request.POST,
                            instance=request.user,
                            files=request.FILES)
        if form.is_valid():
            form.save()
    return render(request, 'settings.html', {'form': form})
Exemplo n.º 28
0
def settings(request):
    if request.method == "GET":
        form = SettingsForm(
            initial={
                'first_name':
                request.user.first_name,
                'last_name':
                request.user.last_name,
                'email':
                request.user.email,
                'avatar':
                "/static/{}".format(Users.objects.get_avatar(request.user.pk)),
                'change':
                "/static/{}".format(Users.objects.get_avatar(request.user.pk))
            })
    if request.method == "POST":
        form = SettingsForm(request.POST, request.FILES)
        if form.is_valid():
            user = User.objects.get(pk=request.user.pk)
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            user.email = form.cleaned_data['email']
            if form.cleaned_data['change'] is not None:
                user.users.avatar = form.cleaned_data['change']
                user.users.save()
            user.save()
            messages.success(request, 'Form submission successful')
    form.initial['avatar'] = "/static/{}".format(
        Users.objects.get_avatar(request.user.pk))

    print(form.initial)
    ctx = {'form': form}
    return render(request, 'settings.html', ctx)
Exemplo n.º 29
0
def settings():
    form = SettingsForm()
    settings = GeneralSetting.query.get(1)

    if form.validate_on_submit():
        settings.title = form.title.data
        settings.world_name = form.world_name.data
        settings.welcome_page = form.welcome_page.data
        settings.quicklinks = form.quicklinks.data

        flash("Settings changed.", "success")

        db.session.commit()
    else:
        form.title.data = settings.title
        form.world_name.data = settings.world_name
        form.welcome_page.data = settings.welcome_page
        form.quicklinks.data = settings.quicklinks

    return render_template("settings.html",
                           settings=settings,
                           form=form,
                           title=page_title("General Settings"))
Exemplo n.º 30
0
def settings():
    dct = {"title": "Settings", "current_user": current_user}
    form = SettingsForm()
    dct["form"] = form
    if form.validate_on_submit():
        if form.delete.data:
            username = current_user.username
            logout_user()
            u = User.query.filter_by(username=username).first()
            db.session.delete(u)
            db.session.commit()
            flash("Successfully deleted account!", "info")
            return redirect(url_for("index"))
        elif form.submit.data:
            current_user.username = form.username.data
            current_user.email = form.email.data
            current_user.first_name = form.name.data.split()[0]
            current_user.full_name = form.name.data
            if form.new_password.data:
                current_user.set_password(form.new_password.data)
            db.session.commit()
            flash("Updated settings!", "info")
    return render_template("settings.html", **dct)
Exemplo n.º 31
0
def settings_page(request):
    if request.method == 'POST':
        form = SettingsForm(data=request.POST,
                            instance=request.user,
                            files=request.FILES)
        if form.is_valid():
            form.save()

            return redirect(reverse('settings'))

    else:
        user_data = {
            'username': request.user.username,
            'first_name': request.user.first_name,
            'email': request.user.email
        }

        form = SettingsForm(initial=user_data)

    return render(request, 'settings_page.html', {'form': form})
Exemplo n.º 32
0
def settings():
    form = SettingsForm()
    return render_template('bootstap/settings.html',
                           title='Settings',
                           form=form)
Exemplo n.º 33
0
def save_settings():
    form = SettingsForm()
    form.save(g.user)
    s = OreCalcService(g.user)
    return jsonify(s.to_json())
Exemplo n.º 34
0
def settings():
    target_choice_list, tmp_db = check_targets()
    if len(target_choice_list) == 0:
        flash("Press Start Primerdesign to start primer design")
        return redirect(url_for('controlrun'))

    if tmp_db['new_run']['same_settings']:
        def_path = tmp_db['new_run']['path']
        form = SettingsForm(change_wd=def_path)
        form.targets.choices = [("All targets", "All targets")]
    elif tmp_db['new_run']['change_settings']:
        try:
            form = SettingsForm(data=load_settings(tmp_db))
            form.targets.choices = target_choice_list
        except KeyError as exc:
            flash(" ".join([
                'Setting not found:',
                str(exc), 'maybe you are using an outdated config file'
            ]))
            def_path = tmp_db['new_run']['path']
            form = SettingsForm(change_wd=def_path)
            form.targets.choices = target_choice_list
    else:
        def_path = tmp_db['new_run']['path']
        form = SettingsForm(change_wd=def_path)
        form.targets.choices = target_choice_list

    if form.validate_on_submit():
        if form.reset.data is True:
            reset_form = reset_settings(form)
            return render_template('settings.html',
                                   title='Settings for primerdesign',
                                   form=reset_form)

        settings_data = get_settings(form)
        if tmp_db['new_run']['same_settings']:
            for target in tmp_db['new_run']['targets']:  # for same settings
                config = tmp_db['new_run']['targets'][target]
                new_config = update_db(config, target, settings_data)
                tmp_db['new_run']['targets'][target].update(new_config)
                with open(tmp_db_path, 'w') as f:
                    f.write(json.dumps(tmp_db))
        else:
            for target in [form.targets.data]:
                config = tmp_db['new_run']['targets'][target]
                new_config = update_db(config, target, settings_data)
                tmp_db['new_run']['targets'][target].update(new_config)
                with open(tmp_db_path, 'w') as f:
                    f.write(json.dumps(tmp_db))

        if tmp_db['new_run']['same_settings']:
            flash('Saved settings for {}'.format(
                " & ".join(target_choice_list)))
            flash("Press Start Primerdesign to start primer design for " +
                  " & ".join(target_choice_list))
            return redirect(url_for('controlrun'))
        if tmp_db['new_run']['change_settings']:
            conf_path = tmp_db['new_run']['targets'][target]['path']
            save_to = os.path.join(conf_path, target, "config", "config.json")
            try:
                with open(save_to, 'w') as f:
                    f.write(json.dumps(new_config))
                flash('Changed settings for {}'.format(' '.join(
                    target.split('_'))))
                flash(json.dumps(new_config))
                flash("Press Start Primerdesign to start primer design for " +
                      ' '.join(target.split('_')))
                return redirect(url_for('controlrun'))
            except FileNotFoundError:
                flash("The selected directory does not exist")
                return redirect(url_for('settings'))

        else:
            flash('Saved settings for {}'.format(' '.join(target.split('_'))))
        flash(json.dumps(new_config, sort_keys=True))
        return redirect(url_for('settings'))

    return render_template('settings.html',
                           title='Settings for primerdesign',
                           form=form)
Exemplo n.º 35
0
def settings():
    form = SettingsForm()
    if form.validate_on_submit():
        flash('Settings Saved')
        return redirect(url_for('index'))
    return render_template('settings.html', title='Settings', form=form)