400 Неправильный запрос при загрузке изображения в облачное хранилище Google с помощью Python 3 Flask - PullRequest
0 голосов
/ 17 октября 2019

Я пытаюсь загрузить изображение в облачное хранилище, используя blob.upload_from_string, но получаю

400 Ошибка неверного запроса

Я подписан на этот урок , но разница в том, что я хочу отправить строку вместо файла, а строка содержит изображение.

Это функция:

def upload_image_file(self, file):
    """
    Upload the user-uploaded file to Google Cloud Storage and retrieve its
    publicly-accessible URL.
    """
    if not file:
        return None

    testImageString = "Python is interesting."
    arr = bytes(testImageString, 'utf-8')

    public_url = storage.upload_file(
        arr,
        "fileName.jpg",
        "jpg"
    )

    current_app.logger.info(
        "Uploaded file %s as %s.", file.filename, public_url)

    return public_url

и это функция, которая в примере загружает изображение, это та, которую я вызываю в этой строке storage.upload_file(arr, "fileName.jpg", "jpg").

def upload_file(file_stream, filename, content_type):
   """
   Uploads a file to a given Cloud Storage bucket and returns the public url
to the new object.
"""
_check_extension(filename, current_app.config['ALLOWED_EXTENSIONS'])
filename = _safe_filename(filename)

client = _get_storage_client()
bucket = client.bucket(current_app.config['CLOUD_STORAGE_BUCKET'])
blob = bucket.blob(filename)

blob.upload_from_string(
    file_stream,
    content_type=content_type)

url = blob.public_url

if isinstance(url, six.binary_type):
    url = url.decode('utf-8')

return url

Я получаю эту ошибку

google.api_core.exceptions.BadRequest: 400 POST https://www.googleapis.com/upload/storage/v1/b/image-buck-share/o?uploadType=multipart: («Запрос не выполнен с кодом состояния», 400, «Ожидается один из»,)

Вот полная ошибкаслед:

Traceback (most recent call last):
  File "/home/myUser/Documents/MICROSERVICES/service-upload-img/env/lib64/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/myUser/Documents/MICROSERVICES/service-upload-img/env/lib64/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/myUser/Documents/MICROSERVICES/service-upload-img/env/lib64/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/myUser/Documents/MICROSERVICES/service-upload-img/env/lib64/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/myUser/Documents/MICROSERVICES/service-upload-img/env/lib64/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/myUser/Documents/MICROSERVICES/service-upload-img/env/lib64/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/myUser/Documents/MICROSERVICES/service-upload-img/main.py", line 17, in generate_image_v2
    return resource.generate_image(req)
  File "/home/myUser/Documents/MICROSERVICES/service-upload-img/service/imageGenerator.py", line 20, in generate_image
    transfersResponse = self.testSaveImageLocal(inputData)
  File "/home/myUser/Documents/MICROSERVICES/service-upload-img/service/imageGenerator.py", line 173, in testSaveImageLocal
    self.upload_image_file(output)
  File "/home/myUser/Documents/MICROSERVICES/service-upload-img/service/imageGenerator.py", line 195, in upload_image_file
    "jpg"
  File "/home/myUser/Documents/MICROSERVICES/service-upload-img/service/storage.py", line 66, in upload_file
    content_type=content_type)
  File "/home/myUser/Documents/MICROSERVICES/service-upload-img/env/lib64/python3.7/site-packages/google/cloud/storage/blob.py", line 1296, in upload_from_string
    predefined_acl=predefined_acl,
  File "/home/myUser/Documents/MICROSERVICES/service-upload-img/env/lib64/python3.7/site-packages/google/cloud/storage/blob.py", line 1200, in upload_from_file
    _raise_from_invalid_response(exc)
  File "/home/myUser/Documents/MICROSERVICES/service-upload-img/env/lib64/python3.7/site-packages/google/cloud/storage/blob.py", line 2089, in _raise_from_invalid_response
    raise exceptions.from_http_status(response.status_code, message, response=response)
google.api_core.exceptions.BadRequest: 400 POST https://www.googleapis.com/upload/storage/v1/b/image-buck-share/o?uploadType=multipart: ('Request failed with status code', 400, 'Expected one of', <HTTPStatus.OK: 200>)
127.0.0.1 - - [17/Oct/2019 10:52:04] "POST /img/up/ser/generator/v2 HTTP/1.1" 500
...