コード例 #1
0
ファイル: __init__.py プロジェクト: UmaW5RTC/JavaScript
    def get(self, itemid=None):
        a = None
        if ObjectId.is_valid(itemid):
            itemid = ObjectId(itemid)
            a = self.model.find_one({"_id": itemid, "created.by": current_user.id})

        if a is None:
            pr = reqparse.RequestParser()
            pr.add_argument("surveyid", type=str, store_missing=False)
            pr.add_argument("surveyname", type=unicode, store_missing=False)
            args = pr.parse_args()
            sid = args.get("surveyid")
            sname = args.get("surveyname")

            if not sid and not sname:
                return jsonify({})

            if sname:
                surveyobj = self.db["SurveyDQ"].find_one({"name": sname})
                if surveyobj:
                    sid = str(surveyobj["_id"])
            if sid:
                if ObjectId.is_valid(sid):
                    a = self.model.find_one({"surveyid": ObjectId(sid),
                                             "created.by": current_user.id},
                                            sort=[("_id", pymongo.ASCENDING)])
                if not a:
                    a = self.model.find_one({"surveyname": sid,
                                             "created.by": current_user.id},
                                            sort=[("_id", pymongo.ASCENDING)])

        return jsonify(crudmgo.model_to_json(a, is_single=True) if a else {})
コード例 #2
0
ファイル: databox.py プロジェクト: Earthson/afewords_base
 def objs_gen(infos, depth=0, depth_lim=2):
     # print(depth)
     objs = list_generator(infos)
     if not objs:
         return objs
     if depth == depth_lim:
         return objs
     toget = []
     for each in objs:
         if each is None:
             continue
         for ev in each.cache_info.values():
             if not ObjectId.is_valid(ev[0]):
                 continue
             if ev[0] in oids:
                 continue
             toget.append(ev)
             oids.add(ObjectId(ev[0]))
     tmps = objs_gen(toget, depth + 1)  # get_obj
     for each in tmps:
         # add obj in tmps to pool
         if each is None:
             continue
         obj_pool[each._id] = each
     for each in objs:
         # add obj in obj_pool to objs
         if each is None:
             continue
         for ek, ev in each.cache_info.items():
             if not ObjectId.is_valid(ev[0]):
                 continue
             ev = ObjectId(ev[0])
             if ev in obj_pool:
                 each.set_cache(ek, obj_pool[ev])
     return objs
コード例 #3
0
ファイル: forum.py プロジェクト: 91ranjan/gstudio
def delete_thread(request,group_id,forum_id,node_id):
    """ Changing status of thread to HIDDEN
    """
    ins_objectid  = ObjectId()
    if ins_objectid.is_valid(node_id) : 
        thread=node_collection.one({'_id':ObjectId(node_id)})
    else:
        return
    forum = node_collection.one({'_id': ObjectId(forum_id)})
    if ins_objectid.is_valid(group_id) is False :
        group_ins = node_collection.find_one({'_type': "Group","name": group_id})
        auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
        if group_ins:
            group_id = str(group_ins._id)
        else :
            auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
            if auth :
                group_id = str(auth._id)
    else :
        pass
    op = node_collection.collection.update({'_id': ObjectId(node_id)}, {'$set': {'status': u"HIDDEN"}})

    node=node_collection.one({'_id':ObjectId(node_id)})
    forum_threads = []
    exstng_reply = node_collection.find({'$and':[{'_type':'GSystem'},{'prior_node':ObjectId(forum._id)}],'status':{'$nin':['HIDDEN']}})
    exstng_reply.sort('created_at')
    forum_node=node_collection.one({'_id':ObjectId(forum_id)})
    for each in exstng_reply:
        forum_threads.append(each.name)
    #send notifications to all group members
    colg=node_collection.one({'_id':ObjectId(group_id)})
    for each in colg.author_set:
        if each != colg.created_by:
            bx=get_userobject(each)
            if bx:
                activity=request.user.username+" -deleted thread "
                prefix=" in the forum "+forum_node.name
                link="http://"+sitename+"/"+str(colg._id)+"/forum/"+str(forum_node._id)
                msg=activity+"-"+node.name+prefix+"- in the group '"+colg.name+"' created by you."+"'\n"+"Please visit "+link+" to see the forum."  
#                no_check=forum_notification_status(group_id,auth._id)
#                if no_check:
                ret = set_notif_val(request,group_id,msg,activity,bx)
    activity=request.user.username+" -deleted thread "    
    prefix=" in the forum "+forum_node.name
    bx=get_userobject(colg.created_by)
    if bx:
        link="http://"+sitename+"/"+str(colg._id)+"/forum/"+str(forum_node._id)
        msg=activity+"-"+node.name+prefix+"- in the group '"+colg.name+"' created by you."+"'\n"+"Please visit "+link+" to see the forum."  
#        no_check=forum_notification_status(group_id,auth._id)
#        if no_check:
        ret = set_notif_val(request,group_id,msg,activity,bx)
    #send notification code ends here
    variables = RequestContext(request,{
                                        'forum':forum,
                                        'groupid':group_id,'group_id':group_id,
                                        'forum_created_by':User.objects.get(id=forum.created_by).username
                                        })

    return render_to_response("ndf/forumdetails.html",variables)
コード例 #4
0
ファイル: module.py プロジェクト: adityamangla/metaStudio
def delete_module(request, group_id, _id):
    """This method will delete module object and its Attribute and Relation
    """
    ins_objectid  = ObjectId()
    if ins_objectid.is_valid(group_id) is False :
        group_ins = collection.Node.find_one({'_type': "Group","name": group_id})
        auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
        if group_ins:
            group_id = str(group_ins._id)
        else :
            auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
            if auth :
                group_id = str(auth._id)
    else :
        pass
    pageurl = request.GET.get("next", "")
    try:
        node = collection.Node.one({'_id':ObjectId(_id)})
        if node:
            attributes = collection.Triple.find({'_type':'GAttribute','subject':node._id})
            relations = collection.Triple.find({'_type':'GRelation','subject':node._id})
            if attributes.count() > 0:
                for each in attributes:
                    collection.Triple.one({'_id':each['_id']}).delete()
                    
            if relations.count() > 0:
                for each in relations:
                    collection.Triple.one({'_id':each['_id']}).delete()
            node.delete()
    except Exception as e:
        print "Exception:", e
    return HttpResponseRedirect(pageurl) 
コード例 #5
0
ファイル: file.py プロジェクト: adityamangla/metaStudio
def delete_file(request, group_id, _id):
  """Delete file and its data
  """
  ins_objectid  = ObjectId()
  if ins_objectid.is_valid(group_id) is False :
      group_ins = collection.Node.find_one({'_type': "Group","name": group_id})
      auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
      if group_ins:
          group_id = str(group_ins._id)
      else :
          auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
          if auth :
              group_id = str(auth._id)
  else :
      pass
  file_collection = db[File.collection_name]
  auth = collection.Node.one({'_type': u'Group', 'name': unicode(request.user.username) })
  pageurl = request.GET.get("next", "")
  try:
    cur = file_collection.File.one({'_id':ObjectId(_id)})
    rel_obj = collection.GRelation.one({'subject': ObjectId(auth._id), 'right_subject': ObjectId(_id) })
    if rel_obj :
        rel_obj.delete()
    if cur.fs_file_ids:
        for each in cur.fs_file_ids:
            cur.fs.files.delete(each)
    cur.delete()
  except Exception as e:
    print "Exception:", e
  return HttpResponseRedirect(pageurl) 
コード例 #6
0
    def find(cls, name_or_oid, access_token=None):
        logging.info('loading query %s', name_or_oid)

        user = getattr(session, 'user', None)

        if not user and not access_token:
            raise Exception('Missing user')

        if not name_or_oid:
            return None

        if ObjectId.is_valid(name_or_oid):
            filter = db.Q(pk = name_or_oid) | db.Q(name = name_or_oid)
        else:
            filter = db.Q(name = name_or_oid)

        if not access_token:
            filter = filter & (db.Q(owner=user) | db.Q(editors = user))

        try:
            query = cls.objects.get(filter)
        except DoesNotExist:
            query = None

        if query and access_token and access_token != query.access_token:
            return None

        return query
