views/import_export

This commit is contained in:
Tobias Lindenberg
2021-01-10 12:19:39 +01:00
parent 0405c123f4
commit edb9c883f7

View File

@ -23,7 +23,9 @@ def import_recipe(request):
form = ImportForm(request.POST)
if form.is_valid():
try:
data = json.loads(re.sub(r'"id":([0-9])+,', '', form.cleaned_data['recipe']))
data = json.loads(
re.sub(r'"id":([0-9])+,', '', form.cleaned_data['recipe'])
)
sr = RecipeSerializer(data=data)
if sr.is_valid():
@ -34,18 +36,39 @@ def import_recipe(request):
try:
fmt, img = data['image'].split(';base64,')
ext = fmt.split('/')[-1]
recipe.image = ContentFile(base64.b64decode(img), name=f'{recipe.pk}.{ext}') # TODO possible security risk, maybe some checks needed
# TODO possible security risk,
# maybe some checks needed
recipe.image = (ContentFile(
base64.b64decode(img),
name=f'{recipe.pk}.{ext}')
)
recipe.save()
except ValueError:
pass
messages.add_message(request, messages.SUCCESS, _('Recipe imported successfully!'))
return HttpResponseRedirect(reverse_lazy('view_recipe', args=[recipe.pk]))
messages.add_message(
request,
messages.SUCCESS,
_('Recipe imported successfully!')
)
return HttpResponseRedirect(
reverse_lazy('view_recipe', args=[recipe.pk])
)
else:
messages.add_message(request, messages.ERROR, _('Something went wrong during the import!'))
messages.add_message(request, messages.WARNING, sr.errors)
messages.add_message(
request,
messages.ERROR,
_('Something went wrong during the import!')
)
messages.add_message(
request, messages.WARNING, sr.errors
)
except JSONDecodeError:
messages.add_message(request, messages.ERROR, _('Could not parse the supplied JSON!'))
messages.add_message(
request,
messages.ERROR,
_('Could not parse the supplied JSON!')
)
else:
form = ImportForm()
@ -65,18 +88,23 @@ def export_recipe(request):
if recipe.image and form.cleaned_data['image']:
with open(recipe.image.path, 'rb') as img_f:
export['image'] = f'data:image/png;base64,{base64.b64encode(img_f.read()).decode("utf-8")}'
export['image'] = f'data:image/png;base64,{base64.b64encode(img_f.read()).decode("utf-8")}' # noqa: E501
json_string = JSONRenderer().render(export).decode("utf-8")
if form.cleaned_data['download']:
response = HttpResponse(json_string, content_type='text/plain')
response['Content-Disposition'] = f'attachment; filename={recipe.name}.json'
response = HttpResponse(
json_string, content_type='text/plain'
)
response['Content-Disposition'] = f'attachment; filename={recipe.name}.json' # noqa: E501
return response
context['export'] = re.sub(r'"id":([0-9])+,', '', json_string)
else:
form.add_error('recipe', _('External recipes cannot be exported, please share the file directly or select an internal recipe.'))
form.add_error(
'recipe',
_('External recipes cannot be exported, please share the file directly or select an internal recipe.') # noqa: E501
)
else:
form = ExportForm()
recipe = request.GET.get('r')