def json_processor(entity): if not entity.headers.get(ntou('Content-Length'), ntou('')): raise cherrypy.HTTPError(411) body = entity.fp.read() try: cherrypy.serving.request.json = json_decode(body.decode('utf-8')) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document')
def json_processor(entity): """Read application/json data into request.json.""" if not entity.headers.get(ntou('Content-Length'), ntou('')): raise cherrypy.HTTPError(411) body = entity.fp.read() with cherrypy.HTTPError.handle(ValueError, 400, 'Invalid JSON document'): cherrypy.serving.request.json = json_decode(body.decode('utf-8'))
def json_processor(entity): """Read application/json data into request.json.""" if not entity.headers.get(ntou("Content-Length"), ntou("")): raise cherrypy.HTTPError(411) body = entity.fp.read() try: cherrypy.serving.request.json = json_decode(body.decode('utf-8')) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document')
def decompress_json(entity): """Try decompressing json before parsing, incase compressed content was sent to the server""" if not entity.headers.get(ntou("Content-Length"), ntou("")): raise cherrypy.HTTPError(411) body = entity.fp.read() # decompress if gzip content type if entity.headers.get(ntou("Content-Type")) == ntou("application/gzip"): try: body = zlib.decompress(body) except: raise cherrypy.HTTPError(500, 'Invalid gzip data') try: cherrypy.serving.request.json = json_decode(body.decode('utf-8')) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document')
def json_processor(entity): """ Read application/json data into the request arguments. This is am almost identical copy of the CherryPy JSON tool's json_processor() with the only difference that this version merges any json data decoded from the body, into the request arguments instead of the request.json object. This makes JSON and normal form input data completely indistinguishable fvrom each other as far as the request handlers go. """ if not entity.headers.get(ntou("Content-Length"), ntou("")): raise cherrypy.HTTPError(411) body = entity.fp.read() try: cherrypy.serving.request.params.update(json_decode(body.decode('utf-8'))) except ValueError: raise cherrypy.HTTPError(400, 'Invalid JSON document')
def test_0_Session(self): self.getPage('/set_session_cls/cherrypy.lib.sessions.RamSession') self.getPage('/clear') # Test that a normal request gets the same id in the cookies. # Note: this wouldn't work if /data didn't load the session. self.getPage('/data') self.assertBody("{'aha': 'foo'}") c = self.cookies[0] self.getPage('/data', self.cookies) self.assertEqual(self.cookies[0], c) self.getPage('/testStr') self.assertBody('1') cookie_parts = dict( [p.strip().split('=') for p in self.cookies[0][1].split(';')]) # Assert there is an 'expires' param self.assertEqual(set(cookie_parts.keys()), set(['session_id', 'expires', 'Path'])) self.getPage('/testGen', self.cookies) self.assertBody('2') self.getPage('/testStr', self.cookies) self.assertBody('3') self.getPage('/data', self.cookies) self.assertDictEqual(json_decode(self.body), { 'counter': 3, 'aha': 'foo' }) self.getPage('/length', self.cookies) self.assertBody('2') self.getPage('/delkey?key=counter', self.cookies) self.assertStatus(200) self.getPage('/set_session_cls/cherrypy.lib.sessions.FileSession') self.getPage('/testStr') self.assertBody('1') self.getPage('/testGen', self.cookies) self.assertBody('2') self.getPage('/testStr', self.cookies) self.assertBody('3') self.getPage('/delkey?key=counter', self.cookies) self.assertStatus(200) # Wait for the session.timeout (1 second) time.sleep(2) self.getPage('/') self.assertBody('1') self.getPage('/length', self.cookies) self.assertBody('1') # Test session __contains__ self.getPage('/keyin?key=counter', self.cookies) self.assertBody('True') cookieset1 = self.cookies # Make a new session and test __len__ again self.getPage('/') self.getPage('/length', self.cookies) self.assertBody('2') # Test session delete self.getPage('/delete', self.cookies) self.assertBody('done') self.getPage('/delete', cookieset1) self.assertBody('done') def f(): return [ x for x in os.listdir(localDir) if x.startswith('session-') ] self.assertEqual(f(), []) # Wait for the cleanup thread to delete remaining session files self.getPage('/') self.assertNotEqual(f(), []) time.sleep(2) self.assertEqual(f(), [])
def test_0_Session(self): self.getPage('/set_session_cls/cherrypy.lib.sessions.RamSession') self.getPage('/clear') # Test that a normal request gets the same id in the cookies. # Note: this wouldn't work if /data didn't load the session. self.getPage('/data') self.assertBody("{'aha': 'foo'}") c = self.cookies[0] self.getPage('/data', self.cookies) self.assertEqual(self.cookies[0], c) self.getPage('/testStr') self.assertBody('1') cookie_parts = dict([p.strip().split('=') for p in self.cookies[0][1].split(';')]) # Assert there is an 'expires' param self.assertEqual(set(cookie_parts.keys()), set(['session_id', 'expires', 'Path'])) self.getPage('/testGen', self.cookies) self.assertBody('2') self.getPage('/testStr', self.cookies) self.assertBody('3') self.getPage('/data', self.cookies) self.assertDictEqual(json_decode(self.body), {'counter': 3, 'aha': 'foo'}) self.getPage('/length', self.cookies) self.assertBody('2') self.getPage('/delkey?key=counter', self.cookies) self.assertStatus(200) self.getPage('/set_session_cls/cherrypy.lib.sessions.FileSession') self.getPage('/testStr') self.assertBody('1') self.getPage('/testGen', self.cookies) self.assertBody('2') self.getPage('/testStr', self.cookies) self.assertBody('3') self.getPage('/delkey?key=counter', self.cookies) self.assertStatus(200) # Wait for the session.timeout (1 second) time.sleep(2) self.getPage('/') self.assertBody('1') self.getPage('/length', self.cookies) self.assertBody('1') # Test session __contains__ self.getPage('/keyin?key=counter', self.cookies) self.assertBody('True') cookieset1 = self.cookies # Make a new session and test __len__ again self.getPage('/') self.getPage('/length', self.cookies) self.assertBody('2') # Test session delete self.getPage('/delete', self.cookies) self.assertBody('done') self.getPage('/delete', cookieset1) self.assertBody('done') f = lambda: [ x for x in os.listdir(localDir) if x.startswith('session-')] self.assertEqual(f(), []) # Wait for the cleanup thread to delete remaining session files self.getPage('/') f = lambda: [ x for x in os.listdir(localDir) if x.startswith('session-')] self.assertNotEqual(f(), []) time.sleep(2) self.assertEqual(f(), [])
def api(self,a,kw): status=0 errmsg="" if a[0]=="getProfile": jresp=self.profile elif a[0]=="createSection": rbody=cherrypy.request.body.fp.read() print("REQUEST",rbody) req=json_decode(rbody.decode("utf-8")) print("Creating section") sec={"title":"New Section", "publications":[],"sectionKey":self.profile.getSecKey(),"displayOrder":self.profile.getSecKey(),"puborder":[],"secdesc":"No description"} self.profile["sections"].append(sec) self.profile.save() jresp={} elif a[0]=="updateSec": rbody=cherrypy.request.body.fp.read() print("REQUEST",rbody) req=json_decode(rbody.decode("utf-8")) print("Updating section:",req["sectionKey"]) sec=self.profile.getSection(req["sectionKey"]) sec["title"]=req["title"] sec["secdesc"]=req["secdesc"] #self.profile.save()#setsec.save() neworder=req["puborder"] o=1 newpubs=[] for pkey in neworder: pub=sec.getPub(pkey) newpubs.append(pub) #if pub["displayOrder"]!=o: # pub["displayOrder"]=o o+=1 sec["publications"]=newpubs self.profile.saveSec(req["sectionKey"],sec) jresp={} elif a[0]=="deleteSec": rbody=cherrypy.request.body.fp.read() print("REQUEST",rbody) req=json_decode(rbody.decode("utf-8")) print("Deleting section:",req["sectionKey"]) self.profile.deleteSec(req["sectionKey"]) jresp={} elif a[0]=="createPub": rbody=cherrypy.request.body.fp.read() print("REQUEST",rbody) req=json_decode(rbody.decode("utf-8")) print("Creating pub in section:",req["sectionKey"]) sec=self.profile.getSection(req["sectionKey"]) publication={"publicationKey":self.profile.getPubKey(),"parent":sec["sectionKey"],"title":"Başlıksız yayın","displayOrder":len(sec["publications"])+1,"authors":[{"name":self.profile["name"]}], "ispub":False,"issep":False,"pubtype":"article","desc":"Açıklama yok","pfiles":[],"pubinfo":ESBibtex().defaultValues(),"fileorder":[]} if req["ptype"]=="academic": publication["ispub"]=True elif req["ptype"]=="non-academic": pass else:#sep publication["issep"]=True sec["publications"].insert(0,publication) self.profile.saveSec(req["sectionKey"],sec) jresp={} elif a[0]=="updatePub": rbody=cherrypy.request.body.fp.read() print("REQUEST",rbody) req=json_decode(rbody.decode("utf-8")) print("Updating pub in section:",req["publicationKey"]) sec=self.profile.getSection(req["sectionKey"]) pub=sec.getPub(req["publicationKey"]) pub["pubinfo"]=req["pubinfo"] pub["title"]=req["title"] pub["desc"]=req["desc"] pub["pubtype"]=req["pubtype"] pub["abstract"]=req["pubabstract"] #pub["ispub"]=req["ispub"] pub["authors"]=[{"name":x} for x in req["authors"]] forder=[x for x in filter(lambda x:x is not None,req["fileorder"])] def getPfile(pfiles,k): for pf in pfiles: if pf["fileKey"]==k:return pf pub["pfiles"]=[getPfile(pub["pfiles"],k) for k in forder] sec.savePub(req["publicationKey"],pub) self.profile.saveSec(req["sectionKey"],sec) jresp={} elif a[0]=="deletePub": rbody=cherrypy.request.body.fp.read() print("REQUEST",rbody) req=json_decode(rbody.decode("utf-8")) print("Deleting pub in section:",req["publicationKey"]) sec=self.profile.getSection(req["sectionKey"]) sec.deletePub(req["publicationKey"]) self.profile.saveSec(req["sectionKey"],sec) jresp={} elif a[0]=="addPublicationFiles": #rbody=cherrypy.request.body.fp.read() cl = int(cherrypy.request.headers['Content-Length']) #raw=cherrypy.request.body.read(cl) #print("REQUEST",raw) #req=json_decode(raw) print("Adding pub files:",kw["publicationKey"]) sec=self.profile.getSection(int(kw["sectionKey"])) pub=sec.getPub(int(kw["publicationKey"])) print("To pub:",pub) for fname in kw[".fnames"].split("###"): if os.path.exists(os.sep.join(["files",fname])): status=1 errmsg="File already exists" jresp={} retval={"status":status,"message":errmsg,"result":jresp} return json.dumps(retval) for fname in kw[".fnames"].split("###"): pfile={'description': '', 'displayOrder': len(pub["pfiles"])+1, 'downloadCount': 0, 'fileCleanUrl': '/files/'+fname, 'fileKey': fname, 'fileName': fname, 'fileUrl': '/files/'+fname} pub["pfiles"].append(pfile) f=kw[fname].file.read() print("FILE CONTENT",f) open("files/"+fname,"wb").write(f) #raise Exception("not implemented") sec.savePub(int(kw["publicationKey"]),pub) self.profile.saveSec(int(kw["sectionKey"]),sec) jresp={} elif a[0]=="deletePubFile": rbody=cherrypy.request.body.fp.read() print("REQUEST",rbody) req=json_decode(rbody.decode("utf-8")) print("Deleting file in section:",req["fkey"]) self.profile.deleteFile(req["fkey"]) jresp={} elif a[0]=="updateProfile": rbody=cherrypy.request.body.fp.read() print("REQUEST",rbody) req=json_decode(rbody.decode("utf-8")) print("Updating profile:") #self.profile self.profile["title"]=req["profileName"] self.profile["name"]=req["username"] self.profile["desc"]=req["profileDesc"] self.profile["profiledesc"]=req["profileDesc"] self.profile["associations"]=req["associations"] neworder=req["sectionOrder"] o=1 newsecs=[] for skey in neworder: newsecs.append(self.profile.getSection(skey)) o+=1 self.profile["sections"]=newsecs self.profile.save() jresp={} elif a[0]=="setProfilePicture": print("Update profile pic") for fname in kw[".fnames"].split(" "): f=kw[fname].file.read() print("FILE CONTENT",f) open("files/"+fname,"wb").write(f) self.profile["profilePicture"]={'fileCleanUrl': '/files/'+fname, 'fileKey': fname, 'fileName': fname, 'fileUrl': '/files/'+fname} self.profile.save() jresp={} elif a[0]=="deleteProfilePicture": print("Delete profile pic") del self.profile["profilePicture"] self.profile.save() jresp={} else: status=1 errmsg="Unknown command" jresp={} retval={"status":status,"message":errmsg,"result":jresp} return json.dumps(retval)