nopaque/app/profile/routes.py

73 lines
2.5 KiB
Python
Raw Normal View History

2022-12-05 08:40:02 +00:00
from flask import (
abort,
flash,
Markup,
redirect,
render_template,
send_from_directory,
url_for
)
2022-11-29 15:46:33 +00:00
from flask_login import current_user, login_required
2022-12-05 08:40:02 +00:00
import os
2022-11-29 15:46:33 +00:00
from app import db
2022-12-05 15:25:54 +00:00
from app.models import Avatar, User
2022-11-29 15:46:33 +00:00
from . import bp
2022-11-30 13:36:42 +00:00
from .forms import (
EditProfileSettingsForm
)
2022-11-29 15:46:33 +00:00
2022-12-05 08:40:02 +00:00
@bp.before_request
2022-11-29 15:46:33 +00:00
@login_required
2022-12-05 08:40:02 +00:00
def before_request():
pass
2022-12-05 15:25:54 +00:00
@bp.route('/<hashid:user_id>')
def profile(user_id):
user = User.query.get_or_404(user_id)
2022-12-05 08:40:02 +00:00
return render_template('profile/profile_page.html.j2',
2022-12-05 15:25:54 +00:00
user=user)
2022-11-29 15:46:33 +00:00
2022-12-05 15:25:54 +00:00
@bp.route('/<hashid:user_id>/avatars/<hashid:avatar_id>')
def avatar_download(user_id, avatar_id):
avatar_file = Avatar.query.filter_by(user_id = user_id, id = avatar_id).first_or_404()
2022-12-05 08:40:02 +00:00
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
)
2022-12-05 15:25:54 +00:00
@bp.route('/<hashid:user_id>/edit-profile', methods=['GET', 'POST'])
def edit_profile(user_id):
user = User.query.get_or_404(user_id)
2022-12-05 08:40:02 +00:00
edit_profile_settings_form = EditProfileSettingsForm(
2022-11-30 13:36:42 +00:00
current_user,
data=current_user.to_json_serializeable(),
prefix='edit-profile-settings-form'
2022-12-05 08:40:02 +00:00
)
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)
2022-11-30 13:36:42 +00:00
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()
2022-12-05 08:40:02 +00:00
message = Markup(f'Profile settings updated')
flash(message, 'success')
2022-12-05 15:25:54 +00:00
return redirect(url_for('.profile', user_id=user.id))
2022-12-05 08:40:02 +00:00
return render_template('profile/edit_profile.html.j2',
edit_profile_settings_form=edit_profile_settings_form,
2022-12-05 15:25:54 +00:00
user=user,
2022-12-05 08:40:02 +00:00
title='Edit Profile')