0

I am running a django project on ubuntu that is supposed to build a website where I can

  • upload an image
  • run an external script to modify the image on click when uploaded

The uploading process works fine, but when I try to run the external script I get an the internal server error as seen below.

Is this because of the added b' and \n in the path? If so, how can I solve that, please?

Full Code can be found here https://github.com/hackanons/button-python-click/tree/master/Image%20Edit%20Html%20Button%20Run%20Python%20Script/buttonpython

Thanks a lot for help

image is  birdie1.png
file raw url birdie1.png
file full url /home/felix/ucmr/button-python-click/Image_Edit_Html_Button_Run_Python_Script/buttonpython/media/birdie1.png
template url /media/birdie1.png
CompletedProcess(args=['/home/felix/anaconda3/envs/ucmr/bin/python', '//home//felix//ucmr//button-python-click//Image_Edit_Html_Button_Run_Python_Script//test.py', 'upload'], returncode=0, stdout=b'Hi upload welcome to Hackanons & time is 2021-06-01 20:35:53.229957\n')
b'/media/temp.png\n'
[01/Jun/2021 20:35:53] "POST /external/ HTTP/1.1" 200 1074
[01/Jun/2021 20:35:53] "GET /media/birdie1.png HTTP/1.1" 200 103100
Internal Server Error: /external/b'/media/temp.png/n'
Traceback (most recent call last):
  File "/home/felix/anaconda3/envs/ucmr/lib/python3.7/site-packages/django/utils/datastructures.py", line 78, in __getitem__
    list_ = super().__getitem__(key)
KeyError: 'image'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/felix/anaconda3/envs/ucmr/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/felix/anaconda3/envs/ucmr/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/felix/anaconda3/envs/ucmr/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/felix/ucmr/button-python-click/Image_Edit_Html_Button_Run_Python_Script/buttonpython/buttonpython/views.py", line 19, in external
    image=request.FILES['image']
  File "/home/felix/anaconda3/envs/ucmr/lib/python3.7/site-packages/django/utils/datastructures.py", line 80, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'image'
[01/Jun/2021 20:35:53] "GET /external/b'/media/temp.png/n' HTTP/1.1" 500 80417

views.py

from django.shortcuts import render
import requests
import sys
from subprocess import run,PIPE
from django.core.files.storage import FileSystemStorage

def button(request):

    return render(request,'home.html')

def output(request):
    data=requests.get("https://www.google.com/")
    print(data.text)
    data=data.text
    return render(request,'home.html',{'data':data})

def external(request):
    inp=request.POST.get('param', False)
    image=request.FILES['image']
    print("image is ",image)
    fs=FileSystemStorage()
    filename=fs.save(image.name, image)
    fileurl=fs.open(filename)
    templateurl=fs.url(filename)
    print("file raw url",filename)
    print("file full url", fileurl)
    print("template url",templateurl)
    out= run([sys.executable,'//home//felix//ucmr//button-python-click//Image_Edit_Html_Button_Run_Python_Script//test.py',inp],shell=False,stdout=PIPE)
    image= run([sys.executable,'//home//felix//ucmr//button-python-click//Image_Edit_Html_Button_Run_Python_Script//image.py',str(fileurl),str(filename)],shell=False,stdout=PIPE)
    print(out)
    print(image.stdout)
    return render(request,'home.html',{'data':out.stdout,'raw_url':templateurl,'edit_url':image.stdout})

Felix BoeVR
  • 1
  • 1
  • 2
  • Does this answer your question? [django MultiValueDictKeyError error, how do I deal with it](https://stackoverflow.com/questions/5895588/django-multivaluedictkeyerror-error-how-do-i-deal-with-it) – gdef_ Jun 01 '21 at 21:59
  • @gdef_ Unfortunately not, that raises another error "AttributeError: 'bool' object has no attribute 'name'" – Felix BoeVR Jun 01 '21 at 22:16
  • Well, it is fixing the first error then, and then it's failing later in `image.name`.You shouldn't be using `False` as the default, maybe just `None` and then check that the image exists. You are not getting an `image` field in your request, make sure you have that. – gdef_ Jun 01 '21 at 22:29

2 Answers2

0

The problem is that there is no image file in your request. You need to fix that first, make sure that you are getting what you expect.

You should probably start using forms and calling is_valid to do the check for you. If your request does not have the required fields, it will return an error and validation message.

Your first error happens here:

image=request.FILES['image'] # the 'image' key does not exists so you get KeyError

You can fix this using the .get notation to have a default if it doesn't exist.

image=request.FILES.get('image') # this will not throw an error but have `None` as default

After that change, you have the following:

filename=fs.save(image.name, image) # this throws an error if image is None because you can't do None.name

So now you should check that image is not None, and then continue with your logic, or return a BadRequest error response.

if image is not None:
    return HttpResponseBadRequest

# <rest of your code>
gdef_
  • 1,888
  • 9
  • 17
  • Thanks for all your help. That fixed the MultiValueDictKeyError. The image gets uploaded on the server is modified and saved as temp.png in the backend but not displayed correctly in the browser. I still get: Internal Server Error: /external/b'/media/temp.png/n' Something with that above path seems to be corrupted, maybe because the project was done for windows and I'm on Linux? – Felix BoeVR Jun 01 '21 at 23:51
0

The error

Internal Server Error: /external/b'/media/temp.png/n'

was caused by a corrupted path from the stdout Process. I added "universal_newlines=True" from subprocess module and everything works fine.

    out= run([sys.executable,'//home//felix//ucmr//button-python-click//Image_Edit_Html_Button_Run_Python_Script//test.py',inp],shell=False,stdout=PIPE,universal_newlines=True)
    image= run([sys.executable,'//home//felix//ucmr//button-python-click//Image_Edit_Html_Button_Run_Python_Script//image.py',str(fileurl),str(filename)],shell=False,stdout=PIPE,universal_newlines=True)

See also Why does Popen.communicate() return b'hi\n' instead of 'hi'?

Felix BoeVR
  • 1
  • 1
  • 2