Example #1
1
    def _prepare_json_kwargs(self, dumps=False, loads=False):
        assert dumps or loads, "Please, supply ``dumps`` or ``loads`` " "keyword argument first."

        if dumps:
            args = (
                "skipkeys",
                "ensure_ascii",
                "check_circural",
                "allow_nan",
                "cls",
                "indent",
                "separators",
                "encoding",
                "default",
            )
        else:
            args = ("encoding", "cls", "object_hook", "parse_float", "parse_int", "parse_constant", "object_paris_hook")

        kwargs = {}

        for arg in args:
            cls_arg = "cls"

            if arg == "cls":
                cls_arg = "encoder_cls" if dumps else "decoder_cls"

            if not hasattr(self, arg) and not hasattr(self, cls_arg):
                continue

            value = getattr(self, cls_arg) if hasattr(self, cls_arg) else getattr(self, arg)
            kwargs.update({arg: value})

        return kwargs
Example #2
1
 def __call__(self):
     uid = self.request.get("Sample_uid", False)
     if not uid:
         return []
     uc = getToolByName(self.context, "uid_catalog")
     proxies = uc(UID=uid)
     if not proxies:
         return []
     sample = proxies[0].getObject()
     sample_schema = sample.Schema()
     sample_fields = dict([(f.getName(), f) for f in sample_schema.fields()])
     ar_schema = self.context.Schema()
     ar_fields = [
         f.getName() for f in ar_schema.fields() if f.widget.isVisible(self.context, "secondary") == "disabled"
     ]
     ret = []
     for fieldname in ar_fields:
         if fieldname in sample_fields:
             fieldvalue = sample_fields[fieldname].getAccessor(sample)()
             if fieldvalue is None:
                 fieldvalue = ""
             if hasattr(fieldvalue, "Title"):
                 # Must store UID for referencefields.
                 ret.append([fieldname + "_uid", fieldvalue.UID()])
                 fieldvalue = fieldvalue.Title()
             if hasattr(fieldvalue, "year"):
                 fieldvalue = fieldvalue.strftime(self.date_format_short)
         else:
             fieldvalue = ""
         ret.append([fieldname, fieldvalue])
     return json.dumps(ret)
Example #3
1
    def post_validate(self):
        xmlText = []
        xmlChildren = []
        for child in self.children:
            if isinstance(child, xmlbase.XMLText):
                xmlText.append(child)
            else:
                xmlChildren.append(child)

        if len(xmlText) == 0 and hasattr(self, "n_to_v"):
            pass

        elif not hasattr(self, "n_to_v"):
            self.n_to_v = dict(
                [(i, x) for i, x in enumerate("".join([str(x) for x in xmlText]).split(self.attrib["delimiter"]))]
            )
            self.children = xmlChildren

        if "n" in self.attrib:
            if self.attrib["n"] != len(self.n_to_v):
                raise XMLValidationError(
                    'LookupTable["n"] (%d) should be equal to len(LookupTable.n_to_v) (%d)'
                    % (self.attrib["n"], len(self.n_to_v))
                )
        else:
            self.attrib["n"] = len(self.n_to_v)
    def get_attribute(self, instance):
        # Can't have any relationships if not created
        if hasattr(instance, "pk") and instance.pk is None:
            return []

        relationship = get_attribute(instance, self.source_attrs)
        return relationship.all() if (hasattr(relationship, "all")) else relationship
Example #5
1
    def scaffold_list_columns(self):
        """
            Return a list of columns from the model.
        """
        columns = []

        for p in self._get_model_iterator():
            # Verify type
            if hasattr(p, "direction"):
                if self.column_display_all_relations or p.direction.name == "MANYTOONE":
                    columns.append(p.key)
            elif hasattr(p, "columns"):
                column_inherited_primary_key = False
                if len(p.columns) != 1:
                    if is_inherited_primary_key(p):
                        column = get_column_for_current_model(p)
                    else:
                        raise TypeError("Can not convert multiple-column properties (%s.%s)" % (self.model, p.key))
                else:
                    # Grab column
                    column = p.columns[0]

                # An inherited primary key has a foreign key as well
                if column.foreign_keys and not is_inherited_primary_key(p):
                    continue

                if not self.column_display_pk and column.primary_key:
                    continue

                columns.append(p.key)

        return columns
    def process_request(self, request):
        __traceback_hide__ = True
        if self.show_toolbar(request):

            urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
            if isinstance(urlconf, basestring):
                urlconf = import_module(getattr(request, "urlconf", settings.ROOT_URLCONF))

            if urlconf not in self._urlconfs:
                new_urlconf = imp.new_module("urlconf")
                new_urlconf.urlpatterns = debug_toolbar.urls.urlpatterns + patterns("", ("", include(urlconf)))

                if hasattr(urlconf, "handler404"):
                    new_urlconf.handler404 = urlconf.handler404
                if hasattr(urlconf, "handler500"):
                    new_urlconf.handler500 = urlconf.handler500

                self._urlconfs[urlconf] = new_urlconf

            request.urlconf = self._urlconfs[urlconf]

            toolbar = DebugToolbar(request)
            for panel in toolbar.panels:
                panel.process_request(request)
            self.__class__.debug_toolbars[thread.get_ident()] = toolbar
