File size: 909 Bytes
7e6ee3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import os
import mimetypes
import cloudinary
import cloudinary.uploader


def _is_configured():
    return bool(os.getenv("CLOUDINARY_URL"))


def _resource_type_for(path):
    mime_type, _ = mimetypes.guess_type(path)
    if mime_type and mime_type.startswith("image/"):
        return "image"
    return "raw"


def upload_file(path, folder="examcraft", public_id=None, tags=None):
    if not _is_configured():
        return None

    resource_type = _resource_type_for(path)
    options = {
        "folder": folder,
        "resource_type": resource_type,
    }
    if public_id:
        options["public_id"] = public_id
    if tags:
        options["tags"] = tags

    result = cloudinary.uploader.upload(path, **options)
    return {
        "url": result.get("secure_url") or result.get("url"),
        "public_id": result.get("public_id"),
        "resource_type": result.get("resource_type"),
    }