当前位置: 首页>>代码示例>>Python>>正文


Python json_util.default方法代码示例

本文整理汇总了Python中bson.json_util.default方法的典型用法代码示例。如果您正苦于以下问题:Python json_util.default方法的具体用法?Python json_util.default怎么用?Python json_util.default使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在bson.json_util的用法示例。


在下文中一共展示了json_util.default方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: reply

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def reply(self, e, reply):
    if type(reply) in [dict, list]:
      #reply = json.dumps(reply, sort_keys=True, indent=4, default=json_util.default, ensure_ascii=True)
      reply = json.dumps(reply, sort_keys=True, ensure_ascii=True, default=json_util.default)
    else:
      reply = str(reply)

    if e.target == self.connection.nickname:
      target=e.source.nick
    else:
      target=e.target
    _list = reply.split('\n')
    chunk_size = 512 - 12 - len(e.target) # 512 - len("PRIVMSG") - len(" :") - CR/LF - target

    _list = [[x[i:i+chunk_size] for i in range(0, len(x), chunk_size)] for x in _list]
    _list = [item for sublist in _list for item in sublist] # flatten list
    for r in _list[:4]:
      self.connection.privmsg(target, r) 
开发者ID:flipkart-incubator,项目名称:watchdog,代码行数:20,代码来源:search_irc.py

示例2: checknotif

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def checknotif():
    if request.json["product"] == '':
        req = ':' + request.json['vendor'] + ':'
    else:
        req = request.json["vendor"] + ':' + request.json["product"] + ':' + request.json["version"]

    tab = []
    keytab = ['summary']
    for cves in mongo.db.cves.find({'vulnerable_configuration': {'$regex': req}}).sort("Modified", DESCENDING):
        dic = {}
        for key, value in cves.items():
            if key in keytab:
                dic[key] = cgi.escape(value, quote=True)
            else:
                if isinstance(value, datetime):
                    value = str(value)
                dic[key] = value
        tab.append(dic)
    return json.dumps(tab, sort_keys=True, default=json_util.default) 
开发者ID:CIRCL,项目名称:cve-portal,代码行数:21,代码来源:notif.py

示例3: save

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def save(self, dist_dir='result'):
        '''
        save the search results to file
        '''
        if dist_dir not in os.listdir(os.curdir):
            os.mkdir(dist_dir)
        for w in self.results:
            file_name = ''.join([
                    '_'.join([k for k in w['keywords']]),
                    w['mid']
                    ])
            file_name += '.txt'
            f = codecs.open(os.path.join(dist_dir, file_name), 'w', 'utf-8')
            json.dump(w, f, ensure_ascii = False, default=json_util.default, indent = 2)
            # logging.info(w['text'])
            logging.info('writed to file {}'.format(file_name))
        return 
开发者ID:KeithYue,项目名称:weibo-keywords-crawler,代码行数:19,代码来源:weibo_crawler.py

示例4: TRAC_OPTIONS

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def TRAC_OPTIONS(func):  # pylint: disable=invalid-name
    @click.option(
        '--trac-uri',
        default='http://localhost/xmlrpc',
        show_default=True,
        help='uri of the Trac instance XMLRpc endpoint',
    )
    @click.option(
        '--ssl-verify / --no-ssl-verify',
        default=True,
        show_default=True,
        help='Enable/disable SSL certificate verification'
    )
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)

    return wrapper 
开发者ID:tracboat,项目名称:tracboat,代码行数:20,代码来源:cli.py

示例5: post

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def post(self, slug=None):

		### needs XSRF token to work
		### cf : 

		dic = tornado.escape.json_decode(self.request.body)
		app_log.info(dic)

		full_json = { "status" : "ok", "sent" : self.retrieve_results() }

		### write data as json
		# cf : https://stackoverflow.com/questions/35083374/how-to-decode-a-unicode-string-python
		results = json.dumps( full_json, ensure_ascii=False, default=json_util.default ).encode('utf8') 

		self.write( results )
		
		self.finish() 
开发者ID:entrepreneur-interet-general,项目名称:OpenScraper,代码行数:19,代码来源:api_handler.py

