twitter_utils.py 文件源码

python
阅读 15 收藏 0 点赞 0 评论 0

项目:StockRecommendSystem 作者: doncat99 项目源码 文件源码
def parse_media_file(passed_media):
    """ Parses a media file and attempts to return a file-like object and
    information about the media file.

    Args:
        passed_media: media file which to parse.

    Returns:
        file-like object, the filename of the media file, the file size, and
        the type of media.
    """
    img_formats = ['image/jpeg',
                   'image/png',
                   'image/gif',
                   'image/bmp',
                   'image/webp']
    video_formats = ['video/mp4',
                     'video/quicktime']

    # If passed_media is a string, check if it points to a URL, otherwise,
    # it should point to local file. Create a reference to a file obj for
    #  each case such that data_file ends up with a read() method.
    if not hasattr(passed_media, 'read'):
        if passed_media.startswith('http'):
            data_file = http_to_file(passed_media)
            filename = os.path.basename(passed_media)
        else:
            data_file = open(os.path.realpath(passed_media), 'rb')
            filename = os.path.basename(passed_media)

    # Otherwise, if a file object was passed in the first place,
    # create the standard reference to media_file (i.e., rename it to fp).
    else:
        if passed_media.mode not in ['rb', 'rb+', 'w+b']:
            raise TwitterError('File mode must be "rb" or "rb+"')
        filename = os.path.basename(passed_media.name)
        data_file = passed_media

    data_file.seek(0, 2)
    file_size = data_file.tell()

    try:
        data_file.seek(0)
    except Exception as e:
        pass

    media_type = mimetypes.guess_type(os.path.basename(filename))[0]
    if media_type is not None:
        if media_type in img_formats and file_size > 5 * 1048576:
            raise TwitterError({'message': 'Images must be less than 5MB.'})
        elif media_type in video_formats and file_size > 15 * 1048576:
            raise TwitterError({'message': 'Videos must be less than 15MB.'})
        elif media_type not in img_formats and media_type not in video_formats:
            raise TwitterError({'message': 'Media type could not be determined.'})

    return data_file, filename, file_size, media_type
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号