N
N
Neoliz2017-05-19 13:33:24
Python
Neoliz, 2017-05-19 13:33:24

How to upload a video to OK via api?

Hello. Actually the next question is how to upload a video to classmates in a group? Now I'm doing this, but 104 is returned. The SDK is taken as the basis for the controller. https://github.com/alternativshik/python-odnoklassniki

#coding: utf8
import requests
import odnoklassniki
from requests_toolbelt.multipart.encoder import MultipartEncoder

# 1. Получаем урл для загрузки
title = u'Тестовое видео'
video_path = '/var/opt/mp4.mp4'
api = odnoklassniki.Odnoklassniki(
    '', '', ''
)


def __finalize_upload_video(video_id, api):
    """
    Завершает загрузку видео, и возвращает результат.(bool)

    :param video_id: ID загруженного видео.

    :return Результат выполнения операции(bool)

    """
    try:
        result = api.video.update(vid=video_id)
    except ValueError as ex:
        if ex.message == 'No JSON object could be decoded':
            return True
        return False
    except Exception as ex:
        return False

    """
    Согласно манулу, штатное завершение загрузки возвращает '', однако
    простая отправка данных формы(html) возвращает <retval>1</retval>,
    а python возвращает ValueError
    """
    return True if result == '' else result


url_obj = api.video.getUploadUrl(gid='ID группы', file_name=title, file_size=0)
video_id = url_obj.get('video_id')
url = url_obj.get('upload_url')
errors = []
file = open(video_path, 'rb')
# 2. Загружаем ролик request.post
multipart_data = MultipartEncoder(
    fields={'video': (title, file, 'video/mp4')}
)
try:
    response = requests.post(
        url,
        data=multipart_data,
        headers={'Content-Type': multipart_data.content_type}
    )
except Exception as ex:
    print(u"1" + str(ex.message))
    errors.append(ex.message)
else:
    if response.status_code != 200:
        print(u"2" + str(response.content))
        errors.append(response.content)

# 3. Завершаем загрузку
# Проверяем статус окончания загрузки, при успешном завершении возвращает ''
if not __finalize_upload_video(video_id, api):
    errors.append(u"Произошла неизвестная ошибка.")

# 4. Проверяем что не было ошибок.
if errors:
    raise Exception(u"{}".format(errors))

In the logs:

1('Connection aborted.', error(104, 'Connection reset by peer')) # Returned via first print
[ProtocolError('Connection aborted.', error(104, 'Connection reset by peer'))]

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question