Example #7
1
    def test_smart_strings(self):
        """Lxml smart strings return values"""

        class SmartStringsSelector(Selector):
            _lxml_smart_strings = True

        body = """<body>
                    <div class='one'>
                      <ul>
                        <li>one</li><li>two</li>
                      </ul>
                    </div>
                    <div class='two'>
                      <ul>
                        <li>four</li><li>five</li><li>six</li>
                      </ul>
                    </div>
                  </body>"""

        response = HtmlResponse(url="http://example.com", body=body)

        # .getparent() is available for text nodes and attributes
        # only when smart_strings are on
        x = self.sscls(response)
        li_text = x.xpath("//li/text()")
        self.assertFalse(any(map(lambda e: hasattr(e._root, "getparent"), li_text)))
        div_class = x.xpath("//div/@class")
        self.assertFalse(any(map(lambda e: hasattr(e._root, "getparent"), div_class)))

        x = SmartStringsSelector(response)
        li_text = x.xpath("//li/text()")
        self.assertTrue(all(map(lambda e: hasattr(e._root, "getparent"), li_text)))
        div_class = x.xpath("//div/@class")
        self.assertTrue(all(map(lambda e: hasattr(e._root, "getparent"), div_class)))
Example #8
0
def get_file(fileorpath):
    """Get a file-like object, whether given a FileUpload object or a path."""
    if hasattr(fileorpath, "path"):  # FileUpload
        return storage.open(fileorpath.path)
    if hasattr(fileorpath, "name"):
        return fileorpath
    return storage.open(fileorpath)
Example #9
0
    def templates(self, template=None, **kwargs):
        scene = kwargs.get("handler", user.ui.scene)
        actors = scene.cast.actors
        items = scene.data.sprites
        # Cast
        if actors:
            tgt = kwargs.get("target", self.target)
            if not tgt in actors:
                tgt = actors[0]
            castinf = [i for i in tgt.dft if hasattr(tgt, i)]
            castopt = ()
            if self.info in castinf:
                inf = getattr(tgt, self.info)
                keyget = None
                if hasattr(inf, "keys") and inf:
                    try:
                        if inf.keys()[0].type == "actor":
                            keyget = ("key", "arrowsel", {"values": actors})
                        elif inf.keys()[0].type == "node":
                            keyget = ("key", "extsel", {"val": items[0], "values": items, "selsource": scene})
                    except:
                        pass
                if keyget is None and hasattr(inf, "__iter__"):
                    keyget = ("key", "input", {"legend": "Key"})
                if keyget:
                    castopt += (keyget,)
            templatelist = self.templatelist(scene, items, actors, (castinf, castopt))
        else:
            templatelist = self.templatelist(scene, items)

        if template is None:
            return templatelist
        else:
            return templatelist[template]
Example #10
0
 def getvalue(x):
     if hasattr(x, "file") and hasattr(x, "value"):
         return x.value
     elif hasattr(x, "value"):
         return unicodify(x.value)
     else:
         return unicodify(x)
Example #11
0
def set_target(obj_id_src, obj_id_target):
    obj = get_object(obj_id_src)
    target = get_object(obj_id_target)
    for obj in physics.body_update_list:
        if hasattr(obj, "obj_id"):
            if obj.obj_id == obj_id_src and hasattr(obj, "target"):
                obj.target = target
