Skip to content

Commit

Permalink
Revert "converted functions to async (#345)" (#349)
Browse files Browse the repository at this point in the history
This reverts commit 23d7573.
  • Loading branch information
jlucaspains authored Oct 5, 2024
1 parent 23d7573 commit 148ec68
Show file tree
Hide file tree
Showing 12 changed files with 44 additions and 159 deletions.
4 changes: 1 addition & 3 deletions api/function_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@
from functions.process_image import bp as process_image_bp
from functions.receive_recipe import bp as receive_recipe_bp
from functions.share_recipe import bp as share_recipe_bp
from functions.assistant import bp as assistant_bp

app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)

app.register_functions(parse_recipe_bp)
app.register_functions(process_backup_bp)
app.register_functions(process_image_bp)
app.register_functions(receive_recipe_bp)
app.register_functions(share_recipe_bp)
app.register_functions(assistant_bp)
app.register_functions(share_recipe_bp)
45 changes: 0 additions & 45 deletions api/functions/assistant.py

This file was deleted.

7 changes: 0 additions & 7 deletions api/functions/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,4 @@ class ImageResult(BaseModel):
"items": {
"type": "string",
}
}

assistantSchema = {
"type": "array",
"items": {
"type": "string",
}
}
11 changes: 5 additions & 6 deletions api/functions/parse_recipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import azure.functions as func
from contextlib import suppress
from azurefunctions.extensions.http.fastapi import Response, Request, JSONResponse

from pint import UnitRegistry
from uuid import uuid4
Expand All @@ -15,12 +14,12 @@
ureg = UnitRegistry()
bp = func.Blueprint()

@bp.route(route="parse-recipe", methods=[func.HttpMethod.POST])
async def parse_recipe(req: Request) -> JSONResponse:
@bp.route(route="parse-recipe", methods=["POST"])
def parse_recipe(req: func.HttpRequest) -> func.HttpResponse:
start = perf_counter()
correlation_id = uuid4()

req_body = await req.json()
req_body = req.get_json()
url: str = req_body.get("url")
download_image: bool = req_body.get("downloadImage") or False
try:
Expand Down Expand Up @@ -50,11 +49,11 @@ async def parse_recipe(req: Request) -> JSONResponse:

result["image"] = get_recipe_image(result["image"]) if download_image else result["image"]

return JSONResponse(content=result, status_code=200)
return func.HttpResponse(json.dumps(result), status_code=200, mimetype="application/json")
except Exception as e:
logging.error(f"Failed to process parse request id {correlation_id}. Error: {e}")

return JSONResponse(content={"errorMessage": "Could not find a recipe in the web page"}, status_code=400)
return func.HttpResponse("Could not find a recipe in the web page", status_code=400)
finally:
end = perf_counter()
logging.info(f"Finished processing parse request id {correlation_id}. Time taken: {end - start:0.4f}s")
Expand Down
3 changes: 1 addition & 2 deletions api/functions/process_backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import io

import azure.functions as func
from azurefunctions.extensions.http.fastapi import Request, Response

from zipfile import ZipFile
from uuid import uuid4
Expand All @@ -16,7 +15,7 @@
bp = func.Blueprint()

@bp.route(route="process-backup", methods=["POST"])
def process_backup(req: Request) -> Response:
def process_backup(req: func.HttpRequest) -> func.HttpResponse:
start = perf_counter()
correlation_id = uuid4()
try:
Expand Down
3 changes: 1 addition & 2 deletions api/functions/process_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import json

import azure.functions as func
from azurefunctions.extensions.http.fastapi import Request, Response

from zipfile import ZipFile
from uuid import uuid4
Expand All @@ -13,7 +12,7 @@
bp = func.Blueprint()

@bp.route(route="process-image", methods=["POST"])
def process_image(req: Request) -> Response:
def process_image(req: func.HttpRequest) -> func.HttpResponse:
start = perf_counter()
correlation_id = uuid4()
try:
Expand Down
3 changes: 1 addition & 2 deletions api/functions/receive_recipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import json

import azure.functions as func
from azurefunctions.extensions.http.fastapi import Request, Response
from azure.cosmos import exceptions

from uuid import uuid4
Expand All @@ -18,7 +17,7 @@ def mock_repository(mock_repository: Repository):
repository = mock_repository

@bp.route(route="receive-recipe", methods=["POST"])
def receive_recipe(req: Request) -> Response:
def receive_recipe(req: func.HttpRequest) -> func.HttpResponse:
start = perf_counter()
correlation_id = uuid4()

Expand Down
3 changes: 1 addition & 2 deletions api/functions/share_recipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import jsonschema

import azure.functions as func
from azurefunctions.extensions.http.fastapi import Request, Response
from jsonschema import validate

from uuid import uuid4
Expand All @@ -23,7 +22,7 @@ def mock_repository(mock_repository: Repository):
repository = mock_repository

