def load(self): """Load the content for resources. Raise: MissingRequiredFieldError: when no object can be found with the matching attribute. """ resources_structure = self.load_yaml_file( self.BASE_PATH.format(self.structure_file)) for (resource_slug, resource_structure) in resources_structure.items(): try: resource_name = resource_structure["name"] resource_template = resource_structure["webpage-template"] resource_view = resource_structure["generation-view"] resource_thumbnail = resource_structure[ "thumbnail-static-path"] resource_copies = resource_structure["copies"] except: raise MissingRequiredFieldError() resource = Resource( slug=resource_slug, name=resource_name, webpage_template=resource_template, generation_view=resource_view, thumbnail_static_path=resource_thumbnail, copies=resource_copies, ) resource.save() self.log("Added Resource: {}".format(resource.name)) self.log("All resources loaded!\n")
def load(self): """Load the content for resources. Raise: MissingRequiredFieldError: when no object can be found with the matching attribute. """ resources_structure = self.load_yaml_file(self.structure_file_path) for (resource_slug, resource_structure) in resources_structure.items(): try: generator_module = resource_structure["generator-module"] resource_thumbnail = resource_structure[ "thumbnail-static-path"] resource_copies = resource_structure["copies"] except KeyError: raise MissingRequiredFieldError( self.structure_file_path, ["generator-module", "thumbnail-static-path", "copies"], "Resource") resource_translations = self.get_blank_translation_dictionary() content_filename = "{}.md".format(resource_slug) content_translations = self.get_markdown_translations( content_filename) for language, content in content_translations.items(): resource_translations[language][ "content"] = content.html_string resource_translations[language]["name"] = content.title # Remove .py extension if given if generator_module.endswith(".py"): generator_module = generator_module[:-3] # Check module can be imported get_resource_generator(generator_module, QueryDict()) # Check thumbnail exists if not finders.find(resource_thumbnail): error_text = "Thumbnail image {} for resource {} could not be found." raise FileNotFoundError( error_text.format(resource_thumbnail, resource_slug)) # Check copies value is boolean if not isinstance(resource_copies, bool): raise InvalidYAMLValueError(self.structure_file_path, "copies", "'true' or 'false'") resource = Resource( slug=resource_slug, generator_module=generator_module, thumbnail_static_path=resource_thumbnail, copies=resource_copies, ) self.populate_translations(resource, resource_translations) self.mark_translation_availability( resource, required_fields=["name", "content"]) resource.save() self.log("Added Resource: {}".format(resource.name)) self.log("All resources loaded!\n")
def save_resource(self, data, obj): if not obj: obj = Resource() obj._created = True else: obj._created = False obj._changed = False obj._changed_fields = [] self._update_fields(obj, data, ['id', 'purposes']) if obj._created: print("%s created" % obj) print(obj.type_id) obj.save() old_purposes = set([purp.pk for purp in obj.purposes.all()]) new_purposes = set([purp.pk for purp in data['purposes']]) if old_purposes != new_purposes: obj.purposes = new_purposes obj._changed_fields.append('purposes') if obj._changed: if not obj._created: print("%s changed: %s" % (obj, ', '.join(obj._changed_fields))) obj.save() return obj
def create_resource(self, slug, name, content, generator_module, thumbnail=True, copies=False): """Create resource object. Args: slug: Resource slug (str). name: Resource name (str). webpage_template: Path to HTML form template (str). generator_module: Resource generator class filename (str). Returns: Resource object. """ resource = Resource( slug=slug, name=name, content=content, generator_module=generator_module, copies=copies, ) if thumbnail: resource.thumbnail_static_path = "static/images/thumbnail-{}".format( slug) resource.save() return resource
def createResource(entry): resource = Resource() resource.title = entry.custom["title"].text resource.created_at = datetime.datetime.strptime(entry.custom["timestamp"].text, "%m/%d/%Y %H:%M:%S") resource.abstract = entry.custom["abstract"].text resource.media_type = entry.custom["mediatype"].text resource.added_by = entry.custom["enteredby"].text resource.url = entry.custom["link"].text try: resource.length = entry.custom["length"].text except TypeError: print "This resource has no length." try: resource.save() except MySQLdb.Warning: print "Error saving resource.", sys.exc_info()[0] return topics = entry.custom["topictypes"].text.split(",") for topic_string in topics: topic_string = topic_string.strip() try: topic = Topic.objects.get(topic=topic_string) except ObjectDoesNotExist: topic = Topic(topic = topic_string) topic.save() resource.topics.add(topic)
def handle(self, *args, **options): TYPE = '2' ROW_COMMENT = 5 IMPORTED_FROM = 'fallingfruit.org' filename = options['file'][1] print('Importing from {}.'.format(filename)) file = open(filename) count = 0 for row in csv.reader(file, delimiter=','): if row[1] == TYPE: # type in first row; '2' is dumpster lat = row[2] long = row[3] id = str(row[0]) if not Resource.objects.filter(imported_from=IMPORTED_FROM, import_reference=id).exists(): location = 'POINT(' + str(long) + ' ' + str(lat) + ')' resource = Resource(location=location, imported=True, imported_from=IMPORTED_FROM, import_reference=id) resource.save() voting = Voting(resource=resource, comment=row[ROW_COMMENT], value=Voting.GOOD) voting.save() count += 1 print('Finished. Imported {} new objects.'.format(count))
def collection_importer(): data = read_file(FILENAME) for item in data: if item['language'] is not None and item['language'] != '': language = Language.objects.filter(code=item['language']) if language.exists(): lang = Language.objects.get(code=item['language']) else: lang = None else: lang = None if item['type_of_resource'] is not None and item['type_of_resource'] != '': type_of_resource = ResourceType.objects.filter(name=item['type_of_resource']) if type_of_resource.exists(): res_type = ResourceType.objects.get(name=item['type_of_resource']) else: res_type = None else: res_type = None content_manager = User.objects.get(username='******') tagging_person = User.objects.get(username='******') resource = Resource( title=item['title'] if 'title' != '' else 'None', short_title=item['shortTitle'], abstract=item['abstract'], authors=convert_authors(item['authors']), year_of_publication=convert_year(item['year']), doi=item['doi'], language=lang, type_of_resource=res_type, url=item['url'], resource_file=None, added_by=content_manager, ) resource.save() res = Resource.objects.get(id=resource.id) res.tagging_persons.add(tagging_person.id) res_status = ResourceStatus( resource_id=resource.id, waiting_for_tagging=True, status_description='Waiting for tagging' ) res_status.save() tagging_res = TaggingResource( resource_id=resource.id ) tagging_res.save() print('Resource has been added!') print('DONE!')
def mutate(root, info, input=None): ok = True course = Course.objects.get(pk=input.course.id) resource_instance = Resource( resource_name=input.resource_name, resource_file=input.resource_file, course=course, ) resource_instance.save() return CreateResource(ok=ok, resource=resource_instance)
def test_typed_create(self): res1 = Resource(type='MockTestResource') res1.save() self.assertEqual('resources.resource', res1.type) res2 = MockTestResource.objects.create(name='Test resource 2') self.assertTrue(isinstance(res2, MockTestResource)) res3 = MockTestResource.active.create(name='Test resource 3') self.assertTrue(isinstance(res3, MockTestResource))
def load(self): """Load the content for resources. Raise: MissingRequiredFieldError: when no object can be found with the matching attribute. """ resources_structure = self.load_yaml_file(self.structure_file_path) for (resource_slug, resource_structure) in resources_structure.items(): try: resource_name = resource_structure["name"] resource_template = resource_structure["webpage-template"] generator_module = resource_structure["generator-module"] resource_thumbnail = resource_structure[ "thumbnail-static-path"] resource_copies = resource_structure["copies"] except KeyError: raise MissingRequiredFieldError(self.structure_file_path, [ "name", "webpage-template", "generator-module", "thumbnail-static-path", "copies" ], "Resource") # Check resource template file exists open(os.path.join("templates", resource_template), encoding="UTF-8") # Remove .py extension if given if generator_module.endswith(".py"): generator_module = generator_module[:-3] # Check module can be imported get_resource_generator(generator_module, QueryDict()) # Check thumbnail exists if not finders.find(resource_thumbnail): raise FileNotFoundError # Check copies value is boolean if not isinstance(resource_copies, bool): raise InvalidConfigValueError(self.structure_file_path, "copies", "'true' or 'false'") resource = Resource( slug=resource_slug, name=resource_name, webpage_template=resource_template, generator_module=generator_module, thumbnail_static_path=resource_thumbnail, copies=resource_copies, ) resource.save() self.log("Added Resource: {}".format(resource.name)) self.log("All resources loaded!\n")
def submit(req): Info = req.POST subject =Info.get('subject') href = Info.get('href') tag = Info.get('tag') key =Info.get('key') if req.session.has_key('isLogin'): username = req.session.get('username') try: author =PrivateUser.object.get(username=username) except: messages.add_message(req, messages.ERROR, '提交失败', extra_tags='error') return redirect('/resource') newResource = Resource() try: newResource.key=key newResource.author=author newResource.subject=subject newResource.href=href newResource.tag=tag newResource.save() except: messages.add_message(req, messages.ERROR, '提交失败', extra_tags='danger') return redirect('/resource') messages.add_message(req, messages.ERROR, '提交成功!', extra_tags='success') return redirect('/resource') else: messages.add_message(req, messages.ERROR, '提交失败', extra_tags='danger') return redirect('/resource')
def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] name = form_data[0]['name'] description = form_data[0]['description'] mime_type = form_data[0]['mime_type'] is_resource = form_data[0]['is_resource'] original_file = form_data[0]['original_file'] file = form_data[0]['file'] type = self.storage.get_step_data('select_file').get( 'select_file-type') entity_types = self.storage.get_step_data('select_file').getlist( 'select_file-entity_types') path = self.file_storage.path(file.name) map_attrs_data = self.storage.get_step_data('map_attributes') project = self.get_project() org = project.organization config_dict = { 'project': project, 'file': path, 'type': type, 'entity_types': entity_types.copy(), 'party_name_field': form_data[2]['party_name_field'], 'party_type_field': form_data[2]['party_type_field'], 'location_type_field': form_data[2]['location_type_field'], 'geometry_field': form_data[2]['geometry_field'], 'attributes': map_attrs_data.getlist('attributes', None), } importer = self._get_importer(type, path) importer.import_data(config_dict) if is_resource: default_storage = DefaultStorage() file.seek(0) ext = file.name[file.name.rfind('.'):] resource = Resource(name=name, description=description, original_file=original_file, mime_type=mime_type, contributor=self.request.user, project=self.get_project()) upload_to = getattr(resource.file.field, 'upload_to') url = '' while not url: temp_url = upload_to + '/' + random_id() + ext if not Resource.objects.filter( file__contains=temp_url).exists(): url = default_storage.save(temp_url, file.read()) resource.file.url = url resource.save() ContentObject.objects.create(resource=resource, content_object=resource.project) return redirect('organization:project-dashboard', organization=org.slug, project=project.slug)
def setUp(self): self.user = User(username="******") self.user.set_password('12345') self.user.save() self.teacher_user = User(username="******") self.teacher_user.set_password('12345') self.teacher_user.save() self.student = Student(user=self.user) self.student.save() self.teacher = Professor(user=self.teacher_user) self.teacher.save() res1_content = {"title": "Res1"} self.res1 = Resource(added_by=self.teacher_user, content=res1_content) self.res1.save() self.section = Section(id=1, name="Section1") self.section.save() self.section.resource.add(self.res1) self.section.save() self.skill2 = Skill(id=2, name="Skill2", code="2") self.skill2.save() res2_content = {"title": "Res2"} self.res2 = Resource(added_by=self.teacher_user, content=res2_content) self.res2.save() self.skill3 = Skill(id=3, name="Skill3", code="3") self.skill3.save() self.skill3.resource.add(self.res2) self.skill3.save() self.skill4 = Skill(id=4, name="Skill4", code="4") self.skill4.section = self.section self.skill4.save() self.stage = Stage(id=1, name="Stage1", level=1) self.stage.save() self.stage.skills.add(self.skill3) self.stage.skills.add(self.skill4) self.stage.save() self.lesson = Lesson(id=1, name="English", stage_id=1) self.lesson.save() self.lesson.students.add(self.student) self.lesson.professors.add(self.teacher) self.lesson.save() self.s1 = Client() self.s1.login(username=self.user.username, password='******') self.t1 = Client() self.t1.login(username=self.teacher_user.username, password='******')
def resource_add(request, template_name='depot/resource_edit.html'): """adds a new resource""" import urllib # seems url becomes http:/ on server- no idea why # defensive coding ftw. req_path = urllib.unquote(request.path).replace( 'http://', 'http~~').replace('http:/', 'http~~').replace('||', '\n') req_data = get_req_data(req_path) debug_info = (req_path, req_data) template_info = _template_info(req_data.get('popup', '')) if request.method == 'POST': if request.POST.get('result', '') == 'Cancel': return resource_edit_complete(request, None, template_info) form = ShortResourceForm(request.POST) if form.is_valid(request.user): resource = Resource(**form.cleaned_data) # resource.metadata.author = str(request.user.id) try: # resource.collection_status = COLL_STATUS_LOC_CONF user = get_account(request.user.id) resource.owner = user # save will create default moderation and curation using owner acct resource.save(author=user, reindex=True) increment_resource_crud('resouce_add', account=user) # resource.index() # if popup: # return HttpResponseRedirect(reverse('resource-popup-close')) return HttpResponseRedirect( '%s?popup=%s' % (reverse('resource_edit', args=[resource.id]), template_info['popup'])) except OperationError: pass else: description = req_data.get('t', '') initial = { 'uri': req_data.get('page', '').replace('http~~', 'http://'), 'title': req_data.get('title', ''), 'description': description[:1250] } form = ShortResourceForm(initial=initial) return render_to_response( template_name, RequestContext( request, { 'resourceform': form, 'template_info': template_info, 'debug_info': debug_info }))
def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] name = form_data[0]['name'] description = form_data[0]['description'] mime_type = form_data[0]['mime_type'] is_resource = form_data[0]['is_resource'] original_file = form_data[0]['original_file'] file = form_data[0]['file'] type = self.storage.get_step_data( 'select_file').get('select_file-type') entity_types = self.storage.get_step_data('select_file').getlist( 'select_file-entity_types' ) path = self.file_storage.path(file.name) map_attrs_data = self.storage.get_step_data('map_attributes') project = self.get_project() org = project.organization config_dict = { 'project': project, 'file': path, 'type': type, 'entity_types': entity_types.copy(), 'party_name_field': form_data[2]['party_name_field'], 'party_type_field': form_data[2]['party_type_field'], 'location_type_field': form_data[2]['location_type_field'], 'geometry_field': form_data[2]['geometry_field'], 'attributes': map_attrs_data.getlist('attributes', None), } importer = self._get_importer(type, path) importer.import_data(config_dict) if is_resource: default_storage = DefaultStorage() file.seek(0) ext = file.name[file.name.rfind('.'):] resource = Resource( name=name, description=description, original_file=original_file, mime_type=mime_type, contributor=self.request.user, project=self.get_project()) upload_to = getattr(resource.file.field, 'upload_to') url = '' while not url: temp_url = upload_to + '/' + random_id() + ext if not Resource.objects.filter( file__contains=temp_url).exists(): url = default_storage.save(temp_url, file.read()) resource.file.url = url resource.save() ContentObject.objects.create(resource=resource, content_object=resource.project) return redirect('organization:project-dashboard', organization=org.slug, project=project.slug)
def test_tags(self): """docstring for test_tags""" resources = Resource.objects(tags="red") self.assertEqual(len(resources), 4) # 6 tags contain blue OR red resources = Resource.objects(tags__in=["blue", "red"]) self.assertEqual(len(resources), 9) # 2 tags contain blue AND red resources = Resource.objects(tags__all=["blue", "red"]) self.assertEqual(len(resources), 3)
def test_tags(self): """docstring for test_tags""" resources = Resource.objects(tags='red') self.assertEqual(len(resources), 4) # 6 tags contain blue OR red resources = Resource.objects(tags__in=['blue', 'red']) self.assertEqual(len(resources), 9) # 2 tags contain blue AND red resources = Resource.objects(tags__all=['blue', 'red']) self.assertEqual(len(resources), 3)
def get_context_data(self, **kwargs): context = super().get_context_data() context['latest_resource'] = Resource.get_latest(self.request.user) context['most_liked_resource'] = Resource.get_most_liked(self.request.user) context['most_tried_resource'] = Resource.get_most_tried(self.request.user) context['most_published'] = Organisation.get_most_published_this_week() context['latest_resources'] = Resource.objects.approved( self.request.user, ).order_by( '-created_at', )[:12] return context
def clean_uri(self): data = self.cleaned_data['uri'] if data: try: if self.instance: # id__not=instance.id throws an error, this works check = Resource.objects(id__not__in=[self.instance.id], uri=data) else: check = Resource.objects(uri=data) if check.count() > 0: raise forms.ValidationError("There is already an item with this uri") except DoesNotExist: pass return data
def get_context_data(self, **kwargs): context = super().get_context_data() context['carousel_resources'] = Resource.get_carousel_resources( self.request.user) context['latest_resource'] = Resource.get_latest(self.request.user) most_tried_resource = Resource.get_most_tried( self.request.user).first() context['most_tried'] = most_tried_resource kwargs = {'user': self.request.user} if most_tried_resource: kwargs.update({'exclude': most_tried_resource.id}) context['most_liked'] = Resource.get_most_liked(**kwargs).first() context['most_published'] = Organisation.get_most_published_this_week() return context
def test_create(self): resource1 = Resource() resource1.save() resource2 = Resource(status=Resource.STATUS_DELETED) resource2.save() resource3 = Resource(status=Resource.STATUS_LOCKED) resource3.save() self.assertEqual(3, len(Resource.objects.all())) self.assertEqual(2, len(Resource.active.all()))
def _db_info(self): print SEP print 'connection: ' + self.db_name print 'resource: %s' % Resource.objects.count() print 'acct resource: %s' % Resource.objects(owner=self.account).count() print 'related resources: %s' % RelatedResource.objects.count() print 'locations: %s' % Location.objects.count() print SEP
def resource_add(request, template_name='depot/resource_edit.html'): """adds a new resource""" import urllib # seems url becomes http:/ on server- no idea why # defensive coding ftw. req_path = urllib.unquote(request.path).replace('http://', 'http~~').replace('http:/', 'http~~').replace('||', '\n') req_data = get_req_data(req_path) debug_info = (req_path, req_data) template_info = _template_info(req_data.get('popup', '')) if request.method == 'POST': if request.POST.get('result', '') == 'Cancel': return resource_edit_complete(request, None, template_info) form = ShortResourceForm(request.POST) if form.is_valid(request.user): resource = Resource(**form.cleaned_data) # resource.metadata.author = str(request.user.id) try: # resource.collection_status = COLL_STATUS_LOC_CONF user = get_account(request.user.id) resource.owner = user # save will create default moderation and curation using owner acct resource.save(author=user, reindex=True) increment_resource_crud('resouce_add', account=user) # resource.index() # if popup: # return HttpResponseRedirect(reverse('resource-popup-close')) return HttpResponseRedirect('%s?popup=%s' % (reverse('resource_edit', args=[resource.id]), template_info['popup'])) except OperationError: pass else: description= req_data.get('t', '') initial = { 'uri': req_data.get('page', '').replace('http~~', 'http://'), 'title': req_data.get('title', ''), 'description': description[:1250] } form = ShortResourceForm(initial=initial) return render_to_response(template_name, RequestContext( request, {'resourceform': form, 'template_info': template_info, 'debug_info': debug_info }))
def test_filter_queryset_active(self): resource1 = Resource() resource1.save() resource2 = Resource(status=Resource.STATUS_DELETED) resource2.save() resource3 = Resource(status=Resource.STATUS_LOCKED) resource3.save() self.assertEqual(0, len(Resource.active.filter(status=Resource.STATUS_DELETED))) self.assertEqual(1, len(Resource.active.filter(status=Resource.STATUS_LOCKED))) self.assertEqual(2, len(Resource.active.all())) self.assertEqual(1, len(Resource.active.filter(status=Resource.STATUS_LOCKED))) self.assertEqual(0, len(Resource.active.filter(type='unknown')))
def test_proxy_models(self): resource1 = Resource() resource1.status = Resource.STATUS_FREE resource1.save() resource_pool1 = Resource() resource_pool1.status = Resource.STATUS_INUSE resource_pool1.save() resource_pool1.name = 'test pool' # search with target type resource = Resource.active.filter(status=Resource.STATUS_FREE)[0] resource_pool = Resource.active.filter(status=Resource.STATUS_INUSE)[0] self.assertEqual('Resource', resource.type) self.assertEqual('Resource', resource_pool.type)
def create_resource(self, slug, name, content, generator_module, copies=False): """Create resource object. Args: slug: Resource slug (str). name: Resource name (str). webpage_template: Path to HTML form template (str). generator_module: Resource generator class filename (str). Returns: Resource object. """ resource = Resource( slug=slug, name=name, content=content, generator_module=generator_module, copies=copies, ) resource.save() return resource
def test_get_carousel_resources(self): ResourceFactory.create( title='first', likes=UserFactory.create_batch(size=10), status=RESOURCE_APPROVED ) second = ResourceFactory.create( title='second', tried=UserFactory.create_batch(size=5), hits=20, status=RESOURCE_APPROVED, ) resources = Resource.get_carousel_resources(limit=1) self.assertIn(second, resources)
def index(request): if not request.session.has_key('test'): request.session['test'] = 10 else: request.session['test'] = request.session['test'] + 1 pp.pprint(request.session['test']) #resources = Resource.objects.all() if request.method == 'POST': # create a form instance and populate it with data from the request: form = ResourceForm(request.POST) # check whether it's valid: if form.is_valid(): pp.pprint(form.cleaned_data) resource = Resource(name=form.cleaned_data["resource_name"], user_id=request.user.id) resource.save() return HttpResponseRedirect('/resources') else: form = ResourceForm() resources = request.user.resource_set.all() context = {"resources": resources, "form": form} return render(request, "resources/index.html", context)
def delete(self, *args, **kwargs): """docstring for delete""" from issues.models import Issue from resources.models import Resource, Curation res = Resource.objects(owner=self) curs = Curation.objects(owner=self) if curs.count() or res.count(): raise Exception('This account owns resources/curations.') Collection.objects(owner=self).delete() Issue.objects(reporter=self).delete() User.objects.get(pk=self.local_id).delete() self.reindex(remove=True) super(Account, self).delete(*args, **kwargs)
def create_resource(self, slug, name, webpage_template, generation_view): """Create resource object. Args: slug: Resource slug (str). name: Resource name (str). webpage_template: Path to HTML form template (str). generation_view: Python view module filename (str). Returns: Resource object. """ resource = Resource( slug="resource-{}".format(slug), name="Resource {}".format(name), webpage_template=webpage_template, generation_view=generation_view, thumbnail_static_path="static/images/thumbnail-{}".format(slug), copies=False, ) resource.save() return resource
def locations_remove(request, object_id): """docstring for location_remove""" object = get_one_or_404(Location, id=object_id, user=request.user, perm='can_delete') resources = Resource.objects(locations=object) accounts = Account.objects(locations=object) if resources or accounts: res_str = ','.join([res.name for res in resources]) acct_str = ','.join(['<a href="%s">%s</a>' % (reverse('accounts_edit', args=[acct.id]), acct.name) for acct in accounts]) messages.error( request, 'Resources/Accounts using this location:<br>%s<br>%s.' % (res_str, acct_str)) return HttpResponseRedirect(reverse('cab_locations_detail', args=[object.id])) object.delete() messages.success(request, 'Location removed') return HttpResponseRedirect(reverse('cab_locations'))
def save(self): resource_obj = Resource( title=self.validated_data['title'], description=self.validated_data['description'], course_id=self.validated_data['course_id'], content=self.validated_data['content'], ) resource_obj.save() if resource_obj.content != '': result = cloudinary.uploader.upload(resource_obj.content, resource_type="raw") resource_obj.content_url = result['url'] resource_obj.save() os.remove(resource_obj.content.path) return resource_obj
def test_set_get_options(self): resource1 = Resource() resource1.save() resource2 = Resource() resource2.save() self.assertEqual(0, len(ResourceOption.objects.all())) resource1.set_option('g_field1', 'value1') resource1.set_option('ns_field2', 'value2') # пременная с одинаковым именем resource1.set_option('nst_field', 'value_1') resource1.set_option('nst_field', 'value_2') resource1.set_option('nst_field', 'value_3') self.assertEqual(3, len(ResourceOption.objects.all())) # get_option self.assertEqual('value_3', resource1.get_option_value('nst_field')) self.assertEqual('', resource1.get_option_value('nst_field_unk')) self.assertEqual( 'def', resource1.get_option_value('nst_field_unk', default='def')) self.assertEqual('value_3', resource1.get_option_value('nst_field')) # has_option self.assertEqual(True, resource1.has_option('nst_field')) self.assertEqual(False, resource1.has_option('nst_field_unk')) # set_option / edit resource2.set_option('nst_field', 'value_1') self.assertEqual('value_1', resource2.get_option_value('nst_field')) resource2.set_option('nst_field', 'value_2_ed') self.assertEqual('value_2_ed', resource2.get_option_value('nst_field'))
def test_filter_queryset_active(self): resource1 = Resource() resource1.save() resource2 = Resource(status=Resource.STATUS_DELETED) resource2.save() resource3 = Resource(status=Resource.STATUS_LOCKED) resource3.save() self.assertEqual( 0, len(Resource.active.filter(status=Resource.STATUS_DELETED))) self.assertEqual( 1, len(Resource.active.filter(status=Resource.STATUS_LOCKED))) self.assertEqual(2, len(Resource.active.all())) self.assertEqual( 1, len(Resource.active.filter(status=Resource.STATUS_LOCKED))) self.assertEqual(0, len(Resource.active.filter(type='unknown')))
def test_option_type_guessed_format(self): resource1 = Resource() resource1.save() resource1.set_option('g_field0', None) resource1.set_option('g_field1', 'alksdj') resource1.set_option('g_field2', 155) resource1.set_option('g_field3', 155.551) resource1.set_option('g_field4', {'name1': 'val1', 'name2': 'val2'}) resource1.set_option('g_field5', True) self.assertEqual(ResourceOption.FORMAT_STRING, resource1.get_option('g_field0').format) self.assertEqual(ResourceOption.FORMAT_STRING, resource1.get_option('g_field1').format) self.assertEqual(ResourceOption.FORMAT_INT, resource1.get_option('g_field2').format) self.assertEqual(ResourceOption.FORMAT_FLOAT, resource1.get_option('g_field3').format) self.assertEqual(ResourceOption.FORMAT_DICT, resource1.get_option('g_field4').format) self.assertEqual(ResourceOption.FORMAT_BOOL, resource1.get_option('g_field5').format) self.assertEqual(True, resource1.get_option_value('g_field5'))
def test_option_bool_type(self): resource1 = Resource() resource1.save() resource1.set_option('g_field1', True) resource1.set_option('g_field2', False) resource1.set_option('g_field3', 1, format=ResourceOption.FORMAT_BOOL) resource1.set_option('g_field4', 0, format=ResourceOption.FORMAT_BOOL) resource1.set_option('g_field5', '0', format=ResourceOption.FORMAT_BOOL) resource1.set_option('g_field6', '1', format=ResourceOption.FORMAT_BOOL) resource1.set_option('g_field7', 'False', format=ResourceOption.FORMAT_BOOL) resource1.set_option('g_field8', 'True', format=ResourceOption.FORMAT_BOOL) resource1.set_option('g_field9', 'Yes', format=ResourceOption.FORMAT_BOOL) resource1.set_option('g_field10', 'No', format=ResourceOption.FORMAT_BOOL) self.assertEqual(True, resource1.get_option_value('g_field1')) self.assertEqual(False, resource1.get_option_value('g_field2')) self.assertEqual(True, resource1.get_option_value('g_field3')) self.assertEqual(False, resource1.get_option_value('g_field4')) self.assertEqual(False, resource1.get_option_value('g_field5')) self.assertEqual(True, resource1.get_option_value('g_field6')) self.assertEqual(False, resource1.get_option_value('g_field7')) self.assertEqual(True, resource1.get_option_value('g_field8')) self.assertEqual(True, resource1.get_option_value('g_field9')) self.assertEqual(False, resource1.get_option_value('g_field10'))
def test_option_type(self): resource1 = Resource() resource1.save() res_id = resource1.pk resource1.set_option('g_field1', 155, format=ResourceOption.FORMAT_INT) resource1.set_option('g_field2', 155.551, format=ResourceOption.FORMAT_FLOAT) resource1.set_option('g_field3', { 'name1': 'val1', 'name2': 'val2' }, format=ResourceOption.FORMAT_DICT) self.assertEqual(Resource.STATUS_FREE, resource1.status) resource1.delete() resource1 = Resource.objects.get(pk=res_id) self.assertEqual(Resource.STATUS_DELETED, resource1.status) self.assertEqual(155, resource1.get_option_value('g_field1')) self.assertEqual(155.551, resource1.get_option_value('g_field2')) self.assertEqual({ 'name1': 'val1', 'name2': 'val2' }, resource1.get_option_value('g_field3'))
def resource_count(acct): result = cache.get('account_resources_count.%s' % acct.id, None) if result is None: result = Resource.objects(owner=acct).count() cache.set('account_resources_count.%s' % acct.id, result) return result
def run(): with open('resources.txt') as f: while True: line = f.readline().strip() slug, title, description, topic, typ, remote_url, key, reqd = line.split('===') topic = Topic.objects.get(slug=topic) if Resource.objects.filter(slug=slug[:40]): print "SKIPPING %s", title continue key = bool(int(key)) reqd = bool(int(reqd)) if typ == 'Link': print title, resource = Resource( title=title, description=description, topic=topic, slug=slug[:40], status='published', link=remote_url, key=key, required=reqd, ) print remote_url, resource.index_link(remote_url) print ".", resource.save() print "." elif typ == 'File': print title, from django.core.files.base import ContentFile web = urllib2.urlopen(remote_url) the_file = ContentFile(web.read()) resource = Resource( title=title, description=description, topic=topic, slug=slug[:40], status='published', key=key, required=reqd, ) if web.headers.subtype == 'pdf': fname = slug + '.pdf' elif web.headers.subtype == 'html': fname = slug + '.html' else: raise Exception(web.headers.subtype) resource.file.save(fname, the_file, save=False) print ".", resource.index_file(the_file, mimetype=web.headers.type) print ".", resource.save() print "\n\n" web.close() elif typ == 'Image': print title, from django.core.files.base import ContentFile web=urllib2.urlopen(remote_url) the_file=ContentFile(web.read()) resource = Resource( title=title, description=description, topic=topic, slug=slug[:40], status='published', key=key, required=reqd, ) if web.headers.subtype=='jpeg': fname = slug + '.jpg' elif web.headers.subtype=='png': fname = slug + '.png' else: raise Exception(web.headers.subtype) resource.file.save(fname, the_file, save=False) print ".", resource.index_file(the_file, mimetype=web.headers.type) print ".", resource.save() web.close() else: raise Exception("type?")
def test_option_auto_type(self): resource1 = Resource() resource1.save() # setter must guess the value format resource1.set_option('g_field1', 155) resource1.set_option('g_field2', 155.551) resource1.set_option('g_field3', {'name1': 'val1', 'name2': 'val2'}) self.assertEqual(155, resource1.get_option_value('g_field1')) self.assertEqual(155.551, resource1.get_option_value('g_field2')) self.assertEqual({'name1': 'val1', 'name2': 'val2'}, resource1.get_option_value('g_field3'))
def test_option_type(self): resource1 = Resource() resource1.save() res_id = resource1.pk resource1.set_option('g_field1', 155, format=ResourceOption.FORMAT_INT) resource1.set_option('g_field2', 155.551, format=ResourceOption.FORMAT_FLOAT) resource1.set_option('g_field3', {'name1': 'val1', 'name2': 'val2'}, format=ResourceOption.FORMAT_DICT) self.assertEqual(Resource.STATUS_FREE, resource1.status) resource1.delete() resource1 = Resource.objects.get(pk=res_id) self.assertEqual(Resource.STATUS_DELETED, resource1.status) self.assertEqual(155, resource1.get_option_value('g_field1')) self.assertEqual(155.551, resource1.get_option_value('g_field2')) self.assertEqual({'name1': 'val1', 'name2': 'val2'}, resource1.get_option_value('g_field3'))
def test_delete(self): resource1 = Resource() resource1.save() resource2 = Resource() resource2.save() resource3 = Resource(parent=resource2) resource3.save() self.assertEqual(3, len(Resource.active.all())) try: resource2.delete() self.fail("Waiting for the exception.") except ValidationError: pass resource3.delete() resource2.delete() self.assertEqual(3, len(Resource.objects.all())) self.assertEqual(1, len(Resource.active.all()))
def test_set_get_options(self): resource1 = Resource() resource1.save() resource2 = Resource() resource2.save() self.assertEqual(0, len(ResourceOption.objects.all())) resource1.set_option('g_field1', 'value1') resource1.set_option('ns_field2', 'value2') # пременная с одинаковым именем resource1.set_option('nst_field', 'value_1') resource1.set_option('nst_field', 'value_2') resource1.set_option('nst_field', 'value_3') self.assertEqual(3, len(ResourceOption.objects.all())) # get_option self.assertEqual('value_3', resource1.get_option_value('nst_field')) self.assertEqual('', resource1.get_option_value('nst_field_unk')) self.assertEqual('def', resource1.get_option_value('nst_field_unk', default='def')) self.assertEqual('value_3', resource1.get_option_value('nst_field')) # has_option self.assertEqual(True, resource1.has_option('nst_field')) self.assertEqual(False, resource1.has_option('nst_field_unk')) # set_option / edit resource2.set_option('nst_field', 'value_1') self.assertEqual('value_1', resource2.get_option_value('nst_field')) resource2.set_option('nst_field', 'value_2_ed') self.assertEqual('value_2_ed', resource2.get_option_value('nst_field'))