def process_studio(scraper, studio):
    logger.debug("processing studio: "+str(studio.id)+", "+studio.name)

    #http://cloudinary.com/documentation/django_integration#getting_started_guide

    url = studio.url_home
    filename = "C:\\tmp\\new\\screenshots\\"+studio.nameForURL+".png"
    logger.debug("saving screenshot of site: "+url+" to file: "+filename)

    LoadUrl(scraper).run(url)
    scraper.browser.maximize_window()
    scraper.browser.get_screenshot_as_file(filename)

    cloudinary.config(
        cloud_name = "scheduleyoga",
        api_key = "184789393887359",
        api_secret = "5b_y47V0o2CSKgHWDLKyxf4Nmto"
    )

    image_public_id = 'site-screenshots/'+studio.nameForURL
    result = cloudinary.uploader.upload(filename, public_id = image_public_id)
    logger.debug("result of uploading to Cloundary: "+repr(result))

    studio.site_image_cloudinary_id = result['public_id']+".png"
    studio.save()
Пример #2
2
def cloudinary_api_url(action="upload", **options):
    cloudinary_prefix = options.get("upload_prefix", cloudinary.config().upload_prefix) or "https://api.cloudinary.com"
    cloud_name = options.get("cloud_name", cloudinary.config().cloud_name)
    if not cloud_name:
        raise ValueError("Must supply cloud_name")
    resource_type = options.get("resource_type", "image")
    return "/".join([cloudinary_prefix, "v1_1", cloud_name, resource_type, action])
Пример #3
2
 def test_should_add_token_for_public_resource(self):
     cloudinary.config(private_cdn=True)
     url, _ = cloudinary.utils.cloudinary_url("sample.jpg", sign_url=True, resource_type="image", type="public",
                                              version="1486020273")
     self.assertEqual(url, "http://test123-res.cloudinary.com/image/public/v1486020273/sample.jpg?__cld_token__=st"
                           "=11111111~exp=11111411~hmac="
                           "c2b77d9f81be6d89b5d0ebc67b671557e88a40bcf03dd4a6997ff4b994ceb80e")
Пример #4
1
    def setUp(self):
        self.cloud_name = 'test123'
        self.public_id = "sample"
        self.image_format = "jpg"
        self.full_public_id = "{id}.{format}".format(id=self.public_id, format=self.image_format)
        self.upload_url = "http://res.cloudinary.com/{cloud_name}/image/upload".format(cloud_name=self.cloud_name)
        self.common_format = {"url": self.upload_url, "id": self.full_public_id}
        self.image = CloudinaryImage(self.public_id, format=self.image_format)

        self.common_transformation = {"effect": "sepia"}
        self.common_transformation_str = 'e_sepia'
        self.common_image_options = {"cloud_name": self.cloud_name}
        self.common_image_options.update(self.common_transformation)
        self.custom_attributes = {'custom_attr1': 'custom_value1', 'custom_attr2': 'custom_value2'}

        self.min_width = 100
        self.max_width = 399
        self.breakpoint_list = [self.min_width, 200, 300, self.max_width]
        self.common_srcset = {"breakpoints": self.breakpoint_list}

        self.fill_transformation = {"width": self.max_width, "height": self.max_width, "crop": "fill"}
        self.fill_transformation_str = "c_fill,h_{h},w_{w}".format(h=self.max_width, w=self.max_width)

        cloudinary.reset_config()
        cloudinary.config(cloud_name=self.cloud_name, api_secret="1234", cname=None)
Пример #5
0
 def test_should_add_token_if_authToken_is_globally_set_and_signed_is_True(self):
     cloudinary.config(private_cdn=True)
     url, _ = cloudinary.utils.cloudinary_url("sample.jpg", sign_url=True, resource_type="image",
                                              type="authenticated", version="1486020273")
     self.assertEqual(url, "http://test123-res.cloudinary.com/image/authenticated/v1486020273/sample.jpg"
                           "?__cld_token__=st=11111111~exp=11111411~hmac"
                           "=8db0d753ee7bbb9e2eaf8698ca3797436ba4c20e31f44527e43b6a6e995cfdb3")
Пример #6
0
def deleteImg(public_id, **options):
    cloudinary.config( 
      cloud_name = "coopals", 
      api_key="739771188655879",
      api_secret= "jXP-X6O9aK_FnZEWe8viRLVQXyU"
    )
    cloudinary.uploader.destroy(public_id)
Пример #7
0
def call_api(method, uri, params, **options):
    prefix = options.pop("upload_prefix", cloudinary.config().upload_prefix) or "https://api.cloudinary.com"
    cloud_name = options.pop("cloud_name", cloudinary.config().cloud_name)
    if not cloud_name: raise Exception("Must supply cloud_name")
    api_key = options.pop("api_key", cloudinary.config().api_key)
    if not api_key: raise Exception("Must supply api_key")
    api_secret = options.pop("api_secret", cloudinary.config().api_secret)
    if not cloud_name: raise Exception("Must supply api_secret")

    data = urllib.urlencode(params)
    api_url = "/".join([prefix, "v1_1", cloud_name] + uri)
    request = urllib2.Request(api_url, data)
    # Add authentication
    base64string = base64.encodestring('%s:%s' % (api_key, api_secret)).replace('\n', '')
    request.add_header("Authorization", "Basic %s" % base64string)
    request.add_header("User-Agent", cloudinary.USER_AGENT)
    request.get_method = lambda: method.upper()

    try:
        response = urllib2.urlopen(request)
        body = response.read()
    except urllib2.HTTPError, e:
        exception_class = EXCEPTION_CODES.get(e.code)
        if exception_class:
            response = e
            body = response.read()
        else:
            raise GeneralError("Server returned unexpected status code - %d - %s" % (e.code, e.read()))
Пример #8
0
 def test_client_hints_as_false(self):
     """should use normal responsive behaviour"""
     cloudinary.config(responsive = True)
     tag = CloudinaryImage('sample.jpg').image(width= "auto", crop= "scale", cloud_name= "test", client_hints= False)
     self.assertRegexpMatches(tag, '<img.*>')
     self.assertRegexpMatches(tag, 'class=["\']cld-responsive["\']')
     self.assertRegexpMatches(tag, 'data-src=["\']http://res.cloudinary.com/test/image/upload/c_scale,w_auto/sample.jpg["\']')
Пример #9
0
 def __init__(self, baseURL):
     self.baseURL = baseURL
     cloudinary.config(
         cloud_name='evertqin',
         api_key='134222639559228',
         api_secret='Uh9t8SpeCbTtBwBEVUssZiZQWGc'
     )
Пример #10
0
    def __generate_graph(self, data, name):
        graph = graphviz.Digraph(format="png")
        #graph = pydotplus.Dot(graph_type="digraph")

        # validate data
        for i in range(len(data)):
            if len(data[i]) < 3: # each data has to contain (node, node, edge)
                raise ValueError("Wrong input for graph")



        # let's add the relationship between the king and vassals
        for i in range(len(data)):
            #edge = pydotplus.Edge(data[i][0], data[i][1], label=data[i][2], minlen='7')
            #graph.add_edge(edge)
            graph.edge(data[i][0], data[i][1], label=data[i][2], minlen='7')
        # ok, we are set, let's save our graph into a file

        self.png_dir = os.path.join(settings.BASE_DIR, "parsing_result")
        #self.png_dir = os.path.join(self.png_dir, name)
        if os.path.isfile(os.path.join(self.png_dir , name) +".png"):
            os.remove(os.path.join(self.png_dir, name) + ".png")

        #graph.write_png(self.png_dir + '.png')

        graph.render(filename=name, directory=self.png_dir, view=False,cleanup=True)
        cloudinary.config(
            cloud_name="jin8",
            api_key="179139842767459",
            api_secret="BtqQQ54EvWJ8U4TKePyUvFk8kkU"
        )
        response = cloudinary.uploader.upload(os.path.join(self.png_dir, name) + '.png', public_id=name)
        self.url = response['url']
Пример #11
0
 def test_null_token(self):
     cloudinary.config(private_cdn=True)
     url, _ = cloudinary.utils.cloudinary_url("sample.jpg", auth_token=False, sign_url=True, type="authenticated",
                                              version="1486020273")
     self.assertEqual(
         url,
         "http://test123-res.cloudinary.com/image/authenticated/s--v2fTPYTu--/v1486020273/sample.jpg"
     )
Пример #12
0
 def test_explicit_authToken_should_override_global_setting(self):
     cloudinary.config(private_cdn=True)
     url, _ = cloudinary.utils.cloudinary_url("sample.jpg", sign_url=True,
                                              auth_token={"key": ALT_KEY, "start_time": 222222222, "duration": 100},
                                              type="authenticated", transformation={"crop": "scale", "width": 300})
     self.assertEqual(url, "http://test123-res.cloudinary.com/image/authenticated/c_scale,"
                           "w_300/sample.jpg?__cld_token__=st=222222222~exp=222222322~hmac"
                           "=55cfe516530461213fe3b3606014533b1eca8ff60aeab79d1bb84c9322eebc1f")
Пример #13
0
 def test_should_compute_expiration_as_start_time_plus_duration(self):
     cloudinary.config(private_cdn=True)
     token = {"key": KEY, "start_time": 11111111, "duration": 300}
     url, _ = cloudinary.utils.cloudinary_url("sample.jpg", sign_url=True, auth_token=token, resource_type="image",
                                              type="authenticated", version="1486020273")
     self.assertEqual(url, "http://test123-res.cloudinary.com/image/authenticated/v1486020273/sample.jpg"
                           "?__cld_token__=st=11111111~exp=11111411~hmac"
                           "=8db0d753ee7bbb9e2eaf8698ca3797436ba4c20e31f44527e43b6a6e995cfdb3")
Пример #14
0
 def test_client_hints_as_false(self):
     """should use normal responsive behaviour"""
     cloudinary.config(responsive=True)
     tag = CloudinaryImage(self.full_public_id).image(width="auto", crop="scale", cloud_name=self.cloud_name,
                                                      client_hints=False)
     six.assertRegex(self, tag, '<img.*>')
     six.assertRegex(self, tag, 'class=["\']cld-responsive["\']')
     exp = 'data-src=["\']{url}/c_scale,w_auto/{id}["\']'.format(**self.common_format)
     six.assertRegex(self, tag, exp)
Пример #15
0
def _call_api(method, uri, params=None, body=None, headers=None, **options):
    prefix = options.pop("upload_prefix",
                         cloudinary.config().upload_prefix) or "https://api.cloudinary.com"
    cloud_name = options.pop("cloud_name", cloudinary.config().cloud_name)
    if not cloud_name:
        raise Exception("Must supply cloud_name")
    api_key = options.pop("api_key", cloudinary.config().api_key)
    if not api_key:
        raise Exception("Must supply api_key")
    api_secret = options.pop("api_secret", cloudinary.config().api_secret)
    if not cloud_name:
        raise Exception("Must supply api_secret")
    api_url = "/".join([prefix, "v1_1", cloud_name] + uri)

    processed_params = None
    if isinstance(params, dict):
        processed_params = {}
        for key, value in params.items():
            if isinstance(value, list) or isinstance(value, tuple):
                value_list = {"{}[{}]".format(key, i): i_value for i, i_value in enumerate(value)}
                processed_params.update(value_list)
            elif value:
                processed_params[key] = value

    # Add authentication
    req_headers = urllib3.make_headers(
        basic_auth="{0}:{1}".format(api_key, api_secret),
        user_agent=cloudinary.get_user_agent()
    )
    if headers is not None:
        req_headers.update(headers)
    kw = {}
    if 'timeout' in options:
        kw['timeout'] = options['timeout']
    if body is not None:
        kw['body'] = body
    try:
        response = _http.request(method.upper(), api_url, processed_params, req_headers, **kw)
        body = response.data
    except HTTPError as e:
        raise GeneralError("Unexpected error {0}", e.message)
    except socket.error as e:
        raise GeneralError("Socket Error: %s" % (str(e)))

    try:
        result = json.loads(body.decode('utf-8'))
    except Exception as e:
        # Error is parsing json
        raise GeneralError("Error parsing server response (%d) - %s. Got - %s" % (response.status, body, e))

    if "error" in result:
        exception_class = EXCEPTION_CODES.get(response.status) or Exception
        exception_class = exception_class
        raise exception_class("Error {0} - {1}".format(response.status, result["error"]["message"]))

    return Response(result, response)
