Ejemplo n.º 1
0
    def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
        text_params, text_sections_params, resp = self.validate_params(
            request.body.decode('utf8'))

        if resp:
            return resp

        try:
            profile = self.request.user.instructor

            text = Text.create(text_params=text_params,
                               text_sections_params=text_sections_params)

            text.created_by = profile
            text.save()

            return HttpResponse(
                json.dumps({
                    'id':
                    text.pk,
                    'redirect':
                    reverse('text-edit', kwargs={'pk': text.pk})
                }))
        except (IntegrityError, ObjectDoesNotExist) as e:
            return HttpResponseServerError(
                json.dumps({'errors': 'something went wrong'}))
Ejemplo n.º 2
0
    def validate_params(self, text_params: AnyStr, text: Optional['Text'] = None) -> (Dict, Dict, HttpResponse):
        errors = resp = text_sections_params = None

        try:
            text_params = json.loads(text_params)
        except json.JSONDecodeError as e:
            resp = HttpResponse(json.dumps({'errors': {'json': str(e)}}), status=400)

        try:
            jsonschema.validate(text_params, Text.to_json_schema())

            text_sections_params = text_params.pop('text_sections')

            text_params, errors = TextAPIView.validate_text_params(text_params, {}, text)
            text_sections_params, errors = TextAPIView.validate_text_section_params(text_sections_params,
                                                                                    errors,
                                                                                    text_sections=text.sections.all()
                                                                                    if text else None)
        except jsonschema.ValidationError as e:
            resp = HttpResponse(json.dumps({
                'errors': {
                    'malformed_json': e.message + (
                        ' at ' + '_'.join([str(path) for path in e.relative_path])
                        if e.relative_path else '')
                }
            }), status=400)
        except ValidationError as e:
            resp = HttpResponse(json.dumps({'errors': e.message}), status=400)

        if errors:
            resp = HttpResponse(json.dumps({'errors': errors}), status=400)

        return text_params, text_sections_params, resp
