from flask import ( abort, flash, Markup, redirect, render_template, send_from_directory, url_for ) from flask_login import current_user, login_required import os from app import db from app.models import Avatar, User from . import bp from .forms import ( EditProfileSettingsForm ) @bp.before_request @login_required def before_request(): pass @bp.route('/') def profile(user_id): user = User.query.get_or_404(user_id) return render_template('profile/profile_page.html.j2', user=user) @bp.route('//avatars/') def avatar_download(user_id, avatar_id): avatar_file = Avatar.query.filter_by(user_id = user_id, id = avatar_id).first_or_404() if not (avatar_file and avatar_file.filename): abort(404) return send_from_directory( os.path.dirname(avatar_file.path), os.path.basename(avatar_file.path), as_attachment=True, attachment_filename=avatar_file.filename, mimetype=avatar_file.mimetype ) @bp.route('//edit-profile', methods=['GET', 'POST']) def edit_profile(user_id): user = User.query.get_or_404(user_id) edit_profile_settings_form = EditProfileSettingsForm( current_user, data=current_user.to_json_serializeable(), prefix='edit-profile-settings-form' ) if edit_profile_settings_form.validate_on_submit(): if edit_profile_settings_form.avatar.data: try: Avatar.create(edit_profile_settings_form.avatar.data, user=current_user) except (AttributeError, OSError): abort(500) current_user.email = edit_profile_settings_form.email.data current_user.username = edit_profile_settings_form.username.data current_user.about_me = edit_profile_settings_form.about_me.data current_user.location = edit_profile_settings_form.location.data current_user.organization = edit_profile_settings_form.organization.data current_user.website = edit_profile_settings_form.website.data current_user.full_name = edit_profile_settings_form.full_name.data db.session.commit() message = Markup(f'Profile settings updated') flash(message, 'success') return redirect(url_for('.profile', user_id=user.id)) return render_template('profile/edit_profile.html.j2', edit_profile_settings_form=edit_profile_settings_form, user=user, title='Edit Profile')