Added last_modified and etag headers on the user photos

This commit is contained in:
Éloi Rivard 2023-03-18 00:51:09 +01:00
parent 61940844e6
commit dd394391c8
3 changed files with 37 additions and 1 deletions

View file

@ -7,6 +7,7 @@ Added
*****
- Organization field. :pr:`116`
- ETag and Last-Modified headers on user photos. :pr:`116`
Changed
*******

View file

@ -714,9 +714,19 @@ def photo(uid, field):
if not user:
abort(404)
etag = None
if request.if_modified_since and request.if_modified_since >= user.modifyTimestamp:
return "", 304
etag = profile_hash(uid, user.modifyTimestamp.isoformat())
if request.if_none_match and etag in request.if_none_match:
return "", 304
photos = getattr(user, field)
if not photos:
abort(404)
stream = io.BytesIO(photos[0])
return send_file(stream, mimetype="image/jpeg")
return send_file(
stream, mimetype="image/jpeg", last_modified=user.modifyTimestamp, etag=etag
)

View file

@ -1,3 +1,5 @@
import datetime
from canaille.models import User
from webtest import Upload
@ -5,8 +7,31 @@ from webtest import Upload
def test_photo(testclient, user, jpeg_photo):
user.jpegPhoto = [jpeg_photo]
user.save()
user = User.get(id=user.id)
res = testclient.get("/profile/user/jpegPhoto")
assert res.body == jpeg_photo
assert res.last_modified == user.modifyTimestamp
etag = res.etag
assert etag
res = testclient.get(
"/profile/user/jpegPhoto",
headers={
"If-Modified-Since": (
res.last_modified + datetime.timedelta(days=1)
).strftime("%a, %d %b %Y %H:%M:%S UTC")
},
status=304,
)
assert not res.body
res = testclient.get(
"/profile/user/jpegPhoto",
headers={"If-None-Match": etag},
status=304,
)
assert not res.body
def test_photo_invalid_user(testclient, user):