本文整理汇总了Python中slideatlas.common_utils.jsonify函数的典型用法代码示例。如果您正苦于以下问题:Python jsonify函数的具体用法?Python jsonify怎么用?Python jsonify使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了jsonify函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getsections
def getsections():
#pdb.set_trace()
dbName = request.args.get('db', '')
collectionName = request.args.get('col', '')
sectionId = request.args.get('id', None)
objType = request.args.get('type', 'Section')
# passed to server to be returned to client (hack)
sectionIndex = request.args.get('idx', None)
db = conn[dbName]
if sectionId :
sectionObj = db[collectionName].find_one({'_id':ObjectId(sectionId)})
sectionObj["_id"] = str(sectionObj["_id"])
if sectionIndex :
sectionObj["index"] = int(sectionIndex)
return jsonify(sectionObj)
else :
sectionCursor = db[collectionName].find({"type":objType},{"waferName":1, "section":1}).sort([("waferName", 1), ("section", 1)])
# make a new structure to return. Convert the ids to strings.
sectionArray = [];
for section in sectionCursor:
section["_id"] = str(section["_id"])
sectionArray.append(section)
data = {}
data["sections"] = sectionArray
return jsonify(data)
示例2: get
def get(self, restype, resid=None):
"""
Get restype with resid ['users'], if resid is not supplied, returns a list
"""
admin_db = models.ImageStore._get_db()
# Restype has to be between allowed ones or the request will not come here
if resid == None:
objs = admin_db[restype].find()
# TODO: need to paginate in near future
objarray = list()
for anobj in objs:
# Filter the list with passwd if type is user
if restype == "users":
if "passwd" in anobj:
del anobj["passwd"]
objarray.append(anobj)
return jsonify({ restype : objarray})
else:
obj = admin_db[restype].find_one({"_id" : ObjectId(resid)})
if obj :
if restype == "users":
if "passwd" in obj:
del obj["passwd"]
return jsonify(obj)
else:
return Response("{\"error\" : \"resource not found\"}" , status=405)
示例3: post
def post(self, dbid, sessid=None):
# Parse the data in json format
data = request.json
# Unknown request if no parameters
if data == None:
abort(400)
conn.register([Session])
db = self.get_data_db(dbid)
if data.has_key("insert"):
# Create the database object from the supplied parameters
try:
newsession = db["sessions"].Session()
newsession["label"] = data["insert"]["label"]
newsession["images"] = []
newsession.validate()
newsession.save()
except Exception as inst:
# # If valid database object cannot be constructed it is invalid request
return Response("{\"error\" : %s}" % str(inst), status=405)
return jsonify(newsession)
elif data.has_key("modify"):
# Resid must be supplied
if sessid == None :
return Response("{\"error\" : \"No session _id supplied for modification\"}" , status=405)
try:
# Locate the resource
newdb = db["sessions"].Session.find_one({"_id" : ObjectId(sessid)})
if newdb == None:
raise Exception(" Resource %s not found" % (sessid))
except Exception as inst:
# If valid database object cannot be constructed it is invalid request
return Response("{\"error\" : \"%s\"}" % str(inst), status=405)
# Now update
try:
for akey in data["modify"]:
# Presently updating only label is supported
if akey <> "label":
return Response("{\"error\" : \"Cannot modify %s \"}" % (akey) , status=405)
newdb[akey] = data["modify"][akey]
newdb.validate()
newdb.save()
except Exception as inst:
# If valid database object cannot be constructed it is invalid request
return Response("{\"error\" : \"%s\"}" % str(inst), status=405)
return jsonify(newdb)
else:
# Only insert and modify commands are supported
abort(400)
示例4: post
def post(self, dbid, sessid=None):
# Parse the data in json format
data = request.json
# Unknown request if no parameters
if data == None:
abort(400)
db = self.get_data_db(dbid)
if data.has_key("insert"):
# Create the database object from the supplied parameters
try:
newsession = models.Session(image_store=db, label=data["insert"]["label"])
newsession.save()
except Exception as inst:
# If valid database object cannot be constructed it is invalid request
return Response("{\"error\" : %s}" % str(inst), status=405)
return jsonify(newsession)
elif data.has_key("modify"):
# Resid must be supplied
if sessid == None :
return Response("{\"error\" : \"No session _id supplied for modification\"}" , status=405)
try:
# Locate the resource
newdb = models.Session.objects.with_id(sessid)
if newdb == None:
raise Exception(" Resource %s not found" % (sessid))
except Exception as inst:
# If valid database object cannot be constructed it is invalid request
return Response("{\"error\" : \"%s\"}" % str(inst), status=405)
# Now update
try:
for akey in data["modify"]:
# Presently updating only label is supported
if akey != "label":
return Response("{\"error\" : \"Cannot modify %s \"}" % (akey) , status=405)
setattr(newdb, akey, data["modify"][akey])
newdb.save()
except Exception as inst:
# If valid database object cannot be constructed it is invalid request
return Response("{\"error\" : \"%s\"}" % str(inst), status=405)
return jsonify(newdb.to_mongo())
else:
# Only insert and modify commands are supported
abort(400)
示例5: bookmark
def bookmark():
"""
- /bookmark?key=0295cf24-6d51-4ce8-a923-772ebc71abb5
"""
key = request.args.get('key', "0295cf24-6d51-4ce8-a923-772ebc71abb5")
# find the view and the db
return jsonify({"key": key })
# Simple embeddable viewer.
style = request.args.get('style', "default")
# See if editing will be enabled.
edit = request.args.get('edit', False)
# See if the user is requesting a view or session
viewid = request.args.get('view', None)
# get all the metadata to display a view in the webgl viewer.
ajax = request.args.get('json', None)
admindb = models.ImageStore._get_db()
db = admindb
if viewid:
viewobj = readViewTree(db, viewid, -1)
if ajax:
return jsonifyView(db,viewid,viewobj)
# default
return glnote(db,viewid,viewobj,edit,style)
示例6: getfavoriteviews
def getfavoriteviews():
collectionStr = request.args.get('col', "views") # "favorites"
# Saving notes in admin db now.
admindb = models.ImageStore._get_db()
# get a list of the favorite view ids.
viewItr = admindb[collectionStr].find(
{
'User': getattr(security.current_user, 'id', ''),
'Type': 'Favorite'
},
{
'_id': True
}
)
viewArray = []
for viewId in viewItr:
viewObj = readViewTree(admindb, viewId["_id"], -1)
# There should be no legacy views, but keep the check just in case.
if "Type" in viewObj:
convertViewToPixelCoordinateSystem(viewObj)
viewArray.append(viewObj)
data = {'viewArray': viewArray}
return jsonify(data)
示例7: get
def get(self, dbid, sessid=None):
conn.register([Session, Database])
datadb = self.get_data_db(dbid)
if datadb == None:
return Response("{ \"error \" : \"Invalid database id %s\"}" % (dbid), status=405)
if sessid == None:
sessions = datadb["sessions"].Session.find({}, {'images':0, 'views':0, 'attachments':0})
sessionlist = list()
for asession in sessions:
sessionlist.append(asession)
if len(sessionlist) > 0:
return jsonify({'sessions' : sessionlist})
else:
return jsonify({'sessions' : sessionlist, "error" : "You want You want a list of sessions in %s, but there are no sessions in it" %(dbid)})
else:
# Get and return a list of sessions from given database
# TODO: Filter for the user that is requesting
sessobj = datadb["sessions"].find_one({"_id" : ObjectId(sessid)})
if sessobj == None:
return Response("{ \"error \" : \"Session %s does not exist in db %s\"}" % (sessid, dbid), status=405)
# Dereference the views
for aview in sessobj["views"]:
viewdetails = datadb["views"].find_one({"_id" : aview["ref"]})
# Viewdetails might not be a view
if "img" in viewdetails:
viewdetails["image"] = datadb["images"].find_one({"_id" : viewdetails["img"]}, { "thumb" : 0})
else:
if "ViewerRecords" in viewdetails:
viewdetails["image"] = viewdetails["ViewerRecords"][0]["Image"]["_id"]
aview["details"] = viewdetails
# Dereference the attachments
attachments = []
if "attachments" in sessobj:
gfs = GridFS(datadb, "attachments")
for anattach in sessobj['attachments']:
fileobj = gfs.get(anattach["ref"])
anattach["details"] = ({'name': fileobj.name, 'length' : fileobj.length})
else:
sessobj["attachments"] = []
return jsonify(sessobj)
示例8: view_all_sessions
def view_all_sessions():
all_sessions_query = models.Session.objects\
.only('collection', 'label', 'image_store', 'type')\
.order_by('collection', 'label')\
.no_dereference()
# disable dereferencing of of sessions, to prevent running a seperate
# query for every single session's collection
all_collections_query = models.Collection.objects\
.no_dereference()
can_admin_collection_ids = [collection.id for collection in all_collections_query.can_access(g.identity.provides , models.Operation.admin)]
editable_sessions_query = all_sessions_query.can_access(g.identity.provides, models.Operation.edit)
viewable_sessions_query = all_sessions_query.can_access(g.identity.provides, models.Operation.view, strict_operation=True)
# fetch the relevant collections in bulk
collections_by_id = {collection.id: collection for collection in
chain(editable_sessions_query.distinct('collection'),
viewable_sessions_query.distinct('collection')
)}
all_sessions = defaultdict(dict)
for sessions_query, can_admin in [
# viewable must come first, so editable can overwrite
(viewable_sessions_query, False),
(editable_sessions_query, True),
]:
for collection_ref, sessions in groupby(sessions_query, attrgetter('collection')):
collection = collections_by_id[collection_ref.id]
all_sessions[collection].update(dict.fromkeys(sessions, can_admin))
all_sessions = [(collection,
True if collection.id in can_admin_collection_ids else False,
sorted(sessions_dict.iteritems(), key=lambda item: item[0].label)
)
for collection, sessions_dict
in sorted(all_sessions.iteritems(), key=lambda item: item[0].label)]
# Whether to include administrative javascript
is_admin = bool(len(can_admin_collection_ids))
if request.args.get('json'):
ajax_session_list = [
{
'rule': collection.label,
'can_admin': can_admin,
'sessions': [
{
'sessdb': str(session.image_store.id),
'sessid': str(session.id),
'label': session.label
}
for session, can_admin in sessions],
}
for collection, can_admin, sessions in all_sessions]
user_name = security.current_user.full_name if security.current_user.is_authenticated() else 'Guest'
return jsonify(sessions=ajax_session_list, name=user_name, ajax=1)
else:
return render_template('sessionlist.html', all_sessions=all_sessions, is_admin=is_admin)
示例9: image_query
def image_query():
"""
- /query?words=[]
"""
terms = request.args.get('terms', "").split()
db = models.ImageStore._get_db()
# I do not think the $text seach can work on individual fields
# so I can not weight them separatly. I would like title
# to have more weight that text.
db["views"].ensure_index(
[("Title", "text"), ("Text", "text")], name="titletext")
# build up a list of images.
imgDict = dict()
# I may need to search the terms separatly and add the weights
# if the weigths do not properly increase for matches of multiple terms.
# build up a list of images.
# search titles (pretty important).
for term in terms:
viewCursor = db["views"].find({'$text': {'$search': term}},
{'score': {"$meta": "textScore"}, "ViewerRecords": 1})
for view in viewCursor:
for record in view["ViewerRecords"]:
imgId = record["Image"]
if not imgDict.has_key(str(imgId)):
database = models.ImageStore.objects.get_or_404(id=ObjectId(record["Database"]))
imgdb = database.to_pymongo()
imgObj = imgdb["images"].find_one(
{'_id': imgId},
{
'TileSize': True,
'levels': True,
'bounds': True,
'label': True,
'dimensions': True,
'components': True
}
)
if imgObj is not None:
imgObj["_id"] = str(imgId)
imgObj["database"] = str(record["Database"])
imgDict[str(imgId)] = imgObj
imgObj["score"] = view["score"]
# give extra score to iamges that have the term in
# their labels.
for t in terms:
if imgObj["label"].lower().find(t.lower()) != -1:
imgObj["score"] += 2.0
else:
imgObj["score"] += view["score"]
data = dict()
data["images"] = sorted(imgDict.values(), key=itemgetter('score'), reverse=True)
return jsonify(data)
示例10: view_a_session
def view_a_session(session):
# TODO: the template doesn't seem use 'next'
next_arg = int(request.args.get('next', 0))
session_son = apiv2.SessionItemAPI._get(session)
if request.args.get('json'):
images = []
for view_son in session_son['views']:
database = models.ImageStore.objects.get_or_404(id=view_son['image_store_id'])
imgdb = database.to_pymongo()
imgObj = imgdb["images"].find_one({ "_id" : view_son['image_id']})
# these should not happen but to be safe.
if not "dimensions" in imgObj :
imgObj['dimensions'] = [0,0,0]
if not "levels" in imgObj :
imgObj['levels'] = 0
bounds = [0,imgObj['dimensions'][0], 0, imgObj['dimensions'][1]]
if 'bounds' in imgObj:
bounds = imgObj['bounds']
tileSize = 256
if 'tile_size' in imgObj:
tileSize = imgObj['tile_size']
if 'tileSize' in imgObj:
tileSize = imgObj['tileSize']
if 'TileSize' in imgObj:
tileSize = imgObj['TileSize']
images.append({
'db': view_son['image_store_id'],
'img': view_son['image_id'],
'label': view_son['label'],
'view': view_son['id'],
'bounds': bounds,
'tile_size': tileSize,
'levels': imgObj['levels'],
'dimensions': imgObj['dimensions']
})
ajax_data = {
'success': 1,
'session': session_son,
'images': images,
'attachments': session_son['attachments'],
'imagefiles': session_son["imagefiles"],
'db': session.image_store.id, # TODO: deprecate and remove
'sessid': session.id,
'hide': session_son['hide_annotations'],
'next': url_for('.sessions_view', sessid=str(session.id), ajax=1, next=next_arg + NUMBER_ON_PAGE)
}
return jsonify(ajax_data)
else:
return render_template('session.html',
session=session,
session_son=session_son)
示例11: glstacksession
def glstacksession():
"""
- /webgl-viewer/stack-session?db=5123c81782778fd2f954a34a&sess=51256ae6894f5931098069d5
"""
# Comparison is a modified view.
sessid = request.args.get('sess', None)
if not sessid:
sessid = "51256ae6894f5931098069d5"
# this is the same as the sessions db in the sessions page.
dbid = request.args.get('db', None)
admindb = conn[current_app.config["CONFIGDB"]]
dbobj = admindb["databases"].Database.find_one({ "_id" : ObjectId(dbid) })
db = conn[dbobj["dbname"]]
sessobj = db["sessions"].find_one({"_id" : ObjectId(sessid) })
views = [];
for view in sessobj["views"]:
viewid = view["ref"]
viewobj = db["views"].find_one({"_id" : ObjectId(viewid) })
#viewobj["rotation"] = 0
# Having issues with jsonify
imgdbid = dbid
if 'db' in viewobj:
imgdbid = str(viewobj["db"])
myview = {"_id": str(viewobj["_id"]),
"center": viewobj["center"],
"height": viewobj["height"],
"rotation": 0,
"db": imgdbid}
imgobj = db["images"].find_one({"_id" : viewobj["img"] })
#imgobj["_id"] = str(imgobj["_id"])
#imgobj["thumb"] = ""
myimg = {"dimensions": imgobj["dimension"],
"_id": str(imgobj["_id"]),
"levels": imgobj["levels"]}
myview["img"] = myimg
views.append(myview)
for pair in sessobj["transformations"]:
if 'view0' in pair:
pair["view0"] = str(pair["view0"])
pair["view1"] = str(pair["view1"])
if not 'annotations' in sessobj:
sessobj["annotations"] = []
for markup in sessobj["annotations"]:
markup["view"] = str(markup["view"])
return jsonify({"views":views,
"transformations": sessobj["transformations"],
"annotations": sessobj["annotations"]})
示例12: session_save_stack
def session_save_stack():
input_str = request.form['input'] # for post
input_obj = json.loads(input_str)
session_id = ObjectId(input_obj['sessId'])
label = input_obj['label']
stack_items = input_obj['items']
admindb = models.ImageStore._get_db()
session = models.Session.objects.with_id(session_id)
security.EditSessionRequirement(session).test()
records = list()
for item in stack_items:
camera = {'FocalPoint': [item['x'], item['y'], 0],
'Height': item['height'],
'Roll': item['roll']}
viewer_record = {
'Image': ObjectId(item['img']),
'Database': ObjectId(item['db']),
'Camera' : camera}
if 'widget' in item :
viewer_record['Annotations'] = [item['widget']];
records.append(viewer_record)
for idx in range(1,len(stack_items)) :
item0 = stack_items[idx-1]
item1 = stack_items[idx]
correlationHeight = (item0['height']+item1['height'])*0.5;
records[idx]['Transform'] = {'Correlations':[{'point0': [item0['x'], item0['y']],
'point1': [item1['x'], item1['y']],
'roll': item1['roll']-item0['roll'],
'height': correlationHeight } ]}
# Now make the view
user = security.current_user.id if security.current_user.is_authenticated() else 'Guest'
view = {
'CoordinateSystem': 'Pixel',
'User': user,
'Type': 'Stack',
'ViewerRecords': records,
'Title': label,
'HiddenTitle': label
}
# TODO: don't save until the end, to make failure transactional
admindb['views'].save(view, manipulate=True)
# update the session
session.views.insert(0, view['_id'])
session.save()
return jsonify(view)
示例13: put
def put(self, resid):
# put requires admin access
# Get json supplied
data = request.json
# Check for valid parameters
# Check if no parameters
if data is None:
return Response("{\"error\" : \"No parameters ? \"}", status=405)
# See if id matches the resource being modified
try:
if data["_id"] != resid:
raise Exception(1)
except:
return Response("{\"error\" : \"_id mismatch with the location in the url \"}", status=405)
# The object should exist
for anobj in models.ImageStore.objects:
current_app.logger.debug('%s %s', anobj.label, anobj.id)
database = models.ImageStore.objects.with_id(ObjectId(data["_id"]))
current_app.logger.debug('ID: %s %s', data['_id'], ObjectId(data['_id']))
# Unknown request if no parameters
if database == None:
return Response("{\"error\" : \"Resource _id: %s doesnot exist\"}" % (resid), status=403)
# Create the database object from the supplied parameters
try:
database.label = data["label"]
database.host = data["host"]
database.dbname = data["dbname"]
database.copyright = data["copyright"]
database.username = data["username"]
database.password = data["password"]
if database._cls == "TileStore.Database.PtiffTileStore":
database.root_path = data["root_path"]
# Add additional fields
if "_cls" in data:
current_app.logger.debug('%s', data['_cls'])
database.save()
except Exception as inst:
# If valid database object cannot be constructed it is invalid request
return Response("{\"error\" : %s}" % str(inst), status=405)
return jsonify(database.to_mongo())
示例14: jsonifyBookmarks
def jsonifyBookmarks(db, dbid, viewid, viewobj):
# I do not think we can pass an array back.
val = {}
val["Bookmarks"] = []
if 'bookmarks' in viewobj :
for bookmarkId in viewobj["bookmarks"] :
bookmarkObj = db["bookmarks"].find_one({'_id': bookmarkId})
bookmark = bookmarkObj
bookmark["_id"] = str(bookmark["_id"])
bookmark["img"] = str(bookmark["img"])
val["Bookmarks"].append(bookmark)
return jsonify(val)
示例15: get
def get(self, restype, resid=None):
# Restype has to be between allowed ones or the request will not come here
if resid == None:
objs = conn[current_app.config["CONFIGDB"]][restype].find()
objarray = list()
for anobj in objs:
# Filter the list with passwd if type is user
if restype == "users":
if "passwd" in anobj:
del anobj["passwd"]
objarray.append(anobj)
return jsonify({ restype : objarray})
else:
obj = conn[current_app.config["CONFIGDB"]][restype].find_one({"_id" : ObjectId(resid)})
if obj :
if restype == "users":
if "passwd" in obj:
del obj["passwd"]
return jsonify(obj)
else:
return Response("{\"error\" : \"resource not found\"}" , status=405)