コード例 #7
0
def video_detail(request, group_id, _id):
    ins_objectid  = ObjectId()
    if ins_objectid.is_valid(group_id) is False :
        group_ins = collection.Node.find_one({'_type': "Group","name": group_id})
        auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
        if group_ins:
            group_id = str(group_ins._id)
        else :
            auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
            if auth :
                group_id = str(auth._id)
    else :
        pass
    vid_node = collection.File.one({"_id": ObjectId(_id)})
    if vid_node._type == "GSystemType":
	return videoDashboard(request, group_id, _id)
    video_obj=request.GET.get("vid_id","")
    return render_to_response("ndf/video_detail.html",
                                  { 'node': vid_node,
                                    'group_id': group_id,
                                    'groupid':group_id,
                                    'video_obj':video_obj
                                  },
                                  context_instance = RequestContext(request)
        )
コード例 #8
0
ファイル: __init__.py プロジェクト: UmaW5RTC/JavaScript
    def put(self):
        pr = restful.reqparse.RequestParser()
        pr.add_argument("id", type=str, store_missing=False)
        pr.add_argument("order", type=int, store_missing=False)
        args = pr.parse_args()

        if args.get("order") and args["order"] > 0 and args.get("id") and ObjectId.is_valid(args["id"]):
            m = self.model.find_one({"_id": ObjectId(args["id"])})
            if m.get("order", 0) == args["order"]:
                return jsonify(success=True)
            if m.get("order"):
                self.model.collection.update({"order": {"$gt": m["order"]},
                                              "parent": m.get("parent"),
                                              "lang": m.get("lang")},
                                             {"$inc": {"order": -1}},
                                             multi=True)
            self.model.collection.update({"order": {"$gte": args["order"]},
                                          "parent": m.get("parent"),
                                          "lang": m.get("lang")},
                                         {"$inc": {"order": 1}},
                                         multi=True)
            self.model.collection.update({"_id": ObjectId(args["id"])},
                                         {"$set": {"order": args["order"]}})
            return jsonify(success=True)
        return jsonify(success=False)
コード例 #9
0
ファイル: Bib_App.py プロジェクト: 91ranjan/gstudio
def view_sentry(request,group_id,node_id):
    ''' for displaying a specific entry
    '''
    ins_objectid=ObjectId()
    if ins_objectid.is_valid(group_id) is False:
        group_ins = collection.Node.find_one({'_type': "Group","name": group_id})
        auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
        if group_ins:
            group_id = str(group_ins._id)
        else :
            auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
            if auth :
                group_id = str(auth._id)
    else :
        pass
    GST_SENTRY=collection.Node.one({'_id':ObjectId(node_id)})
    GST_one=collection.Node.one({'_type':'AttributeType','name':'BibTex_entry'})
    gst_bibtex=GST_SENTRY.member_of
    ''' converts [ObjectId('node_id')] to node_id
    '''
    s=str(gst_bibtex)
    list(s)
    gst_bibtex=(s[11:-3])
    gst_bibtex=unicode(gst_bibtex, "UTF-8")
    gst_bibtex=collection.Node.one({'_id':ObjectId(gst_bibtex)})
    gst_id=GST_SENTRY._id
    GST_SAttribute=collection.Node.one({'subject':GST_SENTRY._id,'attribute_type.$id':GST_one._id})
    Bibtex=GST_SAttribute.object_value
    gst_note=GST_SENTRY.content_org
    variable=RequestContext(request,{'name':GST_SENTRY.name,'gst_note':gst_note,'Bibtex':Bibtex,'group_id':group_id,'groupid':group_id,'title':gst_bibtex.name})
    template="ndf/view_sentry.html"
    print "before return"
    return render_to_response(template,variable)
コード例 #10
0
ファイル: group.py プロジェクト: adityamangla/metaStudio
def edit_group(request,group_id):
    ins_objectid  = ObjectId()
    if ins_objectid.is_valid(group_id) is False :
	group_ins = collection.Node.find_one({'_type': "Group","name": group_id}) 
        auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) }) 
	if group_ins:
	    group_id = str(group_ins._id)
	else :
	    auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
	    if auth :
	    	group_id = str(auth._id)	
    else :
	pass
    page_node = gs_collection.GSystem.one({"_id": ObjectId(group_id)})

    if request.method == "POST":
            get_node_common_fields(request, page_node, group_id, gst_group)
            if page_node.access_policy == "PUBLIC":
                page_node.group_type = "PUBLIC"
            if page_node.access_policy == "PRIVATE":
                
                page_node.group_type = "PRIVATE"
            page_node.save()
            group_id=page_node._id
            return HttpResponseRedirect(reverse('groupchange', kwargs={'group_id':group_id}))
    page_node,ver=get_page(request,page_node)

    return render_to_response("ndf/edit_group.html",
                                      { 'node': page_node,
                                        'groupid':group_id,
                                        'group_id':group_id
                                        },
                                      context_instance=RequestContext(request)
                                      )
コード例 #11
0
ファイル: power.py プロジェクト: UmaW5RTC/JavaScript
    def update_raw(self, data):
        self["id"] = data.get("id", self.get("id"))
        self["name"] = data.get("name", self.get("name"))
        self["code"] = data.get("code", self.get("code"))
        self["power"] = data.get("power", self.get("power"))
        self["power_id"] = data.get("power_id", self.get("power_id"))

        if self["power_id"] and ObjectId.is_valid(self["power_id"]):
            self["power_id"] = ObjectId(self["power_id"])
            power = self.collection.database["Power"].find_one({"_id": self["power_id"]})
            if power:
                self["power"] = power["name"]

        selcompetencies = data.getlist("selcompetency")
        if selcompetencies and isinstance(selcompetencies, list) and selcompetencies[0] is not None:
            self["selcompetency"] = selcompetencies
            for i in xrange(len(self["selcompetency"])):
                self["selcompetency"][i] = ObjectId(self["selcompetency"][i])

        cwtopics = data.getlist("cwtopic")
        if cwtopics and isinstance(cwtopics, list) and cwtopics[0] is not None:
            self["cwtopic"] = cwtopics
            for i in xrange(len(self["cwtopic"])):
                self["cwtopic"][i] = ObjectId(self["cwtopic"][i])

        cwvalues = data.getlist("cwvalue")
        if cwvalues and isinstance(cwvalues, list) and cwvalues[0] is not None:
            self["cwvalue"] = cwvalues
            for i in xrange(len(self["cwvalue"])):
                self["cwvalue"][i] = ObjectId(self["cwvalue"][i])

        self["level"] = int(data.get("level", self.get("level", 1)))
        self["time"] = int(data.get("time", self.get("time", 5)))
        self["objective"] = data.get("objective", self.get("objective"))
コード例 #12
0
ファイル: encyclopedia.py プロジェクト: UmaW5RTC/JavaScript
 def update_parent(self, value):
     if isinstance(value, ObjectId):
         self['parent'] = value
     elif ObjectId.is_valid(value):
         self['parent'] = ObjectId(value)
     elif value is None:
         self['parent'] = None
コード例 #13
0
def bitcoin_callback(payment_id, secret):
    return_text = ""
    if not ObjectId.is_valid(payment_id):
        return 'Invalid ObjectID', 400
    input_address = request.args['input_address']
    destination_address = request.args['destination_address']
    transaction_hash = request.args['transaction_hash']
    input_transaction_hash = request.args['input_transaction_hash']
    confirmations = int(request.args['confirmations'])
    value = int(request.args['value'])

    item = get('payments/{0}?callback=bitcoin\
&input_address={1}\
&destination_address={2}\
&transaction_hash={3}\
&input_transaction_hash={4}\
&confirmations={5}\
&value={6}\
&secret={7}'.format(payment_id, input_address, destination_address, transaction_hash, input_transaction_hash, confirmations, value, secret))

    #print (item)
    #print (item['_status'])
    #print (r.status_code)
    if '_status' in item and item['_status']=='ERR':
        return '', 400
    else:
        resp = make_response('*ok*', 200)
        resp.mimetype = 'text/plain'
        return resp