Пример #16
0
def uploadImage(file, filename):
	filename = secure_filename(filename)
	file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
	fullname = app.config['UPLOAD_FOLDER'] + '/' + filename
	cloudinary.config( 
			cloud_name = "dyrp1r278", 
			api_key = "717493213556769", 
			api_secret = "mS76ULt6IZc54KnSb5WgyjFlAKE" 
	)
	return app.config['CLOUDINARY_URL'] + cloudinary.uploader.upload(fullname).get('public_id')
Пример #17
0
 def setUpClass(cls):
     cloudinary.reset_config()
     if not cloudinary.config().api_secret:
         return
     print("Running tests for cloud: {}".format(cloudinary.config().cloud_name))
     for id in [API_TEST_ID, API_TEST_ID2]:
         uploader.upload(TEST_IMAGE,
                         public_id=id, tags=[API_TEST_TAG, ],
                         context="key=value", eager=[API_TEST_TRANS_SCALE100],
                         overwrite=True)
Пример #18
0
 def setUpClass(cls):
     cloudinary.reset_config()
     if not cloudinary.config().api_secret:
         return
     print("Running tests for cloud: {}".format(cloudinary.config().cloud_name))
     for id in [API_TEST_ID, API_TEST_ID2]:
         uploader.upload("tests/logo.png",
                         public_id=id, tags=[API_TEST_TAG, ],
                         context="key=value", eager=[{"width": 100, "crop": "scale"}],
                         overwrite=True)
Пример #19
0
def sign_request(params, options):
    api_key = options.get("api_key", cloudinary.config().api_key)
    if not api_key: raise Exception("Must supply api_key")
    api_secret = options.get("api_secret", cloudinary.config().api_secret)
    if not api_secret: raise Exception("Must supply api_secret")

    params = dict( [ (k,v) for (k,v) in params.items() if v] )    
    params["signature"] = api_sign_request(params, api_secret)
    params["api_key"] = api_key
    
    return params
Пример #20
0
def sign_request(params, options):
    api_key = options.get("api_key", cloudinary.config().api_key)
    if not api_key: raise ValueError("Must supply api_key")
    api_secret = options.get("api_secret", cloudinary.config().api_secret)
    if not api_secret: raise ValueError("Must supply api_secret")

    params = cleanup_params(params)
    params["signature"] = api_sign_request(params, api_secret)
    params["api_key"] = api_key
    
    return params
Пример #21
0
def cloudinary_direct_upload(callback_url, **options):
    params = uploader.build_upload_params(callback=callback_url, **options)    
    params["signature"] = utils.api_sign_request(params, cloudinary.config().api_secret)    
    params["api_key"] = cloudinary.config().api_key
    
    api_url = utils.cloudinary_api_url("upload", resource_type=options.get("resource_type", "image"), upload_prefix=options.get("upload_prefix"))

    for k, v in params.items():
        if not v:
            del params[k]

    return {"params": params, "url": api_url}
Пример #22
0
    def profile(self, request, studio, state, curPage):
        cloudinary.config(
            cloud_name = "scheduleyoga",
            api_key = "184789393887359",
            api_secret = "5b_y47V0o2CSKgHWDLKyxf4Nmto"
        )

        return render_to_response('studio/profile.html',
                                  {'studio': studio,
                                   'state': state,
                                   'curPage': curPage},
                                  RequestContext(request))
Пример #23
0
def cloudUpload(localfile):
    """
    takes localfile stored on disk and returns a url to which it is uploaded
    using cloudinary api
    """
    
    cloudinary.config( cloud_name = "dkljngqnl", api_key = "495869372656521", api_secret = "trdnXjXXQVo9LDdpawK0b8W0s7c" )

    b = cloudinary.uploader.upload(img)

    hosted_url = b["secure_url"]
    return hosted_url
Пример #24
0
 def shared_client_hints(self, **options):
     """should not use data-src or set responsive class"""
     tag = CloudinaryImage('sample.jpg').image(**options)
     self.assertRegexpMatches(tag, '<img.*>', "should not use data-src or set responsive class" )
     self.assertNotRegexpMatches(tag, '<.* class.*>', "should not use data-src or set responsive class")
     self.assertNotRegexpMatches(tag, '\bdata-src\b', "should not use data-src or set responsive class" )
     self.assertRegexpMatches(tag, 'src=["\']http://res.cloudinary.com/test/image/upload/c_scale,dpr_auto,w_auto/sample.jpg["\']', "should not use data-src or set responsive class")
     cloudinary.config(responsive= True)
     tag = CloudinaryImage('sample.jpg').image(**options)
     self.assertRegexpMatches(tag, '<img.*>' )
     self.assertNotRegexpMatches(tag, '<.* class.*>', "should override responsive")
     self.assertNotRegexpMatches(tag, '\bdata-src\b', "should override responsive" )
     self.assertRegexpMatches(tag, 'src=["\']http://res.cloudinary.com/test/image/upload/c_scale,dpr_auto,w_auto/sample.jpg["\']', "should override responsive")
Пример #25
0
def call_api(method, uri, params, **options):
    prefix = options.pop("upload_prefix", cloudinary.config().upload_prefix) or "https://api.cloudinary.com"
    cloud_name = options.pop("cloud_name", cloudinary.config().cloud_name)
    if not cloud_name: raise Exception("Must supply cloud_name")
    api_key = options.pop("api_key", cloudinary.config().api_key)
    if not api_key: raise Exception("Must supply api_key")
    api_secret = options.pop("api_secret", cloudinary.config().api_secret)
    if not cloud_name: raise Exception("Must supply api_secret")

    data = to_bytes(urlencode(params))
    api_url = "/".join([prefix, "v1_1", cloud_name] + uri)
    request = urllib2.Request(api_url, data)
    # Add authentication
    byte_value = to_bytes('%s:%s' % (api_key, api_secret))
    encoded_value = base64.encodebytes(byte_value) if PY3 else base64.encodestring(byte_value)
    base64string = to_string(encoded_value).replace('\n', '')
    request.add_header("Authorization", "Basic %s" % base64string)
    request.add_header("User-Agent", cloudinary.USER_AGENT)
    request.get_method = lambda: method.upper()

    kw = {}
    if 'timeout' in options:
        kw['timeout'] = options['timeout']
    try:
        response = urllib2.urlopen(request, **kw)
        body = response.read()
    except socket.error:
        e = sys.exc_info()[1]
        raise GeneralError("Socket Error: %s" % (str(e)))
    except urllib2.HTTPError:
        e = sys.exc_info()[1]
        exception_class = EXCEPTION_CODES.get(e.code)
        if exception_class:
            response = e
            body = response.read()
        else:
            raise GeneralError("Server returned unexpected status code - %d - %s" % (e.code, e.read()))

    try:
        body = to_string(body)
        result = json.loads(body)
    except Exception:
        # Error is parsing json
        e = sys.exc_info()[1]
        raise GeneralError("Error parsing server response (%d) - %s. Got - %s" % (response.code, body, e))

    if "error" in result:
        exception_class = exception_class or Exception
        raise exception_class(result["error"]["message"])

    return Response(result, response)
Пример #26
0
    def shared_client_hints(self, **options):
        """should not use data-src or set responsive class"""
        tag = CloudinaryImage(self.full_public_id).image(**options)
        six.assertRegex(self, tag, '<img.*>', "should not use data-src or set responsive class")
        self.assertIsNone(re.match('<.* class.*>', tag), "should not use data-src or set responsive class")
        self.assertIsNone(re.match('\bdata-src\b', tag), "should not use data-src or set responsive class")
        expected_re = 'src=["\']{url}/c_scale,dpr_auto,w_auto/{id}["\']'.format(**self.common_format)
        six.assertRegex(self, tag, expected_re, "should not use data-src or set responsive class")
        cloudinary.config(responsive=True)
        tag = CloudinaryImage(self.full_public_id).image(**options)
        six.assertRegex(self, tag, '<img.*>')
        self.assertIsNone(re.match('<.* class.*>', tag), "should override responsive")
        self.assertIsNone(re.match('\bdata-src\b', tag), "should override responsive")

        six.assertRegex(self, tag, expected_re, "should override responsive")
Пример #27
0
def cloudinary_url(source, **options):
  original_source = source

  type = options.pop("type", "upload")
  if type == 'fetch':
    options["fetch_format"] = options.get("fetch_format", options.pop("format", None))
  transformation, options = generate_transformation_string(**options)

  resource_type = options.pop("resource_type", "image")
  version = options.pop("version", None)
  format = options.pop("format", None)
  cdn_subdomain = options.pop("cdn_subdomain", cloudinary.config().cdn_subdomain)
    
  cloud_name = options.pop("cloud_name", cloudinary.config().cloud_name or None)
  if cloud_name == None: 
    raise Exception("Must supply cloud_name in tag or in configuration")
  secure = options.pop("secure", cloudinary.config().secure)
  private_cdn = options.pop("private_cdn", cloudinary.config().private_cdn)
  secure_distribution = options.pop("secure_distribution", cloudinary.config().secure_distribution)
    
  if not source:
    return (original_source, options)
  if type == "fetch":
    source = smart_escape(source)
  else:
    if re.match(r'^https?:', source): return (original_source, options)
    if format: source = source + "." + format
  
  if cloud_name.startswith("/"):
    prefix = "/res" + cloud_name
  else:
    if secure and not secure_distribution:
      if private_cdn:
        raise Exception("secure_distribution not defined")
      else:
        secure_distribution = SHARED_CDN 
    
    if secure:
      prefix = "https://" + secure_distribution
    else:
      subdomain = "a" + (zlib.crc32(source)%5 + 1) if cdn_subdomain else ""
      prefix = "http://" + subdomain + (cloud_name + "-" if private_cdn else "") + "res.cloudinary.com"
    if not private_cdn:
      prefix += "/" + cloud_name
  
  components = [prefix, resource_type, type, transformation, "v" + version if version else "", source] 
  source = re.sub(r'([^:])/+', r'\1/', "/".join(components))
  return (source, options)
Пример #28
0
def cloudinary_js_config():
    config = cloudinary.config()
    return dict(
        params = json.dumps(dict(
          (param, getattr(config, param)) for param in CLOUDINARY_JS_CONFIG_PARAMS if getattr(config, param, None)
        ))
    )
Пример #29
0
 def setUp(self):
     self.timestamp_tag = "api_test_tag_{0}".format(utils.now())
     if ApiTest.initialized: return
     ApiTest.initialized = True
     cloudinary.reset_config()
     if not cloudinary.config().api_secret: return
     try:
         api.delete_resources(["api_test", "api_test2", "api_test3"])
     except Exception:
         pass
     for transformation in ["api_test_transformation", "api_test_transformation2", "api_test_transformation3"]:
         try:
             api.delete_transformation(transformation)
         except Exception:
             pass
     for transformation in ["api_test_upload_preset", "api_test_upload_preset2", "api_test_upload_preset3",
                            "api_test_upload_preset4"]:
         try:
             api.delete_upload_preset(transformation)
         except Exception:
             pass
     
     for id in ["api_test", "api_test2"]:
         uploader.upload("tests/logo.png",
                         public_id=id, tags=["api_test_tag", self.timestamp_tag],
                         context="key=value", eager=[{"width": 100, "crop": "scale"}])
 def setUp(self):
     if self.initialized:
         return
     self.initialized = True
     cloudinary.reset_config()
     if not cloudinary.config().api_secret:
         return
Пример #31
0
import datetime
import os

import cloudinary
import cloudinary.uploader
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib import rcParams
from pandas.plotting import register_matplotlib_converters
from statsmodels.tsa.arima_model import ARIMA

cloudinary.config(cloud_name='dqmfcku4a',
                  api_key='986962262222677',
                  api_secret='lbTxe9ZAZsbVZJjfLJ_TgJla4aQ')

# Don't cut xlabel when saving .fig
rcParams.update({'figure.autolayout': True})

# Convert datetime for matplotlib
register_matplotlib_converters()

# Create directory for matplotlib figures
if not os.path.exists('plot/ARIMA'):
    os.makedirs('plot/ARIMA')