示例6: backup_mongo_collection

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def backup_mongo_collection(coll, filepath) :
	"""
	dumps all documents in collection in _backups_collections 
	"""

	app_log.warning('>>> backup_mongo_collection ... ')

	cursor 		= coll.find({})
	backup_file = open(filepath, "w")
	backup_file.write('[')
	for document in cursor:
		backup_file.write(json.dumps(document,indent=4, default=json_util.default))
		backup_file.write(',')
	backup_file.write(']')

### + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ###


### MAIN TORNADO APPLICATION WRAPPER 
开发者ID:entrepreneur-interet-general,项目名称:OpenScraper,代码行数:21,代码来源:main.py

示例7: verisSummary

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def verisSummary(verisRegex=None):
    try:
        # aggregate the veris tags from the incidents collection and return as json
        client = MongoClient(options.mongohost, options.mongoport)
        # use meteor db
        incidents = client.meteor['incidents']

        iveris = incidents.aggregate([
            {"$match": {"tags": {"$exists": True}}},
            {"$unwind": "$tags"},
            {"$match": {"tags": {"$regex": ''}}},
            {"$project": {
                "dateOpened": 1,
                "tags": 1,
                "phase": 1,
                "_id": 0
            }}
        ])
        if iveris:
            return json.dumps(list(iveris), default=json_util.default)
        else:
            return json.dumps(list())
    except Exception as e:
            logger.error('Exception while aggregating veris summary: {0}\n'.format(e)) 
开发者ID:mozilla,项目名称:MozDef,代码行数:26,代码来源:index.py

示例8: test_list_healings

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def test_list_healings(self):
        resp = self.api.get("/admin/healings")
        self.assertEqual(200, resp.status_code)
        self.assertEqual("[]", resp.data)
        loop_time = datetime.datetime(2016, 8, 2, 10, 53, 0)
        healing_list = []
        for x in range(1, 30):
            data = {"instance": "myinstance", "machine": "10.10.1.{}".format(x),
                    "start_time": loop_time, "end_time": loop_time, "status": "success"}
            healing_list.append(json.loads(json.dumps(data, default=json_util.default)))
            self.storage.db[self.storage.healing_collection].insert(data)
            loop_time = loop_time + datetime.timedelta(minutes=5)
        healing_list.reverse()
        resp = self.api.get("/admin/healings")
        self.assertEqual(200, resp.status_code)
        self.assertListEqual(healing_list[:20], json.loads(resp.data))
        resp = self.api.get("/admin/healings?quantity=10")
        self.assertEqual(200, resp.status_code)
        self.assertListEqual(healing_list[:10], json.loads(resp.data))
        resp = self.api.get("/admin/healings?quantity=aaaa")
        self.assertEqual(200, resp.status_code)
        self.assertListEqual(healing_list[:20], json.loads(resp.data)) 
开发者ID:tsuru,项目名称:rpaas,代码行数:24,代码来源:test_admin_api.py

示例9: test_list_healings_empty_json_response

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def test_list_healings_empty_json_response(self, stdout, Request, urlopen):
        lines = []
        stdout.write.side_effect = lambda data, **kw: lines.append(data)
        request = mock.Mock()
        Request.return_value = request
        result = mock.Mock()
        result.getcode.return_value = 200
        urlopen.return_value = result
        healing_list = []
        result.read.return_value = json.dumps(healing_list, default=json_util.default)
        args = ['-s', self.service_name]
        admin_plugin.list_healings(args)
        Request.assert_called_with(self.target +
                                   "services/proxy/service/rpaas?" +
                                   "callback=/admin/healings?quantity=20")
        request.add_header.assert_any_call("Authorization", "bearer " + self.token)
        self.assertEqual("GET", request.get_method())
        expected_output = u"""
+----------+---------+------------+----------+--------+
| Instance | Machine | Start Time | Duration | Status |
+----------+---------+------------+----------+--------+
"""
        self.assertEqual(expected_output, "".join(lines)) 
开发者ID:tsuru,项目名称:rpaas,代码行数:25,代码来源:test_admin_plugin.py

示例10: token_required

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def token_required(funct):
    @wraps(funct)
    def api_token(*args, **kwargs):
      data = Advanced_API.authErrors()
      if data:
        return Response(json.dumps(data[0], indent=2, sort_keys=True, default=json_util.default), mimetype='application/json'), data[1]
      else: return API.api(funct)(*args, **kwargs)
    return api_token

  ##########
  # ROUTES #
  ##########
  # Overriding api_dbInfo to allow for logged-in users to get more info 