def model_post_save(sender, **kwargs):
    """
    A signal handler to run any model presave activities and trigger the built-in
    pre save signals
    1. Detect if the model has been changed and appy these changes to the db
    2. Trigger the pre creation signal
    3. Trigger the pre update signal
    """

    MetaModel = sender
    meta_model = kwargs["instance"]
    update = hasattr(meta_model, "_update")
    creation = hasattr(meta_model, "_creation")

    if update or creation:
        DynamicModel = meta_model.get_model()
        # Create a new table if it's missing
        utils.create_db_table(DynamicModel)

    if creation:
        post_model_creation.send(sender=MetaModel, new_model=DynamicModel)
        del meta_model._creation

    if update:
        post_model_update.send(sender=MetaModel, old_model=meta_model._update, new_model=DynamicModel)
        del meta_model._update
def get_bitno_lin_comb(bloom_filter, key):
    """Apply num_probes_k hash functions to key.  Generate the array index and bitmask corresponding to each result"""

    # This one assumes key is either bytes or str (or other list of integers)

    # I'd love to check for long too, but that doesn't exist in 3.2, and 2.5 doesn't have the numbers.Integral base type
    if hasattr(key, "__divmod__"):
        int_list = []
        temp = key
        while temp:
            quotient, remainder = divmod(temp, 256)
            int_list.append(remainder)
            temp = quotient
    elif hasattr(key[0], "__divmod__"):
        int_list = key
    elif isinstance(key[0], str):
        int_list = [ord(char) for char in key]
    else:
        raise TypeError("Sorry, I do not know how to hash this type")

    hash_value1 = hash1(int_list)
    hash_value2 = hash2(int_list)

    # We're using linear combinations of hash_value1 and hash_value2 to obtain num_probes_k hash functions
    for probeno in range(1, bloom_filter.num_probes_k + 1):
        bit_index = hash_value1 + probeno * hash_value2
        yield bit_index % bloom_filter.num_bits_m
Example #14
0
 def validate(self):
     try:
         if self.diagnoseId is None:
             return FAILURE
         diagnose = Diagnose.getDiagnoseById(self.diagnoseId)
         if diagnose is None:
             return FAILURE
         if diagnose.doctorId and hasattr(diagnose, "doctor") and diagnose.doctor and diagnose.doctor.userId:
             self.receiverId = diagnose.doctor.userId
         else:
             return FAILURE
         if diagnose.patientId and hasattr(diagnose, "patient") and diagnose.patient and diagnose.patient.userID:
             self.userId = diagnose.patient.userID
         else:
             return FAILURE
         # if self.title is None:
         #     return FAILURE
         if self.content is None or len(self.content) < 10:
             failure = ResultStatus(FAILURE.status, "输入的内容长度必须大于等于10")
             return failure
         if self.score is None or self.score == u"":
             return FAILURE
         else:
             self.score = string.atoi(self.score)
     except Exception, e:
         return FAILURE
Example #15
0
 def put(self, url, body="", headers={}):
     headers = copy.deepcopy(headers)
     if "content-length" not in headers:
         headers.update(
             {"content-length": (hasattr(body, "read") and hasattr(body, "len")) and body.len or str(len(body))}
         )
     return self.request("PUT", url, body, headers)
Example #16
0
def _register_model(admin, model):
    if not hasattr(admin, "revision_manager"):
        admin.revision_manager = default_revision_manager
    if not hasattr(admin, "reversion_format"):
        admin.reversion_format = "json"

    if not admin.revision_manager.is_registered(model):
        inline_fields = []
        for inline in getattr(admin, "inlines", []):
            inline_model = inline.model
            if getattr(inline, "generic_inline", False):
                ct_field = getattr(inline, "ct_field", "content_type")
                ct_fk_field = getattr(inline, "ct_fk_field", "object_id")
                for field in model._meta.many_to_many:
                    if (
                        isinstance(field, GenericRelation)
                        and field.rel.to == inline_model
                        and field.object_id_field_name == ct_fk_field
                        and field.content_type_field_name == ct_field
                    ):
                        inline_fields.append(field.name)
                _autoregister(admin, inline_model)
            else:
                fk_name = getattr(inline, "fk_name", None)
                if not fk_name:
                    for field in inline_model._meta.fields:
                        if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(
                            model, field.rel.to
                        ):
                            fk_name = field.name
                _autoregister(admin, inline_model, follow=[fk_name])
                if not inline_model._meta.get_field(fk_name).rel.is_hidden():
                    accessor = inline_model._meta.get_field(fk_name).related.get_accessor_name()
                    inline_fields.append(accessor)
        _autoregister(admin, model, inline_fields)