コード例 #14
0
ファイル: notes.py プロジェクト: a-stringfield/mininote
def edit_note(note_id):
    user_obj = model.User.objects(username=login.username())[0]

    if not ObjectId.is_valid(note_id):
        abort(400)
    if not model.Note.objects(pk=note_id, author=user_obj):
        abort(404)

    try:
        body = request.json['body']
        subject = request.json['subject']
    except:
        abort(400)

    if body != '':
        model.Note.objects(pk=note_id, author=user_obj)[0].update(set__body=body)
    if subject != '':
        model.Note.objects(pk=note_id, author=user_obj)[0].update(set__subject=subject)

    model.Note.objects(pk=note_id, author=user_obj)[0].update(set__modification_time=datetime.now())

    return jsonify({
        'success': True,
        'message': 'Note was edited',
        'data': None
        })
コード例 #15
0
ファイル: forum.py プロジェクト: adityamangla/metaStudio
def display_forum(request,group_id,forum_id):
    
    forum = collection.Node.one({'_id': ObjectId(forum_id)})

    usrname = User.objects.get(id=forum.created_by).username

    ins_objectid  = ObjectId()
    if ins_objectid.is_valid(group_id) is False :
        group_ins = collection.Node.find_one({'_type': "Group","name": group_id})
        auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
        if group_ins:
            group_id = str(group_ins._id)
        else :
            auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
            if auth :
                group_id = str(auth._id)
    else :
        pass
    forum_object = collection.Node.one({'_id': ObjectId(forum_id)})
    if forum_object._type == "GSystemType":
       return forum(request, group_id, forum_id)

    variables=RequestContext(request,{'forum':forum,'groupid':group_id,'group_id':group_id, 'forum_created_by':usrname})

    return render_to_response("ndf/forumdetails.html",variables)
コード例 #16
0
ファイル: Bib_App.py プロジェクト: 91ranjan/gstudio
def delete_sentry(request, group_id, node_id):
    """Change the status to Hidden.
    """
    ins_objectid  = ObjectId()
    if ins_objectid.is_valid(group_id) is False :
        group_ins = collection.Node.find_one({'_type': "Group","name": group_id})
        auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
        if group_ins:
            group_id = str(group_ins._id)
        else :
            auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
            if auth :
                group_id = str(auth._id)
    else :
        pass
    gst_entry=collection.Node.one({'_id':ObjectId(node_id)})
    gst_bibtex=gst_entry.member_of
    ''' converts [ObjectId('node_id')] to node_id
    '''
    s=str(gst_bibtex)
    list(s)
    gst_bibtex=(s[11:-3])
    gst_bibtex=unicode(gst_bibtex, "UTF-8")
    op = collection.update({'_id': ObjectId(node_id)}, {'$set': {'status': u"HIDDEN"}})
    
    return HttpResponseRedirect(reverse('view_entry', kwargs={'group_id': group_id,'node_id':gst_bibtex}))
コード例 #17
0
ファイル: group.py プロジェクト: adityamangla/metaStudio
def publish_group(request,group_id,node):
  ins_objectid  = ObjectId()
  if ins_objectid.is_valid(group_id) is False :
	group_ins = collection.Node.find_one({'_type': "Group","name": group_id}) 
        auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) }) 
	if group_ins:
	    group_id = str(group_ins._id)
	else :
	    auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
	    if auth :
	    	group_id = str(auth._id)	
  else :
	pass

  node=collection.Node.one({'_id':ObjectId(node)})
   
  page_node,v=get_page(request,node)
  
  node.content = page_node.content
  node.content_org=page_node.content_org
  node.status=unicode("PUBLISHED")
  node.modified_by = int(request.user.id)
  node.save() 
 
  return render_to_response("ndf/groupdashboard.html",
                                 { 'group_id':group_id,
                                   'node':node,
                                   'groupid':group_id
                                 },
                                  context_instance=RequestContext(request)
                              )
コード例 #18
0
ファイル: articles.py プロジェクト: nickenilsson/wishlistAPI
 def put(self, article_id):
     if not ObjectId.is_valid(article_id):
         raise tornado.web.HTTPError(400, 'Invalid ObjectId : {0}'.format(article_id))
     article = self.get_article_from_args()
     article['_id'] = article_id
     self.db_helper.update_article(article)
     self.respond_ok()
コード例 #19
0
ファイル: forum.py プロジェクト: adityamangla/metaStudio
def display_thread(request,group_id, thread_id, forum_id=None):
    ins_objectid  = ObjectId()
    if ins_objectid.is_valid(group_id) is False :
        group_ins = collection.Node.find_one({'_type': "Group","name": group_id})
        auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
        if group_ins:
            group_id = str(group_ins._id)
        else :
            auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
            if auth :
                group_id = str(auth._id)
    else :
        pass
    try:
        thread = collection.Node.one({'_id': ObjectId(thread_id)})
        forum=""
        for each in thread.prior_node:
            forum=collection.GSystem.one({'$and':[{'member_of': {'$all': [forum_st._id]}},{'_id':ObjectId(each)}]})
            if forum:
                usrname = User.objects.get(id=forum.created_by).username
                variables = RequestContext(request,
                                            {   'forum':forum,
                                                'thread':thread,
                                                'groupid':group_id,
                                                'group_id':group_id,
                                                'eachrep':thread,
                                                'user':request.user,
                                                'forum_created_by':usrname
                                            })
                return render_to_response("ndf/thread_details.html",variables)
    except:
        pass
コード例 #20
0
ファイル: file.py プロジェクト: adityamangla/metaStudio
def file_edit(request,group_id,_id):
    ins_objectid  = ObjectId()
    if ins_objectid.is_valid(group_id) is False :
        group_ins = collection.Node.find_one({'_type': "Group","name": group_id})
        auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
        if group_ins:
            group_id = str(group_ins._id)
        else :
            auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
            if auth :
                group_id = str(auth._id)
    else :
        pass

    file_node = collection.File.one({"_id": ObjectId(_id)})

    if request.method == "POST":
        get_node_common_fields(request, file_node, group_id, GST_FILE)
        file_node.save()
        return HttpResponseRedirect(reverse('file_detail', kwargs={'group_id': group_id, '_id': file_node._id}))
        
    else:
        return render_to_response("ndf/document_edit.html",
                                  { 'node': file_node,
                                    'group_id': group_id,
                                    'groupid':group_id
                                },
                                  context_instance=RequestContext(request)
                              )
コード例 #21
0
def imageDashboard(request, group_id, image_id=None):
    '''
    fetching image acording to group name
    '''
    ins_objectid  = ObjectId()
    if ins_objectid.is_valid(group_id) is False :
        group_ins = collection.Node.find_one({'_type': "Group","name": group_id})
        auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
        if group_ins:
            group_id = str(group_ins._id)
        else :
            auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
            if auth :
                group_id = str(auth._id)
    else :
        pass
    if image_id is None:
        image_ins = collection.Node.find_one({'_type':"GSystemType", "name":"Image"})
        if image_ins:
            image_id = str(image_ins._id)
    img_col= collection.GSystem.find({'member_of': {'$all': [ObjectId(image_id)]},'_type':'File', 'group_set': {'$all': [ObjectId(group_id)]}})
    template = "ndf/ImageDashboard.html"
    already_uploaded=request.GET.getlist('var',"")
    variable = RequestContext(request, {'imageCollection': img_col,'already_uploaded':already_uploaded,'groupid':group_id,'group_id':group_id })
    return render_to_response(template, variable)
