本文整理匯總了Python中bson.json_util.dumps方法的典型用法代碼示例。如果您正苦於以下問題:Python json_util.dumps方法的具體用法?Python json_util.dumps怎麽用?Python json_util.dumps使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類bson.json_util
的用法示例。
在下文中一共展示了json_util.dumps方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: delete_substage
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def delete_substage(request, id):
try:
sub_stage = Stage.objects.get(pk=id)
old_fsxf = sub_stage.stage_forms
old_fsxf.is_deleted = True
# old_fsxf.stage = None
old_fsxf.save()
# org = sub_stage.stage.project.organization if sub_stage.stage.project else sub_stage.stage.site.project.organization
# desc = "deleted form of stage {} substage {} by {}".format(sub_stage.stage.name, sub_stage.name,
# request.user.username)
# noti = old_fsxf.logs.create(source=request.user, type=1, title="form Deleted",
# organization=org, description=desc)
# result = {}
# result['description'] = desc
# result['url'] = noti.get_absolute_url()
# ChannelGroup("notify-{}".format(org.id)).send({"text": json.dumps(result)})
# ChannelGroup("notify-0").send({"text": json.dumps(result)})
# sub_stage.delete()
return Response({}, status=status.HTTP_200_OK)
except Exception as e:
return Response({'error':e.message}, status=status.HTTP_400_BAD_REQUEST)
示例2: Getplugin
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def Getplugin():
type = request.form.get('type', '')
risk = request.form.get('risk', '')
search = request.form.get('search', '')
query = {}
if type:
query['type'] = type
if risk:
query['level'] = risk
if search:
search = unquote(search)
query['name'] = {"$regex": search, '$options': 'i'}
cursor = Mongo.coll['Plugin'].find(query)
rsp = []
for i in cursor:
result = {'name': i['name'], 'info': i['info']}
rsp.append(result)
return json.dumps(rsp)
# 新增任務異步
示例3: to_json
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def to_json(self, *args, **kwargs) -> str:
"""
Convert this document to JSON.
Parameters:
use_db_field: Serialize field names as they appear in
MongoDB (as opposed to attribute names on this document).
Defaults to True.
raw: Set True to generate MongoDB Extended JSON.
"""
use_db_field = kwargs.pop("use_db_field", True)
raw = kwargs.pop("raw", False)
if not raw:
for (fldname, fld) in self._fields.items():
setattr(fld, "$$mode$$", "json")
ret = json_util.dumps(
self.to_mongo(use_db_field, raw=raw), *args, **kwargs,
)
return ret
示例4: preparations_data
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def preparations_data(self, data):
"""
Data preparation.
Args:
`data` : data from AMQP.
Raises:
`n6QueueProcessingException` when except processing data.
"""
try:
self.raw = loads(data)
# calculate md5, inplace its fastest
self.headers['meta'].update({
'md5': hashlib.md5(dumps(self.raw, sort_keys=True)).hexdigest()})
except Exception as exc:
LOGGER.error('exception when processing: %r %r %r (%r)',
self.dbm.currdb, self.dbm.currcoll, data, exc)
raise
else:
self.write()
示例5: result_list
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def result_list():
from bson import json_util
timedata = request.get_json()
collection_ts = timedata.get('collection', 'NA')
database = timedata.get('database', 'NA')
url = timedata.get('url', 'NA')
###"mongodb://username:pwd@ds261570.mlab.com:61570/ts?retryWrites=false"
import pandas as pd
import pymongo
from pymongo import MongoClient
# Making a Connection with MongoClient
client = MongoClient(url)
# database
db = client[database]
# collection
collection_data= db[collection_ts]
import time
import json
from bson import json_util, ObjectId
#Dump loaded BSON to valid JSON string and reload it as dict
page_sanitized = json.loads(json_util.dumps(collection_data.find({},{'name':1})))
return jsonify(page_sanitized), 201
示例6: get_metadata
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def get_metadata():
if request.query.file_hash == '':
response.status = 400
return jsonize({'message': 'file_hash parameter is missing'})
file_hash = clean_hash(request.query.file_hash)
if not valid_hash(file_hash):
response.status = 400
return jsonize({'message': 'Invalid hash format (use MD5, SHA1 or SHA2)'})
file_hash = get_file_id(file_hash)
if file_hash is None:
response.status = 404
return jsonize({'message': 'Metadata not found in the database'})
mdc = MetaController()
res = mdc.read(file_hash)
if res is None:
log_event("metadata", file_hash)
return dumps(change_date_to_str(res))
示例7: export_metadata
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def export_metadata():
mdc = MetaController()
hashes = request.forms.dict.get("file_hash[]")
dump_to_save = ""
random_id = id_generator()
tmp_path = "/tmp/meta_export"
tmp_folder = os.path.join(tmp_path, random_id)
call_with_output(["mkdir", "-p", tmp_folder])
for hash in hashes:
hash = clean_hash(hash.replace('\r', ''))
res = mdc.read(hash)
dump = dumps(res, indent=4)
file_name = os.path.join(tmp_folder, str(hash) + '.txt')
fd = open(file_name, "w")
fd.write(dump)
fd.close()
zip_path = os.path.join(tmp_path, random_id + '.zip')
call_with_output(["zip", "-jr", zip_path, tmp_folder])
resp = static_file(str(random_id) + '.zip', root=tmp_path, download=True)
resp.set_cookie('fileDownload', 'true')
shutil.rmtree(tmp_folder)
os.remove(zip_path)
return resp
示例8: get_device_group_info
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def get_device_group_info(device_group):
device_group_exists, device_group_json = mongo_connection.mongo_get_device_group(device_group)
if device_group_exists is False:
return jsonify({"device_group_exists": False}), 403
device_group_config = {"apps": [], "apps_list": [], "prune_id": device_group_json["prune_id"], "cron_jobs": [],
"cron_jobs_list": [], "device_group_id": device_group_json["device_group_id"]}
for device_app in device_group_json["apps"]:
app_exists, app_json = mongo_connection.mongo_get_app(device_app)
if app_exists is True:
device_group_config["apps"].append(app_json)
device_group_config["apps_list"].append(app_json["app_name"])
for device_cron_job in device_group_json["cron_jobs"]:
cron_job_exists, cron_job_json = mongo_connection.mongo_get_cron_job(device_cron_job)
if cron_job_exists is True:
device_group_config["cron_jobs"].append(cron_job_json)
device_group_config["cron_jobs_list"].append(cron_job_json["cron_job_name"])
return dumps(device_group_config), 200
# create device_group
示例9: prune_images_on_all_device_groups
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def prune_images_on_all_device_groups():
# get a list of all device_groups
device_groups = mongo_connection.mongo_list_device_groups()
all_device_groups_prune_id = {"prune_ids": {}}
# loop over all device groups
for device_group in device_groups:
# check device_group exists first
device_group_exists = mongo_connection.mongo_check_device_group_exists(device_group)
if device_group_exists is False:
return jsonify({"app_exists": False}), 403
# update db
app_json = mongo_connection.mongo_increase_prune_id(device_group)
all_device_groups_prune_id["prune_ids"][device_group] = app_json["prune_id"]
return dumps(all_device_groups_prune_id), 202
# list reports
示例10: update_user_group_fields
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def update_user_group_fields(user_group):
# check user_group exists first
user_group_exists = mongo_connection.mongo_check_user_group_exists(user_group)
if user_group is False:
return jsonify({"user_group_exists": False}), 403
# check app got update parameters
try:
app_json = request.json
if len(app_json) == 0:
return jsonify({"missing_parameters": True}), 400
except:
return jsonify({"missing_parameters": True}), 400
# update db
app_json = mongo_connection.mongo_update_user_group(user_group, request.json)
return dumps(app_json), 200
# delete a user_group
示例11: run
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def run(mdb):
out = []
async for char in mdb.characters.find({}):
out.append(char)
with open("temp/collection_char.json", 'w') as f:
f.write(json_util.dumps(out))
示例12: delete_mainstage
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def delete_mainstage(request, id):
try:
with transaction.atomic():
stage = Stage.objects.get(pk=id)
org = stage.site.project.organization if stage.site else stage.project.organization
substages = Stage.objects.filter(stage=stage)
for sub_stage in substages:
if hasattr(sub_stage, 'stage_forms'):
old_fsxf = sub_stage.stage_forms
old_fsxf.is_deleted = True
old_fsxf.stage = None
old_fsxf.save()
# desc = "deleted form of stage {} substage {} by {}".format(sub_stage.stage.name, sub_stage.name,
# request.user.username)
# noti = old_fsxf.logs.create(source=request.user, type=1, title="form Deleted",
# organization=org, description=desc)
# result = {}
# result['description'] = desc
# result['url'] = noti.get_absolute_url()
# ChannelGroup("notify-{}".format(org.id)).send({"text": json.dumps(result)})
# ChannelGroup("notify-0").send({"text": json.dumps(result)})
sub_stage.delete()
stage.delete()
return Response({}, status=status.HTTP_200_OK)
except Exception as e:
return Response({'error':e.message}, status=status.HTTP_400_BAD_REQUEST)
示例13: delete_data
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def delete_data(request, fsxf_id=None):
pass
# xform, owner = check_and_set_user_and_form(username, id_string, request)
# response_text = u''
# if not xform or not has_edit_permission(
# xform, owner, request, xform.shared
# ):
# return HttpResponseForbidden(_(u'Not shared.'))
#
# data_id = request.POST.get('id')
# if not data_id:
# return HttpResponseBadRequest(_(u"id must be specified"))
#
# Instance.set_deleted_at(data_id)
# audit = {
# 'xform': xform.id_string
# }
# audit_log(
# Actions.SUBMISSION_DELETED, request.user, owner,
# _("Deleted submission with id '%(record_id)s' "
# "on '%(id_string)s'.") %
# {
# 'id_string': xform.id_string,
# 'record_id': data_id
# }, audit, request)
# response_text = json.dumps({"success": "Deleted data %s" % data_id})
# if 'callback' in request.GET and request.GET.get('callback') != '':
# callback = request.GET.get('callback')
# response_text = ("%s(%s)" % (callback, response_text))
#
# return HttpResponse(response_text, content_type='application/json')
示例14: delete_data
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def delete_data(request, username=None, id_string=None):
xform, owner = check_and_set_user_and_form(username, id_string, request)
response_text = u''
if not xform or not has_edit_permission(
xform, owner, request, xform.shared
):
return HttpResponseForbidden(_(u'Not shared.'))
data_id = request.POST.get('id')
if not data_id:
return HttpResponseBadRequest(_(u"id must be specified"))
Instance.set_deleted_at(data_id)
audit = {
'xform': xform.id_string
}
audit_log(
Actions.SUBMISSION_DELETED, request.user, owner,
_("Deleted submission with id '%(record_id)s' "
"on '%(id_string)s'.") %
{
'id_string': xform.id_string,
'record_id': data_id
}, audit, request)
response_text = json.dumps({"success": "Deleted data %s" % data_id})
if 'callback' in request.GET and request.GET.get('callback') != '':
callback = request.GET.get('callback')
response_text = ("%s(%s)" % (callback, response_text))
return HttpResponse(response_text, content_type='application/json')
示例15: activity_fields
# 需要導入模塊: from bson import json_util [as 別名]
# 或者: from bson.json_util import dumps [as 別名]
def activity_fields(request):
fields = [
{
'id': 'created_on',
'label': _('Performed On'),
'type': 'datetime',
'searchable': False
},
{
'id': 'action',
'label': _('Action'),
'type': 'string',
'searchable': True,
'options': sorted([Actions[e] for e in Actions.enums])
},
{
'id': 'user',
'label': 'Performed By',
'type': 'string',
'searchable': True
},
{
'id': 'msg',
'label': 'Description',
'type': 'string',
'searchable': True
},
]
response_text = json.dumps(fields)
return HttpResponse(response_text, content_type='application/json')