def journal_show(request): request.require_administrator() rid = request.matchdict['id'] timestamp = datetime.now() index = es_index(timestamp) docs = request.env.audit.es.search( index=index, body=dict(query=dict( ids=dict(values=[rid, ]) ))) hits = docs['hits'] if hits['total']['value'] != 1: raise HTTPNotFound() doc = hits['hits'][0] return dict( title=_("Journal record: %s") % rid, doc=doc, dynmenu=request.env.pyramid.control_panel)
def refined_query(self, query, model, req): if model == Contribution: return query.options( joinedload_all(Contribution.references, ContributionReference.source)) if model == Parameter: if req.matchdict['id'][-1] not in ascii_uppercase: # route match for 2008-style URL: redirect! raise HTTPMovedPermanently( req.route_url('contribution', id=req.matchdict['id'])) if model == Source: try: # redirect legacy refdb URLs formed with numeric id: rec = Source.get(int(req.matchdict['id']), default=None) if rec: raise HTTPMovedPermanently( req.route_url('source', id=rec.id)) else: raise HTTPNotFound() except ValueError: pass return query
def my_auth_view(request): if request.method == 'GET': try: username = request.GET['username'] password = request.GET['password'] print('User: {}, Pass: {}'.format(username, password)) return HTTPFound(location=request.route_url('portfolio')) except KeyError: return {} if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] print('User: {}, Pass: {}, Email: {}'.format(username, password, email)) return HTTPFound(location=request.route_url('portfolio')) return HTTPNotFound()
def view_page(request): slug = request.matchdict['slug'] try: page = DBSession.query(Page).filter_by(slug=slug).one() except NoResultFound: return HTTPNotFound('Page not found') content = { 'title': page.title, 'body': markdown(page.body, extensions=['extra', 'headerid(level=2, forceid=False)']), 'edit_url': '' # not implemented yet } return { 'content': content, 'user_can_edit': False, 'navigation': get_navigation(request) }
def category(self): category_id = self.request.matchdict['category'] category = self.get_category(category_id) if category is None or category.language != self.locale: raise HTTPNotFound() pages = self.get_pages_for_category(category_id, self.locale) p = int(self.request.GET.get('p', 0)) empty_defaults = { 'paginator': [], 'category': category, 'p': p, } if not category: return empty_defaults if len(pages) == 0: return empty_defaults paginator = EGPaginator(pages, p, results_per_page=self.results_per_page) # requested page number is out of range total_pages = paginator.total_pages() # sets the floor to 0 p = p if p >= 0 else 0 # sets the roof to `total_pages -1` p = p if p < total_pages else total_pages - 1 paginator = EGPaginator(pages, p, results_per_page=self.results_per_page) return { 'paginator': paginator, 'category': category, 'p': p, 'pages': pages, }
def __init__(self, request): exercise_id = request.matchdict['exercise_id'] self.exercise = request.db.query(Exercise).get(exercise_id) if self.exercise is None: raise HTTPNotFound(detail='Exercise not found') self.exam = self.exercise.exam self.lecture = self.exam.lecture if 'tutorial_ids' in request.matchdict: self.tutorial_ids = request.matchdict['tutorial_ids'].split(',') if len(self.tutorial_ids) == 1 and self.tutorial_ids[0] == '': self.tutorial_ids = [] self.tutorials = [] else: self.tutorials = request.db.query(Tutorial).filter( Tutorial.id.in_(self.tutorial_ids)).all() self.__acl__ = [ (Allow, Authenticated, 'view_points'), (Allow, 'group:administrators', ALL_PERMISSIONS), ] + [(Allow, 'user:{0}'.format(tutor.id), ('statistics')) for tutor in self.exam.lecture.tutors ] + [(Allow, 'user:{0}'.format(assistant.id), ('statistics')) for assistant in self.exam.lecture.assistants]
def alert_channels_rule_PATCH(request): """ Removes specific alert channel rule """ user = request.user json_body = request.unsafe_json_body schema = build_rule_schema(json_body['rule'], REPORT_TYPE_MATRIX) try: schema.deserialize(json_body['rule']) except colander.Invalid as exc: return HTTPUnprocessableEntity(body=json.dumps(exc.asdict())) rule_action = AlertChannelActionService.by_owner_id_and_pkey( user.id, request.GET.get('pkey')) if rule_action: rule_action.rule = json_body['rule'] rule_action.resource_id = json_body['resource_id'] rule_action.action = json_body['action'] return rule_action.get_dict() return HTTPNotFound()
def execute(self): site_repo = SiteRepository(self.request.dbsession) form = SiteForm(self.request.POST) mode = self.request.POST['mode'] if form.validate(): if mode == 'add': site_repo.insert(form.site_name.data, form.site_seq.data) elif mode == 'edit': site_repo.update(self.request.POST['site_id'], form.site_name.data, form.site_seq.data) else: return HTTPNotFound() return HTTPFound(location='/site/list') else: if form.site_seq.data is None: form.site_seq.data = '' return { 'form': form, 'mode': mode, 'mode_name': MODE_NAME_LIST.get(mode), 'site_id': self.request.POST['site_id'], }
def get_sld(self): """ Webservice which delivers an SLD file from parameter input. However this is a proxy pass through only. We use it to call the real method configured in the dedicated yaml file and hope that this method is accepting a pyramid.request.Request as input and is returning a pyramid.response.Response which encapsulates a well designed SLD. .. note:: The config path to define this hook method is: *pyramid_oereb.real_estate.visualisation.method* Returns: pyramid.response.Response: The response provided by the hooked method provided by the configuration Raises: pyramid.httpexceptions.HTTPInternalServerError: When the return value of the hooked method was not of type pyramid.response.Response pyramid.httpexceptions.HTTPNotFound: When the configured method was not found. """ dnr = DottedNameResolver() visualisation_config = Config.get_real_estate_config().get('visualisation') method_path = visualisation_config.get('method') method = dnr.resolve(method_path) if method: result = method(self._request_) if isinstance(result, Response): return result else: log.error( u'The called method {path} does not returned the expected ' u'pyramid.response.Response instance. Returned value was {type}'.format( path=method_path, type=type(result) ) ) raise HTTPInternalServerError() log.error(u'method in path "{path}" not found'.format(path=method_path)) raise HTTPNotFound()
def data_item_delete(request): dbsession = DBSession() experiment = dbsession.query(Experiment).filter( Experiment.id == request.matchdict['eid']).first() data_set = dbsession.query(DataSet).filter( and_(DataSet.id == request.matchdict['did'], DataSet.experiment_id == request.matchdict['eid'], DataSet.type == 'dataset')).first() data_item = dbsession.query(DataItem).filter( and_(DataItem.id == request.matchdict['diid'], DataItem.dataset_id == request.matchdict['did'])).first() if experiment and data_set and data_item: with transaction.manager: dbsession.delete(data_item) dbsession.add(experiment) dbsession.add(data_set) raise HTTPFound( request.route_url('experiment.data.view', eid=experiment.id, did=data_set.id)) else: raise HTTPNotFound()
def get_uri(self): uri = self.request.params.get('uri', self.request.matchdict.get('uri', None)) if not uri: return HTTPBadRequest() if 'application/ld+json' in self.request.accept: self.request.response.content_type = 'application/ld+json' provider = self.skos_registry.get_provider(uri) uri_context = MINI_CONTEXT uri_context['concept_scheme'] = { '@id': 'skos:inScheme', '@type': '@id' } if provider: uri_context['concept_scheme'] = 'skos:ConceptScheme' return { '@context': uri_context, 'type': 'concept_scheme', 'uri': provider.concept_scheme.uri, 'id': provider.get_vocabulary_id() } c = self.skos_registry.get_by_uri(uri) if not c: return HTTPNotFound() return { '@context': uri_context, 'type': c.type, 'uri': c.uri, 'id': c.id, 'concept_scheme': { 'type': 'skos:ConceptScheme', 'uri': c.concept_scheme.uri, 'id': self.skos_registry.get_provider( c.concept_scheme.uri).get_vocabulary_id() } }
def logbook(request): methodtype = request.matchdict['accesstype'] methodkey = request.matchdict['access'] try: datasetid = lib( 'dataset', lib(**{methodtype: methodkey})['Instruments'][0])['DatasetID'] except RuntimeError: return HTTPNotFound(methodtype + "-" + methodkey + " is invalid") # return HTTPTemporaryRedirect(location=request.route_path("home")) parms = {'dataset': '%i' % datasetid} for f in [ 'byr', 'bmo', 'bdy', 'bhr', 'bmn', 'eyr', 'emo', 'edy', 'ehr', 'emn', 'rss' ]: if f in request.params: parms[f] = request.params.getone(f) return HTTPTemporaryRedirect( location='http://lidar.ssec.wisc.edu/cgi-bin/logbook/showlogbook.cgi?' + '&'.join([(k + '=' + parms[k]) for k in parms.keys()]))
def wrap_action(self, action_, *args, **kwargs): """ Wrap the controller action ``action_``. :param action_: The controller action to be wrapped. ``args`` and ``kwargs`` are the positional and named arguments which will be passed to ``action_`` when called. """ base = '/niimanga/public/index.html' # request should be the one and only arg to the view function request = args[0].R # If requester is a bot, serve custom "bot version" crawlers = ('Googlebot', 'facebookexternalhit', 'Slackbot', 'Facebot', 'Twitterbot') for crawler in crawlers: LOG.debug(request.headers['User-Agent']) if crawler in request.headers['User-Agent']: return action_(*args, **kwargs) mobiles = ('Android', 'webOS', 'iPhone', 'iPad', 'iPod', 'BlackBerry', 'IEMobile', 'Opera Mini') for mobile in mobiles: if mobile in request.headers['User-Agent']: base = '/niimanga/public/mobile.html' try: # Not a bot. Let's serve the js app! with open(os.getcwd() + base, 'r') as f: request.response.content_type = 'text/html' request.response.charset = 'utf8' request.response.status_int = 200 request.response.body = f.read() LOG.info('dari crawlable decorated123') return request.response except Exception as e: LOG.debug(e.message) raise HTTPNotFound()
def blog_index(context, request): """ Handles blog index page """ try: # Get posts of requested page. If page number is invalid integer, # or out of range, it will raise "404 Not Found". page_num = int(request.GET.get('page', 1)) posts = list(context.page(page_num)) except ValueError: raise HTTPNotFound() authors = {} if not context.parent(cls=resources.Author): # If Blog resource (context) has no Author one in its lineage, # then we need to render link to author's profile. Therefore # we need to get author resources. ids = set(p.author for p in posts) authors = dict((a.id, a) for a in request.root['authors'].all(ids)) return { 'posts': posts, 'page_num': page_num, 'page_count': context.page_count, 'authors': authors, }
def mocked_file_response(path, url): # type: (str, str) -> Union[Response, HTTPException] """ Generates a mocked response from the provided file path, and represented as if coming from the specified URL. :param path: actual file path to be served in the response :param url: wanted file URL :return: generated response """ if not os.path.isfile(path): raise HTTPNotFound("Could not find mock file: [{}]".format(url)) resp = Response() ext = os.path.splitext(path)[-1] typ = CONTENT_TYPE_APP_JSON if ext == ".json" else CONTENT_TYPE_TEXT_XML if ext == ".xml" else None if not typ: return HTTPUnprocessableEntity( "Unknown Content-Type for mock file: [{}]".format(url)) resp.status_code = 200 resp.headers["Content-Type"] = typ setattr(resp, "content_type", typ) content = open(path, "rb").read() resp._content = content # noqa: W0212 class StreamReader(object): _data = [ None, content ] # should technically be split up more to respect chuck size... def read(self, chuck_size=None): # noqa: E811 return self._data.pop(-1) # add extra methods that 'real' response would have and that are employed by underlying code setattr(resp, "raw", StreamReader()) if isinstance(resp, TestResponse): setattr(resp, "url", url) setattr(resp, "reason", getattr(resp, "explanation", "")) setattr(resp, "raise_for_status", lambda: Response.raise_for_status(resp)) return resp
def create_user_credit(request): """Adds credit to a user account, negative or positive. Only an administrator can do this directly. Boost and Deboost actions will do this implicitly. Checks if username is valid, otherwise throws HTTP 404. Checks if credit is an integer, otherwise throws HTTP 400. :param name: User for which we are amending credit. :returns: JSON containing actor id, credit change and new balance. """ username, credit = request.matchdict['name'], request.POST['credit'] try: user_id = server.get_user_id_from_name(username) server.touch_to_add_credit(user_id, int(credit)) credits = server.check_credit(user_id) return {'actor_id': int(user_id), 'credit_change': int(credit), 'credit_balance': int(credits)} except ValueError: return HTTPBadRequest() except KeyError: return HTTPNotFound()
def view_page(request): pagename = request.matchdict['pagename'] session = DBSession() page = session.query(Page).filter_by(name=pagename).first() if page is None: return HTTPNotFound('No such page') def check(match): word = match.group(1) exists = session.query(Page).filter_by(name=word).all() if exists: view_url = request.route_url('view_page', pagename=word) return '<a href="%s">%s</a>' % (view_url, word) else: add_url = request.route_url('add_page', pagename=word) return '<a href="%s">%s</a>' % (add_url, word) content = publish_parts(page.data, writer_name='html')['html_body'] content = wikiwords.sub(check, content) edit_url = request.route_url('edit_page', pagename=pagename) return dict(page=page, content=content, edit_url=edit_url, logged_in=authenticated_userid(request))
def set_user_dis_connected(request, connecting): ctx = request.context discussion_id = ctx.get_discussion_id() if not discussion_id: # This view should only exist in discussion+user context raise HTTPNotFound() token = request.POST.get('token') # see if token corresponds to user user = ctx.get_instance_of_class(User) try: token = decode_token(token, TOKEN_SECRET) assert token['userId'] == user.id except TokenInvalid: raise HTTPUnauthorized() status = user.get_status_in_discussion(discussion_id) assert status if connecting: status.last_connected = datetime.now() else: status.last_disconnected = datetime.now() return HTTPOk()
def cloudwatch_alarm_view(self): if not self.alarm: raise HTTPNotFound() existing_dimensions = self.alarm.dimensions dimension_options = DimensionChoicesManager( self.request, existing_dimensions).choices_by_namespace(self.alarm.namespace) # Handle when resource in dimensions is no longer available (e.g. instance was terminated) invalid_dimensions = len([ option for option in dimension_options if option.get('value') == '' ]) self.render_dict.update( metric_display_name=METRIC_TITLE_MAPPING.get( self.alarm.metric, self.alarm.metric), dimension_options=dimension_options, dimension_options_json=json.dumps(dimension_options), invalid_dimensions=invalid_dimensions, ) return self.render_dict
def get(self): document_id = self.request.validated['id'] lang = self.request.validated['lang'] def create_response(): return self._get_history(document_id, lang) # history entry point does no precise document type. cache_key = get_cache_key(document_id, lang, document_type=DOCUMENT_TYPE) if not cache_key: raise HTTPNotFound( 'no version for document {0}'.format(document_id)) else: # set and check the etag: if the etag value provided in the # request equals the current etag, return 'NotModified' etag_cache(self.request, cache_key) return get_or_create(cache_document_history, cache_key, create_response)
def render(self, request, result, model_description): """ Execute the rendering process by matching the requested format to the mapped renderer. If no renderer could be found a error is raised. Args: request (pyramid.request.Request): The request which comes all the way through the application from the client result (list of sqlalchemy.ext.declarative.DeclarativeMeta): A list of database records found for the request. model_description (pyramid_georest.lib.description.ModelDescription): The description object of the data set which will be rendered. Returns: pyramid.response.Response: An pyramid response object. Raises: HTTPNotFound """ response_format = request.matchdict['format'] renderer_name = self._format_to_renderer.get(response_format, False) if renderer_name: return render_to_response( renderer_name, { 'features': result, 'model_description': model_description }, request=request ) else: text = 'The Format "{format}" is not defined for this service. Sorry...'.format( format=response_format ) log.error(text) raise HTTPNotFound( detail=text )
def render(self): package = Package.by_name(self.session, self.request.matchdict['package_name']) if not package: raise HTTPNotFound() if 'form.refresh_package' in self.request.params: package.update_at = None self.session.add(package) if 'release_version' in self.request.matchdict: release = Release.by_version( self.session, package.name, self.request.matchdict['release_version']) else: release = package.sorted_releases[0] return { u'package': package, u'release': release, }
def ban(request): r = request s = request.session p = s['safe_post'] if 'logged_in_admin' not in s or s['logged_in_admin'] == False: return HTTPNotFound() if 'ip' in p: if p['ip'].strip() == '': ip = None else: ip = p['ip'] if p['username'].strip() == '': username = None user_id = None else: username = p['username'] if p['duration'].strip() == 'infinite': duration = None else: duration = "timedelta({0})".format(p['duration']) duration = eval(duration) if username: user_id = users.get_user_by_name(username).id b = Ban(ip=ip, username=username, duration=duration, user_id=user_id, added_by=s['users.id']) dbsession = DBSession() dbsession.add(b) bans = general.list_bans() return {'bans': bans}
def reorder_transition(request): dbsession = DBSession() experiment = dbsession.query(Experiment).filter(Experiment.id == request.matchdict['eid']).first() if experiment: page = dbsession.query(Page).filter(and_(Page.id == request.matchdict['pid'], Page.experiment == experiment)).first() else: page = None if experiment and page: try: params = ReorderSchema().to_python(request.params, State(request=request)) with transaction.manager: for idx, tid in enumerate(params['item']): transition = dbsession.query(Transition).filter(and_(Transition.id == tid, Transition.source == page)).first() if transition is not None: transition.order = idx return {'status': 'ok'} except formencode.Invalid: return {'status': 'error'} else: raise HTTPNotFound()
def geolocate_post(request): data = request.validated session = request.db_slave_session result = None if data['wifiAccessPoints']: result = search_wifi_ap(session, data) else: result = search_cell_tower(session, data) if result is None: result = HTTPNotFound() result.content_type = 'application/json' result.body = NOT_FOUND return result return { "location": { "lat": result['lat'], "lng": result['lon'], }, "accuracy": float(result['accuracy']), }
def read_many_public(self): """ Return many :term:`Activities` which are visible to the public. .. seealso:: :class:`lmkp.views.activities.ActivityView.read_many` for details on the request parameters. In contrary to :class:`lmkp.views.activities.ActivityView.read_many`, no pending versions are returned even if the user is logged in. Matchdict parameters: ``/activities/public/{output}`` ``output`` (str): If the output format is not valid, a 404 Response is returned. The following output formats are supported: ``json``: Return the :term:`Activities` as JSON. ``geojson``: Return the :term:`Activities` as GeoJSON. ``html``: Return the :term:`Activities` as HTML (eg. the `Grid View`) Returns: ``HTTPResponse``. Either a HTML or a JSON response. """ output_format = get_output_format(self.request) if output_format in ['json', 'geojson', 'html']: return self.read_many(public=True) else: raise HTTPNotFound()
def mark_post_read(request): """Mark this post as un/read. Return the read post count for all affected ideas.""" discussion_id = int(request.matchdict['discussion_id']) discussion = Discussion.get_instance(discussion_id) post_id = request.matchdict['id'] post = Post.get_instance(post_id) if not post: raise HTTPNotFound("Post with id '%s' not found." % post_id) post_id = post.id user_id = authenticated_userid(request) if not user_id: raise HTTPUnauthorized() read_data = json.loads(request.body) db = discussion.db change = False with transaction.manager: if read_data.get('read', None) is False: view = db.query(ViewPost).filter_by( post_id=post_id, actor_id=user_id, tombstone_date=None).first() if view: change = True view.is_tombstone = True else: count = db.query(ViewPost).filter_by( post_id=post_id, actor_id=user_id, tombstone_date=None).count() if not count: change = True db.add(ViewPost(post=post, actor_id=user_id)) new_counts = [] if change: new_counts = Idea.idea_read_counts(discussion_id, post_id, user_id) return { "ok": True, "ideas": [ {"@id": Idea.uri_generic(idea_id), "num_read_posts": read_posts } for (idea_id, read_posts) in new_counts] }
def session_invite(request): next_url = request.params.get('next', request.application_url) if request.method == 'GET': if any(k not in request.GET for k in ('sid', 'expires')): raise HTTPNotFound() return dict(session_id=request.GET['sid'], expires=request.GET['expires'], next_url=next_url) elif request.method == 'POST': sid = request.POST['sid'] expires = request.POST['expires'] try: store = SessionStore.filter_by(session_id=sid, key='auth.policy.current').one() except NoResultFound: raise InvalidCredentialsException(message=_("Session not found.")) value = json.loads(store.value) exp = datetime.fromtimestamp(value[2]) if datetime.fromisoformat(expires) != exp: raise InvalidCredentialsException( message=_("Invalid 'expires' parameter.")) now = datetime.utcnow() if exp <= now: raise InvalidCredentialsException(message=_("Session expired.")) cookie_settings = WebSession.cookie_settings(request) cookie_settings['max_age'] = int((exp - now).total_seconds()) cookie_name = request.env.pyramid.options['session.cookie.name'] response = HTTPFound(location=next_url) response.set_cookie(cookie_name, value=sid, **cookie_settings) return response
def view_page(request): pagename = request.matchdict['pagename'] page = request.dbsession.query( models.Page).filter_by(name=pagename).first() if page is None: raise HTTPNotFound('No such page') def add_link(match): word = match.group(1) exists = request.dbsession.query( models.Page).filter_by(name=word).all() if exists: view_url = request.route_url('view_page', pagename=word) return '<a href="%s">%s</a>' % (view_url, escape(word)) else: add_url = request.route_url('add_page', pagename=word) return '<a href="%s">%s</a>' % (add_url, escape(word)) content = publish_parts(page.data, writer_name='html')['html_body'] content = wikiwords.sub(add_link, content) edit_url = request.route_url('edit_page', pagename=page.name) return dict(page=page, content=content, edit_url=edit_url)
def user_getfilebyid(request): """获取文件 """ conn = DBSession() fsfileid = request.params.get('fsfileid') fsfile = conn.query(Fsfile).filter(Fsfile.id == fsfileid).first() if os.path.exists(fsfile.filepath): extension = fsfile.filename.split('.')[-1:][0] content_type = mimetypes.types_map['.' + extension] file = open(fsfile.filepath) response = request.response response.headers['Pragma'] = 'no-cache' response.headers['Cache-Control'] = 'no-cache' response.headers['Content-Disposition'] = str( "attachment; filename=\"" + fsfile.filename + " \"") # log.debug(response.headers['Content-Disposition']) response.headers['Content-Type'] = content_type response.headers['Expires'] = '0' # response.headers['Accept-Charset']='utf-8' response.write(file.read()) return response return HTTPNotFound()