コード例 #22
0
ファイル: page.py プロジェクト: adityamangla/metaStudio
def publish_page(request,group_id,node):
    ins_objectid  = ObjectId()
    if ins_objectid.is_valid(group_id) is False :
        group_ins = collection.Node.find_one({'_type': "Group","name": group_id})
        auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
        if group_ins:
            group_id = str(group_ins._id)
        else :
            auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
            if auth :
                group_id = str(auth._id)
    else :
        pass

    node=collection.Node.one({'_id':ObjectId(node)})
    group=collection.Node.one({'_id':ObjectId(group_id)})
    if group.post_node:
        node.status=unicode("PUBLISHED")
        node.save('UnderModeration')
    else:
        page_node,v=get_page(request,node)
        node.content = page_node.content
        node.content_org=page_node.content_org
        node.status=unicode("PUBLISHED")
        node.modified_by = int(request.user.id)
        node.save() 
    #no need to use this section as seprate view is created for group publish
    #if node._type == 'Group':
    # return HttpResponseRedirect(reverse('groupchange', kwargs={'group_id': group_id}))    

    return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': node._id}))
コード例 #23
0
ファイル: observation.py プロジェクト: 91ranjan/gstudio
def save_image(request, group_id, app_id=None, app_name=None, app_set_id=None, slug=None):

    if request.method == "POST" :
        
        for index, each in enumerate(request.FILES.getlist("doc[]", "")):

            title = each.name
            userid = request.POST.get("user", "")
            content_org = request.POST.get('content_org', '')
            tags = request.POST.get('tags', "")
            img_type = request.POST.get("type", "")
            language = request.POST.get("lan", "")
            usrname = request.user.username
            page_url = request.POST.get("page_url", "")
            access_policy = request.POST.get("login-mode", '') # To add access policy(public or private) to file object

            # for storing location in the file
            
            # location = []
            # location.append(json.loads(request.POST.get("location", "{}")))
            # obs_image = save_file(each,title,userid,group_id, content_org, tags, img_type, language, usrname, access_policy, oid=True, location=location)

            obs_image = save_file(each,title,userid,group_id, content_org, tags, img_type, language, usrname, access_policy, oid=True)
            # Sample output of (type tuple) obs_image: (ObjectId('5357634675daa23a7a5c2900'), 'True') 

            # if image sucessfully get uploaded then it's valid ObjectId
            if obs_image[0] and ObjectId.is_valid(obs_image[0]):

            	return StreamingHttpResponse(str(obs_image[0]))
            
            else: # file is not uploaded sucessfully or uploaded with error
            	
            	return StreamingHttpResponse("UploadError")	
コード例 #24
0
ファイル: file.py プロジェクト: adityamangla/metaStudio
def readDoc(request, _id, group_id, file_name = ""):
    '''Return Files 
    '''
    ins_objectid  = ObjectId()
    if ins_objectid.is_valid(group_id) is False :
        group_ins = collection.Node.find_one({'_type': "Group","name": group_id})
        auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
        if group_ins:
            group_id = str(group_ins._id)
        else :
            auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
            if auth :
                group_id = str(auth._id)
    else :
        pass

    file_node = collection.File.one({"_id": ObjectId(_id)})
    if file_node is not None:
        if file_node.fs_file_ids:
            if (file_node.fs.files.exists(file_node.fs_file_ids[0])):
                grid_fs_obj = file_node.fs.files.get(ObjectId(file_node.fs_file_ids[0]))
                return HttpResponse(grid_fs_obj.read(), content_type = grid_fs_obj.content_type)
            else:
                return HttpResponse("")
        else:
            return HttpResponse("")
    else:
        return HttpResponse("")
コード例 #25
0
ファイル: mongodb.py プロジェクト: Dogild/garuda
    def get(self, user_identifier, resource_name, identifier=None, filter=None):
        """
        """
        if identifier and not ObjectId.is_valid(identifier):
            return GAStoragePluginQueryResponse.init_with_error(error_type=GAError.TYPE_NOTFOUND,
                                                                title='Resource not found',
                                                                description='Could not find resource')

        query_filter = {}
        if filter:
            try:
                query_filter = self._predicate_converter.convert(filter)
            except SyntaxError:
                return GAStoragePluginQueryResponse(data=[], count=0)

        if identifier:
            data = self.db[resource_name].find_one({'$and': [{'_id': ObjectId(identifier)}, query_filter]})
        else:
            data = self.db[resource_name].find_one(query_filter)

        if not data:
            return GAStoragePluginQueryResponse.init_with_error(error_type=GAError.TYPE_NOTFOUND,
                                                                title='Resource not found',
                                                                description='Could not find resource')

        obj = self.instantiate(resource_name)
        obj.from_dict(self._convert_from_dbid(data))

        if not self.permissions_controller.has_permission(resource=user_identifier, target=obj, permission='read'):
            return GAStoragePluginQueryResponse.init_with_error(error_type=GAError.TYPE_UNAUTHORIZED,
                                                                title='Permission Denied',
                                                                description='You do not have permission to access this object')

        return GAStoragePluginQueryResponse.init_with_data(data=obj)
コード例 #26
0
ファイル: file.py プロジェクト: adityamangla/metaStudio
def getFileThumbnail(request, group_id, _id):
    """Returns thumbnail of respective file
    """
    ins_objectid  = ObjectId()
    if ins_objectid.is_valid(group_id) is False :
        group_ins = collection.Node.find_one({'_type': "Group","name": group_id})
        auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
        if group_ins:
            group_id = str(group_ins._id)
        else :
            auth = collection.Node.one({'_type': 'Author', 'name': unicode(request.user.username) })
            if auth :
                group_id = str(auth._id)
    else :
        pass

    file_node = collection.File.one({"_id": ObjectId(_id)})

    if file_node is not None:
        if file_node.fs_file_ids:
            if (file_node.fs.files.exists(file_node.fs_file_ids[1])):
                f = file_node.fs.files.get(ObjectId(file_node.fs_file_ids[1]))
                return HttpResponse(f.read(), content_type=f.content_type)
            else:
                return HttpResponse("")
        else:
            return HttpResponse("")
    else:
        return HttpResponse("")
コード例 #27
0
ファイル: __init__.py プロジェクト: UmaW5RTC/JavaScript
    def get(self, answerid=None):
        a = None
        if ObjectId.is_valid(answerid):
            answerid = ObjectId(answerid)
            a = self.model.find_one({"_id": answerid, "created.by": current_user.id})

        if a is None:
            pr = reqparse.RequestParser()
            pr.add_argument("surveyid", type=str, store_missing=False)
            pr.add_argument("missionid", type=str, store_missing=False)
            pr.add_argument("messenger", type=int, store_missing=False)
            pr.add_argument("nocreate", type=int, store_missing=False)
            args = pr.parse_args()

            surveyid = None
            missionid = None

            if args.get("messenger"):
                args["surveyname"] = args["surveyid"]
            elif not ObjectId.is_valid(args.get("surveyid")):
                return jsonify({})
            else:
                surveyid = ObjectId(args["surveyid"])

            if ObjectId.is_valid(args.get("missionid")):
                missionid = ObjectId(args["missionid"])
                d = {"missionid": missionid, "created.by": current_user.id}
                if surveyid:
                    d["surveyid"] = surveyid
                else:
                    d["surveyname"] = args["surveyname"]
                a = self.model.find_one(d)
            elif args.get("messenger"):
                return jsonify(success=False)

            if a is None and not args.get("nocreate"):
                a = self.model()
                a["surveyid"] = surveyid or ObjectId()
                a["missionid"] = missionid or ObjectId()
                a["surveyname"] = args.get("surveyname")
                a["answers"] = []
                a["meta"] = {}
                if not missionid or args.get("messenger"):
                    a["meta"]["not_mission"] = True
                a.save()

        return jsonify(crudmgo.model_to_json(a, is_single=True) if a is not None else {})
