Python bson 模块,Binary() 实例源码

我们从Python开源项目中,提取了以下5个代码示例,用于说明如何使用bson.Binary()

项目:maas    作者:maas    | 项目源码 | 文件源码
def details(self, request, system_id):
        """Obtain various system details.

        For example, LLDP and ``lshw`` XML dumps.

        Returns a ``{detail_type: xml, ...}`` map, where
        ``detail_type`` is something like "lldp" or "lshw".

        Note that this is returned as BSON and not JSON. This is for
        efficiency, but mainly because JSON can't do binary content
        without applying additional encoding like base-64.

        Returns 404 if the node is not found.
        """
        node = get_object_or_404(self.model, system_id=system_id)
        probe_details = get_single_probed_details(node)
        probe_details_report = {
            name: None if data is None else bson.Binary(data)
            for name, data in probe_details.items()
        }
        return HttpResponse(
            bson.BSON.encode(probe_details_report),
            # Not sure what media type to use here.
            content_type='application/bson')
项目:flask-zhenai-mongo-echarts    作者:Fretice    | 项目源码 | 文件源码
def to_mongo(self, value):
        return Binary(value)
项目:flask-zhenai-mongo-echarts    作者:Fretice    | 项目源码 | 文件源码
def validate(self, value):
        if not isinstance(value, (six.binary_type, six.text_type, Binary)):
            self.error('BinaryField only accepts instances of '
                       '(%s, %s, Binary)' % (
                           six.binary_type.__name__, six.text_type.__name__))

        if self.max_bytes is not None and len(value) > self.max_bytes:
            self.error('Binary value is too long')
项目:meta    作者:Ejhfast    | 项目源码 | 文件源码
def bind(self,id,imports=[]):
        def bind_decorator(func):
            def func_wrapper(*args, **kwargs):
                t_overhead1 = time.clock()
                instrumented = False
                try:
                    t1 = time.clock()
                    v = func(*args, **kwargs)
                    t2 = time.clock()
                except Exception as e:
                    # record bad input
                    bad_input = {"args":Binary(dill.dumps(args)), "snippet_id":id, "time":datetime.now(),
                                 "exception_type":type(e).__name__, "exception":Binary(dill.dumps(e))}
                    self.cache.record_bug(bad_input)
                    raise e
                if random.randint(0,func_wrapper.called) == 0:
                    instrumented = True
                    params = tuple(list(args)+[v])
                    sig = " -> ".join([util.pp_type(x) for x in util.fancy_type(params).__tuple_params__])
                    # args_ = [a if type(a).__name__ != 'generator' else type(a) for a in args]
                    # v_ = v if type(v).__name__ != 'generator' else type(v)
                    #if sys.getsizeof(args) < self.max_obj_size and sys.getsizeof(v) < self.max_obj_size and not type(v).__name__ == 'generator':
                    if not type(v).__name__ == 'generator':
                        runtime = {"snippet_id":id, "call":Binary(dill.dumps((args,v))),"time_running":t2-t1,"file":__file__,
                               "user":self.user,"time":datetime.now(),"type":sig, "imports":imports}
                        if sys.getsizeof(runtime["call"]) < self.max_obj_size:
                            self.cache.record_call(runtime)
                func_wrapper.called += 1
                t_overhead2 = time.clock()
                if self.overhead: self.overhead_call.append({"id":id,"meta_time":t_overhead2-t_overhead1,"normal_time":t2-t1, "inst":instrumented})
                return v
            func_wrapper.called = 0
            return func_wrapper
        return bind_decorator
项目:StuffShare    作者:StuffShare    | 项目源码 | 文件源码
def represent(self, obj, fieldtype):
        # the base adatpter does not support MongoDB ObjectId
        if isinstance(obj, self.ObjectId):
            value = obj
        else:
            value = NoSQLAdapter.represent(self, obj, fieldtype)
        # reference types must be convert to ObjectID
        if fieldtype == 'date':
            if value is None:
                return value
            # this piece of data can be stripped off based on the fieldtype
            t = datetime.time(0, 0, 0)
            # mongodb doesn't has a date object and so it must datetime,
            # string or integer
            return datetime.datetime.combine(value, t)
        elif fieldtype == 'time':
            if value is None:
                return value
            # this piece of data can be stripped of based on the fieldtype
            d = datetime.date(2000, 1, 1)
            # mongodb doesn't has a  time object and so it must datetime,
            # string or integer
            return datetime.datetime.combine(d, value)
        elif fieldtype == "blob":
            if value is None:
                return value
            from bson import Binary
            if not isinstance(value, Binary):
                if not isinstance(value, basestring):
                    return Binary(str(value))
                return Binary(value)
            return value
        elif (isinstance(fieldtype, basestring) and
              fieldtype.startswith('list:')):
            if fieldtype.startswith('list:reference'):
                newval = []
                for v in value:
                    newval.append(self.object_id(v))
                return newval
            return value
        elif ((isinstance(fieldtype, basestring) and
               fieldtype.startswith("reference")) or
               (isinstance(fieldtype, Table)) or fieldtype == "id"):
            value = self.object_id(value)
        return value