Example #17
0
    def __init__(self, param, cursor, strings_only=False):
        # With raw SQL queries, datetimes can reach this function
        # without being converted by DateTimeField.get_db_prep_value.
        if settings.USE_TZ and isinstance(param, datetime.datetime):
            if timezone.is_naive(param):
                warnings.warn(
                    "Oracle received a naive datetime (%s)" " while time zone support is active." % param,
                    RuntimeWarning,
                )
                default_timezone = timezone.get_default_timezone()
                param = timezone.make_aware(param, default_timezone)
            param = param.astimezone(timezone.utc).replace(tzinfo=None)

        # Oracle doesn't recognize True and False correctly in Python 3.
        # The conversion done below works both in 2 and 3.
        if param is True:
            param = "1"
        elif param is False:
            param = "0"
        if hasattr(param, "bind_parameter"):
            self.force_bytes = param.bind_parameter(cursor)
        else:
            self.force_bytes = convert_unicode(param, cursor.charset, strings_only)
        if hasattr(param, "input_size"):
            # If parameter has `input_size` attribute, use that.
            self.input_size = param.input_size
        elif isinstance(param, six.string_types) and len(param) > 4000:
            # Mark any string param greater than 4000 characters as a CLOB.
            self.input_size = Database.CLOB
        else:
            self.input_size = None
Example #18
0
    def test_localtime_timezone(self):

        # Get the localtime and examine it for the offset and zone.
        lt = time.localtime()
        self.assertTrue(hasattr(lt, "tm_gmtoff"))
        self.assertTrue(hasattr(lt, "tm_zone"))

        # See if the offset and zone are similar to the module
        # attributes.
        if lt.tm_gmtoff is None:
            self.assertTrue(not hasattr(time, "timezone"))
        else:
            self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
        if lt.tm_zone is None:
            self.assertTrue(not hasattr(time, "tzname"))
        else:
            self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])

        # Try and make UNIX times from the localtime and a 9-tuple
        # created from the localtime. Test to see that the times are
        # the same.
        t = time.mktime(lt)
        t9 = time.mktime(lt[:9])
        self.assertEqual(t, t9)

        # Make localtimes from the UNIX times and compare them to
        # the original localtime, thus making a round trip.
        new_lt = time.localtime(t)
        new_lt9 = time.localtime(t9)
        self.assertEqual(new_lt, lt)
        self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
        self.assertEqual(new_lt.tm_zone, lt.tm_zone)
        self.assertEqual(new_lt9, lt)
        self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
        self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
Example #19
0
 def check_server_disallowed(self):
     """
     Check if server domain name or IP is disallowed in settings.py.
     """
     hostname = self.netloc_parts[2].lower()
     if (hasattr(settings, 'DISALLOWED_DOMAIN_LIST') and
         settings.DISALLOWED_DOMAIN_LIST):
         for domain in settings.DISALLOWED_DOMAIN_LIST:
             if hostname == domain or hostname.endswith('.' + domain):
                 raise ValidationError(unicode(
                     _("Domain name %(domain)s is disallowed.") % locals()))
     try:
         ip = socket.gethostbyname(hostname)
     except socket.error:
         raise ValidationError(unicode(
             _("Could not resolve IP address for %(hostname)s.") %
             locals()))
     if (not hasattr(settings, 'DISALLOWED_SERVER_IP_LIST') or
         not settings.DISALLOWED_SERVER_IP_LIST):
         return
     server = long_ip(ip)
     # print 'server', server, dotted_ip(server), ip
     for disallowed in settings.DISALLOWED_SERVER_IP_LIST:
         disallowed = disallowed.strip()
         if disallowed == '' or disallowed.startswith('#'):
             continue
         mask = bit_mask(32)
         if '/' in disallowed:
             disallowed, bits = disallowed.split('/', 1)
             mask = slash_mask(int(bits))
         identifier = long_ip(disallowed) & mask
         masked = server & mask
         if masked == identifier:
             raise ValidationError(unicode(
                 _("Server IP address %(ip)s is disallowed.") % locals()))
Example #20
0
File: tabgroup.py Project: Reve/eve
 def OnDropData(self, dragObj, nodes):
     if hasattr(self, 'OnTabDropData'):
         if self.OnTabDropData(dragObj, nodes):
             self.BlinkOnDrop()
     elif isinstance(self.sr.panel, uicls.DragDropObject) and hasattr(self.sr.panel, 'OnDropData'):
         if self.sr.panel.OnDropData(dragObj, nodes):
             self.BlinkOnDrop()