コード例 #28
0
    def post(self, wishlist_id):

        if not ObjectId.is_valid(wishlist_id):
            raise tornado.web.HTTPError(400, 'Invalid ObjectId')
        user = self.get_current_user()
        article = self.get_article_from_args()

        article_id = self.db_helper.add_article_to_list(article, user['_id'], wishlist_id)
        self.write({'response':{'message':'Article created successfully!', 'article_id': article_id}})
コード例 #29
0
ファイル: __init__.py プロジェクト: UmaW5RTC/JavaScript
    def get(self):
        pr = restful.reqparse.RequestParser()
        pr.add_argument("power", type=str, store_missing=False)
        args = pr.parse_args()

        if args.get("power") and ObjectId.is_valid(args["power"]):
            self.filter_by = {"power_id": ObjectId(args["power"])}

        return super(MissionList, self).get()
コード例 #30
0
ファイル: __init__.py プロジェクト: zjiee/mongorm
def pb2_type_to_mongo_type(field, field_type, value):
    """将python类型转为mongodb类型"""
    if field == "_id":
        return ObjectId(value) if ObjectId.is_valid(value) else value

    if field_type == FieldDescriptor.TYPE_BYTES:
        value = Binary(value)

    return value
コード例 #31
0
    def on_put(self, req, resp):
        ''' Issues Controller Put Request Method '''

        if 'id' in req.params and ObjectId.is_valid(req.params['id']):
            try:
                issue = Issue.objects(id=req.params['id'])[0]
                if hasattr(req, 'json') and 'title' in req.json:
                    issue.title = req.get_json('title')
                if hasattr(req, 'json') and 'description' in req.json:
                    issue.description = req.get_json('description')
                if hasattr(req, 'json') and 'author' in req.json:
                    issue.author = ObjectId(req.get_json('author'))
                if hasattr(req, 'json') and 'resolved_by' in req.json:
                    issue.resolved_by = ObjectId(req.get_json('resolved_by'))
                issue.save()
                resp.json = issue.to_json()
            except Exception:
                resp.status = falcon.HTTP_400
                resp.json = {
                    "message":
                    "Issue id: %s not found in database!" % req.params['id']
                }
コード例 #32
0
    def on_delete(self, req, resp):
        ''' City Controller Delete Request Method '''

        # If ?id= is in url and value for id is valid ObjectId
        if 'id' in req.params and ObjectId.is_valid(req.params['id']):

            # Find document by Id and delete it
            res = City.objects(id=req.params['id']).delete()

            # If document was deleted, send success message
            # in json - otherwise send error message
            if res == 1:
                resp.json = {
                    "message":
                    "City id: %s deleted successfully!" % req.params['id']
                }
            else:
                resp.status = falcon.HTTP_400
                resp.json = {
                    "message":
                    "City id: %s not in database!" % req.params['id']
                }
コード例 #33
0
def update():
    access_status = judging_permissions('2_1_2')
    if access_status.get('code') != 200:
        return jsonify(access_status)
    _update = {}
    data = {key: dict(request.form)[key][0] for key in dict(request.form)}
    if not data:
        data = request.get_json()
    _id = data.get('_id')
    if not _id or not ObjectId.is_valid(_id):
        return jsonify({'code': 201, 'msg': u'参数错误'})
    _obj = income.find_one({'_id': ObjectId(_id)})
    if not _obj:
        return jsonify({'code': 202, 'msg': u'不存在'})
    for key in default_values:
        if key in data:
            _values = data.get(key)
            if _values:
                # if isinstance(_values, str) or isinstance(_values, unicode):
                if isinstance(_values, str):
                    _values = _values.strip()
                if key in int_key:
                    try:
                        _values = int(_values)
                    except:
                        return jsonify({'code': 201, 'msg': u'参数错误'})
                if _obj.get(key) != _values:
                    if key == 'password':
                        _values = generate_password_hash(_values)
                    _update.update({key: _values})
    if _update:
        try:
            income.update_one({'_id': ObjectId(_id)}, {'$set': _update})
            return jsonify({'code': 200, 'msg': u'成功'})
        except:
            pass
    else:
        return jsonify({'code': 203, 'msg': u'无更新数据'})
    return jsonify({'code': 204, 'msg': u'失败'})
コード例 #34
0
    def get(self, user):

        # step 1: check if wishlist is empty
        wishlist = user['wishlist']

        # step 2: query all furniture_ids to get details
        furnitures_json = []
        for furniture_id in wishlist:

            furniture = find_furniture_by_id(furniture_id)

            # Error checking
            if not ObjectId.is_valid(furniture_id) or furniture is None:
                continue
            try:
                product_name = furniture['furniture_name']
                category = furniture['category']
                images = furniture['images']
                price = furniture['price']

                furnitures_json.append({
                    'furniture_name': product_name,
                    'category': category,
                    'product_image': images,
                    'price': price,
                    'furniture_id': furniture_id
                })
            except KeyError:
                continue

        if not furnitures_json:
            return jsonify({"status": 613, "msg": "Empty wishlist"})

        # step 3: return json representation of furnitures
        return jsonify({
            "status": 200,
            "msg": "get wishlist succeeded",
            "result": json.dumps(furnitures_json)
        })
コード例 #35
0
 def get(self):
     survey_id = request.args.get('id')
     try:
         time = int(request.args.get('time'))
     except (ValueError, TypeError):
         return jsonify(code=0, msg='参数格式错误。')
     if not survey_id or time < 1 or time > 999 or not ObjectId.is_valid(survey_id):
         return jsonify(code=0, msg='参数格式错误。')
     try:
         result = mongo.db.surveys.count_documents({'_id': ObjectId(survey_id)})
         if result != 1:
             return jsonify(code=0, msg='未查询到该问卷。')
         end_date = datetime.now() + timedelta(days=time)
         # end_date = Cryptor(KEY).encrypt('{}-{}-{}'.format(end_date.year, end_date.month, end_date.day))
         end_date = AESCryptor(KEY1).encrypt(end_date.strftime('%Y-%m-%d'))
         url = '{}/surveys?id={}&token={}'.format(DOMAIN, survey_id, end_date)
         out = BytesIO()
         make(url).save(out, format='png')
         out.seek(0)
         return jsonify(code=1, msg='分享成功。', data=b64encode(out.read()).decode(), url=url)
     except Exception as e:
         return jsonify(code=0, msg=str(e))
コード例 #36
0
ファイル: logistic.py プロジェクト: quanpower/xielaoban
def restruct_query(data):
    format_date = lambda d: datetime.datetime.strptime(
        d, '%Y-%m-%dT%H:%M:%S.%fZ')
    status = data.get('status')
    query = {}
    for k, v in data.items():
        if v in [None, u"None", "", "null"]: continue
        if k[-3:] == '_no':
            query.update({'detail__%s' % k: v})
        elif k in ['status']:
            query.update({'detail__%s' % k: v})
        elif k == 'start':
            if status:
                date_field = Models.LogisticDetail.attr_by_log_stat[status]
                query.update({'detail__%s__gte' % date_field: format_date(v)})
            else:
                query.update({'created_at__gte': format_date(v)})
        elif k == 'end':
            if status:
                date_field = Models.LogisticDetail.attr_by_log_stat[status]
                query.update({'detail__%s__lt' % date_field: format_date(v)})
            else:
                query.update({'created_at__lt': format_date(v)})
        elif k == 'query':
            if v.startswith('MB'):
                query.update({'detail__partner_tracking_no': v})
            elif ObjectId.is_valid(v):
                query.update({'id': v})
            else:
                query.update({'tracking_no': v})
        elif k == 'partner':
            partner = Models.Partner.objects(name=v).first()
            query.update({'detail__partner': partner})
        elif k == 'channel':
            query.update({'detail__channel': v})
        else:
            query.update({'%s' % k: v})

    return query
