def project_new_arbitrary(request): _ = request.translate ngettext = request.plural_translate user_id = authenticated_userid(request) user = DBSession.query(User).get(user_id) try: project = Project( _(u'Untitled project'), user ) count = project.import_from_geojson(request.POST['geometry']) request.session.flash( ngettext('Successfully imported ${n} geometry', 'Successfully imported ${n} geometries', count, mapping={'n': count}), 'success') return HTTPFound(location=route_path('project_edit', request, project=project.id)) except Exception, e: msg = _("Sorry, could not create the project. <br />%s") % e.message request.session.flash(msg, 'alert') raise HTTPFound(location=route_path('project_new', request))
def test_resources_with_parent_resource(self): self.config.add_resource('pyramid_routehelper.tests:DummyCrudHandler', 'message', 'messages', parent_resource = dict(member_name='category', collection_name='categories')) assert route_path('category_messages', testing.DummyRequest(), category_id=2) == '/categories/2/messages' assert route_path('category_message', testing.DummyRequest(), category_id=2, id=1) == '/categories/2/messages/1'
def user(request): username = request.matchdict['username'] try: user = DBSession.query(User).filter(User.username == username).one() except NoResultFound: _ = request.translate request.session.flash(_("Sorry, this user doesn't exist")) return HTTPFound(location=route_path('users', request)) user = check_user_name(user) creation_date, changeset_count = get_addl_user_info(user.id) # username has changed if user.username != username: return HTTPFound( location=route_path('user', request, username=user.username)) projects = __get_projects(user.id) return dict(page_id="user", contributor=user, projects=projects, creation_date=creation_date, changeset_count=changeset_count)
def test_basic_resources(self): from nefertari.resource import add_resource_routes add_resource_routes(self.config, DummyCrudView, 'message', 'messages') self.assertEqual('/messages', route_path('messages', testing.DummyRequest())) self.assertEqual('/messages/1', route_path('message', testing.DummyRequest(), id=1))
def menu(request): """ returns the main menu """ # TODO : view/edit permission ... menu = ( dict(label="Users", url=route_path("users", request), title="User management", icon=""), dict(label="Contacts", url=route_path("contacts", request), title="Contact and relationships", icon=""), ) return dict(menu=menu)
def test_basic_resources(self): from nefertari.resource import add_resource_routes add_resource_routes(self.config, DummyCrudView, 'message', 'messages') self.assertEqual( '/messages', route_path('messages', testing.DummyRequest()) ) self.assertEqual( '/messages/1', route_path('message', testing.DummyRequest(), id=1) )
def test_singular_resource(self, *a): View = get_test_view_class() config = _create_config() root = config.get_root_resource() root.add('thing', view=View) grandpa = root.add('grandpa', 'grandpas', view=View) wife = grandpa.add('wife', view=View, renderer='string') wife.add('child', 'children', view=View) config.begin() app = TestApp(config.make_wsgi_app()) self.assertEqual( '/grandpas/1/wife', route_path('grandpa:wife', testing.DummyRequest(), grandpa_id=1) ) self.assertEqual( '/grandpas/1', route_path('grandpa', testing.DummyRequest(), id=1) ) self.assertEqual( '/grandpas/1/wife/children/2', route_path('grandpa_wife:child', testing.DummyRequest(), grandpa_id=1, id=2) ) self.assertEqual(app.put('/grandpas').body, six.b('update_many')) self.assertEqual(app.head('/grandpas').body, six.b('')) self.assertEqual(app.options('/grandpas').body, six.b('')) self.assertEqual(app.delete('/grandpas/1').body, six.b('delete')) self.assertEqual(app.head('/grandpas/1').body, six.b('')) self.assertEqual(app.options('/grandpas/1').body, six.b('')) self.assertEqual(app.put('/thing').body, six.b('replace')) self.assertEqual(app.patch('/thing').body, six.b('update')) self.assertEqual(app.delete('/thing').body, six.b('delete')) self.assertEqual(app.head('/thing').body, six.b('')) self.assertEqual(app.options('/thing').body, six.b('')) self.assertEqual(app.put('/grandpas/1/wife').body, six.b('replace')) self.assertEqual(app.patch('/grandpas/1/wife').body, six.b('update')) self.assertEqual(app.delete('/grandpas/1/wife').body, six.b('delete')) self.assertEqual(app.head('/grandpas/1/wife').body, six.b('')) self.assertEqual(app.options('/grandpas/1/wife').body, six.b('')) self.assertEqual(six.b('show'), app.get('/grandpas/1').body) self.assertEqual(six.b('show'), app.get('/grandpas/1/wife').body) self.assertEqual( six.b('show'), app.get('/grandpas/1/wife/children/1').body)
def test_resources_with_path_prefix_with_trailing_slash(self): self.config.add_resource('pyramid_routehelper.tests:DummyCrudHandler', 'message', 'messages', path_prefix='/category/:category_id/') assert route_path('messages', testing.DummyRequest(), category_id=2) == '/category/2/messages' assert route_path('json_formatted_messages', testing.DummyRequest(), category_id=2) == '/category/2/messages.json' assert route_path('new_message', testing.DummyRequest(), category_id=2) == '/category/2/messages/new' assert route_path('json_formatted_new_message', testing.DummyRequest(), category_id=2) == '/category/2/messages/new.json' assert route_path('json_formatted_message', testing.DummyRequest(), id=1, category_id=2) == '/category/2/messages/1.json' assert route_path('message', testing.DummyRequest(), id=1, category_id=2) == '/category/2/messages/1' assert route_path('json_formatted_edit_message', testing.DummyRequest(), id=1, category_id=2) == '/category/2/messages/1/edit.json' assert route_path('edit_message', testing.DummyRequest(), id=1, category_id=2) == '/category/2/messages/1/edit'
def test_resources_with_path_prefix_with_trailing_slash(self): from nefertari.resource import add_resource_routes add_resource_routes(self.config, DummyCrudView, 'message', 'messages', path_prefix='/category/{category_id}/') self.assertEqual( '/category/2/messages', route_path('messages', testing.DummyRequest(), category_id=2)) self.assertEqual( '/category/2/messages/1', route_path('message', testing.DummyRequest(), id=1, category_id=2))
def test_resources_with_parent_resource_override_name_prefix(self): self.config.add_resource('pyramid_routehelper.tests:DummyCrudHandler', 'message', 'messages', parent_resource=dict( member_name='category', collection_name='categories'), name_prefix='') assert route_path('messages', testing.DummyRequest(), category_id=2) == '/categories/2/messages' assert route_path('message', testing.DummyRequest(), category_id=2, id=1) == '/categories/2/messages/1'
def route(self, route_name, *elements, **kw): """Generate a route URL. I return a URL based on a named route. Calling the URLGenerator instance is the same as calling me. If the constructor arg 'qualified' is true, I call ``pyramid.url.route_url``, otherwise I call ``pyramid.url.route_path``. Arguments: * ``route_name``: the name of a route. * ``*elements``: additional segments to append to the URL path. Keyword arguments are passed to the underlying function. The following are recognized: * ``_query``: the query parameters. May be a dict-like object with an ``.items()`` method or a sequence of 2-tuples. * ``_anchor``: the URL's "#ancor" fragment without the "#". * ``_qualified``: override the constructor's "qualified" flag. * ``_app_url``: override the "scheme://host" prefix. (This also causes the result to be qualified if it wouldn't otherwise be.) * Other keyword args override path variables defined in the route. If the relevant route has a *pregenerator* defined, it may modify the elements or keyword args. """ qualified = kw.get("_qualified", self.qualified) if qualified or "_app_url" in kw: return url.route_url(route_name, self.request, *elements, **kw) else: return url.route_path(route_name, self.request, *elements, **kw)
def route(self, route_name, *elements, **kw): """Generate a route URL. I return a URL based on a named route. Calling the URLGenerator instance is the same as calling me. If the constructor arg 'qualified' is true, I call ``pyramid.url.route_url``, otherwise I call ``pyramid.url.route_path``. Arguments: * ``route_name``: the name of a route. * ``*elements``: additional segments to append to the URL path. Keyword arguments are passed to the underlying function. The following are recognized: * ``_query``: the query parameters. May be a dict-like object with a ``.items()`` method or a sequence of 2-tuples. * ``_anchor``: the URL's "#ancor" fragment without the "#". * ``_app_url``: override the "scheme://host" prefix. (This also causes the result to be qualified if it wouldn't otherwise be.) * Other keyword args override path variables defined in the route. If the relevant route has a *pregenerator* defined, it may modify the elements or keyword args. """ if self.qualified or "_app_url" in kw: return url.route_url(route_name, self.request, *elements, **kw) else: return url.route_path(route_name, self.request, *elements, **kw)
def project(request): check_project_expiration() id = request.matchdict['project'] project = DBSession.query(Project).get(id) if project is None: _ = request.translate request.session.flash(_("Sorry, this project doesn't exist")) return HTTPFound(location=route_path('home', request)) project.locale = get_locale_name(request) filter = and_(TaskState.project_id == id, TaskState.state != TaskState.state_removed, TaskState.state != TaskState.state_ready) history = DBSession.query(TaskState) \ .filter(filter) \ .order_by(TaskState.date.desc()) \ .limit(20).all() user_id = authenticated_userid(request) locked_task = None user = None if user_id: user = DBSession.query(User).get(user_id) locked_task = get_locked_task(project.id, user) features = [] for area in project.priority_areas: features.append(Feature(geometry=shape.to_shape(area.geometry))) return dict(page_id='project', project=project, locked_task=locked_task, history=history, priority_areas=FeatureCollection(features),)
def project(request): check_task_expiration() id = request.matchdict['project'] project = DBSession.query(Project).get(id) if project is None: _ = request.translate request.session.flash(_("Sorry, this project doesn't exist")) return HTTPFound(location=route_path('home', request)) project.locale = get_locale_name(request) filter = and_(TaskHistory.project_id == id, TaskHistory.state != TaskHistory.state_removed, TaskHistory.update.isnot(None)) history = DBSession.query(TaskHistory) \ .filter(filter) \ .order_by(TaskHistory.update.desc()) \ .limit(10).all() user_id = authenticated_userid(request) locked_task = None if user_id: user = DBSession.query(User).get(user_id) locked_task = get_locked_task(project.id, user) return dict( page_id='project', project=project, locked_task=locked_task, history=history, )
def project_new_grid(request): if 'zoom' in request.params: user_id = authenticated_userid(request) user = DBSession.query(User).get(user_id) project = Project( u'Untitled project', user ) DBSession.add(project) DBSession.flush() zoom = int(request.params['zoom']) geometry = request.params['geometry'] polygons = parse_geojson(geometry) from shapely.geometry import MultiPolygon multipolygon = MultiPolygon([polygon for polygon in polygons]) geometry = shape.from_shape(multipolygon, 4326) project.area = Area(geometry) project.auto_fill(zoom) _ = request.translate request.session.flash(_("Project #${project_id} created successfully", mapping={'project_id': project.id}), 'success') return HTTPFound(location=route_path('project_edit', request, project=project.id)) return dict(page_id='project_new_grid')
def edit(request): settings = load_settings() my = MySetting() for setting in settings: if setting.valuex: my.__dict__[setting.name] = setting.valuex else: my.__dict__[setting.name] = setting.value form = Form(request, schema=SettingSchema, obj=my) if form.validate(): form.bind(my) # persist model somewhere... for setting in settings: if setting.name == "motion_id_prefix": update_setting(setting.name, my.motion_id_prefix) if setting.name == "admin_password": update_setting(setting.name, my.admin_password) if setting.name == "user_password": update_setting(setting.name, my.user_password) if setting.name == "mail_sender": update_setting(setting.name, my.mail_sender) if setting.name == "mail_smtppassword": update_setting(setting.name, my.mail_smtppassword) if setting.name == "mail_template": update_setting(setting.name, "", my.mail_template) return HTTPFound(location=route_path("setting_edit", request)) return dict(renderer=FormRenderer(form))
def result_view(request): logger.info("result_view") image = request.session.get('image') logger.debug('From session got image: {0}'.format(image)) if not image: return HTTPFound(location=route_path('home', request)) def retrieve_similar_images(ref, images): img_distance_pairs = [(img, ImgStatisticCounter.distance(ref, img) , ImgStatisticCounter.deviation_distance(ref, img)) for img in images] img_distance_pairs.sort(key=lambda (image, distance, deviation): distance) result = [] for pair in img_distance_pairs: if not ImgStatisticCounter.are_similar(ref, pair[0]): break result.append(pair) return result images = retrieve_similar_images( ref=image, images=DBManager.retrieve_all_except_one(image_id=image['id']) ) return { 'image': image, 'images': images, 'page_name': 'Result' }
def motion_add(request): """create a new motion. 1. show new motion form 2. save to database after user submit """ # initialize the form to select all participants all_users = load_users() all_user_options = [(itm.id, itm.name) for itm in all_users] selected_users = [itm.id for itm in all_users] # add four blank options on new motion form form = Form(request, schema=MotionSchema, defaults=dict(participants = selected_users, options=["","","",""])) if form.validate(): title = form.data.get("title") desc = form.data.get("desc") options = form.data.get("options") users = form.data.get("participants") add_motion(title, desc, options, users) return HTTPFound(location=route_path('motion_list', request)) return dict(renderer=FormRenderer(form), all_user_options=all_user_options)
def project_new_grid(request): if 'zoom' in request.params: user_id = authenticated_userid(request) user = DBSession.query(User).get(user_id) project = Project(u'Untitled project', user) DBSession.add(project) DBSession.flush() zoom = int(request.params['zoom']) geometry = request.params['geometry'] polygons = parse_geojson(geometry) from shapely.geometry import MultiPolygon multipolygon = MultiPolygon([polygon for polygon in polygons]) geometry = shape.from_shape(multipolygon, 4326) project.area = Area(geometry) project.auto_fill(zoom) _ = request.translate request.session.flash( _("Project #${project_id} created successfully", mapping={'project_id': project.id}), 'success') return HTTPFound( location=route_path('project_edit', request, project=project.id)) return dict(page_id='project_new_grid')
def promote_owner(request): userid = request.matchdict['id'] promuser = DBSession.query(User).get(userid) promuser.role = User.role_owner if not promuser.is_owner else None DBSession.flush() return HTTPFound(location=route_path('admin_user_list',request))
def test_resources_with_collection_action(self): self.config.add_resource('pyramid_routehelper.tests:DummyCrudHandler', 'message', 'messages', collection=dict(sorted='GET')) assert route_path('sorted_messages', testing.DummyRequest()) == '/messages/sorted'
def test_resources_with_member_action(self): self.config.add_resource('pyramid_routehelper.tests:DummyCrudHandler', 'message', 'messages', member=dict(comment='GET')) assert route_path('comment_message', testing.DummyRequest(), id=1) == '/messages/1/comment'
def test_resources_with_name_prefix(self): self.config.add_resource('pyramid_routehelper.tests:DummyCrudHandler', 'message', 'messages', name_prefix="special_") assert route_path('special_message', testing.DummyRequest(), id=1) == '/messages/1'
def test_resources_with_new_action(self): self.config.add_resource('pyramid_routehelper.tests:DummyCrudHandler', 'message', 'messages', new=dict(preview='GET')) assert route_path('preview_new_message', testing.DummyRequest(), id=1) == '/messages/new/preview'
def project_publish(request): id = request.matchdict['project'] project = DBSession.query(Project).get(id) project.status = project.status_published return HTTPFound(location=route_path('project', request, project=project.id))
def book_delete(request): try: book_id = int(request.matchdict['id']) if book_id: DBSession.query(Book).filter(Book.id==book_id).delete() return HTTPFound(location=route_path("book_list", request)) except Exception: return HTTPForbidden()
def add_urlhelpers(event): """ Add helpers to the template engine. """ event['static_url'] = lambda x: static_path(x, event['request']) event['route_url'] = lambda name, *args, **kwargs: \ route_path(name, event['request'], *args, **kwargs) event['parse_rest'] = parse_rest event['has_permission'] = event['request'].has_permission
def user_add(request): form = Form(request, schema=UserSchema) if form.validate(): add_user(form.data.get("name"), form.data.get("email"), form.data.get("vote_weight")) return HTTPFound(location=route_path("user_list", request)) return dict(renderer=FormRenderer(form))
def add_urlhelpers(event): """ Add helpers to the template engine. """ event['static_url'] = lambda x: static_path(x, event['request']) event['route_url'] = lambda name, *args, **kwargs: route_path( name, event['request'], *args, **kwargs) event['has_permission'] = lambda perm: has_permission( perm, event['request'].context, event['request'])
def user_validator(request): id = request.matchdict['id'] user = DBSession.query(User).get(id) user.role ^= User.role_validator DBSession.flush() return HTTPFound(location=route_path("user", request, username=user.username))
def genpadname(request): """ Redirect to a new pad with a random name """ all_pads = [p.get_name() for p in get_all_pads()] name = gen_random() while name in all_pads: name = gen_random() return HTTPFound(route_path('pad', request, padid=name))
def user_validator(request): id = request.matchdict['id'] user = DBSession.query(User).get(id) user.role ^= User.role_validator DBSession.flush() return HTTPFound( location=route_path("user", request, username=user.username))
def test_resources_with_path_prefix_with_trailing_slash(self): from nefertari.resource import add_resource_routes add_resource_routes( self.config, DummyCrudView, 'message', 'messages', path_prefix='/category/{category_id}/' ) self.assertEqual( '/category/2/messages', route_path('messages', testing.DummyRequest(), category_id=2) ) self.assertEqual( '/category/2/messages/1', route_path('message', testing.DummyRequest(), id=1, category_id=2) )
def user_delete(request): id = request.matchdict['id'] user = load_user(id) if not user: return HTTPUnauthorized() delete_user(id) return HTTPFound(location=route_path("user_list", request))
def test_basic_resources(self): self.config.add_resource('pyramid_routehelper.tests:DummyCrudHandler', 'message', 'messages') assert route_path('messages', testing.DummyRequest()) == '/messages' assert route_path('json_formatted_messages', testing.DummyRequest()) == '/messages.json' assert route_path('new_message', testing.DummyRequest()) == '/messages/new' assert route_path('json_formatted_new_message', testing.DummyRequest()) == '/messages/new.json' assert route_path('json_formatted_message', testing.DummyRequest(), id=1) == '/messages/1.json' assert route_path('message', testing.DummyRequest(), id=1) == '/messages/1' assert route_path('json_formatted_edit_message', testing.DummyRequest(), id=1) == '/messages/1/edit.json' assert route_path('edit_message', testing.DummyRequest(), id=1) == '/messages/1/edit'
def user(request): username = request.matchdict['username'] try: user = DBSession.query(User).filter(User.username == username).one() except NoResultFound: _ = request.translate request.session.flash(_("Sorry, this user doesn't exist")) return HTTPFound(location=route_path('users', request)) user = check_user_name(user) # username has changed if user.username != username: return HTTPFound(location=route_path('user', request, username=user.username)) projects = __get_projects(user.id) return dict(page_id="user", contributor=user, projects=projects)
def user_project_manager(request): id = request.matchdict['id'] user = DBSession.query(User).get(id) user.role = User.role_project_manager if not user.is_project_manager \ else None DBSession.flush() return HTTPFound(location=route_path("user", request, username=user.username))
def user_admin(request): id = request.matchdict['id'] user = DBSession.query(User).get(id) user.admin = not user.admin DBSession.flush() return HTTPFound(location=route_path("user", request, username=user.username))
def add_urlhelpers(event): """ Add helpers to the template engine. """ event['static_url'] = lambda x: static_path(x, event['request']) event['route_url'] = lambda name, *args, **kwargs: route_path( name, event['request'], *args, **kwargs) event['has_permission'] = lambda perm: has_permission(perm, event['request'].context, event['request'])
def crime_delete(request): try: crime_id = int(request.matchdict['id']) if crime_id: DBSession.query(Crime).filter(Crime.id==crime_id).delete() return HTTPFound(location=route_path("crimes", request)) except Exception: return HTTPForbidden()
def user_admin(request): id = request.matchdict['id'] user = DBSession.query(User).get(id) user.admin = not user.admin DBSession.flush() return HTTPFound( location=route_path("user", request, username=user.username))
def user_project_manager(request): id = request.matchdict['id'] user = DBSession.query(User).get(id) user.role = User.role_project_manager if not user.is_project_manager \ else None DBSession.flush() return HTTPFound( location=route_path("user", request, username=user.username))
def test_resources_with_name_prefix(self): from nefertari.resource import add_resource_routes add_resource_routes(self.config, DummyCrudView, 'message', 'messages', name_prefix="special_") self.assertEqual( '/messages/1', route_path('special_message', testing.DummyRequest(), id=1))
def test_resources_with_name_prefix_from_config(self): from nefertari.resource import add_resource_routes self.config.route_prefix = 'api' add_resource_routes(self.config, DummyCrudView, 'message', 'messages', name_prefix='foo_') self.assertEqual( '/api/messages/1', route_path('api_foo_message', testing.DummyRequest(), id=1))
def license_delete(request): id = request.matchdict['license'] license = DBSession.query(License).get(id) if not license: request.session.flash('License doesn\'t exist!') else: DBSession.delete(license) DBSession.flush() request.session.flash('License removed!') return HTTPFound(location=route_path('licenses', request))
def project_edit(request): id = request.matchdict['project'] project = DBSession.query(Project).get(id) licenses = DBSession.query(License).all() if 'form.submitted' in request.params: for locale, translation in project.translations.iteritems(): with project.force_locale(locale): for field in ['name', 'short_description', 'description', 'instructions', 'per_task_instructions']: translated = '_'.join([field, locale]) if translated in request.params: setattr(project, field, request.params[translated]) DBSession.add(project) for p in ['changeset_comment', 'entities_to_map', 'imagery']: if p in request.params: setattr(project, p, request.params[p]) if 'license_id' in request.params and \ request.params['license_id'] != "": license_id = int(request.params['license_id']) license = DBSession.query(License).get(license_id) project.license = license if 'private' in request.params and \ request.params['private'] == 'on': project.private = True else: project.private = False project.status = request.params['status'] project.priority = request.params['priority'] if request.params.get('due_date', '') != '': due_date = request.params.get('due_date') due_date = datetime.datetime.strptime(due_date, "%m/%d/%Y") project.due_date = due_date else: project.due_date = None if 'josm_preset' in request.params: josm_preset = request.params.get('josm_preset') if hasattr(josm_preset, 'value'): project.josm_preset = josm_preset.value.decode('UTF-8') DBSession.add(project) return HTTPFound(location=route_path('project', request, project=project.id)) return dict(page_id='project_edit', project=project, licenses=licenses)
def label_delete(request): _ = request.translate id = request.matchdict['label'] label = DBSession.query(Label).get(id) if not label: request.session.flash(_("Label doesn't exist!")) else: DBSession.delete(label) DBSession.flush() request.session.flash(_("Label removed!")) return HTTPFound(location=route_path("labels", request))
def project_new_grid(request): _ = request.translate user_id = authenticated_userid(request) user = DBSession.query(User).get(user_id) try: project = Project( _(u'Untitled project'), user ) DBSession.add(project) DBSession.flush() tile_size = int(request.params['tile_size']) geometry = request.params['geometry'] geoms = parse_geojson(geometry) multipolygon = convert_to_multipolygon(geoms) geometry = shape.from_shape(multipolygon, 4326) geom_3857 = DBSession.execute(ST_Transform(geometry, 3857)).scalar() geom_3857 = shape.to_shape(geom_3857) zoom = get_zoom_for_tile_size(geom_3857, tile_size) project.area = Area(geometry) project.auto_fill(zoom) request.session.flash(_("Project #${project_id} created successfully", mapping={'project_id': project.id}), 'success') return HTTPFound(location=route_path('project_edit', request, project=project.id)) except Exception, e: msg = _("Sorry, could not create the project. <br />%s") % e.message request.session.flash(msg, 'alert') raise HTTPFound(location=route_path('project_new', request))