Example #21
0
    def add_update_fields(self, values_seq):
        """
        Turn a sequence of (field, model, value) triples into an update query.
        Used by add_update_values() as well as the "fast" update path when
        saving models.
        """
        from django.db.models.base import Model

        for field, model, val in values_seq:
            # FIXME: Some sort of db_prep_* is probably more appropriate here.
            if field.rel and isinstance(val, Model):
                val = val.pk

            # Getting the placeholder for the field.
            if hasattr(field, "get_placeholder"):
                placeholder = field.get_placeholder(val)
            else:
                placeholder = "%s"

            if hasattr(val, "evaluate"):
                val = SQLEvaluator(val, self, allow_joins=False)
            if model:
                self.add_related_update(model, field.column, val, placeholder)
            else:
                self.values.append((field.column, val, placeholder))
Example #22
0
def build_suite(app_module):
    """
    Create a complete Django test suite for the provided application module.
    """
    suite = unittest.TestSuite()

    # Load unit and doctests in the models.py module. If module has
    # a suite() method, use it. Otherwise build the test suite ourselves.
    if hasattr(app_module, "suite"):
        suite.addTest(app_module.suite())
    else:
        suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(app_module))
        try:
            suite.addTest(doctest.DocTestSuite(app_module, checker=doctestOutputChecker, runner=DocTestRunner))
        except ValueError:
            # No doc tests in models.py
            pass

    # Check to see if a separate 'tests' module exists parallel to the
    # models module
    test_module = get_tests(app_module)
    if test_module:
        # Load unit and doctests in the tests.py module. If module has
        # a suite() method, use it. Otherwise build the test suite ourselves.
        if hasattr(test_module, "suite"):
            suite.addTest(test_module.suite())
        else:
            suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(test_module))
            try:
                suite.addTest(doctest.DocTestSuite(test_module, checker=doctestOutputChecker, runner=DocTestRunner))
            except ValueError:
                # No doc tests in tests.py
                pass
    return suite
Example #23
0
    def pre(self, emulator=None):
        """
        _pre_

        Pre execution checks

        """
        if emulator is not None:
            return emulator.emulatePre(self.step)
        logging.info("Pre-executing CMSSW step")
        if hasattr(self.step.application.configuration, "configCacheUrl"):
            # means we have a configuration & tweak in the sandbox
            psetFile = self.step.application.command.configuration
            psetTweak = self.step.application.command.psetTweak
            self.stepSpace.getFromSandbox(psetFile)

            if psetTweak:
                self.stepSpace.getFromSandbox(psetTweak)

        if hasattr(self.step, "pileup"):
            self.stepSpace.getFromSandbox("pileupconf.json")

        # add in ths scram env PSet manip script whatever happens
        self.step.runtime.scramPreScripts.append("SetupCMSSWPset")
        return None
    def sql_indexes_for_model(self, model, *args, **kwargs):
        """Creates ``model`` indexes.

        :param model: The model containing the fields inside group.
        :param \*args: Extra args not used in this engine.
        :param \*\*kwargs: Extra kwargs not used in this engine.
        """
        if not model._meta.managed or model._meta.proxy:
            return []
        fields = [f for f in model._meta.local_fields if f.db_index]
        if not fields and not hasattr(model._meta, "index_together") and not hasattr(model._meta, "unique_together"):
            return []
        print "Installing index for %s.%s model" % (model._meta.app_label, model._meta.object_name)
        for field in fields:
            self.sql_indexes_for_field(model, field)
        for group in getattr(model._meta, "index_together", []):
            self.index_fields_group(model, group)

        # unique_together support
        unique_together = getattr(model._meta, "unique_together", [])
        # Django should do this, I just wanted to be REALLY sure.
        if len(unique_together) > 0 and isinstance(unique_together[0], basestring):
            unique_together = (unique_together,)
        for fields in unique_together:
            group = {"fields": fields, "unique": True}
            self.index_fields_group(model, group)
        return []