コード例 #37
0
def update_todo(oid):
    if not ObjectId.is_valid(oid):
        return Response({'message': 'Invalid ObjectId'}, 400)
    oid = ObjectId(oid)
    record = mongo.db.todos.find_one({'_id': oid})
    if record is None:
        return Response({'message': 'TODO not found'}, 404)

    data = request.get_json(force=True)
    text = data.get('text')
    completed = data.get('completed')
    upd = {}
    if text is not None:
        upd['text'] = text

    if completed is not None:
        upd['completed'] = completed

    if len(upd) != 0:
        mongo.db.todos.update_one({'_id': oid}, upd)

    return {'message': 'Success'}
コード例 #38
0
def delete_module():
    """Delete a module from the database

    Deletes the module and all of it quizzes from the database.
    Must also adjust the it's parents and/or children. Can use
    either objectId or the module name

    query parameter: /module?input=input
    input can be an objectId or a module name

    :rtype: None
    """
    input_ = request.args.get('input')
    if ObjectId.is_valid(input_):
        o = Module.objects.get_or_404(id=input_)
    else:
        o = Module.objects.get_or_404(module_name=input_)
        print(o.quiz)
    for e in o.quiz:
        e.delete()
    o.delete()
    return Response('Success', 200)
コード例 #39
0
def update():
    _update = {}
    data = {key: dict(request.form)[key][0] for key in dict(request.form)}
    if not data:
        data = request.get_json()
    _id = data.get('_id')
    if not _id or not ObjectId.is_valid(_id):
        return jsonify({'code': 201, 'msg': u'参数错误'})
    _obj = admin_user.find_one({'_id': ObjectId(_id)})
    if not _obj:
        return jsonify({'code': 202, 'msg': u'不存在'})
    for key in default_values:
        if key in data:
            _values = data.get(key)
            if _values:
                # if isinstance(_values, str) or isinstance(_values, unicode):
                if isinstance(_values, str):
                    _values = _values.strip()
                if key in int_key:
                    try:
                        _values = int(_values)
                    except:
                        return jsonify({'code': 201, 'msg': u'参数错误'})
                if _obj.get(key) != _values:
                    if key == 'password':
                        _values = generate_password_hash(_values)
                    _update.update({key: _values})

    if _update:
        _update.update({'updated_time': timestamp_to_strftime(time.time())})
        try:
            admin_user.update_one({'_id': ObjectId(_id)}, {'$set': _update})
            return jsonify({'code': 200, 'msg': u'成功'})
        except:
            pass
    else:
        return jsonify({'code': 203, 'msg': u'无更新数据'})
    return jsonify({'code': 204, 'msg': u'失败'})
コード例 #40
0
def update():
    access_status = judging_permissions('2_1_2')
    if access_status.get('code') != 200:
        return jsonify(access_status)
    _update = {}
    data = get_request_params()
    _id = data.get('_id')
    if not ObjectId.is_valid(_id):
        return jsonify({'code': 202, 'msg': u'参数错误'})
    _obj = bulletin_notice.find_one({'_id': ObjectId(_id)})
    if not _obj:
        return jsonify({'code': 202, 'msg': u'参数错误'})
    for key in default_values:
        if key == 'user_num':
            continue
        _values = data.get(key, '')
        # if isinstance(_values, str) or isinstance(_values, unicode):
        if isinstance(_values, str):
            _values = _values.strip()

        if key in int_key:
            try:
                _values = int(_values)
            except:
                return jsonify({'code': 201, 'msg': u'参数错误'})
        if _obj.get(key) != _values:
            _update.update({key: _values})
    if _update:
        try:
            _update.update({
                'created_time':
                datetime.now().strftime(format='%Y-%m-%d %H:%M:%S')
            })
            bulletin_notice.update({'_id': _obj.get('_id')}, {'$set': _update})
            bulletin_notice.update_many({}, {'$set': {'user_num': 0}})
        except:
            return jsonify({'code': 203, 'msg': u'修改失败'})
    return jsonify({'code': 200, 'msg': u'success'})
コード例 #41
0
ファイル: users.py プロジェクト: Safoniks/aiohttp-proj
    async def post(self, **kw):
        me = self.request.user
        user_id = self.request.match_info.get('user_id', None)

        if not ObjectId.is_valid(user_id):
            raise InvalidUserId

        user = await User.find_one({'_id': ObjectId(user_id)})
        if user is None:
            raise NoSuchUser

        users_relationship = await UserRelationship.find_one({
            '$or': [
                {
                    'from_user': ObjectId(me.pk),
                    'to_user': ObjectId(user_id)
                },
                {
                    'from_user': ObjectId(user_id),
                    'to_user': ObjectId(me.pk)
                },
            ]
        })

        if users_relationship is not None:
            if users_relationship['status'] == 'blocked':
                raise UserAlreadyBlocked
            users_relationship.from_user = me.pk
            users_relationship.to_user = user.pk
            users_relationship.status = 'blocked'
        else:
            users_relationship = UserRelationship(from_user=me.pk,
                                                  to_user=user.pk,
                                                  status='blocked',
                                                  date=datetime.utcnow())

        await users_relationship.commit()
        raise Ok
コード例 #42
0
    def get(self, id):
        """Get All/Semi datas from database

        ...

        Parameters
        ----------
        id : integer
            Object Id, i.e 12-byte, 24 char hexadicmal

        Returns
        -------
            Json Dictionaries

        """
        # start by validating request fields for extra security
        # step 1 validation: valid if id is 12-hex
        if not ObjectId.is_valid(id):
            raise InvalidObjectId({'payloads': [{'id': id}]})

        # retrieve a result that should be unique in the collection, use get().
        # this will raise DoesNotExist if no document matches the query,
        # and MultipleObjectsReturned if more than one document matched the query
        transaction = Transaction.objects.get(id=id)

        if not transaction:
            return make_response(
                jsonify({
                    'status_code': 204,
                    'status': 'No Content'
                }), 204)
        else:
            return make_response(
                jsonify({
                    'status_code': 200,
                    'status': 'OK',
                    'datas': transaction
                }), 200)
コード例 #43
0
def add_questions(id_, r):
    if 'questions' not in r:
        return Response('Failed: no questions provided', 400)

    for e in r['questions']:
        if 'word' not in e:
            return Response('Failed: word not provided', 400)

        if not ObjectId.is_valid(e['word']):
            return Response('Failed: invalid Id', 400)

        if not Dictionary.objects(id=e['word'], in_dictionary=True):
            return Response('', 204)

    for e in r['questions']:
        try:
            question = Question(
                question_text=e['question_text'], word=e['word'])
            question.save()
            Quiz.objects(id=id_).update_one(push__questions=question)
        except Exception as e:
            print(str(datetime.now()) + ' ', e)
            return Response('Failed: invalid request', 400)
コード例 #44
0
def configs_put(id):
    auth_middleware.authorize(auth_middleware.rokwire_app_config_manager_group)

    req_data = request.get_json(force=True)
    if not check_format(req_data):
        abort(405)
    if not ObjectId.is_valid(id):
        abort(405)
    try:
        db = conn.get_db()
        add_version_numbers(req_data)
        status = db[cfg.APP_CONFIGS_COLLECTION].update_one({'_id': ObjectId(id)}, {"$set": req_data})
        msg = "[PUT]: api config id %s, nUpdate = %d " % (str(id), status.modified_count)
        __logger.info(msg)

    except DuplicateKeyError as err:
        __logger.error(err)
        abort(405)

    except Exception as ex:
        __logger.exception(ex)
        abort(500)
    return success_response(200, msg, str(id))
コード例 #45
0
def interactions():
    queryParams = request.args
    engagementId = queryParams.get('engagementId')
    response = None
    if engagementId is None:
        response = {'error': 'Mandatory parameter engagementId is missing'}
    elif not ObjectId.is_valid(engagementId):
        response = {
            'error': 'Value of mandatory parameter engagementId is not valid'
        }
    else:
        dbFilterParams = {'engagementId': ObjectId(engagementId)}
        interactionDate = queryParams.get('interactionDate')
        if interactionDate is not None:
            try:
                dbFilterParams['interactionDate'] = dateutil.parser.parse(
                    interactionDate)
            except:
                print(
                    "InteractionData is not a valid date.. Ignoring the parameter"
                )
        response = db.interactions.find(dbFilterParams)
    return json_util.dumps(response)
