basic importing working

This commit is contained in:
vabene1111
2020-06-23 10:34:04 +02:00
parent dc91e1e8ed
commit 8594346488
4 changed files with 139 additions and 33 deletions

View File

@@ -18,6 +18,7 @@ from icalendar import Calendar, Event
from rest_framework import viewsets, permissions
from rest_framework.exceptions import APIException
from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin, ListModelMixin
from urllib3.exceptions import NewConnectionError
from cookbook.helper.permission_helper import group_required, CustomIsOwner, CustomIsAdmin, CustomIsUser
from cookbook.helper.recipe_url_import import find_recipe_json
@@ -264,10 +265,14 @@ def get_plan_ical(request, html_week):
@group_required('user')
def recipe_from_url(request, url):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'}
response = requests.get(url, headers=headers)
try:
response = requests.get(url, headers=headers)
except requests.exceptions.ConnectionError:
return JsonResponse({'error': True, 'msg': _('The requested page could not be found.')}, status=400)
if response.status_code == 403:
return JsonResponse({'error': _('The requested page refused to provide any information (Status Code 403).')})
return JsonResponse({'error': True, 'msg': _('The requested page refused to provide any information (Status Code 403).')}, status=400)
soup = BeautifulSoup(response.text, "html.parser")
@@ -288,7 +293,7 @@ def recipe_from_url(request, url):
if '@type' in ld_json_item and ld_json_item['@type'] == 'Recipe':
return find_recipe_json(ld_json_item)
except JSONDecodeError:
JsonResponse({'error': _('The requested site does not provided malformed data and cannot be read.')})
JsonResponse({'error': True, 'msg': _('The requested site does not provided malformed data and cannot be read.')}, status=400)
# now try to find microdata
items = microdata.get_items(response.text)
@@ -297,4 +302,4 @@ def recipe_from_url(request, url):
if 'schema.org/Recipe' in str(md_json['type']):
return find_recipe_json(md_json['properties'])
return JsonResponse({'error': _('The requested site does not provide any recognized data format to import the recipe from.')})
return JsonResponse({'error': True, 'msg': _('The requested site does not provide any recognized data format to import the recipe from.')}, status=400)

View File

@@ -1,8 +1,13 @@
import json
from datetime import datetime
from io import BytesIO
import requests
from PIL import Image
from django.contrib import messages
from django.core.files import File
from django.utils.translation import gettext as _
from django.http import HttpResponseRedirect
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import redirect, render
from django.urls import reverse
from django.utils.translation import ngettext
@@ -90,6 +95,53 @@ def batch_edit(request):
@group_required('user')
def import_url(request):
if request.method == 'POST':
data = json.loads(request.body)
recipe = Recipe.objects.create(
name=data['name'],
instructions=data['recipeInstructions'],
internal=True,
created_by=request.user,
)
for kw in data['keywords']:
if kw['id'] != "null" and (k := Keyword.objects.filter(id=kw['id']).first()):
recipe.keywords.add(k)
elif data['all_keywords']:
k = Keyword.objects.create(name=kw['text'])
recipe.keywords.add(k)
for ing in data['recipeIngredient']:
i, i_created = Ingredient.objects.get_or_create(name=ing['ingredient'])
u, u_created = Unit.objects.get_or_create(name=ing['unit'])
if isinstance(ing['amount'], str):
try:
ing['amount'] = float(ing['amount'].replace(',', '.'))
except ValueError:
# TODO return proper error
pass
RecipeIngredient.objects.create(recipe=recipe, ingredient=i, unit=u, amount=ing['amount'])
if data['image'] != '':
response = requests.get(data['image'])
img = Image.open(BytesIO(response.content))
# todo move image processing to dedicated function
basewidth = 720
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
im_io = BytesIO()
img.save(im_io, 'PNG', quality=70)
recipe.image = File(im_io, name=f'{uuid.uuid4()}_{recipe.pk}.png')
recipe.save()
return HttpResponse(reverse('view_recipe', args=[recipe.pk]))
return render(request, 'url_import.html', {})