Ejemplo n.º 3
0
    def put(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
        if 'pk' not in kwargs:
            return HttpResponseNotAllowed(permitted_methods=self.allowed_methods)

        try:
            text = Text.objects.get(pk=kwargs['pk'])

            profile = self.request.user.instructor

            text_params, text_sections_params, resp = self.validate_params(request.body.decode('utf8'), text)

            if resp:
                return resp

            try:
                text = Text.update(text_params=text_params, text_sections_params=text_sections_params)
                text.last_modified_by = profile

                text.save()

                return HttpResponse(json.dumps({'id': text.pk, 'updated': True}))
            except WriteLocked:
                return HttpResponseServerError(json.dumps({'errors': 'text {0} is locked.'.format(kwargs['pk'])}))
            except IntegrityError:
                return HttpResponseServerError(json.dumps({'errors': 'something went wrong'}))

        except (Text.DoesNotExist, ObjectDoesNotExist):
            return HttpResponse(json.dumps({'errors': 'something went wrong'}))
Ejemplo n.º 4
0
    def get_context_data(self, **kwargs):
        context = super(AdminCreateEditElmLoadView,
                        self).get_context_data(**kwargs)
        text = None

        if 'pk' in context:
            try:
                text = Text.objects.get(pk=context['pk'])
            except Text.DoesNotExist:
                pass

        context['elm']['text'] = {
            'quote': False,
            'safe': True,
            'value': json.dumps(text.to_dict() if text else None)
        }

        context['elm']['tags'] = {
            'quote': False,
            'safe': True,
            'value': json.dumps([tag.name for tag in Text.tag_choices()])
        }

        context['elm']['translation_flags'] = {
            'quote':
            False,
            'safe':
            True,
            'value':
            json.dumps({
                'csrftoken':
                get_token(self.request),
                'add_as_text_word_endpoint_url':
                reverse('text-word-api'),
                'merge_textword_endpoint_url':
                reverse('text-word-group-api'),
                'text_translation_match_endpoint':
                reverse('text-translation-match-method')
            })
        }

        context['elm']['text_endpoint_url'] = {
            'quote': False,
            'safe': True,
            'value': json.dumps(reverse('text-api'))
        }

        context['elm']['answer_feedback_limit'] = {
            'quote': False,
            'safe': True,
            'value': Answer._meta.get_field('feedback').max_length
        }

        return context
Ejemplo n.º 5
0
 def setUp(self):
     self.request = RequestFactory().get('/text/a_text_node_en-us/')
     self.request.user = User.objects.create_user('admin',
                                                  '*****@*****.**',
                                                  'password')
     self.view = TextView.as_view()
     self.text = Text(name='a_text_node',
                      body='hello',
                      type=Text.TYPE_TEXT,
                      language='en-us')
     self.text.save()
Ejemplo n.º 6
0
 def setUp(self):
     self.view = TextUpdateView.as_view()
     self.text = Text(name='a_text_node',
                      body='hello',
                      type=Text.TYPE_TEXT,
                      language='en-us')
     self.text.save()
     self.request = RequestFactory().post('/update_text/{0}/'.format(
         self.text.id))
     self.request.user = User.objects.create_user('admin',
                                                  '*****@*****.**',
                                                  'password')
Ejemplo n.º 7
0
    def get_context_data(self, **kwargs) -> Dict:
        context = super(TextSearchLoadElm, self).get_context_data(**kwargs)

        context['elm']['text_difficulties'] = {
            'quote': False,
            'safe': True,
            'value': [[d.slug, d.name] for d in TextDifficulty.objects.all()]
        }

        context['elm']['text_tags'] = {
            'quote': False,
            'safe': True,
            'value': json.dumps([tag.name for tag in Text.tag_choices()])
        }

        context['elm']['text_statuses'] = {
            'quote': False,
            'safe': True,
            'value': json.dumps(text_statuses)
        }

        context['elm']['text_api_endpoint_url'] = {
            'quote': True,
            'safe': True,
            'value': reverse('text-api')
        }

        try:
            welcome_student_search = self.request.session['welcome'][
                'student_search']
        except KeyError:
            welcome_student_search = False

        try:
            student_session = self.request.session['welcome']

            del student_session['student_search']

            self.request.session['welcome'] = student_session
        except KeyError:
            pass

        context['elm']['welcome'] = {
            'quote': False,
            'safe': True,
            'value': json.dumps(welcome_student_search)
        }

        return context
Ejemplo n.º 8
0
  def post(self, request):
    if 'content' in request.POST and 'title' in request.POST:
      content = request.POST['content']    
      title = request.POST['title']    

      text = Text(content=content, title=title)

      if request.user.is_authenticated:
        if request.user.id:
          text.user_id = self.request.user.id;

      add_language_to_paste.delay(text)
      text.save()
      response = { 'id': text.id }
    else:
      response = { 'error': 'malformed request'}
    
    return response
Ejemplo n.º 9
0
 def test_render(self):
     t = Text(body='# hello', type=Text.TYPE_MARKDOWN)
     self.assertEqual(t.render(), '<h1>hello</h1>')
     t = Text(body='# hello')
     self.assertEqual(t.render(), '# hello')
Ejemplo n.º 10
0
 def test_text_id(self):
     t = Text(name='hello', language='sv')
     self.assertEqual(t.text_id, 'hello_sv')
     self.assertEqual(t.text_id, str(t))
Ejemplo n.º 11
0
    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
        text = None
        text_sections = None
        filter_by = {}

        user = request.user.student if hasattr(
            request.user, 'student') else request.user.instructor

        all_difficulties = {
            difficulty: 1
            for difficulty in TextDifficulty.difficulty_keys()
        }
        all_tags = {tag.name: 1 for tag in Text.tag_choices()}
        all_statuses = dict(text_statuses)

        difficulties = request.GET.getlist('difficulty')
        tags = request.GET.getlist('tag')
        statuses = request.GET.getlist('status')

        if 'difficulties' in request.GET.keys():
            return HttpResponse(
                json.dumps([(d.slug, d.name)
                            for d in TextDifficulty.objects.all()]))

        valid_difficulties = all(
            list(
                map(lambda difficulty: difficulty in all_difficulties,
                    difficulties)))
        valid_tags = all(list(map(lambda tag: tag in all_tags, tags)))
        valid_statuses = all(
            list(map(lambda status: status in all_statuses, statuses)))

        if not (valid_difficulties or valid_tags or valid_statuses):
            return HttpResponseServerError(json.dumps(
                {'errors': {
                    'text': "something went wrong"
                }}),
                                           status=400)

        if 'pk' in kwargs:
            try:
                # query reverse relation to consolidate queries
                text_sections = TextSection.objects.select_related(
                    'text').filter(text=kwargs['pk'])

                if not text_sections.exists():
                    raise Text.DoesNotExist()

                text = text_sections[0].text
            except Text.DoesNotExist:
                return HttpResponseServerError(json.dumps({
                    'errors': {
                        'text':
                        "text with id {0} does not exist".format(kwargs['pk'])
                    }
                }),
                                               status=400)

        if 'text_words' in request.GET.keys() and text is not None:
            return HttpResponse(json.dumps(text.text_words))

        if difficulties:
            filter_by['difficulty__slug__in'] = difficulties

        if tags:
            filter_by['tags__name__in'] = tags

        if 'pk' in kwargs:
            return HttpResponse(
                json.dumps(text.to_dict(text_sections=text_sections)))
        else:
            texts = [
                user.to_text_summary_dict(text=txt) for txt in
                self.get_texts_queryset(user, set(statuses), filter_by)
            ]

            return HttpResponse(json.dumps(texts))