コード例 #46
0
def method_name(room_id):

    if str(request.method) != 'POST':
        return 'NOT OPTIONS', 400

    data = json.loads(request.get_data().decode())

    if 'newBoard' not in data:
        return 'Missing data parameter', 401
    
    is_valid = ObjectId.is_valid(room_id)
    if not is_valid:
        return 'Room id is not valid omer', 402

    room = Rooms.objects(id=room_id).first()
    if not room:
        return 'No such room', 404
    
    # All good:
    room.resultsTable = data['newBoard']
    room.save()

    return 'goods', 200
コード例 #47
0
ファイル: routers.py プロジェクト: Xpp521/Online_Surveys
def preview_survey_handler():
    survey_id = request.args.get('id')
    if not ObjectId.is_valid(survey_id):
        return abort(404)
    try:
        survey = mongo.db.surveys.find_one({'_id': ObjectId(survey_id)})  # 查询问卷
    except Exception as e:
        return show_msg(':(', '查询失败', '主页', '/', '查询问卷失败:{}'.format(e))
    if not survey:
        return abort(404)
    if current_user.user_id != survey.get('user_id'):
        return show_msg(':(', '无法预览', '主页', '/', '这不是你的问卷。')
    survey['title'] = '{} - 预览'.format(survey.get('title'))
    questions = []
    try:
        for question in mongo.db.questions.find({'survey_id': survey_id}):
            questions.append(question)
    except Exception as e:
        return show_msg(':(', '查询失败', '主页', '/', '查询问卷失败:{}'.format(e))
    if not questions:
        return show_msg(':(', '查询失败', '主页', '/', '此问卷尚未添加问题。')
    questions.sort(key=itemgetter('num'))  # 将题目按题号排序
    return render_template('survey.html', survey=survey, questions=questions, preview=1)
コード例 #48
0
ファイル: routers.py プロジェクト: Xpp521/Online_Surveys
def design_handler():
    survey_id = request.args.get('id')
    if not ObjectId.is_valid(survey_id):
        return abort(404)
    survey = mongo.db.surveys.find_one({'_id': ObjectId(survey_id)})
    if not survey:
        return abort(404)
    if survey.get('status'):
        return show_msg(':(', '现在无法设计问卷', '主页', '/home', '该问卷正在运行中,无法进行设计操作。', 5)
    answer = mongo.db.answers.count_documents({'survey_id': str(survey.get('_id'))})
    if answer != 0:
        return show_msg(':(', '现在无法设计问卷', '主页', '/home', '该问卷仍存在答卷,无法进行设计操作。', 5)
    questions = []
    try:
        for question in mongo.db.questions.find({'survey_id': survey_id}):
            question['_id'] = str(question.get('_id'))
            questions.append(question)
    except Exception as e:
        return show_msg(':(', '加载失败', '主页', '/', '查询问卷失败:{}'.format(e))
    if questions:
        questions.sort(key=itemgetter('num'))  # 将题目按题号排序
    return render_template('design.html', survey_id=survey_id, title=survey.get('title'),
                           note=survey.get('note'), public=survey.get('public'), questions=questions)
コード例 #49
0
ファイル: routers.py プロジェクト: Xpp521/Online_Surveys
def summary_handler():
    survey_id = request.args.get('id')
    if not survey_id or not ObjectId.is_valid(survey_id):
        abort(404)
    surveys = []
    try:
        for survey in mongo.db.surveys.find({'user_id': current_user.user_id}):
            surveys.append({'_id': str(survey.get('_id')), 'title': survey.get('title')})
        if not surveys:
            return show_msg(':(', '您尚未添加任何问卷', '主页', '/home', '无法进行统计与分析。')
        for index, survey in enumerate(surveys):
            if survey_id == survey.get('_id'):
                surveys[0], surveys[index] = surveys[index], surveys[0]
                break
        else:
            return show_msg(':(', '该问卷不属于当前用户', '主页', '/home', '无法进行统计与分析。')
        questions = []
        for question in mongo.db.questions.find({'survey_id': survey_id}):
            questions.append(question)
    except Exception as e:
        return show_msg(':(', '加载失败', '主页', '/home', str(e))
    questions.sort(key=itemgetter('num'))  # 将题目按题号排序
    return render_template('summary.html', surveys=surveys, questions=questions)
コード例 #50
0
ファイル: task.py プロジェクト: eclogue/eclogue
def task_log_buffer(_id):
    if not ObjectId.is_valid(_id):
        return jsonify({
            'message': 'invalid id',
            'code': 104000
        }), 400

    query = request.args
    record = None
    if query.get('type') == 'task':
        record = TaskModel.find_by_id(_id)
    elif query.get('type') == 'book':
        # @todo
        record = Perform.find_by_id(_id)
    if not record:
        return jsonify({
            'message': 'record not found',
            'code': 104040
        }), 404

    start = int(query.get('page', 0))
    end = -1
    reporter = Reporter(task_id=_id)
    buffer = reporter.get_buffer(start=start, end=end)
    if not buffer and record.get('trace'):
        buffer = [record.get('trace')]

    return jsonify({
        'message': 'ok',
        'code': 0,
        'data': {
            'list': buffer,
            'page': start,
            'state': record.get('state'),
            'record': record
        }
    })
コード例 #51
0
def post_drawing(request, part_id):
    #part_id invalid, part_id not exist
    if not ObjectId.is_valid(part_id):
        return HttpResponse(json.dumps(
            {
                'status': 'Failed',
                'Info': 'Wrong para.Plz check whether it\'s valid Id'
            },
            indent=4),
                            content_type="application/json")
    if db.part.find({'_id': ObjectId(part_id)}).count() == 0:
        return HttpResponse(json.dumps(
            {
                'status': 'Failed',
                'Info':
                'Part Id {0} not exists. plz check again'.format(part_id)
            },
            indent=4),
                            content_type="application/json")

    body = {}
    re = {}
    re['obj_id'] = []
    try:  #
        body = json.loads(request.body)

    except Exception, e:
        logger.debug('[1]---{0}---{1}---{2}'.format(Exception, e,
                                                    request.body))
        return HttpResponse(json.dumps(
            {
                'status': 'Failed',
                'Info': 'Request body is not valid json. plz check again',
                'Data': request.body
            },
            indent=4),
                            content_type="application/json")
コード例 #52
0
def svg_card_creator():
    download_id = request.args.get('id')
    if download_id and ObjectId.is_valid(download_id):
        found_contact = CONTACTS.find_one({
            '_id': ObjectId(download_id),
            'org': session.get('org')
        })
    else:
        return "No contact"
    full_name = "%s %s" % (found_contact.get('first_name'),
                           found_contact.get('last_name'))
    role = found_contact.get('role')
    company_name = found_contact.get('company_name')
    email_address = found_contact.get('email_address')
    phone_number = found_contact.get('phone_number')
    qr_code = create_qr_code(url_for('download', _external=True), download_id)
    qr_code = qr_code.split('svg11.dtd">\n')[1]
    qr_code = qr_code.replace('viewBox="0 0 33 33"',
                              'x="158.9" y="35.4" width="70.9" height="70.9"')
    qr_code = qr_code.replace('<path', '<path transform="scale(2)"')
    with open('static/template.svg', 'r+') as f:
        svg_file = Template(f.read())
    formatted_svg = svg_file.safe_substitute(name=full_name,
                                             email=email_address,
                                             role=role,
                                             company_name=company_name,
                                             telephone=phone_number,
                                             qr=qr_code)
    formatted_pdf = cairosvg.svg2pdf(bytestring=formatted_svg.encode('utf-8'),
                                     scale=1.3333)
    return Response(formatted_pdf,
                    mimetype='application/pdf',
                    headers={
                        "Content-Disposition":
                        "attachment;filename=%s.pdf" %
                        (full_name.replace(' ', '_'))
                    })