def qry_ARIMA(cons, start_date, end_date, pdq):
    """Runs a query for the forecast consumption using an ARIMA model.
Пример #32
0
 def test_upload(self):
   """should successfully upload file """
   result = uploader.upload("tests/logo.png")
   self.assertEqual(result["width"], 241)
   self.assertEqual(result["height"], 51)
   expected_signature = utils.api_sign_request(dict(public_id=result["public_id"], version=result["version"]), cloudinary.config().api_secret)
   self.assertEqual(result["signature"], expected_signature)
Пример #33
0
USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Configure Django App for Heroku.
django_heroku.settings(locals())


cloudinary.config(
    cloud_name=config('cloud_name'),
    api_key=config('api_key'),
    api_secret=config('api_secret')
)
Пример #34
0
import cloudinary as Cloud
import cloudinary.uploader as uploader
import cloudinary.api
import os

Cloud.config(cloud_name=os.environ.get('CLOUD_NAME'),
             api_key=os.environ.get('API_KEY'),
             api_secret=os.environ.get('API_SECRET'))


def upload_file(filename: str):
    upload_data = Cloud.uploader.upload_image(filename)
    return upload_data.url
Пример #35
0
def cloudinary_js_config():
    config = cloudinary.config()
    return dict(params=json.dumps(
        dict((param, getattr(config, param))
             for param in CLOUDINARY_JS_CONFIG_PARAMS
             if getattr(config, param, None))))
Пример #36
0
def checkout(request):
    if request.method == "POST":
        if request.user.is_authenticated:
            # removepunc = request.POST.get('removepunc', 'off')
            # fullcaps = request.POST.get('fullcaps', 'off')
            # if removepunc == "on":
            #     print("removepunc")
            # if fullcaps == "on":
            #     print("fullcaps")
            print(request)
            #To be done
            # seller = Seller.objects.filter(seller_name="shop_test")
            # seller = seller.seller_user

            items_json = request.POST.get('itemsJson', '')
            mode = request.POST.get('mode', '')
            # print("pickup : ", pickup)
            # delivery = request.POST.get('delivery', '')
            # print("delivery : ", delivery)
            address = request.POST.get('address1', '') + " " + request.POST.get('address2', '')
            zip_code = request.POST.get('zip_code', '')
            name = request.user.customer
            amount = request.POST.get('totalPrice_database')
            email = request.user.email
            phone = request.POST.get('inputPhone')
            print("amount : ", amount)
            print("amount : ", type(amount))
            order = Orders(customer=name, items_json=items_json , amount=amount, name=name, email=email, phone_number=phone, address=address, zip_code=zip_code, mode=mode)
            order.save()



            update = OrderUpdate(customer=name, order_id=order.order_id, update_desc="The order has been placed")
            update.save()
            thank = True
            id = order.order_id                                                     # To get id of the order, that is displayed in alert box and helps to track orders
            messages.success(request, f"Thanks for Ordering. Your order is id {id}. Use this to track your order using order tracker!")
            # ---------------------------------------------------------------------------------------------------
            # sample = f'''{items_json}, {{"id":{id}}}'''
            # filtered = order.objects.values('order_id','items_json')
            # print("filtered")
            # print(filtered)
            
            # file1 = open('myfile.txt', 'w')
            # myData = Orders.objects.values('items_json', 'order_id')
            # string_myData = json.dumps(myData)
            # print("myData : ", myData)
            # file1.write(myData)
            # sample = f'''{items_json}, {{'order_id': {id}}}'''
            sample = f'''{{'order_id': {id}}}'''
            # string_sample = json.dumps(sample)
            sample = sample.replace("\'","\"")
            airtable_order_id = order.order_id
            # AIRTABLE-PYTHON INTEGRATION STARTS
            update_url = env("AIRTABLE_ORDER_UPDATE_URL")
            update_headers = {
                'Authorization': 'Bearer keydq2SURfHCN4Aig',
                'Content-Type': 'application/json'
            }
            update_data = {
                "fields": {
                # "Name": 33,
                "OrderValue": sample,
                "OrderId": airtable_order_id,
                "OrderStatus": "Pending",
            },
            #   "createdTime": "2021-01-02T20:33:49.000Z"
            }
            
            # print(update_data)
            update_response = requests.post(update_url, headers=update_headers, json=update_data)
            # AIRTABLE-PYTHON INTEGRATION ENDS
            
            # file1 = open('myfile.txt','a')
            # file1.write(sample)
            # file1.write("\n")  

            # print("sample :", string_sample)
            big_code = pyqrcode.create(sample, error='L', version=15, mode='binary')
            image_name = id
            image_qrcode = big_code.png(f'media/qrcode/{id}.png', scale=3, module_color=[0, 0, 0], background=[0xff, 0xff, 0xcc])
            order.order_qr = f"media/qrcode/{id}.png"

            cloudinary.config(cloud_name=env("CLOUD_NAME"),api_key=env("API_KEY"), api_secret=env("API_SECRET_CLOUDINARY"))
            cloudinary.uploader.upload(f"media/qrcode/{id}.png",public_id = f'{id}', folder="media/qrcode")



            # qr_photo = Orders.objects.get(order_id=order.order_id)
            # qr_photo.objects.update()
            Orders.objects.filter(order_id=id).update(order_qr=f"media/qrcode/{id}.png")
            
            # Orders.objects.update(
            #     customer=name, items_json=items_json , amount=amount, name=name, email=email, phone=phone, address=address, zip_code=zip_code, mode=mode, order_qr= f"media/qrcode/{id}.png"
            # )


            # qr_photo.order_qr = f"media/qrcode/{id}.png"
            # qr_photo.save()
            # qr_photo, created = Cart.objects.update_or_create(
            #     customer=customer, defaults={"cart_items": data}
            # )
            

            # ---------------------------------------------------------------------------------------------------
            print("imtems_json : ", items_json)

            return render(request, 'shop/checkout.html', {'thank': thank, 'id': id})                    # 'thank' --> new parameter, : thank --> already declared variable
        else:
            # seller = Seller.objects.filter(seller_name="shop_test")
            # seller = seller.seller_user.name
            items_json = request.POST.get('itemsJson', '')
            name = request.POST.get('name', '')
            email = request.POST.get('email', '')
            amount = request.POST.get('totalPrice_database')
            phone = request.POST.get('inputPhone')
            address = request.POST.get('address1', '') + " " + request.POST.get('address2', '')
            zip_code = request.POST.get('zip_code', '')
            mode = request.POST.get('mode', '')

            
            order = Orders(items_json=items_json, amount=amount , name=name, email=email, phone_number=phone, address=address, zip_code=zip_code, mode=mode)
            order.save()

            update = OrderUpdate(order_id=order.order_id, update_desc="The order has been placed")
            update.save()
            thank = True
            id = order.order_id                                                         # To get id of the order, that is displayed in alert box and helps to track orders
            messages.success(request, f"Thanks for Ordering. Your order is id {id}. Use this to track your order using order tracker!")
            # ---------------------------------------------------------------------------------------------------
            sample = f'''{{'order_id': {id}}}'''
            sample = sample.replace("\'","\"")
            airtable_order_id = order.order_id
            # AIRTABLE-PYTHON INTEGRATION STARTS
            update_url = env("AIRTABLE_ORDER_UPDATE_URL")
            update_headers = {
                'Authorization': 'Bearer keydq2SURfHCN4Aig',
                'Content-Type': 'application/json'
            }
            update_data = {
                "fields": {
                # "Name": 33,
                "OrderValue": sample,
                "OrderId": airtable_order_id,
                "OrderStatus": "Pending",
            },
            #   "createdTime": "2021-01-02T20:33:49.000Z"
            }
            
            # print(update_data)
            update_response = requests.post(update_url, headers=update_headers, json=update_data)
            # AIRTABLE-PYTHON INTEGRATION ENDS
            
            
            # file1 = open('myfile.txt','a')
            # file1.write(sample)         
            # file1.write("\n")          
            big_code = pyqrcode.create(sample, error='L', version=15, mode='binary')
            image_name = id
            image_qrcode = big_code.png(f'media/qrcode/{id}.png', scale=3, module_color=[0, 0, 0], background=[0xff, 0xff, 0xcc])
            order.order_qr = f"media/qrcode/{id}.png"
            cloudinary.config(cloud_name=env("CLOUD_NAME"),api_key=env("API_KEY"), api_secret=env("API_SECRET_CLOUDINARY"))
            cloudinary.uploader.upload(f"media/qrcode/{id}.png",public_id = f'{id}', folder="media/qrcode")
            # ---------------------------------------------------------------------------------------------------
            
            return render(request, 'shop/checkout.html', {'thank': thank, 'id': id})      

    return render(request, 'shop/checkout.html')
Пример #37
0
import os
import cloudinary

DEBUG = True
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SQLALCHEMY_DATABASE_URI = "sqlite:///" + BASE_DIR + "/app.db"

cloudinary.config(cloud_name="fvo2006",
                  api_key="153618543686195",
                  api_secret="gso1RKZn740oV1RagH8begwo2TY")
Пример #38
0
    
    


    #documentação 
    

    #Minhas APPS
    'servicos',
    'conta',
    'frontend',
    
]
cloudinary.config(
    cloud_name="repoimgaxesoft",
    api_key="447527866849349",
    api_secret="Op130juc8Tp4AfaneCBE8TAkCaA"
)

# DJOSER = {
#     'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}',
#     'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}',
#     'ACTIVATION_URL': '#/activate/{uid}/{token}',
#     'SEND_ACTIVATION_EMAIL': True,
#     'SERIALIZERS': {},
# }
AUTH_USER_MODEL = 'conta.Account'

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
Пример #39
0
LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

cloudinary.config(cloud_name="toffy",
                  api_key="393415259869955",
                  api_secret="XISdAJ5DC6g01zRqpZxxWrYZnVs")

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
# STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

ACCOUNT_EMAIL_VERIFICATION = 'none'
ACCOUNT_AUTHENTICATION_METHOD = 'username'
ACCOUNT_EMAIL_REQUIRED = False

SITE_ID = 1

# To reconfigure the production database
import dj_database_url
Пример #40
0
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'insta/static'), )

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'insta/static')]

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Configure Django App for Heroku.
django_heroku.settings(locals())

# Cloudinary settings using python code. Run before pycloudinary is used.
import cloudinary
cloudinary.config(cloud_name=os.environ.get('CLOUDINARY_CLOUD_NAME'),
                  api_key=os.environ.get('CLOUDINARY_API_KEY'),
                  api_secret=os.environ.get('CLOUDINARY_API_SECRET'))
Пример #41
0
import sys
sys.path.append('../')

from receiptapp.models import Receipt, Image, Food, Fooddetail, Progress
from receiptapp.modules import receipt_tyuusyutu2
from receiptapp.modules import receipt_text2, receipt_text3
import environ
import cloudinary
import celery

env = environ.Env()
env.read_env('.env')

cloudinary.config(cloud_name=env('CLOUD_NAME'),
                  api_key=env('API_KEY'),
                  api_secret=env('API_SECRET'))


@shared_task(bind=True)
def get_search_list(self, image_id):
    task_id = self.request.id
    print("task_idは" + task_id)

    # 1
    progress = Progress(task_id=task_id, progress_no=1)
    progress.save()

    search_list = []
    image = Image.objects.get(pk=image_id).image.url
    filename = image
Пример #42
0
# Cloudinary API imports
import cloudinary
import cloudinary.uploader
from cloudinary.uploader import upload
import cloudinary.api
from cloudinary.utils import cloudinary_url

from flask import Flask, render_template, request

app = Flask(__name__)

# Cloudinary Configuration:
cloudinary.config(cloud_name='*****', api_key='*****', api_secret='*****')


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    upload_result = None
    thumbnail_url1 = None
    thumbnail_url2 = None
    if request.method == 'POST':
        file_to_upload = request.files['file']
        if file_to_upload:
            upload_result = upload(file_to_upload)
            thumbnail_url1, options = cloudinary_url(
                upload_result['public_id'],
                format="jpg",
                crop="fill",
                width=100,
                height=100)
            thumbnail_url2, options = cloudinary_url(
Пример #43
0
TIME_ZONE = 'Africa/Nairobi'

USE_I18N = True

USE_L10N = True

USE_TZ = True

CRISPY_TEMPLATE_PACK = 'bootstrap4'

LOGIN_REDIRECT_URL = 'home-view'
LOGIN_URL = 'login'

cloudinary.config(cloud_name="dtydg6xpa",
                  api_key="568552354739641",
                  api_secret="plPkmm4WcrylYnuoJxu3gSNNTuI")

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Пример #44
0
#lineas de configuracion para envio de correo electrino de confirmacion al crear nuevos usuarios
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
EMAIL_PORT = 587
#fin lineas de configuracion para envio de correo electrino de confirmacion al crear nuevos usuarios

# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/

STATIC_URL = '/static/'

STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), )

STATIC_ROOT = os.path.join(BASE_DIR, "live-static", "static-root")

STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

#STATIC_ROOT = "/home/cfedeploy/webapps/cfehome_static_root/"

MEDIA_URL = "/media/"

MEDIA_ROOT = os.path.join(BASE_DIR, "live-static", "media-root")

#para servir archivos media con claudinary
cloudinary.config(cloud_name=os.environ.get('CLOUD_NAME'),
                  api_key=os.environ.get('API_KEY'),
                  api_secret=os.environ.get('API_SECRET'),
                  secure=True)
Пример #45
0
class UploaderTest(unittest.TestCase):
    rbp_trans = {"angle": 45, "crop": "scale"}
    rbp_format = "png"
    rbp_values = [206, 50]
    rbp_params = {
        "use_cache":
        True,
        "responsive_breakpoints": [{
            "create_derived": False,
            "transformation": {
                "angle": 90
            },
            "format": "gif"
        }, {
            "create_derived": False,
            "transformation": rbp_trans,
            "format": rbp_format
        }, {
            "create_derived": False
        }],
        "type":
        "upload"
    }

    def setUp(self):
        cloudinary.reset_config()

    @classmethod
    def tearDownClass(cls):
        cloudinary.api.delete_resources_by_tag(UNIQUE_TAG)
        cloudinary.api.delete_resources_by_tag(UNIQUE_TAG, resource_type='raw')
        cloudinary.api.delete_resources_by_tag(UNIQUE_TAG, type='twitter_name')
        cloudinary.api.delete_resources([TEST_ID1, TEST_ID2])
        cloudinary.api.delete_resources([TEXT_ID], type='text')
        cloudinary.api.delete_resources([TEST_DOCX_ID], resource_type='raw')

        for trans in [TEST_TRANS_SCALE2_STR, TEST_TRANS_SCALE2_PNG_STR]:
            try:
                api.delete_transformation(trans)
            except Exception:
                pass

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_upload(self):
        """should successfully upload file """
        result = uploader.upload(TEST_IMAGE, tags=[UNIQUE_TAG])
        self.assertEqual(result["width"], TEST_IMAGE_WIDTH)
        self.assertEqual(result["height"], TEST_IMAGE_HEIGHT)
        expected_signature = utils.api_sign_request(
            dict(public_id=result["public_id"], version=result["version"]),
            cloudinary.config().api_secret)
        self.assertEqual(result["signature"], expected_signature)

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_upload_unicode_filename(self):
        """should successfully upload file with unicode characters"""
        expected_name = os.path.splitext(
            os.path.basename(TEST_UNICODE_IMAGE))[0]

        result = uploader.upload(TEST_UNICODE_IMAGE,
                                 tags=[UNIQUE_TAG],
                                 use_filename=True,
                                 unique_filename=False)

        self.assertEqual(result["width"], TEST_IMAGE_WIDTH)
        self.assertEqual(result["height"], TEST_IMAGE_HEIGHT)

        self.assertEqual(expected_name, result["public_id"])
        self.assertEqual(expected_name, result["original_filename"])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_upload_file_io_without_filename(self):
        """should successfully upload FileIO file """
        with io.BytesIO() as temp_file, open(TEST_IMAGE, 'rb') as input_file:
            temp_file.write(input_file.read())
            temp_file.seek(0)

            result = uploader.upload(temp_file, tags=[UNIQUE_TAG])

        self.assertEqual(result["width"], TEST_IMAGE_WIDTH)
        self.assertEqual(result["height"], TEST_IMAGE_HEIGHT)
        self.assertEqual('stream', result["original_filename"])

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_upload_async(self, mocker):
        """should pass async value """
        mocker.return_value = MOCK_RESPONSE
        async_option = {"async": True}
        uploader.upload(TEST_IMAGE, tags=[UNIQUE_TAG], **async_option)
        params = mocker.call_args[0][2]
        self.assertTrue(params['async'])

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_ocr(self, mocker):
        """should pass ocr value """
        mocker.return_value = MOCK_RESPONSE
        uploader.upload(TEST_IMAGE, tags=[UNIQUE_TAG], ocr='adv_ocr')
        args, kargs = mocker.call_args
        self.assertEqual(get_params(args)['ocr'], 'adv_ocr')

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_quality_override(self, mocker):
        """should pass quality_override """
        mocker.return_value = MOCK_RESPONSE
        test_values = ['auto:advanced', 'auto:best', '80:420', 'none']
        for quality in test_values:
            uploader.upload(TEST_IMAGE,
                            tags=UNIQUE_TAG,
                            quality_override=quality)
            params = mocker.call_args[0][2]
            self.assertEqual(params['quality_override'], quality)
        # verify explicit works too
        uploader.explicit(TEST_IMAGE, quality_override='auto:best')
        params = mocker.call_args[0][2]
        self.assertEqual(params['quality_override'], 'auto:best')

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_upload_url(self):
        """should successfully upload file by url """
        result = uploader.upload(REMOTE_TEST_IMAGE, tags=[UNIQUE_TAG])
        self.assertEqual(result["width"], TEST_IMAGE_WIDTH)
        self.assertEqual(result["height"], TEST_IMAGE_HEIGHT)
        expected_signature = utils.api_sign_request(
            dict(public_id=result["public_id"], version=result["version"]),
            cloudinary.config().api_secret)
        self.assertEqual(result["signature"], expected_signature)

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_upload_unicode_url(self):
        """should successfully upload file by unicode url """
        unicode_image_url = u"{}".format(REMOTE_TEST_IMAGE)
        result = uploader.upload(unicode_image_url, tags=[UNIQUE_TAG])
        self.assertEqual(result["width"], TEST_IMAGE_WIDTH)
        self.assertEqual(result["height"], TEST_IMAGE_HEIGHT)
        expected_signature = utils.api_sign_request(
            dict(public_id=result["public_id"], version=result["version"]),
            cloudinary.config().api_secret)
        self.assertEqual(result["signature"], expected_signature)

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_upload_data_uri(self):
        """should successfully upload file by data url """
        result = uploader.upload(u"""\
