def __setitem__(self, name: str, principal: Union[Principal, dict]) -> None: name = name if isinstance(principal, dict): principal = self.factory(**principal) DBSession.add(principal)
def view_review(context, request): jquery.need() contextbody = jinja2.Markup(context.body) user = get_user(request) if request.POST : if user is None: request.session.flash(u"请先登陆..","info") came_from = request.url return HTTPFound("/login?came_from=%s" % came_from) if 'submit' in request.POST: comment_content = request.params.get("review-comment-input") comment = Comment() comment.type = comment.TYPE_MEETUP_REVIEW comment.user_id = user.id comment.document_id = context.id # ACTION!!!: There is a SQL injection risk here! should be prevented comment.content = comment_content DBSession.add( comment) DBSession.flush() return wrap_user2(request, {'context':context, 'contextbody': contextbody, 'comments_count': len(context.comments) })
def test_unique_constraint(self): # Try to add two children with the same name to the root node: session = DBSession() root = get_root() session.add(Node(name=u'child1', parent=root)) session.add(Node(name=u'child1', parent=root)) self.assertRaises(IntegrityError, session.flush)
def create(self, content, filename=None, content_type=None): """Saves a new file and returns the file id :param content: can either be ``bytes``, another ``file object`` or a :class:`cgi.FieldStorage`. When ``filename`` and ``content_type`` parameters are not provided they are deducted from the content itself. :param filename: filename for this file :type filename: string :param content_type: Mimetype of this file :type content_type: string :return: the unique ``file_id`` associated to this file :rtype: string """ new_file_id = str(uuid.uuid1()) content, filename, content_type = self.fileinfo( content, filename, content_type) if hasattr(content, 'read'): content = content.read() fstore = DBStoredFile(data=content, file_id=new_file_id, filename=filename, content_type=content_type, ) DBSession.add(fstore) return new_file_id
def test_resume2(): stu = DBSession.query(MbaUser).filter_by(email='*****@*****.**').first() resume1 = Resume(title=u'resume1', user=stu) start_date = datetime.strptime('2003-1-1','%Y-%m-%d').date() finish_date = datetime.strptime('2008-1-1','%Y-%m-%d').date() edu = Education( school_name = u'电子科技大学', start_date=start_date, finish_date=finish_date, major=u'通信工程', degree = 1) resume1.educations.append(edu) job = Job( industy = u'美丽的台湾公司', industy_type = 1, industy_scale = 1, duty = u'软件工程师', start_date = start_date, finish_date = finish_date, ) resume1.jobs.append(job) DBSession.add(resume1) DBSession.flush()
def save_success(self, appstruct): appstruct.pop('csrf_token', None) DBSession.add( self.add(**appstruct) ) self.request.session.flash(self.success_message, 'success') location = self.success_url return HTTPFound(location=location)
def create( self, content: Union[bytes, FieldStorage], filename: Optional[str] = None, content_type: Optional[str] = None, ) -> str: """Saves a new file and returns the file id :param content: can either be ``bytes``, another ``file object`` or a :class:`cgi.FieldStorage`. When ``filename`` and ``content_type`` parameters are not provided they are deducted from the content itself. :param filename: filename for this file :type filename: string :param content_type: Mimetype of this file :type content_type: string :return: the unique ``file_id`` associated to this file :rtype: string """ new_file_id = str(uuid.uuid1()) content, filename, content_type = self.fileinfo(content, filename, content_type) if hasattr(content, "read"): content = content.read() fstore = DBStoredFile( data=content, file_id=new_file_id, filename=filename, content_type=content_type, ) DBSession.add(fstore) return new_file_id
def create_fruit_category(self, request): data = ast.literal_eval(request.body) # Assume only one fruit_categories folder. fruit_categories_folder = \ DBSession.query(FruitCategoriesFolder).first() name = str(uuid.uuid4()) fruit_category = FruitCategory(name=name, title=data['title'], parent=fruit_categories_folder) fruit_category.__acl__ = SITE_ACL session = DBSession() session.add(fruit_category) workflow = get_workflow(fruit_category) if workflow: session.flush() workflow.transition_to_state(fruit_category, None, u'public') else: print '################ NO WORKFLOW for ', fruit_category.title session.flush() transaction.commit() fruit_category = \ DBSession.query(FruitCategory).filter_by(name=name).first() return {u'id': fruit_category.id, u'title': fruit_category.title}
def create_fruit(self, request): data = ast.literal_eval(request.body) fruit_category = \ DBSession.query(FruitCategory).filter_by( id=data['fruit_category']).first() name = str(uuid.uuid4()) fruit = Fruit(parent=fruit_category) fruit.__acl__ = SITE_ACL session = DBSession() session.add(fruit) workflow = get_workflow(fruit) if workflow: session.flush() workflow.transition_to_state(fruit, None, u'public') else: print '################ NO WORKFLOW for ', fruit.title session.flush() transaction.commit() fruit = DBSession.query(Fruit).filter_by(name=name).first() return {u'id': fruit.id, u'title': fruit.title, u'fruit_category': fruit.__parent__.id}
def test_persistent_settings_add_new(self): from kotti.resources import Settings session = DBSession() [settings] = session.query(Settings).all() data = {'foo.bar': u'spam', 'kotti.db_version': u'next'} new_settings = settings.copy(data) session.add(new_settings) self.assertEqual(get_settings()['foo.bar'], u'spam') self.assertEqual(get_settings()['kotti.db_version'], u'next')
def test_unique_constraint(self): from kotti import DBSession from kotti.resources import get_root from kotti.resources import Node # Try to add two children with the same name to the root node: root = get_root() DBSession.add(Node(name=u'child1', parent=root)) DBSession.add(Node(name=u'child1', parent=root)) self.assertRaises(IntegrityError, DBSession.flush)
def __setitem__(self, key, value): """See zope.annotation.interfaces.IAnnotations""" # import pdb; pdb.set_trace() if not isinstance(key, string_types): raise TypeError("Only string key is supported") if not key in self.obj._annotations: anno = Annotation(self.obj.id, key, value) self.obj._annotations[key] = anno DBSession.add(anno) else: self.obj._annotations[key].value = value
def test_persistent_settings_add_new(self): from kotti import DBSession from kotti import get_settings from kotti.resources import Settings [settings] = DBSession.query(Settings).all() data = {'foo.bar': u'spam', 'kotti.db_version': u'next'} new_settings = settings.copy(data) DBSession.add(new_settings) self.assertEqual(get_settings()['foo.bar'], u'spam') self.assertEqual(get_settings()['kotti.db_version'], u'next')
def set_groups(name, context, groups_to_set=()): """Set the list of groups for principal with given ``name`` and in given ``context``. """ name = unicode(name) from kotti.resources import LocalGroup DBSession.query(LocalGroup).filter( LocalGroup.node_id == context.id).filter( LocalGroup.principal_name == name).delete() for group_name in groups_to_set: DBSession.add(LocalGroup(context, name, unicode(group_name)))
def create_columns_from_dbf(data, context): tmp = tempfile.NamedTemporaryFile(suffix='.dbf') tmp.file.write(data) tmp.file.flush() dbt = dbf.Table(tmp.name) for fieldname in dbt.field_names: fieldinfo = dbt.field_info(fieldname) column_type = None column_lenght = 0 if fieldinfo[0] in ['N', 'F', 'B', 'Y']: column_type = 'Float' if fieldinfo[2] == 0: column_type = 'Integer' elif fieldinfo[0] in [ 'I', ]: column_type = 'Integer' elif fieldinfo[0] in ['C']: column_type = 'String' column_lenght = fieldinfo[1] elif fieldinfo[0] in ['D']: column_type = 'Date' elif fieldinfo[0] in ['T']: column_type = 'DateTime' elif fieldinfo[0] in ['L']: column_type = 'Boolean' elif fieldinfo[0] in ['P']: logger.warn('Picture type not suppported') if column_type: name = title_to_name(fieldname, blacklist=context.keys()) if fieldname.endswith('_'): destname = fieldname[:-1] else: destname = fieldname if len(destname) < 2: destname = destname + '0' column = RDBTableColumn(parent=context, name=name, title=fieldname, src_column_name=fieldname, dest_column_name=destname, column_type=column_type, column_lenght=column_lenght, is_pk=False) DBSession.add(column) else: raise TypeError(u'Unsupported type %s' % fieldinfo[0]) dbt.close() tmp.close()
def test_node_copy_with_local_groups(self): from kotti import DBSession from kotti.resources import get_root from kotti.resources import Node from kotti.resources import LocalGroup root = get_root() child1 = root['child1'] = Node() local_group1 = LocalGroup(child1, u'joe', u'role:admin') DBSession.add(local_group1) DBSession.flush() child2 = root['child2'] = child1.copy() DBSession.flush() assert child2.local_groups == []
def test_container_methods(self): from kotti import DBSession from kotti.resources import get_root from kotti.resources import Node # Test some of Node's container methods: root = get_root() self.assertEquals(root.keys(), []) child1 = Node(name=u'child1', parent=root) DBSession.add(child1) self.assertEquals(root.keys(), [u'child1']) self.assertEquals(root[u'child1'], child1) del root[u'child1'] self.assertEquals(root.keys(), []) # When we delete a parent node, all its child nodes will be # released as well: root[u'child2'] = Node() root[u'child2'][u'subchild'] = Node() self.assertEquals( DBSession.query(Node).filter(Node.name == u'subchild').count(), 1) del root[u'child2'] self.assertEquals( DBSession.query(Node).filter(Node.name == u'subchild').count(), 0) # We can pass a tuple as the key to more efficiently reach # down to child objects: root[u'child3'] = Node() subchild33 = Node(name=u'subchild33', parent=root[u'child3']) DBSession.add(subchild33) del root.__dict__['_children'] # force a different code path self.assertTrue( root[u'child3', u'subchild33'] is root[u'child3'][u'subchild33']) self.assertTrue( root[(u'child3', u'subchild33')] is subchild33) self.assertTrue( root[(u'child3', u'subchild33')] is subchild33) self.assertRaises(KeyError, root.__getitem__, (u'child3', u'bad-name')) root.children # force a different code path self.assertRaises(KeyError, root.__getitem__, (u'child3', u'bad-name')) del root[u'child3'] # Overwriting an existing Node is an error; first delete manually! child4 = Node(name=u'child4', parent=root) DBSession.add(child4) self.assertEquals(root.keys(), [u'child4']) child44 = Node(name=u'child4') DBSession.add(child44) root[u'child4'] = child44 self.assertRaises(SQLAlchemyError, DBSession.flush)
def test_container_methods(self, db_session): from kotti import DBSession from kotti.resources import get_root from kotti.resources import Node # Test some of Node's container methods: root = get_root() assert root.keys() == [] child1 = Node(name=u'child1', parent=root) DBSession.add(child1) assert root.keys() == [u'child1'] assert root[u'child1'] == child1 del root[u'child1'] assert root.keys() == [] # When we delete a parent node, all its child nodes will be # released as well: root[u'child2'] = Node() root[u'child2'][u'subchild'] = Node() assert (DBSession.query(Node).filter( Node.name == u'subchild').count() == 1) del root[u'child2'] assert (DBSession.query(Node).filter( Node.name == u'subchild').count() == 0) # We can pass a tuple as the key to more efficiently reach # down to child objects: root[u'child3'] = Node() subchild33 = Node(name=u'subchild33', parent=root[u'child3']) DBSession.add(subchild33) del root.__dict__['_children'] # force a different code path assert root[u'child3', u'subchild33'] is root[u'child3'][u'subchild33'] assert root[(u'child3', u'subchild33')] is subchild33 assert root[(u'child3', u'subchild33')] is subchild33 with raises(KeyError): root[u'child3', u'bad-name'] root.children # force a different code path with raises(KeyError): root[u'child3', u'bad-name'] del root[u'child3'] # Overwriting an existing Node is an error; first delete manually! child4 = Node(name=u'child4', parent=root) DBSession.add(child4) assert root.keys() == [u'child4'] child44 = Node(name=u'child4') DBSession.add(child44) root[u'child4'] = child44 with raises(SQLAlchemyError): DBSession.flush()
def save_answers(self, request, questions, answers, username=None): browser_data = { "host": request.host, "client_ip": request.client_addr, "user_agent": request.user_agent, } if self.collect_user_info: if not username and not request.user: request.session.flash( _("Please login or provide your username to continue."), "warning") return False survey = UserSurvey.query.filter( UserSurvey.survey_id == self.id, UserSurvey.username == (username or request.user.name)).first() if survey: request.session.flash(_("You have already done this survey."), "warning") return False survey = UserSurvey( browser_data=browser_data, survey_id=self.id, id=uuid_factory(), username=(username or request.user.name), ) else: survey = UserSurvey(browser_data=browser_data, survey_id=self.id, id=uuid_factory()) if survey.save_answers(questions, answers): DBSession.add(survey) request.session.flash( _(u'Thank you for completing ${title}.', mapping=dict(title=self.title)), 'success') return survey else: request.session.flash( _((u'Something went wrong, pleace check' ' if all required fields are field out.')), 'danger') return False
def populate(): """ Create the root node (:class:`~kotti.resources.Document`) and the 'about' subnode in the nodes tree if there are no nodes yet. """ lrm = LocalizerRequestMixin() lrm.registry = get_current_registry() lrm.locale_name = get_settings()['pyramid.default_locale_name'] localizer = lrm.localizer if DBSession.query(Node.id).count() == 0: localized_root_attrs = dict([(k, localizer.translate(v)) for k, v in _ROOT_ATTRS.iteritems()]) root = Document(**localized_root_attrs) root.__acl__ = SITE_ACL DBSession.add(root) localized_about_attrs = dict([(k, localizer.translate(v)) for k, v in _ABOUT_ATTRS.iteritems()]) root['about'] = Document(**localized_about_attrs) DBSession.flush() populate_users()
def extract_from_archive(data, context): tmp = tempfile.NamedTemporaryFile() tmp.file.write(data) tmp.file.flush() if tarfile.is_tarfile(tmp.name): tmptf = tarfile.open(tmp.name) for ti in tmptf.getmembers(): if ti.isfile() and ti.size > 0: tf = tmptf.extractfile(ti) import ipdb ipdb.set_trace() tf.close() tmptf.close() elif zipfile.is_zipfile(tmp.name): tmpzip = zipfile.ZipFile(tmp.file) extensions = [] for zi in tmpzip.infolist(): tz = tmpzip.open(zi) extensions.append(zi.filename[-4:]) #mimetypes.guess_type(filename, strict=False) if zi.filename.endswith('.dbf'): create_columns_from_dbf(tz.read(), context) tz.close() if (('.dbf' in extensions) and ('.shp' in extensions) and ('.shx' in extensions)): if SPATIAL: nfo = extract_geometry_info(data) column = RDBTableColumn( parent=context, name='geometry', title='Geometry', src_column_name=None, dest_column_name=nfo['name'], column_type=nfo['geometry'], column_lenght=2, #XXX dimensions 2 or 3 is_pk=False) DBSession.add(column) tmpzip.close() tmp.close()
def __setitem__(self, name, principal): name = unicode(name) if isinstance(principal, dict): principal = self.factory(**principal) DBSession.add(principal)