开发者ID:flipkart-incubator,项目名称:watchdog,代码行数:15,代码来源:advanced_api.py

示例11: api_search

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def api_search(self, vendor=None, product=None):
    if not (vendor and product): return {}
    search = vendor + ":" + product
    # Not using query.cvesForCPE, because that one gives too much info
    #return json.dumps(db.cvesForCPE(search), default=json_util.default)
    return db.cvesForCPE(search)

  # /api/search/<path:search> 
开发者ID:flipkart-incubator,项目名称:watchdog,代码行数:10,代码来源:api.py

示例12: format_message

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def format_message(self, message):
        if type(message) in [dict, list]:
            message = json.dumps(message, sort_keys=True, indent=4, default=json_util.default)
        else:
            message = str(message)
        return message 
开发者ID:flipkart-incubator,项目名称:watchdog,代码行数:8,代码来源:search_xmpp.py

示例13: execute_analysis

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def execute_analysis(self, indicator):

        # crits was the first intel platform supported by ace
        # so if there is no prefix to the value then it's assumed to be crits
        if ':' in indicator.value:
            return False

        analysis = self.create_analysis(indicator)

        # download the crits indicator JSOn directly from the crits mongo database
        mongodb_uri = saq.CONFIG['crits']['mongodb_uri']
        if not mongodb_uri:
            logging.warn("A Mongo DB URI is not configured for Crits Analysis.")
            return False
        client = MongoClient(saq.CONFIG['crits']['mongodb_uri'])
        db = client['crits']
        collection = db['indicators']

        mongo_object = analysis.details = collection.find_one({'_id' : ObjectId(indicator.value)})

        if analysis.details is None:
            logging.error("unable to find details of indicator {}".format(indicator.value))
            return False
        
        # this extra step is required to remove the ObjectId objects in the JSON result
        analysis.details = json.loads(json.dumps(analysis.details, default=json_util.default))

        # extract any tags (buckets) associated with the indicator
        if 'bucket_list' in mongo_object and isinstance(mongo_object['bucket_list'], list):
            for tag in mongo_object['bucket_list']:
                indicator.add_tag(tag)

        # add any associated campaigns as tags as well
        if 'campaign' in analysis.details:
            for actor in analysis.details['campaign']:
                indicator.add_tag('apt:{0}'.format(actor['name']))

        return True 
开发者ID:IntegralDefense,项目名称:ACE,代码行数:40,代码来源:crits.py

示例14: init_session

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def init_session(request):
    pass
    # Put all the incident templates in the session
    request.session['incident_templates'] = list(IncidentTemplate.objects.exclude(name='default').values('name'))
    request.session['has_incident_templates'] = len(request.session['incident_templates']) > 0
    request.session['can_report_event'] = request.user.has_perm('incidents.handle_incidents', obj=Incident) or \
                                          request.user.has_perm('incidents.report_events', obj=Incident)


# audit trail ===================================================== 
开发者ID:certsocietegenerale,项目名称:FIR,代码行数:12,代码来源:views.py

示例15: new_event

# 需要导入模块: from bson import json_util [as 别名]
# 或者: from bson.json_util import default [as 别名]
def new_event(request):
    if request.method == 'POST':
        form = IncidentForm(request.POST, for_user=request.user)

        form.status = _('Open')

        if form.is_valid():
            i = form.save(commit=False)

            if not form.cleaned_data['is_major']:
                i.is_major = form.cleaned_data['category'].is_major

            if i.is_major:
                i.is_incident = True

            i.opened_by = request.user
            i.save()
            form.save_m2m()
            i.refresh_main_business_lines()
            i.done_creating()

            if i.is_incident:
                return redirect("incidents:details", incident_id=i.id)
            else:
                return redirect("events:details", incident_id=i.id)

    else:
        template = request.GET.get('template', 'default')
        try:
            template = IncidentTemplate.objects.get(name=template)
            data = model_to_dict(template)
            data['description'] = Template(data['description']).render(RequestContext(request))
        except ObjectDoesNotExist:
            data = {}
        form = IncidentForm(initial=data, for_user=request.user)

    return render(request, 'events/new.html', {'form': form, 'mode': 'new'}) 
开发者ID:certsocietegenerale,项目名称:FIR,代码行数:39,代码来源:views.py


注:本文中的bson.json_util.default方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。