data:image/png;base64,iVBORw0KGgoAA
AANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0l
EQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6
P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC\
""",
                                 tags=[UNIQUE_TAG])
        self.assertEqual(result["width"], 16)
        self.assertEqual(result["height"], 16)
        expected_signature = utils.api_sign_request(
            dict(public_id=result["public_id"], version=result["version"]),
            cloudinary.config().api_secret)
        self.assertEqual(result["signature"], expected_signature)

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_upload_responsive_breakpoints_cache(self):
        """Should save responsive breakpoints to cache after upload"""
        cache = responsive_breakpoints_cache.instance
        cache.set_cache_adapter(KeyValueCacheAdapter(DummyCacheStorage()))

        upload_result = uploader.upload(TEST_IMAGE, **self.rbp_params)

        cache_value = cache.get(upload_result["public_id"],
                                transformation=self.rbp_trans,
                                format=self.rbp_format)

        self.assertEqual(self.rbp_values, cache_value)

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_rename(self):
        """should successfully rename a file"""
        result = uploader.upload(TEST_IMAGE, tags=[UNIQUE_TAG])
        uploader.rename(result["public_id"], result["public_id"] + "2")
        self.assertIsNotNone(api.resource(result["public_id"] + "2"))
        result2 = uploader.upload(TEST_ICON, tags=[UNIQUE_TAG])
        self.assertRaises(api.Error, uploader.rename, result2["public_id"],
                          result["public_id"] + "2")
        uploader.rename(result2["public_id"],
                        result["public_id"] + "2",
                        overwrite=True)
        self.assertEqual(
            api.resource(result["public_id"] + "2")["format"], "ico")

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_rename_parameters(self, mocker):
        """should support to_type, invalidate, and overwrite """
        mocker.return_value = MOCK_RESPONSE
        uploader.rename(TEST_IMAGE,
                        TEST_IMAGE + "2",
                        to_type='raw',
                        invalidate=True,
                        overwrite=False)
        args, kargs = mocker.call_args
        self.assertEqual(get_params(args)['to_type'], 'raw')
        self.assertTrue(get_params(args)['invalidate'])
        self.assertTrue(get_params(args)['overwrite'])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_use_filename(self):
        """should successfully take use file name of uploaded file in public id if specified use_filename """
        result = uploader.upload(TEST_IMAGE,
                                 use_filename=True,
                                 tags=[UNIQUE_TAG])
        six.assertRegex(self, result["public_id"], 'logo_[a-z0-9]{6}')
        result = uploader.upload(TEST_IMAGE,
                                 use_filename=True,
                                 unique_filename=False,
                                 tags=[UNIQUE_TAG])
        self.assertEqual(result["public_id"], 'logo')

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_explicit(self):
        """should support explicit """
        result = uploader.explicit("cloudinary",
                                   type="twitter_name",
                                   eager=[TEST_TRANS_SCALE2_PNG],
                                   tags=[UNIQUE_TAG])
        params = dict(TEST_TRANS_SCALE2_PNG,
                      type="twitter_name",
                      version=result["version"])
        url = utils.cloudinary_url("cloudinary", **params)[0]
        actual = result["eager"][0]["url"]
        self.assertEqual(parse_url(actual).path, parse_url(url).path)

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_explicit_responsive_breakpoints_cache(self):
        """Should save responsive breakpoints to cache after explicit"""
        cache = responsive_breakpoints_cache.instance
        cache.set_cache_adapter(KeyValueCacheAdapter(DummyCacheStorage()))

        upload_result = uploader.upload(TEST_IMAGE)
        explicit_result = uploader.explicit(upload_result["public_id"],
                                            **self.rbp_params)

        cache_value = cache.get(explicit_result["public_id"],
                                transformation=self.rbp_trans,
                                format=self.rbp_format)

        self.assertEqual(self.rbp_values, cache_value)

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_eager(self):
        """should support eager """
        uploader.upload(TEST_IMAGE,
                        eager=[TEST_TRANS_SCALE2],
                        tags=[UNIQUE_TAG])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_header(self):
        """should support headers """
        uploader.upload(TEST_IMAGE, headers=["Link: 1"], tags=[UNIQUE_TAG])
        uploader.upload(TEST_IMAGE, headers={"Link": "1"}, tags=[UNIQUE_TAG])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_text(self):
        """should successfully generate text image """
        result = uploader.text("hello world", public_id=TEXT_ID)
        self.assertGreater(result["width"], 1)
        self.assertGreater(result["height"], 1)

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_tags(self):
        """should successfully upload file """
        result = uploader.upload(TEST_IMAGE, tags=[UNIQUE_TAG])
        result2 = uploader.upload(TEST_IMAGE, tags=[UNIQUE_TAG])
        uploader.add_tag("tag1", [result["public_id"], result2["public_id"]])
        uploader.add_tag("tag2", result["public_id"])
        self.assertEqual(
            api.resource(result["public_id"])["tags"],
            ["tag1", "tag2", UNIQUE_TAG])
        self.assertEqual(
            api.resource(result2["public_id"])["tags"], ["tag1", UNIQUE_TAG])
        uploader.remove_tag("tag1", result["public_id"])
        self.assertEqual(
            api.resource(result["public_id"])["tags"], ["tag2", UNIQUE_TAG])
        uploader.replace_tag("tag3", result["public_id"])
        self.assertEqual(api.resource(result["public_id"])["tags"], ["tag3"])
        uploader.replace_tag(UNIQUE_TAG, result["public_id"])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_remove_all_tags(self):
        """should successfully remove all tags"""
        result = uploader.upload(TEST_IMAGE, public_id=TEST_ID1)
        result2 = uploader.upload(TEST_IMAGE, public_id=TEST_ID2)
        uploader.add_tag("tag1", [result["public_id"], result2["public_id"]])
        uploader.add_tag("tag2", result["public_id"])
        self.assertEqual(
            api.resource(result["public_id"])["tags"], ["tag1", "tag2"])
        self.assertEqual(api.resource(result2["public_id"])["tags"], ["tag1"])
        uploader.remove_all_tags([result["public_id"], result2["public_id"]])
        self.assertFalse("tags" in api.resource(result["public_id"]))
        self.assertFalse("tags" in api.resource(result2["public_id"]))

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_allowed_formats(self):
        """ should allow whitelisted formats if allowed_formats """
        result = uploader.upload(TEST_IMAGE,
                                 allowed_formats=['png'],
                                 tags=[UNIQUE_TAG])
        self.assertEqual(result["format"], "png")

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_allowed_formats_with_illegal_format(self):
        """should prevent non whitelisted formats from being uploaded if allowed_formats is specified"""
        self.assertRaises(api.Error,
                          uploader.upload,
                          TEST_IMAGE,
                          allowed_formats=['jpg'])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_allowed_formats_with_format(self):
        """should allow non whitelisted formats if type is specified and convert to that type"""
        result = uploader.upload(TEST_IMAGE,
                                 allowed_formats=['jpg'],
                                 format='jpg',
                                 tags=[UNIQUE_TAG])
        self.assertEqual("jpg", result["format"])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_face_coordinates(self):
        """should allow sending face coordinates"""
        coordinates = [[120, 30, 109, 150], [121, 31, 110, 151]]
        result_coordinates = [[120, 30, 109, 51], [121, 31, 110, 51]]
        result = uploader.upload(TEST_IMAGE,
                                 face_coordinates=coordinates,
                                 faces=True,
                                 tags=[UNIQUE_TAG])
        self.assertEqual(result_coordinates, result["faces"])

        different_coordinates = [[122, 32, 111, 152]]
        custom_coordinates = [1, 2, 3, 4]
        uploader.explicit(result["public_id"],
                          face_coordinates=different_coordinates,
                          custom_coordinates=custom_coordinates,
                          type="upload")
        info = api.resource(result["public_id"], faces=True, coordinates=True)
        self.assertEqual(different_coordinates, info["faces"])
        self.assertEqual(
            {
                "faces": different_coordinates,
                "custom": [custom_coordinates]
            }, info["coordinates"])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_context(self):
        """should allow sending context"""
        context = {"caption": "some caption", "alt": "alternative|alt=a"}
        result = uploader.upload(TEST_IMAGE,
                                 context=context,
                                 tags=[UNIQUE_TAG])
        info = api.resource(result["public_id"], context=True)
        self.assertEqual({"custom": context}, info["context"])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_add_context(self):
        """should allow adding context"""
        context = {"caption": "some caption", "alt": "alternative|alt=a"}
        result = uploader.upload(TEST_IMAGE, tags=[UNIQUE_TAG])
        info = api.resource(result["public_id"], context=True)
        self.assertFalse("context" in info)
        uploader.add_context(context, result["public_id"])
        info = api.resource(result["public_id"], context=True)
        self.assertEqual({"custom": context}, info["context"])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_remove_all_context(self):
        """should allow removing all context"""
        context = {"caption": "some caption", "alt": "alternative|alt=a"}
        result = uploader.upload(TEST_IMAGE,
                                 context=context,
                                 tags=[UNIQUE_TAG])
        info = api.resource(result["public_id"], context=True)
        self.assertEqual({"custom": context}, info["context"])
        uploader.remove_all_context(result["public_id"])
        info = api.resource(result["public_id"], context=True)
        self.assertFalse("context" in info)

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_manual_moderation(self):
        """ should support setting manual moderation status """
        resource = uploader.upload(TEST_IMAGE,
                                   moderation="manual",
                                   tags=[UNIQUE_TAG])

        self.assertEqual(resource["moderation"][0]["status"], "pending")
        self.assertEqual(resource["moderation"][0]["kind"], "manual")

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_raw_conversion(self):
        """ should support requesting raw_convert """
        with six.assertRaisesRegex(self, api.Error, 'Raw convert is invalid'):
            uploader.upload(TEST_DOC,
                            public_id=TEST_DOCX_ID,
                            raw_convert="illegal",
                            resource_type="raw",
                            tags=[UNIQUE_TAG])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_categorization(self):
        """ should support requesting categorization """
        with six.assertRaisesRegex(self, api.Error, 'is not valid'):
            uploader.upload(TEST_IMAGE,
                            categorization="illegal",
                            tags=[UNIQUE_TAG])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_detection(self):
        """ should support requesting detection """
        with six.assertRaisesRegex(self, api.Error, 'illegal is not a valid'):
            uploader.upload(TEST_IMAGE, detection="illegal", tags=[UNIQUE_TAG])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_upload_large(self):
        """ should support uploading large files """
        with tempfile.NamedTemporaryFile() as temp_file:
            populate_large_file(temp_file, LARGE_FILE_SIZE)
            temp_file_name = temp_file.name

            self.assertEqual(LARGE_FILE_SIZE, os.path.getsize(temp_file_name))

            resource = uploader.upload_large(
                temp_file_name,
                chunk_size=LARGE_CHUNK_SIZE,
                tags=["upload_large_tag", UNIQUE_TAG])

            self.assertEqual(resource["tags"],
                             ["upload_large_tag", UNIQUE_TAG])
            self.assertEqual(resource["resource_type"], "raw")

            resource2 = uploader.upload_large(
                temp_file_name,
                chunk_size=LARGE_CHUNK_SIZE,
                tags=["upload_large_tag", UNIQUE_TAG],
                resource_type="image")

            self.assertEqual(resource2["tags"],
                             ["upload_large_tag", UNIQUE_TAG])
            self.assertEqual(resource2["resource_type"], "image")
            self.assertEqual(resource2["width"], LARGE_FILE_WIDTH)
            self.assertEqual(resource2["height"], LARGE_FILE_HEIGHT)

            resource3 = uploader.upload_large(
                temp_file_name,
                chunk_size=LARGE_FILE_SIZE,
                tags=["upload_large_tag", UNIQUE_TAG])

            self.assertEqual(resource3["tags"],
                             ["upload_large_tag", UNIQUE_TAG])
            self.assertEqual(resource3["resource_type"], "raw")

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_upload_large_url(self):
        """Should allow fallback of upload large with remote url to regular upload"""
        resource4 = uploader.upload_large(REMOTE_TEST_IMAGE, tags=[UNIQUE_TAG])

        self.assertEqual(resource4["width"], TEST_IMAGE_WIDTH)
        self.assertEqual(resource4["height"], TEST_IMAGE_HEIGHT)

        expected_signature = utils.api_sign_request(
            dict(public_id=resource4["public_id"],
                 version=resource4["version"]),
            cloudinary.config().api_secret)

        self.assertEqual(resource4["signature"], expected_signature)

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_upload_large_file_io(self):
        """Should support uploading large streams"""
        with io.BytesIO() as temp_file:
            populate_large_file(temp_file, LARGE_FILE_SIZE)
            resource = uploader.upload_large(
                temp_file,
                chunk_size=LARGE_CHUNK_SIZE,
                tags=["upload_large_tag", UNIQUE_TAG],
                resource_type="image")

            self.assertEqual(resource["tags"],
                             ["upload_large_tag", UNIQUE_TAG])
            self.assertEqual(resource["resource_type"], "image")
            self.assertEqual(resource["width"], LARGE_FILE_WIDTH)
            self.assertEqual(resource["height"], LARGE_FILE_HEIGHT)

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_upload_preset(self):
        """ should support unsigned uploading using presets """
        preset = api.create_upload_preset(folder="upload_folder",
                                          unsigned=True,
                                          tags=[UNIQUE_TAG])
        result = uploader.unsigned_upload(TEST_IMAGE,
                                          preset["name"],
                                          tags=[UNIQUE_TAG])
        six.assertRegex(self, result["public_id"],
                        r'^upload_folder\/[a-z0-9]+$')
        api.delete_upload_preset(preset["name"])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_background_removal(self):
        """ should support requesting background_removal """
        with six.assertRaisesRegex(self, api.Error, 'is invalid'):
            uploader.upload(TEST_IMAGE,
                            background_removal="illegal",
                            tags=[UNIQUE_TAG])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_upload_timeout(self):
        with six.assertRaisesRegex(self, cloudinary.api.Error, 'timed out'):
            uploader.upload(TEST_IMAGE, timeout=0.001, tags=[UNIQUE_TAG])

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    def test_responsive_breakpoints(self):
        result = uploader.upload(TEST_IMAGE,
                                 tags=[UNIQUE_TAG],
                                 responsive_breakpoints=dict(
                                     create_derived=False,
                                     transformation=dict(angle=90)))

        self.assertIsNotNone(result["responsive_breakpoints"])
        self.assertEqual(result["responsive_breakpoints"][0]["transformation"],
                         "a_90")

        result = uploader.explicit(result["public_id"],
                                   type="upload",
                                   tags=[UNIQUE_TAG],
                                   responsive_breakpoints=[
                                       dict(create_derived=False,
                                            transformation=dict(angle=90)),
                                       dict(create_derived=False,
                                            transformation=dict(angle=45))
                                   ])

        self.assertIsNotNone(result["responsive_breakpoints"])
        self.assertEqual(result["responsive_breakpoints"][0]["transformation"],
                         "a_90")
        self.assertEqual(result["responsive_breakpoints"][1]["transformation"],
                         "a_45")

    @unittest.skipUnless(cloudinary.config().api_secret,
                         "requires api_key/api_secret")
    @patch('urllib3.request.RequestMethods.request')
    def test_access_control(self, request_mock):
        request_mock.return_value = MOCK_RESPONSE

        # Should accept a dictionary of strings
        acl = OrderedDict((("access_type", "anonymous"),
                           ("start", "2018-02-22 16:20:57 +0200"),
                           ("end", "2018-03-22 00:00 +0200")))
        exp_acl = '[{"access_type":"anonymous","start":"2018-02-22 16:20:57 +0200","end":"2018-03-22 00:00 +0200"}]'

        uploader.upload(TEST_IMAGE, access_control=acl)
        params = get_params(request_mock.call_args[0])

        self.assertIn("access_control", params)
        self.assertEqual(exp_acl, params["access_control"])

        # Should accept a dictionary of datetime objects
        acl_2 = OrderedDict(
            (("access_type", "anonymous"),
             ("start",
              datetime.strptime("2019-02-22 16:20:57Z", "%Y-%m-%d %H:%M:%SZ")),
             ("end", datetime(2019, 3, 22, 0, 0, tzinfo=UTC()))))

        exp_acl_2 = '[{"access_type":"anonymous","start":"2019-02-22T16:20:57","end":"2019-03-22T00:00:00+00:00"}]'

        uploader.upload(TEST_IMAGE, access_control=acl_2)
        params = get_params(request_mock.call_args[0])

        self.assertEqual(exp_acl_2, params["access_control"])

        # Should accept a JSON string
        acl_str = '{"access_type":"anonymous","start":"2019-02-22 16:20:57 +0200","end":"2019-03-22 00:00 +0200"}'
        exp_acl_str = '[{"access_type":"anonymous","start":"2019-02-22 16:20:57 +0200","end":"2019-03-22 00:00 +0200"}]'

        uploader.upload(TEST_IMAGE, access_control=acl_str)
        params = get_params(request_mock.call_args[0])

        self.assertEqual(exp_acl_str, params["access_control"])

        # Should accept a list of all the above values
        list_of_acl = [acl, acl_2, acl_str]
        # Remove starting "[" and ending "]" in all expected strings and combine them into one string
        expected_list_of_acl = "[" + ",".join(
            [v[1:-1] for v in (exp_acl, exp_acl_2, exp_acl_str)]) + "]"

        uploader.upload(TEST_IMAGE, access_control=list_of_acl)
        params = get_params(request_mock.call_args[0])

        self.assertEqual(expected_list_of_acl, params["access_control"])

        # Should raise ValueError on invalid values
        invalid_values = [[[]], ["not_a_dict"], [7357]]
        for invalid_value in invalid_values:
            with self.assertRaises(ValueError):
                uploader.upload(TEST_IMAGE, access_control=invalid_value)
Пример #46
0
from decouple import config, Csv
import cloudinary
import cloudinary.uploader
import cloudinary.api

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'

STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )

cloudinary.config(
    cloud_name='dqofyimn2',
    api_key='255523988776555',
    api_secret='UKR2jJ2pR_WhPU-oeLfKcGb0hsc',
)

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'avatar',
    'cloudinary',
    'gramclone',
Пример #47
0
STATICFILES_DIRS = (
    'main/static',
    'account/static',
    'items/static',
)

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

ASGI_APPLICATION = "dontbuyit.asgi.application"

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            # "hosts": [os.environ.get('REDIS_URL', ('127.0.0.1', 6379))],
            "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
        },
    },
}

django_heroku.settings(locals())

if os.environ.get('REDIS_URL'):
    cloudinary.config(
      cloud_name="hachlwujp",
      api_key=os.environ.get('cloudinary_api_key', ''),
      api_secret=os.environ.get('cloudinary_api_secret', '')
    )
    DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'
Пример #48
0
USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'
CRISPY_TEMPLATE_PACK = 'bootstrap4'

# LOGIN_REDIRECT_URL='gram-landing'
# LOGIN_URL='login'

cloudinary.config(cloud_name="sawedee",
                  api_key="616212518566398",
                  api_secret="9vv5at5ybHBCEkz0HAcprG3WwAI")

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )
APPEND_SLASH = True
CORS_ALLOW_ALL_ORIGINS = True
LOGIN_REDIRECT_URL = 'account'
LOGIN_URL = 'login'
Пример #49
0
def generate_transformation_string(**options):
    responsive_width = options.pop("responsive_width",
                                   cloudinary.config().responsive_width)
    size = options.pop("size", None)
    if size:
        options["width"], options["height"] = size.split("x")
    width = options.get("width")
    height = options.get("height")
    has_layer = ("underlay" in options) or ("overlay" in options)

    crop = options.pop("crop", None)
    angle = ".".join(
        [str(value) for value in build_array(options.pop("angle", None))])
    no_html_sizes = has_layer or angle or crop == "fit" or crop == "limit" or responsive_width

    if width and (str(width).startswith("auto") or str(width) == "ow"
                  or is_fraction(width) or no_html_sizes):
        del options["width"]
    if height and (str(height) == "oh" or is_fraction(height)
                   or no_html_sizes):
        del options["height"]

    background = options.pop("background", None)
    if background:
        background = background.replace("#", "rgb:")
    color = options.pop("color", None)
    if color:
        color = color.replace("#", "rgb:")

    base_transformations = build_array(options.pop("transformation", None))
    if any(isinstance(bs, dict) for bs in base_transformations):

        def recurse(bs):
            if isinstance(bs, dict):
                return generate_transformation_string(**bs)[0]
            else:
                return generate_transformation_string(transformation=bs)[0]

        base_transformations = list(map(recurse, base_transformations))
        named_transformation = None
    else:
        named_transformation = ".".join(base_transformations)
        base_transformations = []

    effect = options.pop("effect", None)
    if isinstance(effect, list):
        effect = ":".join([str(x) for x in effect])
    elif isinstance(effect, dict):
        effect = ":".join([str(x) for x in list(effect.items())[0]])

    border = options.pop("border", None)
    if isinstance(border, dict):
        border_color = border.get("color", "black").replace("#", "rgb:")
        border = "%(width)spx_solid_%(color)s" % {
            "color": border_color,
            "width": str(border.get("width", 2))
        }

    flags = ".".join(build_array(options.pop("flags", None)))
    dpr = options.pop("dpr", cloudinary.config().dpr)
    duration = norm_range_value(options.pop("duration", None))
    start_offset = norm_range_value(options.pop("start_offset", None))
    end_offset = norm_range_value(options.pop("end_offset", None))
    offset = split_range(options.pop("offset", None))
    if offset:
        start_offset = norm_range_value(offset[0])
        end_offset = norm_range_value(offset[1])

    video_codec = process_video_codec_param(options.pop("video_codec", None))

    aspect_ratio = options.pop("aspect_ratio", None)
    if isinstance(aspect_ratio, Fraction):
        aspect_ratio = str(aspect_ratio.numerator) + ":" + str(
            aspect_ratio.denominator)

    overlay = process_layer(options.pop("overlay", None), "overlay")
    underlay = process_layer(options.pop("underlay", None), "underlay")
    if_value = process_conditional(options.pop("if", None))

    params = {
        "a": normalize_expression(angle),
        "ar": normalize_expression(aspect_ratio),
        "b": background,
        "bo": border,
        "c": crop,
        "co": color,
        "dpr": normalize_expression(dpr),
        "du": normalize_expression(duration),
        "e": normalize_expression(effect),
        "eo": normalize_expression(end_offset),
        "fl": flags,
        "h": normalize_expression(height),
        "l": overlay,
        "o": normalize_expression(options.pop('opacity', None)),
        "q": normalize_expression(options.pop('quality', None)),
        "r": normalize_expression(options.pop('radius', None)),
        "so": normalize_expression(start_offset),
        "t": named_transformation,
        "u": underlay,
        "w": normalize_expression(width),
        "x": normalize_expression(options.pop('x', None)),
        "y": normalize_expression(options.pop('y', None)),
        "vc": video_codec,
        "z": normalize_expression(options.pop('zoom', None))
    }
    simple_params = {
        "ac": "audio_codec",
        "af": "audio_frequency",
        "br": "bit_rate",
        "cs": "color_space",
        "d": "default_image",
        "dl": "delay",
        "dn": "density",
        "f": "fetch_format",
        "g": "gravity",
        "ki": "keyframe_interval",
        "p": "prefix",
        "pg": "page",
        "sp": "streaming_profile",
        "vs": "video_sampling",
    }

    for param, option in simple_params.items():
        params[param] = options.pop(option, None)

    variables = options.pop('variables', {})
    var_params = []
    for key, value in options.items():
        if re.match(r'^\$', key):
            var_params.append(u"{0}_{1}".format(
                key, normalize_expression(str(value))))

    var_params.sort()

    if variables:
        for var in variables:
            var_params.append(u"{0}_{1}".format(
                var[0], normalize_expression(str(var[1]))))

    variables = ','.join(var_params)

    sorted_params = sorted([
        param + "_" + str(value) for param, value in params.items()
        if (value or value == 0)
    ])
    if variables:
        sorted_params.insert(0, str(variables))

    if if_value is not None:
        sorted_params.insert(0, "if_" + str(if_value))
    transformation = ",".join(sorted_params)
    if "raw_transformation" in options:
        transformation = transformation + "," + options.pop(
            "raw_transformation")
    transformations = base_transformations + [transformation]
    if responsive_width:
        responsive_width_transformation = cloudinary.config().responsive_width_transformation \
                                          or DEFAULT_RESPONSIVE_WIDTH_TRANSFORMATION
        transformations += [
            generate_transformation_string(
                **responsive_width_transformation)[0]
        ]
    url = "/".join([trans for trans in transformations if trans])

    if str(width).startswith("auto") or responsive_width:
        options["responsive"] = True
    if dpr == "auto":
        options["hidpi"] = True
    return url, options
Пример #50
0
USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/


STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]


STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
cloudinary.config(
  cloud_name = "dyoo1jto9",
  api_key = "477667266123915",
  api_secret = "QsodG6nbmkKcaSAlDFAS3rRMvVM"
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')


# Configure Django App for Heroku.
django_heroku.settings(locals())
Пример #51
0
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

# media config
MEDIA_URL = '/media/'
MEDIA_ROOT = 'os.path.join(BASE_DIR, media)'

# cloudinary config
cloudinary.config(cloud_name='dl3h6iib2',
                  api_key='975132373835258',
                  api_secret='8hW3R3U4n-fj9msb3F_um8EPF2s')

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'

#LOGGING = {
#    'version': 1,
#    'disable_existing_loggers': False,
#    'handlers': {
#        'console': {
#            'class': 'logging.StreamHandler',
#        },
#    },
#    'loggers': {
#        'django': {
Пример #52
0
ALLOWED_HOSTS = [
    'localhost', '127.0.0.1', '143.198.185.124', 'reactsongs.com',
    'www.reactsongs.com', "app", "api.reactsongs.com"
]

# Application definition
INSTALLED_APPS = [
    'corsheaders', 'django.contrib.admin', 'django.contrib.auth',
    'django.contrib.contenttypes', 'django.contrib.sessions',
    'django.contrib.messages', 'django.contrib.staticfiles', 'graphene_django',
    'tracks', 'cloudinary'
]

cloudinary.config(cloud_name=CLOUD_NAME,
                  api_key=API_KEY,
                  api_secret=API_SECRET)

GRAPHENE = {
    'SCHEMA': 'app.schema.schema',
    'MIDDLEWARE': [
        'graphql_jwt.middleware.JSONWebTokenMiddleware',
    ],
}

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
Пример #53
0
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Africa/Nairobi'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

cloudinary.config(cloud_name="dvwhabrxu",
                  api_key="865355552273268",
                  api_secret="DlJC_ZnUWOqgnFeI0FJTlWBuAx4")

# Configure Django App for Heroku.
django_heroku.settings(locals())
Пример #54
0
USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

cloudinary.config(cloud_name="awwards",
                  api_key="765749693498919",
                  api_secret="18UpmsJOybt23x4GbyT5-xUwWh8")

CRISPY_TEMPLATE_PACK = 'bootstrap4'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = '/'

# Configure Django App for Heroku.
django_heroku.settings(locals())
Пример #55
0
        'NAME':
        'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME':
        'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Africa/Nairobi'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

cloudinary.config(cloud_name="dapwcit3i",
                  api_key="917726294659896",
                  api_secret="PeLRKhRoA2E-r-5ykRTpuEBNcH4")
Пример #56
0
    'instaApp',
    'bootstrap4',
    'tinymce',
    'vote',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'cloudinary',
]

cloudinary.config(
    cloud_name='dloburkp7',
    api_key='743211362166119',
    api_secret='XYyewjb2QVfl9rUerT8UNTHsAf4',
)
DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage'

MIDDLEWARE = [
    # Simplified static file serving.
    # https://warehouse.python.org/project/whitenoise/
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
Пример #57
0
# Email configurations remember to install python-decouple
EMAIL_USE_TLS = config('EMAIL_USE_TLS')
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_PORT = config('EMAIL_PORT')
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

cloudinary.config(cloud_name="dec8li4lj",
                  api_key="137358617789222",
                  api_secret="-ZrBTOGfZcirrxMN1oJXw1jJ2cg")

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'knox.auth.TokenAuthentication',
    )
}

django_heroku.settings(locals())
Пример #58
0
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'clone.apps.CloneConfig',
    'bootstrap4',
    'bootstrap3',
    'cloudinary',
    'crispy_forms',
]

cloudinary.config(
    cloud_name=config('CLOUD_NAME'),
    api_key=config('API_KEY'),
    api_secret=config('API_SECRET'),
    cloudinary_url=config('CLOUDINARY_URL'),
)

MIDDLEWARE = [
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
]

ROOT_URLCONF = 'instagram.urls'
Пример #59
0
class ApiTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cloudinary.reset_config()
        if not cloudinary.config().api_secret:
            return
        print("Running tests for cloud: {}".format(cloudinary.config().cloud_name))
        for id in [API_TEST_ID, API_TEST_ID2]:
            uploader.upload(TEST_IMAGE,
                            public_id=id, tags=[API_TEST_TAG, ],
                            context="key=value", eager=[API_TEST_TRANS_SCALE100],
                            overwrite=True)

    @classmethod
    def tearDownClass(cls):
        cleanup_test_resources([([API_TEST_ID, API_TEST_ID2, API_TEST_ID3, API_TEST_ID4, API_TEST_ID5],)])

        cleanup_test_transformation([
            ([API_TEST_TRANS, API_TEST_TRANS2, API_TEST_TRANS3, API_TEST_TRANS_SCALE100_STR],),
        ])

        cleanup_test_resources_by_tag([
            (UNIQUE_API_TAG,),
            (UNIQUE_API_TAG, {'resource_type': 'raw'}),
        ])

        with ignore_exception(suppress_traceback_classes=(api.NotFound,)):
            api.delete_upload_mapping(MAPPING_TEST_ID)

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test01_resource_types(self):
        """ should allow listing resource_types """
        self.assertIn("image", api.resource_types()["resource_types"])

    test01_resource_types.tags = ['safe']

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test02_resources(self, mocker):
        """ should allow listing resources """
        mocker.return_value = MOCK_RESPONSE
        api.resources()
        args, kargs = mocker.call_args
        self.assertTrue(get_uri(args).endswith('/resources/image'))

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test03_resources_cursor(self):
        """ should allow listing resources with cursor """
        result = api.resources(max_results=1)
        self.assertNotEqual(result["resources"], None)
        self.assertEqual(len(result["resources"]), 1)
        self.assertNotEqual(result["next_cursor"], None)

        result2 = api.resources(max_results=1, next_cursor=result["next_cursor"])
        self.assertNotEqual(result2["resources"], None)
        self.assertEqual(len(result2["resources"]), 1)
        self.assertNotEqual(result2["resources"][0]["public_id"], result["resources"][0]["public_id"])

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test04_resources_types(self, mocker):
        """ should allow listing resources by type """
        mocker.return_value = MOCK_RESPONSE
        api.resources(type="upload", context=True, tags=True)
        args, kargs = mocker.call_args
        self.assertTrue(get_uri(args).endswith('/resources/image/upload'))
        self.assertTrue(get_params(args)['context'])
        self.assertTrue(get_params(args)['tags'])

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test05_resources_prefix(self, mocker):
        """ should allow listing resources by prefix """
        mocker.return_value = MOCK_RESPONSE
        api.resources(prefix=API_TEST_PREFIX, context=True, tags=True, type="upload")
        args, kargs = mocker.call_args
        self.assertTrue(get_uri(args).endswith('/resources/image/upload'))
        self.assertEqual(get_params(args)['prefix'], API_TEST_PREFIX)
        self.assertTrue(get_params(args)['context'])
        self.assertTrue(get_params(args)['tags'])

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test06_resources_tag(self, mocker):
        """ should allow listing resources by tag """
        mocker.return_value = MOCK_RESPONSE
        api.resources_by_tag(API_TEST_TAG, context=True, tags=True)
        args, kargs = mocker.call_args
        self.assertTrue(get_uri(args).endswith('/resources/image/tags/{}'.format(API_TEST_TAG)))
        self.assertTrue(get_params(args)['context'])
        self.assertTrue(get_params(args)['tags'])

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test06a_resources_by_ids(self, mocker):
        """ should allow listing resources by public ids """
        mocker.return_value = MOCK_RESPONSE
        api.resources_by_ids([API_TEST_ID, API_TEST_ID2], context=True, tags=True)
        args, kargs = mocker.call_args
        self.assertTrue(get_uri(args).endswith('/resources/image/upload'), get_uri(args))
        self.assertIn(API_TEST_ID, get_list_param(mocker, 'public_ids'))
        self.assertIn(API_TEST_ID2, get_list_param(mocker, 'public_ids'))
        self.assertEqual(get_param(mocker, 'context'), True)
        self.assertEqual(get_param(mocker, 'tags'), True)

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test06b_resources_direction(self, mocker):
        """ should allow listing resources in both directions """
        mocker.return_value = MOCK_RESPONSE
        api.resources_by_tag(API_TEST_TAG, direction="asc", type="upload")
        args, kargs = mocker.call_args
        self.assertTrue(get_uri(args).endswith('/resources/image/tags/{}'.format(API_TEST_TAG)))
        self.assertEqual(get_params(args)['direction'], 'asc')
        api.resources_by_tag(API_TEST_TAG, direction="desc", type="upload")
        args, kargs = mocker.call_args
        self.assertTrue(get_uri(args).endswith('/resources/image/tags/{}'.format(API_TEST_TAG)))
        self.assertEqual(get_params(args)['direction'], 'desc')

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test07_resource_metadata(self):
        """ should allow get resource metadata """
        resource = api.resource(API_TEST_ID)
        self.assertNotEqual(resource, None)
        self.assertEqual(resource["public_id"], API_TEST_ID)
        self.assertEqual(resource["bytes"], 3381)
        self.assertEqual(len(resource["derived"]), 1, "{} should have one derived resource.".format(API_TEST_ID))

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test07a_resource_quality_analysis(self):
        """ should allow getting resource quality analysis """
        resource = api.resource(API_TEST_ID, quality_analysis=True)
        self.assertNotEqual(resource, None)
        self.assertEqual(resource["public_id"], API_TEST_ID)
        self.assertIn("quality_analysis", resource)
        self.assertIn("focus", resource["quality_analysis"])
        self.assertIsInstance(resource["quality_analysis"]["focus"], float)

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test08_delete_derived(self, mocker):
        """ should allow deleting derived resource """
        mocker.return_value = MOCK_RESPONSE
        api.delete_derived_resources([API_TEST_ID])
        args, kargs = mocker.call_args
        self.assertTrue(get_uri(args).endswith('/derived_resources'))
        self.assertIn(API_TEST_ID, get_list_param(mocker, 'derived_resource_ids'))

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test08a_delete_derived_by_transformation(self, mocker):
        """ should allow deleting derived resource by transformations """
        public_resource_id = 'public_resource_id'
        public_resource_id2 = 'public_resource_id2'
        transformation = {"crop": "scale", "width": 100}
        transformation2 = {"crop": "scale", "width": 200}

        mocker.return_value = MOCK_RESPONSE
        api.delete_derived_by_transformation(public_resource_id, transformation)
        method, url, params = mocker.call_args[0][0:3]
        self.assertEqual('DELETE', method)
        self.assertTrue(url.endswith('/resources/image/upload'))
        self.assertIn(public_resource_id, get_list_param(mocker, 'public_ids'))
        self.assertEqual(get_param(mocker, 'transformations'), utils.build_eager([transformation]))
        self.assertTrue(get_param(mocker, 'keep_original'))

        mocker.return_value = MOCK_RESPONSE
        api.delete_derived_by_transformation(
            [public_resource_id, public_resource_id2], [transformation, transformation2],
            resource_type='raw', type='fetch', invalidate=True, foo='bar')
        method, url, params = mocker.call_args[0][0:3]
        self.assertEqual('DELETE', method)
        self.assertTrue(url.endswith('/resources/raw/fetch'))
        self.assertIn(public_resource_id, get_list_param(mocker, 'public_ids'))
        self.assertIn(public_resource_id2, get_list_param(mocker, 'public_ids'))
        self.assertEqual(get_param(mocker, 'transformations'), utils.build_eager([transformation, transformation2]))
        self.assertTrue(get_param(mocker, 'keep_original'))
        self.assertTrue(get_param(mocker, 'invalidate'))

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test09_delete_resources(self, mocker):
        """ should allow deleting resources """
        mocker.return_value = MOCK_RESPONSE
        api.delete_resources([API_TEST_ID, API_TEST_ID2])
        args, kargs = mocker.call_args
        self.assertEqual(args[0], 'DELETE')
        self.assertTrue(get_uri(args).endswith('/resources/image/upload'))
        param = get_list_param(mocker, 'public_ids')
        self.assertIn(API_TEST_ID, param)
        self.assertIn(API_TEST_ID2, param)

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test09a_delete_resources_by_prefix(self, mocker):
        """ should allow deleting resources by prefix """
        mocker.return_value = MOCK_RESPONSE
        api.delete_resources_by_prefix("api_test")
        args, kargs = mocker.call_args
        self.assertEqual(args[0], 'DELETE')
        self.assertTrue(get_uri(args).endswith('/resources/image/upload'))
        self.assertEqual(get_params(args)['prefix'], "api_test")

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test09b_delete_resources_by_tag(self, mocker):
        """ should allow deleting resources by tags """
        mocker.return_value = MOCK_RESPONSE
        api.delete_resources_by_tag("api_test_tag_for_delete")
        args, kargs = mocker.call_args
        self.assertEqual(args[0], 'DELETE')
        self.assertTrue(get_uri(args).endswith('/resources/image/tags/api_test_tag_for_delete'))

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test09c_delete_resources_by_transformations(self, mocker):
        """ should allow deleting resources by transformations """
        mocker.return_value = MOCK_RESPONSE

        api.delete_resources(['api_test', 'api_test2'], transformations=['c_crop,w_100'])
        self.assertEqual(get_method(mocker), 'DELETE')
        self.assertEqual(get_param(mocker, 'transformations'), 'c_crop,w_100')

        api.delete_all_resources(transformations=['c_crop,w_100', {"crop": "scale", "width": 107}])
        self.assertEqual(get_method(mocker), 'DELETE')
        self.assertEqual(get_param(mocker, 'transformations'), 'c_crop,w_100|c_scale,w_107')

        api.delete_resources_by_prefix("api_test_by", transformations='c_crop,w_100')
        self.assertEqual(get_method(mocker), 'DELETE')
        self.assertEqual(get_param(mocker, 'transformations'), 'c_crop,w_100')

        api.delete_resources_by_tag("api_test_tag", transformations=['c_crop,w_100'])
        self.assertEqual(get_method(mocker), 'DELETE')
        self.assertEqual(get_param(mocker, 'transformations'), 'c_crop,w_100')

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test09_delete_resources_tuple(self, mocker):
        """ should allow deleting resources """
        mocker.return_value = MOCK_RESPONSE
        api.delete_resources((API_TEST_ID, API_TEST_ID2,))
        args, kargs = mocker.call_args
        self.assertEqual(args[0], 'DELETE')
        self.assertTrue(get_uri(args).endswith('/resources/image/upload'))
        param = get_list_param(mocker, 'public_ids')
        self.assertIn(API_TEST_ID, param)
        self.assertIn(API_TEST_ID2, param)

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test10_tags(self, mocker):
        """ should allow listing tags """
        mocker.return_value = MOCK_RESPONSE
        api.tags()
        args, kargs = mocker.call_args
        self.assertTrue(get_uri(args).endswith('/tags/image'))

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test11_tags_prefix(self, mocker):
        """ should allow listing tag by prefix """
        mocker.return_value = MOCK_RESPONSE
        api.tags(prefix=API_TEST_PREFIX)
        args, kargs = mocker.call_args
        self.assertTrue(get_uri(args).endswith('/tags/image'))
        self.assertEqual(get_params(args)['prefix'], API_TEST_PREFIX)

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test12_transformations(self):
        """ should allow listing transformations """
        transformations = api.transformations()["transformations"]
        self.assertLess(0, len(transformations))
        transformation = transformations[0]
        self.assertIsNotNone(transformation)
        self.assertIn("used", transformation)

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test12a_transformations_cursor(self, mocker):
        """ should allow listing transformations with cursor """
        mocker.return_value = MOCK_RESPONSE
        api.transformation(API_TEST_TRANS_SCALE100, next_cursor='2412515', max_results=10)
        params = mocker.call_args[0][2]
        self.assertEqual(params['next_cursor'], '2412515')
        self.assertEqual(params['max_results'], 10)

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test_transformations_list_named(self, mocker):
        """ should allow listing only named transformations"""
        mocker.return_value = MOCK_RESPONSE
        api.transformations(named=True)
        params = mocker.call_args[0][2]
        self.assertEqual(params['named'], True)

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test13_transformation_metadata(self):
        """ should allow getting transformation metadata """
        transformation = api.transformation(API_TEST_TRANS_SCALE100_STR)
        self.assertNotEqual(transformation, None)
        self.assertEqual(transformation["info"], [API_TEST_TRANS_SCALE100])
        transformation = api.transformation(API_TEST_TRANS_SCALE100)
        self.assertNotEqual(transformation, None)
        self.assertEqual(transformation["info"], [API_TEST_TRANS_SCALE100])

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test14_transformation_update(self, mocker):
        """ should allow updating transformation allowed_for_strict """
        mocker.return_value = MOCK_RESPONSE
        api.update_transformation(API_TEST_TRANS_SCALE100_STR, allowed_for_strict=True)
        args, kargs = mocker.call_args
        self.assertEqual(args[0], 'PUT')
        self.assertTrue(get_uri(args).endswith('/transformations'))
        self.assertTrue(get_params(args)['allowed_for_strict'])
        self.assertEqual(API_TEST_TRANS_SCALE100_STR, get_params(args)['transformation'])

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test15_transformation_create(self, mocker):
        """ should allow creating named transformation """
        mocker.return_value = MOCK_RESPONSE
        api.create_transformation(API_TEST_TRANS, {"crop": "scale", "width": 102})
        args, kargs = mocker.call_args
        self.assertEqual(args[0], 'POST')
        self.assertTrue(get_uri(args).endswith('/transformations'), get_uri(args))
        self.assertEqual(get_params(args)['transformation'], 'c_scale,w_102')
        self.assertEqual(API_TEST_TRANS, get_params(args)['name'])

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test15a_transformation_unsafe_update(self):
        """ should allow unsafe update of named transformation """
        api.create_transformation(API_TEST_TRANS3, {"crop": "scale", "width": 102})
        api.update_transformation(API_TEST_TRANS3, unsafe_update={"crop": "scale", "width": 103})
        transformation = api.transformation(API_TEST_TRANS3)
        self.assertNotEqual(transformation, None)
        self.assertEqual(transformation["info"], [{"crop": "scale", "width": 103}])
        self.assertEqual(transformation["used"], False)

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test15b_transformation_create_unnamed_with_format(self, mocker):
        """ should allow creating unnamed transformation with extension"""
        mocker.return_value = MOCK_RESPONSE

        with_extension = dict(API_TEST_TRANS_SCALE100)
        with_extension.update(format="jpg")

        with_extension_str = API_TEST_TRANS_SCALE100_STR + "/jpg"

        api.create_transformation(with_extension_str, with_extension)

        args, kargs = mocker.call_args

        self.assertEqual(args[0], 'POST')
        self.assertTrue(get_uri(args).endswith('/transformations'), get_uri(args))
        self.assertEqual(with_extension_str, get_params(args)['transformation'])
        self.assertEqual(with_extension_str, get_params(args)['name'])

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test15c_transformation_create_unnamed_with_empty_format(self, mocker):
        """ should allow creating unnamed transformation with empty extension"""
        mocker.return_value = MOCK_RESPONSE

        with_extension = dict(API_TEST_TRANS_SCALE100)
        with_extension.update(format="")

        with_extension_str = API_TEST_TRANS_SCALE100_STR + "/"

        api.create_transformation(with_extension_str, with_extension)

        args, kargs = mocker.call_args

        self.assertEqual(args[0], 'POST')
        self.assertTrue(get_uri(args).endswith('/transformations'), get_uri(args))
        self.assertEqual(with_extension_str, get_params(args)['transformation'])
        self.assertEqual(with_extension_str, get_params(args)['name'])

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test16_transformation_delete(self):
        """ should allow deleting named transformation """
        api.create_transformation(API_TEST_TRANS2, {"crop": "scale", "width": 103})
        api.transformation(API_TEST_TRANS2)
        api.delete_transformation(API_TEST_TRANS2)
        self.assertRaises(api.NotFound, api.transformation, API_TEST_TRANS2)

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test17_transformation_implicit(self, mocker):
        """ should allow deleting implicit transformation """
        mocker.return_value = MOCK_RESPONSE
        api.delete_transformation(API_TEST_TRANS_SCALE100)
        args, kargs = mocker.call_args
        self.assertEqual(args[0], 'DELETE')
        self.assertTrue(get_uri(args).endswith('/transformations'))
        self.assertEqual(API_TEST_TRANS_SCALE100_STR, get_params(args)['transformation'])

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test18_usage(self):
        """ should support usage API """
        self.assertIn("last_updated", api.usage())

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    @unittest.skip("Skip delete all derived resources by default")
    def test19_delete_derived(self):
        """ should allow deleting all resource """
        uploader.upload(TEST_IMAGE, public_id=API_TEST_ID5, eager=[{"width": 101, "crop": "scale"}])
        resource = api.resource(API_TEST_ID5)
        self.assertNotEqual(resource, None)
        self.assertEqual(len(resource["derived"]), 1)
        api.delete_all_resources(keep_original=True)
        resource = api.resource(API_TEST_ID5)
        self.assertNotEqual(resource, None)
        self.assertEqual(len(resource["derived"]), 0)

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test20_manual_moderation(self):
        """ should support setting manual moderation status """
        resource = uploader.upload(TEST_IMAGE, moderation="manual", tags=[UNIQUE_API_TAG])

        self.assertEqual(resource["moderation"][0]["status"], "pending")
        self.assertEqual(resource["moderation"][0]["kind"], "manual")

        api_result = api.update(resource["public_id"], moderation_status="approved")
        self.assertEqual(api_result["moderation"][0]["status"], "approved")
        self.assertEqual(api_result["moderation"][0]["kind"], "manual")

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test21_notification_url(self, mocker):
        """ should support notification_url param """
        mocker.return_value = MOCK_RESPONSE
        api.update("api_test", notification_url="http://example.com")
        params = mocker.call_args[0][2]
        self.assertEqual(params['notification_url'], "http://example.com")

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test22_raw_conversion(self):
        """ should support requesting raw_convert """
        resource = uploader.upload(TEST_DOC, resource_type="raw", tags=[UNIQUE_API_TAG])
        with six.assertRaisesRegex(self, api.BadRequest, 'Illegal value'):
            api.update(resource["public_id"], raw_convert="illegal", resource_type="raw")

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test23_categorization(self):
        """ should support requesting categorization """
        with six.assertRaisesRegex(self, api.BadRequest, 'Illegal value'):
            api.update(API_TEST_ID, categorization="illegal")

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test24_detection(self):
        """ should support requesting detection """
        with six.assertRaisesRegex(self, api.BadRequest, 'Illegal value'):
            api.update(API_TEST_ID, detection="illegal")

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test26_1_ocr(self, mocker):
        """ should support requesting ocr """
        mocker.return_value = MOCK_RESPONSE
        api.update(API_TEST_ID, ocr='adv_ocr')
        args, kargs = mocker.call_args
        params = get_params(args)
        self.assertEqual(params['ocr'], 'adv_ocr')

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test26_2_quality_override(self, mocker):
        """ should support quality_override """
        mocker.return_value = MOCK_RESPONSE
        test_values = ['auto:advanced', 'auto:best', '80:420', 'none']
        for quality in test_values:
            api.update("api_test", quality_override=quality)
            params = mocker.call_args[0][2]
            self.assertEqual(params['quality_override'], quality)

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test27_start_at(self, mocker):
        """ should allow listing resources by start date """
        mocker.return_value = MOCK_RESPONSE
        start_at = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())
        api.resources(type="upload", start_at=start_at, direction="asc")
        args, kargs = mocker.call_args
        params = get_params(args)
        self.assertEqual(params['start_at'], start_at)

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test28_create_upload_preset(self, mocker):
        """ should allow creating upload_presets """
        mocker.return_value = MOCK_RESPONSE

        api.create_upload_preset(name=API_TEST_PRESET, folder="folder")

        args, kargs = mocker.call_args

        self.assertTrue(get_uri(args).endswith("/upload_presets"))
        self.assertEqual("POST", get_method(mocker))
        self.assertEqual(get_param(mocker, "name"), API_TEST_PRESET)
        self.assertEqual(get_param(mocker, "folder"), "folder")

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test28a_list_upload_presets(self, mocker):
        """ should allow listing upload_presets """
        mocker.return_value = MOCK_RESPONSE

        api.upload_presets()

        args, kargs = mocker.call_args

        self.assertTrue(get_uri(args).endswith("/upload_presets"))
        self.assertEqual("GET", get_method(mocker))

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test29_get_upload_presets(self, mocker):
        """ should allow getting a single upload_preset """
        mocker.return_value = MOCK_RESPONSE

        api.upload_preset(API_TEST_PRESET)

        args, kargs = mocker.call_args

        self.assertTrue(get_uri(args).endswith("/upload_presets/" + API_TEST_PRESET))
        self.assertEqual("GET", get_method(mocker))

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test30_delete_upload_presets(self, mocker):
        """ should allow deleting upload_presets """
        mocker.return_value = MOCK_RESPONSE
        api.delete_upload_preset(API_TEST_PRESET)
        args, kargs = mocker.call_args
        self.assertEqual(args[0], 'DELETE')
        self.assertTrue(get_uri(args).endswith('/upload_presets/{}'.format(API_TEST_PRESET)))

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test31_update_upload_presets(self, mocker):
        """ should allow getting a single upload_preset """
        mocker.return_value = MOCK_RESPONSE
        api.update_upload_preset(API_TEST_PRESET, colors=True, unsigned=True, disallow_public_id=True)
        args, kargs = mocker.call_args
        self.assertEqual(args[0], 'PUT')
        self.assertTrue(get_uri(args).endswith('/upload_presets/{}'.format(API_TEST_PRESET)))
        self.assertTrue(get_params(args)['colors'])
        self.assertTrue(get_params(args)['unsigned'])
        self.assertTrue(get_params(args)['disallow_public_id'])

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test32_background_removal(self):
        """ should support requesting background_removal """
        with six.assertRaisesRegex(self, api.BadRequest, 'Illegal value'):
            api.update(API_TEST_ID, background_removal="illegal")

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    @unittest.skip("For this test to work, 'Auto-create folders' should be enabled in the Upload Settings, " +
                   "and the account should be empty of folders. " +
                   "Comment out this line if you really want to test it.")
    def test_folder_listing(self):
        """ should support listing folders """
        uploader.upload(TEST_IMAGE, public_id="{}1/item".format(PREFIX), tags=[UNIQUE_API_TAG])
        uploader.upload(TEST_IMAGE, public_id="{}2/item".format(PREFIX), tags=[UNIQUE_API_TAG])
        uploader.upload(TEST_IMAGE, public_id="{}1/test_subfolder1/item".format(PREFIX), tags=[UNIQUE_API_TAG])
        uploader.upload(TEST_IMAGE, public_id="{}1/test_subfolder2/item".format(PREFIX), tags=[UNIQUE_API_TAG])
        result = api.root_folders()
        self.assertEqual(result["folders"][0]["name"], "{}1".format(PREFIX))
        self.assertEqual(result["folders"][1]["name"], "{}2".format(PREFIX))
        result = api.subfolders("{}1".format(PREFIX))
        self.assertEqual(result["folders"][0]["path"], "{}1/test_subfolder1".format(PREFIX))
        self.assertEqual(result["folders"][1]["path"], "{}1/test_subfolder2".format(PREFIX))
        with six.assertRaisesRegex(self, api.NotFound):
            api.subfolders(PREFIX)

    def test_CloudinaryImage_len(self):
        """Tests the __len__ function on CloudinaryImage"""
        metadata = {
            "public_id": "test_id",
            "format": "tst",
            "version": "1234",
            "signature": "5678",
        }
        my_cloudinary_image = cloudinary.CloudinaryImage(metadata=metadata)
        self.assertEqual(len(my_cloudinary_image), len(metadata["public_id"]))

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test_restore(self):
        """ should support restoring resources """
        uploader.upload(TEST_IMAGE, public_id=RESTORE_TEST_ID, backup=True, tags=[UNIQUE_API_TAG])
        resource = api.resource(RESTORE_TEST_ID)
        self.assertNotEqual(resource, None)
        self.assertEqual(resource["bytes"], 3381)
        api.delete_resources([RESTORE_TEST_ID])
        resource = api.resource(RESTORE_TEST_ID)
        self.assertNotEqual(resource, None)
        self.assertEqual(resource["bytes"], 0)
        self.assertIs(resource["placeholder"], True)
        response = api.restore([RESTORE_TEST_ID])
        info = response[RESTORE_TEST_ID]
        self.assertNotEqual(info, None)
        self.assertEqual(info["bytes"], 3381)
        resource = api.resource(RESTORE_TEST_ID)
        self.assertNotEqual(resource, None)
        self.assertEqual(resource["bytes"], 3381)

    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test_upload_mapping(self):

        api.create_upload_mapping(MAPPING_TEST_ID, template="http://cloudinary.com", tags=[UNIQUE_API_TAG])
        result = api.upload_mapping(MAPPING_TEST_ID)
        self.assertEqual(result["template"], "http://cloudinary.com")
        api.update_upload_mapping(MAPPING_TEST_ID, template="http://res.cloudinary.com")
        result = api.upload_mapping(MAPPING_TEST_ID)
        self.assertEqual(result["template"], "http://res.cloudinary.com")
        result = api.upload_mappings()
        self.assertIn({"folder": MAPPING_TEST_ID, "template": "http://res.cloudinary.com"},
                      result["mappings"])
        api.delete_upload_mapping(MAPPING_TEST_ID)
        result = api.upload_mappings()
        self.assertNotIn(MAPPING_TEST_ID, [mapping.get("folder") for mapping in result["mappings"]])

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test_publish_by_ids(self, mocker):
        mocker.return_value = MOCK_RESPONSE
        api.publish_by_ids(["pub1", "pub2"])
        self.assertTrue(get_uri(mocker.call_args[0]).endswith('/resources/image/publish_resources'))
        self.assertIn('pub1', get_list_param(mocker, 'public_ids'))
        self.assertIn('pub2', get_list_param(mocker, 'public_ids'))

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test_publish_by_prefix(self, mocker):
        mocker.return_value = MOCK_RESPONSE
        api.publish_by_prefix("pub_prefix")
        self.assertTrue(get_uri(mocker.call_args[0]).endswith('/resources/image/publish_resources'))
        self.assertEqual(get_param(mocker, 'prefix'), 'pub_prefix')

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test_publish_by_tag(self, mocker):
        mocker.return_value = MOCK_RESPONSE
        api.publish_by_tag("pub_tag")
        self.assertTrue(get_uri(mocker.call_args[0]).endswith('/resources/image/publish_resources'))
        self.assertEqual(get_param(mocker, 'tag'), "pub_tag")

    @patch('urllib3.request.RequestMethods.request')
    @unittest.skipUnless(cloudinary.config().api_secret, "requires api_key/api_secret")
    def test_update_access_control(self, mocker):
        """ should allow the user to define ACL in the update parameters """
        mocker.return_value = MOCK_RESPONSE

        acl = OrderedDict((("access_type", "anonymous"),
                           ("start", "2018-02-22 16:20:57 +0200"),
                           ("end", "2018-03-22 00:00 +0200")))
        exp_acl = '[{"access_type":"anonymous","start":"2018-02-22 16:20:57 +0200","end":"2018-03-22 00:00 +0200"}]'

        api.update(API_TEST_ID, access_control=acl)

        params = get_params(mocker.call_args[0])

        self.assertIn("access_control", params)
        self.assertEqual(exp_acl, params["access_control"])
Пример #60
0
    {
        'NAME':
        'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME':
        'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'pt-br'

TIME_ZONE = 'America/Sao_Paulo'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

cloudinary.config(cloud_name="leandrof",
                  api_key="111917512795497",
                  api_secret="NBBiveSQeZtISyPu8xR03T8K6XQ")