Beispiel #1
0
def create(request):
    """
    Creates a new translation request for the current user.

    Does not yet work for anonymous users!
    """
    LOGGER.info('Rendering create request view for user "{0}".'.format(request.user.username))

    form = None

    if request.method == "POST":
        form = TranslationRequestForm(request.user, request.POST, request.FILES)

        if form.errors:
            LOGGER.info(
                "Form validation errors: {0}".format(["{0}: {1}".format(a, b[0]) for a, b in form.errors.items()])
            )

        if form.is_valid():
            LOGGER.info("Create request form is valid.")

            new = TranslationRequest()
            new.shortname = request.POST["shortname"]
            new.owner = request.user
            new.worker = WorkerServer.objects.get(pk=int(request.POST["worker"]))

            message = TranslationRequestMessage()
            message.request_id = new.request_id
            message.source_language = request.POST["source_language"]
            message.target_language = request.POST["target_language"]
            message.source_text = u""
            for chunk in request.FILES["source_text"].chunks():
                message.source_text += unicode(chunk, "utf-8")

            handle = open("{0}/{1}.message".format(TRANSLATION_MESSAGE_PATH, new.request_id), "w+b")
            # pylint: disable-msg=E1101
            handle.write(message.SerializeToString())
            handle.close()

            new.save()

            # cfedermann: We have to decide whether the translation process
            #   should directly be sent to the worker server or whether it
            #   makes more sense to "queue" it on the broker server and have
            #   a cronjob start the process when the worker is not busy...
            #   This does have impact on system performance/robustness!
            new.start_translation()

            messages.add_message(
                request, messages.SUCCESS, "Successfully " 'started translation request "{0}".'.format(new.shortname)
            )
            return HttpResponseRedirect(reverse("dashboard"))

    else:
        try:
            form = TranslationRequestForm(user=request.user)

        except AssertionError, msg:
            messages.add_message(request, messages.ERROR, msg)
            return HttpResponseRedirect(reverse("dashboard"))
Beispiel #2
0
def create(request):
    """
    Creates a new translation request for the current user.
    
    Does not yet work for anonymous users!
    """
    LOGGER.info('Rendering create request view for user "{0}".'.format(
      request.user.username))

    form = None
    
    if request.method == "POST":
        form = TranslationRequestForm(request.POST, request.FILES)
        
        if form.errors:
            LOGGER.info('Form validation errors: {0}'.format(
              ['{0}: {1}'.format(a, b[0]) for a, b in form.errors.items()]))
        
        if form.is_valid():
            LOGGER.info('Create request form is valid.')

            new = TranslationRequest()
            new.shortname = request.POST['shortname']
            new.worker = WorkerServer.objects.get(
              pk=int(request.POST['worker']))
            new.source_text = request.FILES['source_text']
            
            text = ''
            for chunk in request.FILES['source_text'].chunks():
                text += chunk
            
            new.request_id = new.start_translation(text)
            
            if not new.request_id:
                LOGGER.warning('Could not start translation request!')
                messages.add_message(request, messages.ERROR,
                  'Could not start translation request!')
                return HttpResponseRedirect('/dashboard/')
            
            new.owner = request.user
            new.save()
            
            messages.add_message(request, messages.SUCCESS,
              'Successfully started translation request.')
            return HttpResponseRedirect('/dashboard/')
        
    else:
        form = TranslationRequestForm()

    #from serverland.dashboard.models import WorkerServer
    #workers = WorkerServer.objects.all()
    #active_workers = [w for w in workers if w.is_alive()]
    
    dictionary = {'title': 'MT Server Land (prototype) -- Create translation',
      'form': form}
    return render_to_response('dashboard/create.html', dictionary,
      context_instance=RequestContext(request))