コード例 #53
0
ファイル: task.py プロジェクト: eclogue/eclogue
def task_logs(_id):
    if not ObjectId.is_valid(_id):
        return jsonify({
            'message': 'invalid id',
            'code': 104000
        }), 400

    query = request.args
    page = int(query.get('page', 1))
    limit = 1000
    skip = (page - 1) * limit
    obj_id = ObjectId(_id)
    record = db.collection('tasks').find_one({'_id': obj_id})
    if not record:
        return jsonify({
            'message': 'record not found',
            'code': 104040
        }), 404

    logs = db.collection('task_logs').find({'task_id': _id}, skip=skip, limit=limit)
    total = logs.count()
    records = []
    for log in logs:
        message = log.get('content')
        records.append(message)

    return jsonify({
        'message': 'ok',
        'code': 0,
        'data': {
            'list': records,
            'total': total,
            'page': page,
            'pageSize': limit,
            'state': record.get('state')
        }
    })
コード例 #54
0
def check_withdraw_reward():
    """
    检查邀请用户首次提现是否奖励
    :return:
    """
    if int(timestamp_to_strftime(int(time.time()), format='%H')) == 0:
        return False
    today_str = timestamp_to_strftime((int(time.time()) - 60 * 60), format='%Y-%m-%d')
    last_hour_str = timestamp_to_strftime((int(time.time()) - 60 * 60), format='%Y-%m-%d %H')
    withdraw_record_cur = withdraw_record.find({'review_time': {'$regex': last_hour_str}, 'status': 1})
    for withdraw_record_obj in withdraw_record_cur:
        user_id = withdraw_record_obj.get('user_id')
        user_obj = user.find_one({'_id': ObjectId(user_id)})
        invite_id = user_obj.get('invite_id', '')
        if ObjectId.is_valid(invite_id):
            if not commission_record.find_one({'origin': u'邀请用户首次提现', 'user_id': invite_id,
                                               'contributor_id': user_id}):
                _withdraw_record_obj = withdraw_record.find({'user_id': user_id,
                                                             'status': 1}).sort([('review_time', 1)])[0]

                first_time_today = _withdraw_record_obj.get('review_time').split(' ')[0]
                if first_time_today == today_str:
                    redis_invite_code.lpush('invite_json', json.dumps({'is_bind': 2, 'invite_id': invite_id,
                                                                       'user_id': user_id}))
コード例 #55
0
ファイル: views.py プロジェクト: InSearchOfInspiration/server
def process_specific_category(category_id):
    if not ObjectId.is_valid(category_id):
        return json_abort({
            'message': 'Invalid category id'
        }, 400)
    user = current_identity
    filter_query = {'_id': ObjectId(category_id)}
    not_found_message = 'No such category'
    if 'GET' not in request.method:
        filter_query.update({
            'user': user.id
        })
        not_found_message = 'This user did not create this category to update/delete'

    try:
        category = EventCategory.objects.get(filter_query)
        if 'GET' in request.method:
            result = CategorySchema().dump(category).data
            return Response(json.dumps(result), mimetype=JSON_MIME)
        elif 'PUT' in request.method:
            data = request.get_json(force=True)
            if isinstance(data, str):
                data = json.loads(data)
            save_category(data, user, category)
        else:
            category.delete()
        return Response("Success")
    except EventCategory.DoesNotExist:
        return json_abort({
            'message': not_found_message
        }, 400)
    except InvalidDataException as ex:
        return json_abort({
            'message': ex.message,
            'fields': ex.fields
        }, 400)
コード例 #56
0
def offer_name_game(room_id):

    is_valid = ObjectId.is_valid(room_id)
    if not is_valid:
        socketio.emit("newGameOffer", {"data": 'This is not a valid room id bobo', 'status': 400}, room=request.sid)
        return

    room = Rooms.objects(id=room_id).first()
    if not room:
        socketio.emit('newGameOffer', {'data': 'No room', 'status': 404}, room=request.sid)
        return

    if not room.gameEnded:
        socketio.emit('newGameOffer', {'data': 'Game didnt end yet', 'status': 401}, room=request.sid)
        return


    # default
    sid_target = room.players[0].sid
    # check if the first player is the asker, if he is, set the other player as target
    if request.sid == room.players[0].sid:
        sid_target = room.players[1].sid

    socketio.emit('newGameOffer', {'status': 200} ,room=sid_target)
コード例 #57
0
ファイル: meeting.py プロジェクト: smitpatwa/gstudio
def output(request, group_id, meetingid):
    newmeetingid = meetingid
    ins_objectid = ObjectId()
    if ins_objectid.is_valid(group_id) is False:
        group_ins = node_collection.find_one({
            '_type': "Group",
            "name": group_id
        })
        auth = node_collection.one({
            '_type': 'Author',
            'name': unicode(request.user.username)
        })
        if group_ins:
            group_id = str(group_ins._id)
        else:
            auth = node_collection.one({
                '_type': 'Author',
                'name': unicode(request.user.username)
            })
            if auth:
                group_id = str(auth._id)
    else:
        group_ins = node_collection.find_one({
            '_type': "Group",
            "_id": ObjectId(group_id)
        })
        pass
        #template = "https://chatb/#"+meetingid

    return render_to_response("ndf/newmeeting.html", {
        'group_id': group_id,
        'appId': app._id,
        'groupid': group_id,
        'newmeetingid': newmeetingid
    },
                              context_instance=RequestContext(request))
コード例 #58
0
def view_cocktail(cocktail_id):
    """
    route to view a specific cocktail
    """
    user = get_user()
    if ObjectId.is_valid(cocktail_id):
        connection = mongo_connect()
        cocktail = connection["cocktails"].find_one(
            {"_id": ObjectId(cocktail_id)}
        )
        if cocktail:

            return render_template(
                'viewcocktail.html',
                cocktail=cocktail,
                user=user
            )
    elif cocktail_id == "random":
        return render_template(
            'viewcocktail.html',
            cocktail=dict(random_cocktail()),
            user=user
        )
    return render_template('notfound.html', user=get_user()), 404
コード例 #59
0
    def on_put(self, req, resp):
        ''' Users Controller Put Request Method '''

        if 'id' in req.params and ObjectId.is_valid(req.params['id']):
            try:
                user = User.objects(id=req.params['id'])[0]
                if hasattr(req, 'json') and 'avatar' in req.json:
                    user.avatar = req.get_json('avatar')
                if hasattr(req, 'json') and 'first_name' in req.json:
                    user.first_name = req.get_json('first_name')
                if hasattr(req, 'json') and 'last_name' in req.json:
                    user.last_name = req.get_json('last_name')
                if hasattr(req, 'json') and 'email' in req.json:
                    user.email = req.get_json('email')
                if hasattr(req, 'json') and 'password' in req.json:
                    user.password = req.get_json('password')
                user.save()
                resp.json = user.to_json()
            except Exception:
                resp.status = falcon.HTTP_400
                resp.json = {
                    "message":
                    "User id: %s not found in database!" % req.params['id']
                }
コード例 #60
0
def get_module():
    """Get a specific module

    Get a single module givin a module Id

    query parameter (optional): /module?oid=someObjectId
    no request body

    :rtype: json
    """
    # check if a specific object Id was provided
    if 'oid' in request.args:
        # get the module object given a specific module Id
        if ObjectId.is_valid(oid):
            return Response(Module.objects.get_or_404(id=oid).to_json(),
                            mimetype='application/json')
        return Response('Failed: invalid Id', 400)

    # Otherwise get a list of all modules available to the user.
    # Excludes word and quiz lists to limit the response size.
    # Ment to be used to get top level info about all modules.
    else:
        return Response(Module.objects.exclude('words', 'quiz').to_json(),
                        mimetype='application/json')