Skip to content

Commit

Permalink
save WIP ajax add likes
Browse files Browse the repository at this point in the history
  • Loading branch information
danielzeljko committed Dec 16, 2022
1 parent 59fadc4 commit 0710ed7
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 3 deletions.
31 changes: 30 additions & 1 deletion app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
from dotenv import load_dotenv

from flask import Flask, render_template, request, flash, redirect, session, g
from flask import Flask, jsonify, render_template, request, flash, redirect, session, g
from flask_debugtoolbar import DebugToolbarExtension
from sqlalchemy.exc import IntegrityError

Expand Down Expand Up @@ -478,3 +478,32 @@ def add_header(response):
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
response.cache_control.no_store = True
return response




# ============================= API ===============================

@app.post('/api/messages/<int:message_id>/like')
def like_message_api(message_id):
"""
Allows a user to “like” or "unlike" a warble.
Returns: {message: {id, text, user_id }}
"""

# TODO: refactor this

if not g.user:
flash("Access unauthorized.", "danger")
return redirect("/")

message = Message.query.get_or_404(message_id)

if message.user == g.user:
flash("You cannot like your own warble.", "danger")
return redirect("/")

serialized = message.serialize()

return (jsonify(message=serialized), 201)
11 changes: 11 additions & 0 deletions models.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,17 @@ class Message(db.Model):
# self in g.user.liked_messages
# return t f

def serialize(self):
""" Serialize message instance to python dictionary """

return {
"id": self.id,
"text": self.text,
"timestamp": self.timestamp,
"user_id": self.user_id,
}





Expand Down
3 changes: 3 additions & 0 deletions templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,8 @@
{% endblock %}

</div>

<script src="https://unpkg.com/jquery"></script>
<script src="https://unpkg.com/axios/dist/axios.js"></script>
</body>
</html>
4 changes: 2 additions & 2 deletions templates/home.html
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ <h4>
<p>{{ message.text }}</p>
</div>
{% if not message.user == g.user %}
{% include 'messages/like_button.html' %}
{% endif %}
{% include 'messages/like_button.html' %}
{% endif %}
</li>
<div>

Expand Down

0 comments on commit 0710ed7

Please sign in to comment.