0
votes

I want to use microsoft vision api in django i am getting this error "HTTPError at /posts/create/ 415 Client Error: Unsupported Media Type for url: https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures=Categories%2CDescription%2CColor"

@login_required()
def post_create(request):
    form = PostModelForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        print(instance.image)

        vision_base_url = 
"https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/"
        vision_analyze_url = vision_base_url + "analyze"
        image_path = instance.image
        #image_data = open(settings.MEDIA_ROOT, "rb").read()
        headers    = {'Ocp-Apim-Subscription-Key': 
'Subscription-Key', 
                  "Content-Type": "multipart/form-data" }
        params     = {'visualFeatures': 'Categories,Description,Color'}
        response   = requests.post(vision_analyze_url, 
                               headers=headers, 
                               params=params, 
                               data=image_path)

        response.raise_for_status()

        analysis      = response.json()
        image_caption = analysis["description"]["captions"][0] 
                        ["text"].capitalize()
        print(image_caption)
        instance.save()

        messages.success(request, "Successfully Saved!")
        return redirect(instance.get_absolute_url())
    else:
        messages.error(request, "Not Successfully Saved!!")
    context = {
        "form": form
    }
    return render(request, "posts/post_create.html", context)

Request Method: POST Request URL: http://127.0.0.1:8000/posts/create/

Django Version: 2.0.3
Python Version: 3.6.4
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'crispy_forms',
 'pagedown',
 'markdown_deux',
 'comments',
 'posts']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "D:\project\ks\ks-venv\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request)

File "D:\project\ks\ks-venv\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request)

File "D:\project\ks\ks-venv\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "D:\project\ks\ks-venv\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs)

File "D:\project\ks\ks\posts\views.py" in post_create 43. response.raise_for_status()

File "D:\project\ks\ks-venv\lib\site-packages\requests\models.py" in raise_for_status 935. raise HTTPError(http_error_msg, response=self)

Exception Type: HTTPError at /posts/create/ Exception Value: 415 Client Error: Unsupported Media Type for url: https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures=Categories%2CDescription%2CColor

after changing the object to url i am getting following error

Traceback:

File "D:\project\ks\ks-venv\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request)

File "D:\project\ks\ks-venv\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request)

File "D:\project\ks\ks-venv\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "D:\project\ks\ks-venv\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs)

File "D:\project\ks\ks\posts\views.py" in post_create 38. image_data = open('/media/aaaasdaa-21-22/post-detail-page.JPG', "rb").read()

Exception Type: FileNotFoundError at /posts/create/ Exception Value: [Errno 2] No such file or directory: '/media/aaaasdaa-21-22/post-detail-page.JPG'

1

1 Answers

0
votes

I think its more of MS API issue than a Django issue. I have looked at Microsoft Vision API and the issue is in the image parameter. What you are passing is an image object itself and the API expects a url path to the image

Try changing

image_path = instance.image

to

image_path = instance.image.url

Refer this documentation to get a better understanding https://docs.djangoproject.com/en/1.11/topics/files/#managing-files