Beispiel #3
0
    def create(self, request, shortname = None, results = False):
        '''Handles a POST request to create a new translation request.'''
        if shortname is not None or results:
            return rc.BAD_REQUEST
        print 'CREATE content-type', request.content_type # DEBUG
        # get the data from the POST request
        postdata = self.flatten_dict(request.data)
        # ensure that the worker field is present
        postdata['worker'] = postdata.get('worker','')
        # convert worker shortname to a worker ID if needed
        if not postdata['worker'].isdigit():
            try:
                postdata['worker'] = str(WorkerServer.objects.get(
                    shortname=postdata['worker']).id)
            except ObjectDoesNotExist:
                return rc.BAD_REQUEST
        # check whether the translation request is a duplicate
        if 'shortname' in postdata:
            try:
                TranslationRequest.objects.get(shortname=postdata['shortname'])
                return rc.DUPLICATE_ENTRY
            except MultipleObjectsReturned:
                return rc.DUPLICATE_ENTRY
            except ObjectDoesNotExist:
                pass
        # validate POST data using our Django form
        form = TranslationRequestForm(request.user, postdata, request.FILES)
        try:
            if not form.is_valid():
                return rc.BAD_REQUEST
        except KeyError:
            return rc.BAD_REQUEST
        # create a new request object
        new = TranslationRequest()
        new.shortname = form.cleaned_data['shortname']
        new.owner = request.user
        new.worker = form.cleaned_data['worker']
        # create a new worker message
        message = TranslationRequestMessage()
        message.request_id = new.request_id
        message.source_language = form.cleaned_data['source_language']
        message.target_language = form.cleaned_data['target_language']
        message.source_text = u''
        for chunk in request.FILES['source_text'].chunks():
            message.source_text += unicode(chunk, 'utf-8')

        handle = open('{0}/{1}.message'.format(TRANSLATION_MESSAGE_PATH,
                                               new.request_id), 'w+b')
        handle.write(message.SerializeToString())
        handle.close()

        new.save()
        new.start_translation()

        messages.add_message(request, messages.SUCCESS, 'Successfully ' \
                             'started translation request "{0}".'.format(
                                new.shortname))
        # return 201 CREATED
        response = rc.CREATED
        # put the URI of the newly created object into the HTTP header
        # Location field (see RFC 2616)
        response['Location'] = reverse('requests', args=[new.request_id + '/'])
        # echo the created object inside the HTTP response
        # NOTE: this overwrites the "Location" header field set above.
        # See piston.resource.__call__()
        response.content = RequestHandler.request_to_dict(new)
        return response
Beispiel #4
0
def create(request):
    """
    Creates a new translation request for the current user.

    Does not yet work for anonymous users!
    """
    LOGGER.info('Rendering create request view for user "{0}".'.format(request.user.username))

    form = None

    if request.method == "POST":
        form = TranslationRequestForm(request.POST, request.FILES)

        if form.errors:
            LOGGER.info(
                "Form validation errors: {0}".format(["{0}: {1}".format(a, b[0]) for a, b in form.errors.items()])
            )

        if form.is_valid():
            LOGGER.info("Create request form is valid.")

            new = TranslationRequest()
            new.shortname = request.POST["shortname"]
            new.owner = request.user
            new.worker = WorkerServer.objects.get(pk=int(request.POST["worker"]))

            message = TranslationRequestMessage()
            message.request_id = new.request_id
            message.source_language = request.POST["source_language"]
            message.target_language = request.POST["target_language"]
            message.source_text = u""
            for chunk in request.FILES["source_text"].chunks():
                message.source_text += unicode(chunk, "utf-8")

            handle = open("{0}/{1}.message".format(TRANSLATION_MESSAGE_PATH, new.request_id), "w+b")
            handle.write(message.SerializeToString())
            handle.close()

            new.save()

            # cfedermann: We have to decide whether the translation process
            #   should directly be sent to the worker server or whether it
            #   makes more sense to "queue" it on the broker server and have
            #   a cronjob start the process when the worker is not busy...
            #   This does have impact on system performance/robustness!
            new.start_translation()

            messages.add_message(
                request, messages.SUCCESS, "Successfully " 'started translation request "{0}".'.format(new.shortname)
            )
            return HttpResponseRedirect("/dashboard/")

    else:
        form = TranslationRequestForm()

    # from serverland.dashboard.models import WorkerServer
    # workers = WorkerServer.objects.all()
    # active_workers = [w for w in workers if w.is_alive()]

    dictionary = {"title": "MT Server Land (prototype) -- Create translation", "form": form}
    return render_to_response("dashboard/create.html", dictionary, context_instance=RequestContext(request))