Example #25
0
File: sql.py Project: Will-So/blaze
def lower_column(col):
    """ Return column from lower level tables if possible

    >>> metadata = sa.MetaData()

    >>> s = sa.Table('accounts', metadata,
    ...              sa.Column('name', sa.String),
    ...              sa.Column('amount', sa.Integer),
    ...              sa.Column('id', sa.Integer, primary_key=True),
    ...              )

    >>> s2 = select([s])
    >>> s2.c.amount is s.c.amount
    False

    >>> lower_column(s2.c.amount) is s.c.amount
    True

    >>> lower_column(s2.c.amount)
    Column('amount', Integer(), table=<accounts>)
    """

    old = None
    while col is not None and col is not old:
        old = col
        if not hasattr(col, "table") or not hasattr(col.table, "froms"):
            return col
        for f in col.table.froms:
            if f.corresponding_column(col) is not None:
                col = f.corresponding_column(col)

    return old
    def sql_create_model(self, model, *args, **kwargs):
        """Creates the collection for model. Mostly used for capped collections.

        :param model: The model that should be created.
        :param \*args: Extra args not used in this engine.
        :param \*\*kwargs: Extra kwargs not used in this engine.

        Example

            >>> class TestFieldModel(Task):
            ...
            ...     class MongoMeta:
            ...         capped = True
            ...         collection_max = 100000
            ...         collection_size = 10
        """
        opts = model._meta
        kwargs = {}
        kwargs["capped"] = getattr(opts, "capped", False)
        if hasattr(opts, "collection_max") and opts.collection_max:
            kwargs["max"] = opts.collection_max
        if hasattr(opts, "collection_size") and opts.collection_size:
            kwargs["size"] = opts.collection_size
        col = Collection(self.connection.db_connection, model._meta.db_table, **kwargs)
        return [], {}
Example #27
0
    def __get__(self, instance, owner):
        if not instance:
            return self

        if self.name in instance.__dict__:
            # This condition has already been processed, so don't try getting it again
            return None

        # Customizes the field for this particular instance
        # Use field instead of self for the rest of the method
        with self.for_instance(instance):

            a = self.a
            if hasattr(a, "resolve"):
                a = a.resolve(instance)

            b = self.b
            if hasattr(b, "resolve"):
                b = b.resolve(instance)

            if self.compare(a, b):
                # The comparison succeeded, so the fields should be processed

                raw_bytes = b""
                for f in self.fields:
                    with f.for_instance(instance):
                        bytes, value = f.read_value(instance)
                        raw_bytes += bytes
                        instance.__dict__[f.name] = value
                        f.after_decode.apply(instance, value)
                instance._raw_values[self.name] = raw_bytes

        return None
Example #28
0
    def adjust_for_viewer(self, X):
        """
        .. todo::

            WRITEME
        """
        # assumes no preprocessing. need to make preprocessors mark the new
        # ranges
        rval = X.copy()

        # patch old pkl files
        if not hasattr(self, "center"):
            self.center = False
        if not hasattr(self, "gcn"):
            self.gcn = False

        if self.gcn is not None:
            rval = X.copy()
            for i in xrange(rval.shape[0]):
                rval[i, :] /= np.abs(rval[i, :]).max()
            return rval

        if not self.center:
            rval -= 127.5

        rval /= 127.5
        rval = np.clip(rval, -1.0, 1.0)

        return rval
Example #29
0
def get_gravatar_url(request, user, size=None):
    from django.conf import settings

    if user.is_anonymous() or not user.email:
        return ""

    email = user.email.strip().lower()
    email_hash = md5(email).hexdigest()

    if request.is_secure():
        url_base = "https://secure.gravatar.com"
    else:
        url_base = "http://www.gravatar.com"

    url = "%s/avatar/%s" % (url_base, email_hash)
    params = []

    if not size and hasattr(settings, "GRAVATAR_SIZE"):
        size = settings.GRAVATAR_SIZE

    if size:
        params.append("s=%s" % size)

    if hasattr(settings, "GRAVATAR_RATING"):
        params.append("r=%s" % settings.GRAVATAR_RATING)

    if hasattr(settings, "GRAVATAR_DEFAULT"):
        params.append("d=%s" % settings.GRAVATAR_DEFAULT)

    if params:
        url += "?" + "&".join(params)

    return url
Example #30
0
        def proxy(**forgettable_view_args):
            # Always use the global request object's view_args, because they
            # can be modified by intervening function before an endpoint or
            # wrapper gets called. This matches Flask's behavior.
            del forgettable_view_args

            if hasattr(i, "before_request"):
                response = i.before_request(name, **request.view_args)
                if response is not None:
                    return response

            before_view_name = "before_" + name
            if hasattr(i, before_view_name):
                before_view = getattr(i, before_view_name)
                response = before_view(**request.view_args)
                if response is not None:
                    return response

            response = view(**request.view_args)
            if not isinstance(response, Response):
                response = make_response(response)

            after_view_name = "after_" + name
            if hasattr(i, after_view_name):
                after_view = getattr(i, after_view_name)
                response = after_view(response)

            if hasattr(i, "after_request"):
                response = i.after_request(name, response)

            return response