Skip to content

Commit

Permalink
Merge pull request #56 from nnayk/main
Browse files Browse the repository at this point in the history
Merge progress to allow for CD
  • Loading branch information
caseyavila authored Dec 4, 2023
2 parents d22e7d8 + 6f5bd50 commit 2572504
Show file tree
Hide file tree
Showing 5 changed files with 114 additions and 135 deletions.
81 changes: 81 additions & 0 deletions .github/workflows/main_picture-perfect.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
# More GitHub Actions for Azure: https://github.com/Azure/actions
# More info on Python, GitHub Actions, and Azure App Service: https://aka.ms/python-webapps-actions

name: Build and deploy Python app to Azure Web App - picture-perfect

on:
push:
branches:
- main
workflow_dispatch:

jobs:
build:
runs-on: ubuntu-latest
# Set the working directory for all steps in this job
defaults:
run:
working-directory: Backend

steps:
- uses: actions/checkout@v4

- name: Set up Python version
uses: actions/setup-python@v1
with:
python-version: '3.10'

- name: Create and start virtual environment
run: |
python -m venv venv
source venv/bin/activate
pwd
echo "hello there"
ls
- name: Install dependencies
run: pip install -r requirements.txt

# Optional: Add step to run tests here (PyTest, Django test suites, etc.)
- name: Zip artifact for deployment
run: zip release.zip ./* -r

- name: Upload artifact for deployment jobs
uses: actions/upload-artifact@v3
with:
name: python-app
path: |
Backend/release.zip
Backend/!venv/
deploy:
runs-on: ubuntu-latest
# Set the working directory for all steps in this job
needs: build
environment:
name: 'Production'
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}

steps:
- name: Download artifact from build job
uses: actions/download-artifact@v3
with:
name: python-app

- name: test
run: |
pwd
ls -la
- name: Unzip artifact for deployment
run:
unzip release.zip

- name: 'Deploy to Azure Web App'
uses: azure/webapps-deploy@v2
id: deploy-to-webapp
with:
app-name: 'picture-perfect'
slot-name: 'Production'
publish-profile: ${{ secrets.AZUREAPPSERVICE_PUBLISHPROFILE_AE9068FBDCAE45A29EB6212CEEEE72F8 }}
26 changes: 8 additions & 18 deletions Backend/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from db_access import User
from db_access import Image
from db_access import get_user, create_user


app = Flask(__name__)
Expand Down Expand Up @@ -65,7 +66,8 @@ def store_image():
{
"message": "Image submitted successfully!",
"image_id": str(image.id),
# if you wish to return the timestamp when the image was stored
# if you wish to return the timestamp when
# the image was stored
"timestamp": datetime.utcnow(),
}
),
Expand Down Expand Up @@ -136,18 +138,6 @@ def login():
return jsonify({"message": str(e)}), 500


@app.route("/create_user", methods=["POST"])
def create_user():
print("received register request")
print(request, request.data)
return jsonify(
{
"""message": "No endpoint called create_user,
perhaps you meant: /register"""
}
)


@app.route("/register", methods=["POST"])
def register():
data = request.get_json()
Expand All @@ -173,7 +163,7 @@ def register():

# Hash the password
hashed_password = generate_password_hash(
plain_text_password, method="sha256"
plain_text_password, method="scrypt"
)

# Prepare the user data with the hashed password
Expand All @@ -182,15 +172,15 @@ def register():
"email": email,
"password": hashed_password,
}
response = requests.get(f"{DB_ACCESS_URL}/users", json=user_data)
response = get_user(user_data)
if response.status_code == 401:
print(f"responsey={response.text}")
print(f"responsey={response.message}")
return (
jsonify({"message": response.text}),
jsonify({"message": response.message}),
400,
)
# Send the user data with the hashed password to the database access layer
response = requests.post(f"{DB_ACCESS_URL}/create_user", json=user_data)
response = create_user(user_data)
# Handle the response from the database access layer
if response.status_code == 201:
print("User created successfully!")
Expand Down
140 changes: 23 additions & 117 deletions Backend/db_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@
from werkzeug.security import check_password_hash
import secrets
from mongoengine.errors import DoesNotExist
from dotenv import load_dotenv

load_dotenv()
# from dotenv import load_dotenv

# load_dotenv()

import os

Expand All @@ -25,6 +26,12 @@
connect(host=mongo_uri)


class Response:
def __init__(self, message, status_code) -> None:
self.status_code = status_code
self.message = message


class User(Document):
username = StringField(required=True, unique=True)
email = StringField(required=True)
Expand All @@ -43,140 +50,39 @@ class Image(Document):
meta = {"collection": "images"}


@app.route("/create_test_user", methods=["POST"])
def create_test_user():
user = User(
username="bob",
encrypted_password="pwd",
email="bob@gmail.com",
)
try:
user.save()
return (
jsonify(
{
"message": "User created successfully!",
"user_id": str(user.id),
}
),
201,
)
except NotUniqueError:
return (
jsonify(
{
"error": """Username or email already exists.
Choose another."""
}
),
400,
)


@app.route("/create_user", methods=["POST"])
def create_user():
data = json.loads(request.data.decode("utf-8"))
def create_user(data):
data = data
user = User(
username=data["username"],
encrypted_password=data["password"],
email=data["email"],
)
try:
user.save()
return (
jsonify(
{
"message": "User created successfully!",
"user_id": str(user.id),
}
),
201,
)
except:
return (
jsonify(
{
"message": "Internal server error",
}
),
500,
)


@app.route("/create_image", methods=["POST"])
def create_image():
data = request.get_json()

# Retrieve the user by ObjectId
creator = User.objects.get(id=data["creator"])

# Associate the image with the user and save it
image = Image(creator=creator, prompt=data["prompt"], url=data["url"])
image.save()

return (
jsonify(
{
"message": "Image data added successfully!",
"image_id": str(image.id),
}
),
201,
)
print(f"successfully added user {user.username}")
return Response("User created successfully!", 201)
except Exception as e:
return Response(f"Internal server error {e}", 500)


@app.route("/users", methods=["GET"])
def get_users():
data = json.loads(request.data.decode("utf-8"))
def get_user(data):
# data = json.loads(data.decode("utf-8"))
user = User.objects(username=data["username"]).first()
print(f"user={user}")
if user:
return (
jsonify(
{
"error": """Username already exists.
Choose another."""
}
),
return Response(
"Username already exists. Choose another.",
401,
)
user = User.objects(email=data["email"]).first()
print(f"user={user}")
if user:
return (
jsonify(
{
"error": """Email already exists.
Choose another."""
}
),
return Response(
"Email already exists. Choose another.",
401,
)
if user is None:
return (
jsonify({"error": """User credentials are unique"""}),
return Response(
"User credentials are unique.",
200,
)


@app.route("/images")
def get_images():
images = Image.objects.all()
return jsonify(
[
{
"creator_id": str(
image.creator.id
), # updated from user to creator
"prompt": image.prompt,
"url": image.url,
"votes": image.votes,
"image_id": str(image.id),
}
for image in images
]
)


if __name__ == "__main__":
app.run(host="0.0.0.0", port=5001, debug=True)
1 change: 1 addition & 0 deletions Backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ flask_cors
mongoengine
werkzeug
requests
flask_jwt_extended
1 change: 1 addition & 0 deletions startup.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
gunicorn --bind=0.0.0.0 --timeout 600 --chdir Backend backend:app

0 comments on commit 2572504

Please sign in to comment.