Example #1
0
def edit_avatar(id, name):
	user = _prepare_edit_user(id, name)

	errors = []

	form = AvatarForm()
	if form.validate_on_submit():
		file = request.files[form.image.name]

		orig_name = file.filename
		ext = orig_name[orig_name.rindex('.')+1:].lower()

		file.stream.seek(0, os.SEEK_END)
		size = file.stream.tell()

		if ext not in AVATAR_EXTENSIONS:
			errors.append('The uploaded file does not have a valid extension.')
		elif size > AVATAR_FILE_SIZE:
			errors.append('The uploaded file was too big (%.1f kB).' % (size/1024.0))
		else:
			from PIL import Image

			# Looks good so far?
			file.stream.seek(0)
			im = Image.open(file.stream)
			im.verify()

			# reopen it as specified by the PIL docs
			file.stream.seek(0)
			im = Image.open(file.stream)
			w, h = im.size

			if w > AVATAR_IMAGE_SIZE[0] or h > AVATAR_IMAGE_SIZE[1]:
				errors.append('The uploaded file was too large (%d x %d pixels).' % (w,h))
			else:
				file.stream.seek(0)

				filename = '%d.%s' % (user.id, ext)
				file.save(os.path.join(AVATAR_DIR, filename))

				if user.avatar_path:
					os.unlink(path_to_avatar(user.avatar_path))

				rand_token = random.randint(0,1000000)
				user.avatar_path = '%s?%d' % (filename, rand_token)
				db.session.commit()

				flash('Your new avatar has been saved.')


	return render_template('edit_avatar.html',
			form=form, errors=errors, user=user,
			url=url_for_edit_user('edit_avatar'),
			delete_url=url_for_edit_user('delete_avatar'),
			valid_extensions=AVATAR_EXTENSIONS,
			max_kilobytes=AVATAR_FILE_SIZE/1024.0,
			max_width=AVATAR_IMAGE_SIZE[0],
			max_height=AVATAR_IMAGE_SIZE[1])
Example #2
0
def delete_avatar(id, name):
	user = _prepare_edit_user(id, name)

	if user.avatar_path:
		os.unlink(path_to_avatar(user.avatar_path))
		user.avatar_path = None
		db.session.commit()

		flash('Your avatar has been deleted.')

	return redirect(url_for_edit_user('edit_avatar'), code=303)