Skip to content

Commit

Permalink
Merge pull request #58 from grant-baer/mondays_db_refactoring
Browse files Browse the repository at this point in the history
edited db to work with image_store worked on backend to talk to db_access
  • Loading branch information
caseyavila authored Dec 6, 2023
2 parents 5696cd3 + 73de467 commit c3bc59d
Show file tree
Hide file tree
Showing 2 changed files with 116 additions and 31 deletions.
85 changes: 55 additions & 30 deletions Backend/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

from db_access import User
from db_access import Image
from db_access import check_user, create_user, db_connect
from db_access import check_user, create_user, db_connect, get_image, create_image


app = Flask(__name__)
Expand All @@ -34,7 +34,10 @@


@app.route("/generate_image", methods=["POST"])
@jwt_required()
def generate_image():
current_user = get_jwt_identity()

data = request.get_json()
url = "https://imagegolf.io/api/generate"
url_data = {"inputValue": data["prompt"]}
Expand Down Expand Up @@ -79,45 +82,64 @@ def update_image_elo():


@app.route("/store_image", methods=["POST"])
@jwt_required()
def store_image():
current_user = get_jwt_identity() # Gets the identity of the current user

data = request.get_json()
# Validate required fields
required_fields = ["creator", "prompt", "url"]
required_fields = ["prompt", "url"]
for field in required_fields:
if field not in data:
return jsonify({"error": f"Missing field: {field}"}), 400
# Retrieve creator user by user

# Prepare the data for creating an image
image_data = {
"creator": current_user, # Assuming the creator is the logged-in user
"prompt": data["prompt"],
"url": data["url"]
}

# Call the create_image function from db_access
response = create_image(image_data)

# Handle the response
if response.status_code == 201:
print("Image created successfully!")
return jsonify({"message": "Image submitted successfully!"}), 201
else:
print(f"Failed to create image: {response.message}")
return jsonify({"message": response.message}), response.status_code


@app.route("/fetch_portfolio", methods=["GET"])
@jwt_required()
def fetch_portfolio():
current_user_username = get_jwt_identity() # Get the username from the JWT token

try:
creator = User.objects.get(username=data["creator"])
# Retrieve the user by username
user = User.objects.get(username=current_user_username)

# Fetch all images created by this user
user_images = Image.objects(creator=user)

# Format the response with the list of images
portfolio = [{
"image_id": str(image.id),
"prompt": image.prompt,
"url": image.url,
"creator": user
} for image in user_images]

return jsonify(portfolio), 200

except DoesNotExist:
return jsonify({"error": "Creator user does not exist."}), 404
except Exception as e:
return jsonify({"error": str(e)}), 400
try:
# votes default to 0 as defined in the Image class
# timestamp can be added if we want to have more variation
# between similar objects
image = Image(creator=creator, prompt=data["prompt"], url=data["url"])
image.save()
return (
jsonify(
{
"message": "Image submitted successfully!",
"image_id": str(image.id),
# if you wish to return the timestamp when
# the image was stored
"timestamp": datetime.utcnow(),
}
),
201,
)
# If the user is not found
return jsonify({"error": "User not found"}), 404
except Exception as e:
# Handle any other exceptions
return jsonify({"error": str(e)}), 500
data = request.get_json()
text = data["text"]

print(text)
return jsonify({"message": "Text logged successfully!"})


@app.route("/login", methods=["POST"])
Expand Down Expand Up @@ -187,6 +209,7 @@ def login():

@app.route("/register", methods=["POST"])
def register():

data = request.get_json()

# Validate required fields
Expand All @@ -207,6 +230,7 @@ def register():
username = data["username"]
plain_text_password = data["password"]
email = data["email"]
portfolio = [] #initialized to []

# Hash the password
hashed_password = generate_password_hash(
Expand All @@ -218,6 +242,7 @@ def register():
"username": username,
"email": email,
"password": hashed_password,
"portfolio": portfolio,
}
response = check_user(user_data)
if response.status_code == 401:
Expand Down
62 changes: 61 additions & 1 deletion Backend/db_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,18 @@
Document,
StringField,
IntField,
ListField,
ReferenceField,
NotUniqueError,
)
from werkzeug.security import check_password_hash
import secrets
from mongoengine.errors import DoesNotExist


from dotenv import load_dotenv


load_dotenv()

app = Flask(__name__)
Expand All @@ -37,6 +40,7 @@ class User(Document):
email = StringField(required=True)
encrypted_password = StringField(required=True)
ranking = IntField()
portfolio = ListField(ReferenceField('Image')) # List of image references

meta = {"collection": "users"}

Expand All @@ -45,7 +49,6 @@ class Image(Document):
creator = ReferenceField(User, required=True)
url = StringField(required=True)
prompt = StringField(required=True)
votes = IntField(default=0)

meta = {"collection": "images"}

Expand All @@ -56,6 +59,8 @@ def create_user(data):
username=data["username"],
encrypted_password=data["password"],
email=data["email"],
portfolio=[] # Initialize an empty portfolio

)
try:
user.save()
Expand All @@ -82,3 +87,58 @@ def check_user(data):
"User credentials are unique.",
200,
)


def create_image(data):
try:
# Retrieve the user by username
creator = User.objects.get(username=data["creator"])

# Create and save the image
image = Image(
creator=creator,
prompt=data["prompt"],
url=data["url"]
)
image.save()

# Optionally, you can also append this image to the user's portfolio here
creator.update(push__portfolio=image)

return Response("Image created successfully!", 201)
except DoesNotExist:
return Response("Creator user does not exist.", 404)
except Exception as e:
return Response(f"Internal server error {e}", 500)


def get_image(image_id):
try:
image = Image.objects.get(id=image_id)
return jsonify({
"creator": str(image.creator.id),
"prompt": image.prompt,
"url": image.url,
}), 200
except DoesNotExist:
return Response("Image not found.", 404)
except Exception as e:
return Response(f"Internal server error {e}", 500)


def get_portfolio(username):
try:
user = User.objects.get(username=username)
images = Image.objects(creator=user)

return jsonify([
{
"image_id": str(image.id),
"prompt": image.prompt,
"url": image.url,
} for image in images
]), 200
except DoesNotExist:
return Response("User not found.", 404)
except Exception as e:
return Response(f"Internal server error {e}", 500)

0 comments on commit c3bc59d

Please sign in to comment.