@bp.route(route="share-recipe", methods=["POST"])
def share_recipe(req: Request) -> Response:
def share_recipe(req: func.HttpRequest) -> func.HttpResponse:
start = perf_counter()
correlation_id = uuid4()

Expand Down
2 changes: 1 addition & 1 deletion api/functions/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,4 +186,4 @@ def get_recipe_image(image_url: str):
def get_html(url: str) -> AbstractScraper:
html = requests.get(url, headers=request_headers).content

return scrape_html(html, url, supported_only=False)
return scrape_html(html, url, wild_mode=True)
4 changes: 1 addition & 3 deletions api/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ python-multipart~=0.0.12
Pillow~=10.4
pillow-avif-plugin~=1.4
pytest~=8.3
anyio
azure-cosmos~=4.7
jsonschema~=4.23
lxml==5.1.0
azurefunctions-extensions-http-fastapi
lxml==5.1.0
67 changes: 32 additions & 35 deletions api/test/test_parse_recipe.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,23 @@
import json
import azure.functions as func
import pytest
from azurefunctions.extensions.http.fastapi import Request
from unittest import mock;
from unittest.mock import AsyncMock;

from ..functions.parse_recipe import parse_recipe

@pytest.fixture
def anyio_backend():
return 'asyncio'

# parse recipe post method
@pytest.mark.anyio()
async def test_recipe_parse():
mock_request = AsyncMock()
mock_request.json.return_value = {
"url": "https://www.foodnetwork.com/recipes/rachael-ray/pork-chops-with-golden-apple-sauce-recipe-1915826",
"downloadImage": False
}
def test_recipe_parse():
request = func.HttpRequest(
method='POST',
url='api/parse-recipe',
body=json.dumps({
'url': 'https://www.foodnetwork.com/recipes/rachael-ray/pork-chops-with-golden-apple-sauce-recipe-1915826',
}).encode('utf8')
)

func_call = parse_recipe.build().get_user_function()
response = await func_call(mock_request)
response = func_call(request)

assert response.status_code == 200
parsed_response = json.loads(response.body.decode())
parsed_response = json.loads(response.get_body().decode())
assert parsed_response["title"] == "Pork Chops with Golden Apple Sauce"
assert len(parsed_response["ingredients"]) == 12
assert parsed_response["ingredients"][1]["raw"] == "2 teaspoons lemon juice"
Expand All @@ -46,19 +39,21 @@ async def test_recipe_parse():
assert parsed_response["nutrients"]["cholesterol"] == 83
assert parsed_response["nutrients"]["sodium"] == 832

@pytest.mark.anyio
async def test_recipe_parse_download_image():
mock_request = AsyncMock()
mock_request.json.return_value = {
"url": "https://www.foodnetwork.com/recipes/rachael-ray/pork-chops-with-golden-apple-sauce-recipe-1915826",
"downloadImage": True
}
def test_recipe_parse_download_image():
request = func.HttpRequest(
method='POST',
url='api/parse-recipe',
body=json.dumps({
'url': 'https://www.foodnetwork.com/recipes/rachael-ray/pork-chops-with-golden-apple-sauce-recipe-1915826',
"downloadImage": True
}).encode('utf8')
)

func_call = parse_recipe.build().get_user_function()
response = await func_call(mock_request)
response = func_call(request)

assert response.status_code == 200
parsed_response = json.loads(response.body.decode())
parsed_response = json.loads(response.get_body().decode())
assert parsed_response["title"] == "Pork Chops with Golden Apple Sauce"
assert len(parsed_response["ingredients"]) == 12
assert parsed_response["ingredients"][1]["raw"] == "2 teaspoons lemon juice"
Expand All @@ -70,16 +65,18 @@ async def test_recipe_parse_download_image():

assert parsed_response["image"].startswith("data:")

@pytest.mark.anyio
async def test_recipe_parse_exception():
mock_request = AsyncMock()
mock_request.json.return_value = {
"url": "https://www.foodnk.com/recipes/rachael-ray/pork-chops-with-golden-apple-sauce-recipe-1915826"
}
def test_recipe_parse_exception():
request = func.HttpRequest(
method='POST',
url='api/parse-recipe',
body=json.dumps({
"url": "https://www.foodnk.com/recipes/rachael-ray/pork-chops-with-golden-apple-sauce-recipe-1915826",
}).encode('utf8')
)

func_call = parse_recipe.build().get_user_function()
response = await func_call(mock_request)
response = func_call(request)

assert response.status_code == 400
parsed_response = response.body.decode()
assert parsed_response == r'{"errorMessage":"Could not find a recipe in the web page"}'
parsed_response = response.get_body().decode()
assert parsed_response == r'Could not find a recipe in the web page'
51 changes: 0 additions & 51 deletions api/tools/shareRecipe.http

Large diffs are not rendered by default.

0 comments on commit 148ec68

Please sign in to comment.