def _request(self, method, mimeType, *args, **kwargs): 'dispatch to proper handler method, or return appropriate error' try: # do we support this method? action = getattr(self, '_' + method) except AttributeError: return view.report_error('%s objects do not allow %s' % (self.name, method), 405) try: # execute the request o = action(*args, **kwargs) except KeyError: return view.report_error('Not found: %s: args=%s, kwargs=%s' % (self.name, str(args), str(kwargs)), status=404, webMsg="""Sorry, the data that you requested does not exist in the database. Please check whether you have the correct ID or spelling.""") if isinstance(o, Response): return o() # send the redirect try: # do we support this mimeType? viewFunc = getattr(self, method.lower() + '_' + mimeType) except AttributeError: return view.report_error('%s objects cannot return %s' % (self.name, mimeType), 406) try: return viewFunc(o, **kwargs) except Exception: return view.report_error('view function error', 500)
def _request(self, method, mimeType, *args, **kwargs): 'dispatch to proper handler method, or return appropriate error' try: # do we support this method? action = getattr(self, '_' + method) except AttributeError: return view.report_error( '%s objects do not allow %s' % (self.name, method), 405) try: # execute the request o = action(*args, **kwargs) except KeyError: return view.report_error('Not found: %s: args=%s, kwargs=%s' % (self.name, str(args), str(kwargs)), status=404, webMsg="""Sorry, the data that you requested does not exist in the database. Please check whether you have the correct ID or spelling.""") if isinstance(o, Response): return o() # send the redirect try: # do we support this mimeType? viewFunc = getattr(self, method.lower() + '_' + mimeType) except AttributeError: return view.report_error( '%s objects cannot return %s' % (self.name, mimeType), 406) try: return viewFunc(o, **kwargs) except Exception: return view.report_error('view function error', 500)
def default(self, docID=None, *args, **kwargs): 'process all requests for this collection' try: method, mimeType = request_tuple() if docID: # a specific document from this collection docID = IdString(docID) # implements proper cmp() vs. ObjectId if not args: # perform the request return self._request(method, mimeType, docID, **kwargs) else: # pass request on to subcollection try: subcoll = getattr(self, args[0]) except AttributeError: return view.report_error('no such subcollection: %s.%s' % (self.name, args[0]), 404) try: parents = kwargs['parents'].copy() except KeyError: parents = {} try: parents[self.name] = self._GET(docID, parents=parents) except KeyError: return view.report_error('invalid ID: %s' % docID, 404, """Sorry, the data ID %s that you requested does not exist in the database. Please check whether you have the correct ID.""" % docID) kwargs['parents'] = parents # pass dict of parents return subcoll.default(*args[1:], **kwargs) elif method == 'GET': # search the collection return self._request('search', mimeType, **kwargs) else: return view.report_error('REST does not permit collection-%s' % method, 405) except Exception: return view.report_error('REST collection error', 500)
def check_permission(self, method, personID, *args, **kwargs): if method == 'GET': # permitted return False try: if personID != get_session()['person']._id: return view.report_error('TRAP set_interest by different user!', 403, "You cannot change someone else's settings!") except (KeyError,AttributeError): return view.report_error('TRAP set_interest, not logged in!', 401, 'You must log in to access this interface')
def check_permission(self, method, *args, **kwargs): if method == 'GET': # permitted return False user = get_session().get('person', None) if not user: return view.report_error('TRAP set_interest, not logged in!', 401, 'You must log in to access this interface') person = kwargs['parents'].values()[0] if person != user: return view.report_error('TRAP set_interest by different user!', 403, "You cannot change someone else's settings!")
def check_permission(self, method, personID, *args, **kwargs): if method == 'GET': # permitted return False try: if personID != get_session()['person']._id: return view.report_error( 'TRAP set_interest by different user!', 403, "You cannot change someone else's settings!") except (KeyError, AttributeError): return view.report_error( 'TRAP set_interest, not logged in!', 401, 'You must log in to access this interface')
def check_permission(self, method, *args, **kwargs): if method == 'GET': # permitted return False user = get_session().get('person', None) if not user: return view.report_error( 'TRAP set_interest, not logged in!', 401, 'You must log in to access this interface') person = kwargs['parents'].values()[0] if person != user: return view.report_error( 'TRAP set_interest by different user!', 403, "You cannot change someone else's settings!")
def _search(self, searchString, searchType): searchString = searchString.strip() if not searchString: s = view.report_error('empty searchString', 400, 'You did not provide a search string.') return rest.Response(s) # user may type "Google Search:..." into Google Search box if searchString.lower().startswith('arxiv:'): searchString = searchString[6:].strip() searchType = 'arxivID' if searchType == 'arxivID': return rest.Redirect('/arxiv/%s' % searchString.replace('/', '_')) elif searchType == 'arxiv': return rest.Redirect('/arxiv?' + urlencode(dict(searchString=searchString))) elif searchType == 'PMID': return rest.Redirect('/pubmed/%s' % searchString) elif searchType == 'pubmed': return rest.Redirect('/pubmed?' + urlencode(dict(searchString=searchString))) elif searchType == 'ncbipubmed': return rest.Redirect('http://www.ncbi.nlm.nih.gov/sites/entrez?' + urlencode(dict(term=searchString, db='pubmed'))) elif searchType == 'shortDOI': return rest.Redirect('/shortDOI/%s' % searchString) elif searchType == 'DOI': dpd = core.DoiPaperData(DOI=searchString, insertNew='findOrInsert') return rest.Redirect('/shortDOI/%s' % dpd.id) elif searchType == 'spnetPerson': return rest.Redirect('/people?' + urlencode(dict(searchString=searchString))) elif searchType == 'topic': return rest.Redirect('/topics?' + urlencode(dict(searchString=searchString))) elif searchType == 'comment': return rest.Redirect('/posts?' + urlencode(dict(searchAll=searchString))) else: raise KeyError('unknown searchType ' + searchType)
def _search(self, searchString=None, searchID=None, ipage=0, block_size=10, session=None): import arxiv ipage = int(ipage) block_size = int(block_size) if session is None: session = get_session() if searchID: # just get this ID return ParentCollection._search(self, searchID) if not searchString: s = view.report_error('empty searchString', 400, 'You did not provide a search string.') return rest.Response(s) elif arxiv.is_id_string(searchString): # just get this ID return ParentCollection._search(self, searchString) try: # get from existing query results queryResults = session['queryResults'] if queryResults.get_page(ipage, self.collectionArgs['uri'], searchString=searchString): return queryResults except KeyError: pass # no stored queryResults, so construct it pbl = view.PaperBlockLoader(arxiv.search_arxiv, uri=self.collectionArgs['uri']) queryResults = view.MultiplePages(pbl, block_size, ipage, self.collectionArgs['uri'], 'arXiv.org Search Results', searchString=searchString) session['queryResults'] = queryResults # keep for this user return queryResults
def _search(self, searchString=None, searchID=None, ipage=0, block_size=20, session=None): import pubmed ipage = int(ipage) block_size = int(block_size) try: # get from existing query results queryResults = cherrypy.session['queryResults'] if queryResults.get_page(ipage, self.collectionArgs['uri'], searchString=searchString): return queryResults except KeyError: pass # no stored queryResults, so construct it try: ps = pubmed.PubmedSearch(searchString, block_size) pbl = view.PaperBlockLoader(ps, uri=self.collectionArgs['uri']) queryResults = view.MultiplePages(pbl, block_size, ipage, self.collectionArgs['uri'], 'Pubmed Search Results', searchString=searchString) except (errors.BackendFailure,KeyError): s = view.report_error('eutils error: ' + searchString, 502, '''Unfortunately, the NCBI eutils server failed to perform the requested query. To run the <A HREF="/papers?%s">same search</A> on NCBI Pubmed, please click here. When you find a paper of interest, you can copy its PMID (Pubmed ID) and paste it in the search box on this page.''' % urlencode(dict(searchType='ncbipubmed', searchString=searchString))) return rest.Response(s) cherrypy.session['queryResults'] = queryResults # keep for this user return queryResults
def _search(self, searchString, searchType): searchString = searchString.strip() if not searchString: s = view.report_error('empty searchString', 400, 'You did not provide a search string.') return rest.Response(s) # user may type "Google Search:..." into Google Search box if searchString.lower().startswith('arxiv:'): searchString = searchString[6:].strip() searchType = 'arxivID' if searchType == 'arxivID': return rest.Redirect('/arxiv/%s' % searchString.replace('/', '_')) elif searchType == 'arxiv': return rest.Redirect('/arxiv?' + urlencode(dict(searchString=searchString))) elif searchType == 'PMID': return rest.Redirect('/pubmed/%s' % searchString) elif searchType == 'pubmed': return rest.Redirect('/pubmed?' + urlencode(dict(searchString=searchString))) elif searchType == 'ncbipubmed': return rest.Redirect( 'http://www.ncbi.nlm.nih.gov/sites/entrez?' + urlencode(dict(term=searchString, db='pubmed'))) elif searchType == 'shortDOI': return rest.Redirect('/shortDOI/%s' % searchString) elif searchType == 'DOI': dpd = core.DoiPaperData(DOI=searchString, insertNew='findOrInsert') return rest.Redirect('/shortDOI/%s' % dpd.id) else: raise KeyError('unknown searchType ' + searchType)
def _search(self, searchString=None, searchID=None, ipage=0, block_size=20, session=None): import pubmed if not searchString: s = view.report_error('empty searchString', 400, 'You did not provide a search string.') return rest.Response(s) ipage = int(ipage) block_size = int(block_size) try: # get from existing query results queryResults = get_session()['queryResults'] if queryResults.get_page(ipage, self.collectionArgs['uri'], searchString=searchString): return queryResults except KeyError: pass # no stored queryResults, so construct it try: ps = pubmed.PubmedSearch(searchString, block_size) pbl = view.PaperBlockLoader(ps, uri=self.collectionArgs['uri']) queryResults = view.MultiplePages(pbl, block_size, ipage, self.collectionArgs['uri'], 'Pubmed Search Results', searchString=searchString) except (errors.BackendFailure, KeyError): s = view.report_error( 'eutils error: ' + searchString, 502, '''Unfortunately, the NCBI eutils server failed to perform the requested query. To run the <A HREF="/papers?%s">same search</A> on NCBI Pubmed, please click here. When you find a paper of interest, you can copy its PMID (Pubmed ID) and paste it in the search box on this page.''' % urlencode( dict(searchType='ncbipubmed', searchString=searchString))) return rest.Response(s) get_session()['queryResults'] = queryResults # keep for this user return queryResults
def default(self, docID=None, *args, **kwargs): 'process all requests for this collection' try: method, mimeType = request_tuple() if docID: # a specific document from this collection docID = IdString(docID) # implements proper cmp() vs. ObjectId invalidResponse = self.check_permission( method, docID, *args, **kwargs) if invalidResponse: return invalidResponse if not args: # perform the request return self._request(method, mimeType, docID, **kwargs) else: # pass request on to subcollection try: subcoll = getattr(self, args[0]) except AttributeError: return view.report_error( 'no such subcollection: %s.%s' % (self.name, args[0]), 404) try: parents = kwargs['parents'].copy() except KeyError: parents = {} try: parents[self.name] = self._GET(docID, parents=parents) except KeyError: return view.report_error( 'invalid ID: %s' % docID, 404, """Sorry, the data ID %s that you requested does not exist in the database. Please check whether you have the correct ID.""" % docID) kwargs['parents'] = parents # pass dict of parents return subcoll.default(*args[1:], **kwargs) elif method == 'GET': # search the collection return self._request('search', mimeType, **kwargs) else: return view.report_error( 'REST does not permit collection-%s' % method, 405) except Exception: return view.report_error('REST collection error', 500)
def oauth2callback(self, error=False, **kwargs): if error: return error try: oauth = get_session()['gplus_oauth'] except KeyError: return view.report_error('session storage failed', 403, '''Login session info storage (cookie) failed. Please make sure that your browser accepts cookies from selectedpapers.net. ''', traceback=False) oauth.get_credentials(**kwargs) get_session()['person'] = oauth.get_person() return view.redirect('/')