Esempio n. 1
0
def reviewUpdate(request):

    if request.POST['score'] == '0':
        return HttpResponse(request)

    oldScore = 0
    newScore = request.POST['score']
    beer = Beer.objects.all()[int(request.POST['beer_pk']) - 1]

    #print('update')
    if BeerReview.objects.filter(
            user=request.user,
            beer_pk=request.POST['beer_pk']):  # 기존 리뷰 평점 업데이트
        select = BeerReview.objects.get(user=request.user,
                                        beer_pk=request.POST['beer_pk'])
        oldScore = select.score
        select.score = decimal.Decimal(newScore)
        select.published_date = timezone.now()
        select.save()

    else:  # 새로운 리뷰 작성
        BeerReview(user=request.user,
                   beer_pk=request.POST['beer_pk'],
                   beer_name=beer.name,
                   review="Good",
                   score=request.POST['score'],
                   published_date=timezone.now()).save()

    updateBeerScore(beer, decimal.Decimal(oldScore), decimal.Decimal(newScore))

    return HttpResponse(request)
Esempio n. 2
0
class CiProduct(models.Model):
    class Meta:
        db_table = 'ci_product'
        verbose_name = '产品管理'  # 表名称 别名 中文显示
        verbose_name_plural = '产品管理'  # 表名称 别名 中文显示
        ordering = ['product_number']  # 排序字段
        # unqiue_together = ('product_id', 'product_number')  # 联合为一

    product_id = models.AutoField('ID', max_length=11, primary_key=True)
    product_number = models.CharField('产品编号', max_length=255)
    product_type = models.CharField('产品类型',
                                    max_length=50,
                                    null=True,
                                    blank=True)
    product_brand = models.CharField('品牌',
                                     max_length=50,
                                     null=True,
                                     blank=True)
    product_model = models.CharField('产品型号',
                                     max_length=50,
                                     null=True,
                                     blank=True)
    product_alias = models.CharField('产地',
                                     max_length=50,
                                     null=True,
                                     blank=True)
    created_time = models.DateTimeField('上线时间', default=timezone.now())
    update_time = models.DateTimeField('更新时间', default=timezone.now())
    uniq_id = models.IntegerField(max_length=11, null=True, blank=True)
    status = models.CharField('产品状态', max_length=8, null=True, blank=True)

    # def __str__(self):
    #     return self.product_number
    def __unicode__(self):
        return self.product_number
Esempio n. 3
0
def run_suite(id):
    '''
    通过apitest/runner下的testrunner脚本运行yaml测试用例文件,根据测试结果新建测试报告对象
    :param query_set:
    :return:
    '''
    # 获取套件所有的测试用例,结果为[[{套件1用例},...],[{套件2用例},...]]
    obj = TESTSUITE.objects.get(id=id)
    testdata = get_suitedata(obj)
    casenum = obj.case.count()
    args = obj.args.all().values_list('name')
    reruns = obj.reruns
    reruns_delay = obj.reruns_delay
    testreport = run_data(num=casenum,
                          data=[testdata],
                          args=args,
                          reruns=reruns,
                          reruns_delay=reruns_delay)
    testreport.testsuite.add(obj)
    for case in obj.case.all():
        testreport.testcases.add(case)
        case.runtime = timezone.now()
        case.save()
    testreport.save()
    obj.runtime = timezone.now()
    obj.save
Esempio n. 4
0
    def post(self, request):
        password_rese = ForgotPassSerializer(data=request.data)
        if password_rese.is_valid():
            mobile = proper_dial(password_rese.validated_data["phone_number"])
            try:
                this_user = Tuser.objects.get(phone_number=mobile)
            except Tuser.DoesNotExist:
                this_user = None

            if not this_user is None:
                if Reset_password.objects.filter(user=this_user).exists():
                    tuser = Reset_password.objects.get(user=this_user)
                    tuser.reset_code = reset_code()
                    tuser.expiry = timezone.now() + expiry_date()
                    tuser.save()
                else:
                    tuser = Reset_password.objects.create(
                        user=this_user,
                        reset_code=reset_code(),
                        expiry=timezone.now() + expiry_date())

                sms.send("Reset password code: " + tuser.reset_code,
                         [proper_dial(mobile)])
                request.session['u_id'] = this_user.id

            return Response({
                'code': 1,
                'response': password_rese.data
            },
                            status=status.HTTP_200_OK)
        return Response({
            'code': 0,
            'response': password_rese.errors
        },
                        status=status.HTTP_400_BAD_REQUEST)
Esempio n. 5
0
class CiOrder(models.Model):
    class Meta:
        db_table = 'ci_order'  # 创建表名称
        verbose_name = verbose_name_plural = '订单管理'  # 表名称 别名 中文显示
        ordering = ['order_number']

    order_id = models.AutoField('ID', max_length=11,
                                primary_key=True)  # 字段显示别名
    order_number = models.CharField('订单编码', max_length=255)  # 字段显示中文别名
    order_customer = models.CharField('客户',
                                      max_length=50,
                                      null=True,
                                      blank=True)
    order_type = models.CharField('产品类型', max_length=50, null=True, blank=True)
    order_brand = models.CharField('品牌', max_length=50, null=True, blank=True)
    order_model = models.CharField('产品型号',
                                   max_length=50,
                                   null=True,
                                   blank=True)
    order_quantity = models.IntegerField('订单数量', max_length=11)
    order_unitprice = models.IntegerField('订单单价',
                                          max_length=11,
                                          null=True,
                                          blank=True)
    order_owner = models.CharField('业务员', max_length=50, null=True, blank=True)
    order_createdtime = models.DateTimeField('下单时间', default=timezone.now())
    order_delivertime = models.DateTimeField('交付时间', default=timezone.now())
    update_time = models.DateTimeField('更新时间', auto_now=True)
    order_complete = models.IntegerField('完成进度',
                                         max_length=50,
                                         null=True,
                                         blank=True)
    order_alias = models.CharField('订单类型',
                                   max_length=50,
                                   null=True,
                                   blank=True)
    uniq_id = models.IntegerField(max_length=11, null=True, blank=True)
    GENDER_CHOICE = (  #choices2 选项设置
        (0, u'待产'),
        (1, u'完成'),
        (-1, u'延期'),
    )
    status = models.IntegerField('订单状态',
                                 choices=GENDER_CHOICE,
                                 default=0,
                                 max_length=8,
                                 null=True,
                                 blank=True)

    def __str__(self):
        return self.order_number
Esempio n. 6
0
def stock_new(request):
    if request.method == "POST":
        form = StockForm(request.POST)
        if form.is_valid():
            stock = form.save(commit=False)
            stock.created_date = timezone.now()
            stock.save()
            stocks = Stock.objects.filter(purchase_date__lte=timezone.now())
            return render(request, 'portfolio/stock_list.html',
                          {'stocks': stocks})
    else:
        form = StockForm()
        # print("Else")
    return render(request, 'portfolio/stock_new.html', {'form': form})
Esempio n. 7
0
def investment_new(request):
    if request.method == "POST":
        form = InvestmentForm(request.POST)
        if form.is_valid():
            investment = form.save(commit=False)
            investment.created_date = timezone.now()
            investment.save()
            investments = Investment.objects.filter(
                recent_date__lte=timezone.now())
            return render(request, 'portfolio/investment_list.html',
                          {'investments': investments})
    else:
        form = InvestmentForm()
        # print("Else")
    return render(request, 'portfolio/investment_new.html', {'form': form})
Esempio n. 8
0
def customer_new(request):
    if request.method == "POST":
        form = CustomerForm(request.POST)
        if form.is_valid():
            customer = form.save(commit=False)
            customer.created_date = timezone.now()
            customer.save()
            customers = Customer.objects.filter(
                created_date__lte=timezone.now())
            return render(request, 'portfolio/customer_list.html',
                          {'customers': customers})
    else:
        form = CustomerForm()
        # print("Else")
    return render(request, 'portfolio/customer_new.html', {'form': form})
Esempio n. 9
0
def portfolio(request, pk):
    customer = get_object_or_404(Customer, pk=pk)
    customers = Customer.objects.filter(created_date__lte=timezone.now())
    investments = Investment.objects.filter(customer=pk)
    stocks = Stock.objects.filter(customer=pk)
    sum_recent_value = Investment.objects.filter(customer=pk).aggregate(
        Sum('recent_value'))
    sum_acquired_value = Investment.objects.filter(customer=pk).aggregate(
        Sum('acquired_value'))
    #overall_investment_results = sum_recent_value-sum_acquired_value
    # Initialize the value of the stocks
    sum_current_stocks_value = 0
    sum_of_initial_stock_value = 0

    # Loop through each stock and add the value to the total
    for stock in stocks:
        sum_current_stocks_value += stock.current_stock_value()
        sum_of_initial_stock_value += stock.initial_stock_value()

    return render(
        request, 'portfolio/portfolio.html', {
            'customers': customers,
            'investments': investments,
            'stocks': stocks,
            'sum_acquired_value': sum_acquired_value,
            'sum_recent_value': sum_recent_value,
            'sum_current_stocks_value': sum_current_stocks_value,
            'sum_of_initial_stock_value': sum_of_initial_stock_value,
        })
Esempio n. 10
0
def stock_edit(request, pk):
    stock = get_object_or_404(Stock, pk=pk)
    if request.method == "POST":
        form = StockForm(request.POST, instance=stock)
        if form.is_valid():
            stock = form.save()
            # stock.customer = stock.id
            stock.updated_date = timezone.now()
            stock.save()
            stocks = Stock.objects.filter(purchase_date__lte=timezone.now())
            return render(request, 'portfolio/stock_list.html',
                          {'stocks': stocks})
    else:
        # print("else")
        form = StockForm(instance=stock)
    return render(request, 'portfolio/stock_edit.html', {'form': form})
Esempio n. 11
0
def exercise_calories_burn(request):
    try:
        if request.POST["weight"] == '':
            # res = get_exercise_from_nl_query(query=request.POST["exercise-input"])
            messages.warning(request, "Please input weight")
            return render(request, 'fitnesspal/exercise.html')

        else:
            res = get_exercise_from_nl_query(
                query=request.POST["exercise-input"],
                weight_kg=request.POST["weight"])
    except AssertionError:
        messages.warning(request, "Result not found")
        return render(request, 'fitnesspal/exercise.html')
    else:
        try:
            cal = res.json()["exercises"][0]["nf_calories"]
            name = res.json()["exercises"][0]["name"]
            duration = res.json()["exercises"][0]["duration_min"]
            met = res.json()["exercises"][0]["met"]
            new_exercise = Exercise.objects.create(exercise_name=name,
                                                   calories=cal,
                                                   duration=duration,
                                                   met=met,
                                                   date=timezone.now())
        except IndexError:
            messages.warning(request, "Result not found")
            return render(request, 'fitnesspal/exercise.html')
        except KeyError:
            messages.warning(request, "Result not found")
            return render(request, 'fitnesspal/exercise.html')
        else:
            return render(request, 'fitnesspal/exercise.html',
                          {'new_exercise': new_exercise})
Esempio n. 12
0
def calculate_calories(request):
    try:
        res = get_nutrients_from_nl_query(query=request.POST["food-input"])
    except AssertionError:
        messages.warning(request, "Result not found")
        return render(request, 'fitnesspal/calories.html')
    else:
        try:
            cal = res.json()["foods"][0]["nf_calories"]
            name = res.json()["foods"][0]["food_name"]
            carb = res.json()["foods"][0]["nf_total_carbohydrate"]
            fats = res.json()["foods"][0]["nf_total_fat"]
            protein = res.json()["foods"][0]["nf_protein"]
            weight = res.json()["foods"][0]['serving_weight_grams']
            pic = res.json()["foods"][0]["photo"]["thumb"]
            new_food = Calories.objects.create(food_name=name,
                                               calories=cal,
                                               carbohydrates=carb,
                                               fats=fats,
                                               protein=protein,
                                               weight=weight,
                                               date=timezone.now())
        except KeyError:
            messages.warning(request, "Result not found")
            return render(request, 'fitnesspal/calories.html')
        else:
            return render(request, 'fitnesspal/calories.html', {
                'new_food': new_food,
                'pic': pic
            })
Esempio n. 13
0
def post_list(request):
    today = timezone.now().date()
    queryset_list = Post.objects.active()  # .order_by("-timestamp")
    if request.user.is_staff or request.user.is_superuser:
        queryset_list = Post.objects.all()

    query = request.GET.get("q")
    if query:
        queryset_list = queryset_list.filter(
            Q(title__icontains=query) | Q(content__icontains=query)
            | Q(user__first_name__icontains=query)
            | Q(user__last_name__icontains=query)).distinct()
    paginator = Paginator(queryset_list, 8)  # Show 25 contacts per page
    page_request_var = "page"
    page = request.GET.get(page_request_var)
    try:
        queryset = paginator.page(page)
    except PageNotAnInteger:
        queryset = paginator.page(1)
    except EmptyPage:
        queryset = paginator.page(paginator.num_pages)

    context = {
        "object_list": queryset,
        "title": "List",
        "page_request_var": page_request_var,
        "today": today,
    }
    return render(request, "post_list.html", context)
Esempio n. 14
0
 def get_queryset(self):
     queryset = super().get_queryset()
     weeks_count = int(self.request.query_params.get('days', 0))
     if weeks_count > 0:
         start_date = timezone.now() - timedelta(days=weeks_count)
         queryset = queryset.filter(dreated_at__gte=start_date)
     return queryset
Esempio n. 15
0
def sub_comment_add(request, comment_id):
    if request.user.is_authenticated():

        comment = Comment.objects.get(id=comment_id)
        new_comment = Comment(content=request.POST["content"],
                              author=request.user,
                              approved=True,
                              activation_key=0,
                              content_object=comment,
                              email=request.user.email
                              )
        new_comment.save()
    else:
        user = User.objects.get(email=request.POST["email"])
        if not user:
            user = User.objects.create_user(username=uuid.uuid4(),
                                            email=request.POST["email"],
                                            is_active=False)

        comment = Comment()
        comment.content = request.POST["content"]
        comment.author = user
        comment.date = timezone.now()
        comment.approved = False
        comment.email = user.email
        comment.content_object = post
        comment.activation_key = hashlib.sha256(user.email + str(random.random())).hexdigest()
        comment.save()
        content = render_to_string("Email/email.html", {"activation_key": comment.activation_key})
        task.mail_send.delay("Email Activation", content, None, [comment.email])

    return HttpResponseRedirect(request.GET["next"])
Esempio n. 16
0
def investment_edit(request, pk):
    investment = get_object_or_404(Investment, pk=pk)
    if request.method == "POST":
        form = InvestmentForm(request.POST, instance=investment)
        if form.is_valid():
            investment = form.save()
            # investment.customer = investment.id
            investment.updated_date = timezone.now()
            investment.save()
            investments = Investment.objects.filter(
                recent_date__lte=timezone.now())
            return render(request, 'portfolio/investment_list.html',
                          {'investments': investments})
    else:
        # print("else")
        form = InvestmentForm(instance=investment)
    return render(request, 'portfolio/investment_edit.html', {'form': form})
Esempio n. 17
0
class News(models.Model):
    author = models.CharField(max_length=30)
    title = models.CharField(max_length=30)
    description = models.TextField()
    pub_date = models.DateField(default=timezone.now())

    def __str__(self):
        return self.author
Esempio n. 18
0
def customer_edit(request, pk):
    customer = get_object_or_404(Customer, pk=pk)
    if request.method == "POST":
        # update
        form = CustomerForm(request.POST, instance=customer)
        if form.is_valid():
            customer = form.save(commit=False)
            customer.updated_date = timezone.now()
            customer.save()
            customer = Customer.objects.filter(
                created_date__lte=timezone.now())
            return render(request, 'portfolio/customer_list.html',
                          {'customers': customer})
    else:
        # edit
        form = CustomerForm(instance=customer)
    return render(request, 'portfolio/customer_edit.html', {'form': form})
Esempio n. 19
0
    def load(self):

        session_k = self.get_session_entity_key()
        session = db.get(session_k)

        if session and (session.expire_date > timezone.now()):
            return self.decode(force_unicode(session.session_data))
        else:
            # session not found
            self.create()
            return {}
Esempio n. 20
0
File: tasks.py Progetto: crindt/uf
def cleanup_export_job():
    jobs_to_clean = Job.objects.filter(type="export_layer", status="Complete")
    for job in jobs_to_clean:
        if timezone.now() - job.ended_on > DOWNLOAD_FILE_EXPIRY:
            filepath = SENDFILE_ROOT + job.data
            os.remove(filepath)
            job.data = '[deleted]'
            job.status = 'Cleaned'
            job.save()
        else:
            continue
Esempio n. 21
0
 def setUp(self) :
     self.subject = Subject.objects.create(title='Programming news')
     self.owner = Account.objects.create(email= '*****@*****.**',
                             password= '******',
                             fullname= 'Test')
     self.course = Course.objects.create(title = ' books',
                          owner = self.owner,
                          subject = self.subject,
                          overview='this is a sample overview',
                          created = timezone.now()
     )
Esempio n. 22
0
	def _create_user(self, email, password, is_staff, is_superuser, **extra_fileds):
		now = timezone.now()

		if not email:
			raise ValueError('Debes introducir email')

		email = self.normalize_email(email)
		user = self.model(email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields)

		user.set_password(password)
		user.save(using=self._db)
		return user
Esempio n. 23
0
    def get_reset_code(self, email):
        """
        Generates a new password reset code returns user
        """

        try:
            user = self.get(email__iexact=email)
            user.reset_code = self.make_random_password(length=20)
            user.reset_code_expire = timezone.now() + timedelta(days=2)
            user.save()

            return user
        except get_user_model().DoesNotExist:
            raise ValidationError('We can\'t find that email address, sorry!')
Esempio n. 24
0
def run_batch(id):
    batch = Testbatch.objects.get(id=id)
    testbatch = []
    for obj in batch.testsuite.all():
        testsuite = get_suitedata(obj)
        testbatch.extend(testsuite)
    casenum = len(testbatch)
    args = batch.args.all().values_list('name')
    testreport = run_data(num=casenum, data=[testbatch], args=args)
    for suite in batch.testsuite.all():
        testreport.testsuite.add(suite)
        if suite.isorder == False:
            runcases = suite.case.all()
        else:
            runcases = suite.testcaselist_set.all()
            runcases = [case.testcase for case in runcases]
        for case in runcases:
            testreport.testcases.add(case)
            case.runtime = timezone.now()
            case.save()
    testreport.testbatch = batch
    testreport.save()
    obj.runtime = timezone.now()
    obj.save()
Esempio n. 25
0
    def _create_applicant(self, email, password, is_staff, is_superuser,
                          **extra_fields):
        '''create and save a applicant with the given email and password'''
        now = timezone.now()
        if not email:
            raise ValueError('The given email must be set')

        email = self.normalize_email(email)
        applicant = self.model(email=email,
                               is_staff=is_staff,
                               is_active=True,
                               is_superuser=is_superuser,
                               last_login=now,
                               date_joined=now,
                               **extra_fields)
        applicant.set_password(password)
        applicant.seve(using=self.db)
        return applicant
Esempio n. 26
0
    def post_code(self, request):
        user_id = request.session['u_id']
        this_user = Tuser.objects.get(id=user_id)
        my_reset_code = get_object_or_404(Reset_password, user=this_user)
        code = EnterResetSerializer(data=request.data)

        if code.is_valid():
            reset_code = code.validated_data['reset_code']
            if my_reset_code.expiry > timezone.now():
                if reset_code == my_reset_code.reset_code:
                    return Response({
                        'code': 1,
                        'response': code.data
                    },
                                    status=status.HTTP_200_OK)
        return Response({
            'code': 0,
            'response': code.errors
        },
                        status=status.HTTP_400_BAD_REQUEST)
Esempio n. 27
0
    def save(self):
        instance = super(HarvestForm, self).save(commit=False)

        status = self.cleaned_data['status']
        publication_date = self.cleaned_data['publication_date']
        trees = self.cleaned_data['trees']

        if status in ["Ready", "Date-scheduled", "Succeeded"]:
            # if publication_date is None:
            instance.publication_date = timezone.now()

        if status in ["To-be-confirmed", "Orphan", "Adopted"]:
            if publication_date is not None:
                instance.publication_date = None

        if not instance.id:
            instance.save()
        instance.trees = trees
        instance.save()

        return instance
Esempio n. 28
0
def create(request,setpk,tutorialpk):

  if request.method == "POST":
        form = ArticleForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.date = timezone.now()
            post.save()
            return redirect('post_detail', setpk=post.setpk,tutorialpk=post.tutorialpk)
        else:
            form = ArticleForm()
        return render(request, 'create_forum.html', {'form': form})
  else:
    form=ArticleForm()
    TUTORIAL_SET_CHOICES =TutorialSet.objects.get(id = setpk)
    TUTORIAL_ENTRY_CHOICES =TutorialEntry.objects.get(id=tutorialpk)
    args={}
    args.update((request))
    args['form']=form
    args['TUTORIAL_SET_CHOICES']=TUTORIAL_SET_CHOICES
    args['TUTORIAL_ENTRY_CHOICES']=TUTORIAL_ENTRY_CHOICES
    return render_to_response ('create_forum.html',args)
Esempio n. 29
0
 def was_published_recently(self):
     return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
Esempio n. 30
0
def post_detail(request, slug=None):
    instance = get_object_or_404(Post, slug=slug)
    if instance.publish > timezone.now().date() or instance.draft:
        if not request.user.is_staff or not request.user.is_superuser:
            raise Http404
    return render(request, "post_detail.html")
Esempio n. 31
0
 def was_published_recently(self):
     return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
Esempio n. 32
0
 def was_created_recently(self):
     return self.create_date >= timezone.now() - datetime.timedelta(days=1)
Esempio n. 33
0
 def test_func(self):
     obj = self.get_object()
     return ((self.request.user == obj.author)
             and (timezone.now() - obj.date < timedelta(0, 60 * 15)))
Esempio n. 34
0
 def modified_recently(self):
     return self.modified_at >= timezone.now() - datetime.timedelta(days=1)
Esempio n. 35
0
 def was_published_recently(self):
     now = timezone.now()
     return now - datetime.timedelta(days=1) <= self.pub_date <= now
Esempio n. 36
0
    def reset_password(self, user_id, reset_code, password):
        """
        Set new password for the user
        """

        if not password:
            raise ValidationError('New password can\'t be blank.')

        try:
            user = self.get(id=user_id)
            if not user.reset_code or user.reset_code != reset_code or user.reset_code_expire < timezone.now():
                raise ValidationError('Password reset code is invalid or expired.')

            # Password reset code shouldn't be used again
            user.reset_code = None
            user.set_password(password)
            user.save()

        except get_user_model().DoesNotExist:
            raise ValidationError('Password reset code is invalid or expired.')
Esempio n. 37
0
 def get_date(self):
     delta = timezone.now() - self.lifetime
     if delta.seconds < 6000:
         return True
     else:
         return False
Esempio n. 38
0
 def get_recently(self):
     return self.date_alert >= timezone.now() - datetime.timedelta(days=1)
Esempio n. 39
0
 def checkdeadline(self):
     if timezone.now() > self.deadline:
         return True
     else:
         return False
Esempio n. 40
0
def jobs(request, secret):
    ''' This is the view used by the executor.py scripts for getting / putting the test results.
        Fetching some file for testing is changing the database, so using GET here is not really RESTish. Whatever.
        A visible shared secret in the request is no problem, since the executors come
        from trusted networks. The secret only protects this view from outside foreigners.
    '''
    if secret != JOB_EXECUTOR_SECRET:
        raise PermissionDenied
    if request.method == "GET":
        try:
            machine = TestMachine.objects.get(host=request.get_host())
            machine.last_contact = datetime.now()
            machine.save()
        except:
            # ask for configuration of new execution hosts by returning the according action
            machine = TestMachine(host=request.get_host(), last_contact=datetime.now())
            machine.save()
            response = HttpResponse()
            response['Action'] = 'get_config'
            response['MachineId'] = machine.pk
            return response
        subm = Submission.pending_student_tests.all()
        if len(subm) == 0:
            subm = Submission.pending_full_tests.all()
            if len(subm) == 0:
                raise Http404
        for sub in subm:
            assert (sub.file_upload)  # must be given when the state model is correct
            # only deliver jobs that are unfetched so far, or where the executor should have finished meanwhile
            # it may happen in special cases that stucked executors deliver their result after the timeout
            # this is not really a problem, since the result remains the same for the same file
            # TODO: Make this a part of the original query
            # TODO: Count number of attempts to leave the same state, mark as finally failed in case; alternatively, the executor must always deliver a re.
            if (not sub.file_upload.fetched) or (sub.file_upload.fetched + datetime.timedelta(
                    seconds=sub.assignment.attachment_test_timeout) < timezone.now()):
                if sub.file_upload.fetched:
                    # Stuff that has timed out
                    # we mark it as failed so that the user gets informed
                    # TODO:  Late delivery for such a submission by the executor witll break everything
                    sub.file_upload.fetched = None
                    if sub.state == Submission.TEST_COMPILE_PENDING:
                        sub.state = Submission.TEST_COMPILE_FAILED
                        sub.file_upload.test_compile = "Killed due to non-reaction on timeout signals. Please check your application for deadlocks or keyboard input."
                        inform_student(sub, sub.state)
                    if sub.state == Submission.TEST_VALIDITY_PENDING:
                        sub.file_upload.test_validity = "Killed due to non-reaction on timeout signals. Please check your application for deadlocks or keyboard input."
                        sub.state = Submission.TEST_VALIDITY_FAILED
                        inform_student(sub, sub.state)
                    if sub.state == Submission.TEST_FULL_PENDING:
                        sub.file_upload.test_full = "Killed due to non-reaction on timeout signals. Student not informed, since this was the full test."
                        sub.state = Submission.TEST_FULL_FAILED
                    sub.file_upload.save()
                    sub.save()
                    continue
                # create HTTP response with file download
                f = sub.file_upload.attachment
                # on dev server, we sometimes have stale database entries
                if not os.access(f.path, os.F_OK):
                    mail_managers('Warning: Missing file',
                                  'Missing file on storage for submission file entry %u: %s' % (
                                      sub.file_upload.pk, str(sub.file_upload.attachment)), fail_silently=True)
                    continue
                response = HttpResponse(f, content_type='application/binary')
                response['Content-Disposition'] = 'attachment; filename="%s"' % sub.file_upload.basename()
                response['SubmissionFileId'] = str(sub.file_upload.pk)
                response['Timeout'] = sub.assignment.attachment_test_timeout
                if sub.state == Submission.TEST_COMPILE_PENDING:
                    response['Action'] = 'test_compile'
                elif sub.state == Submission.TEST_VALIDITY_PENDING:
                    response['Action'] = 'test_validity'
                    # reverse() is messing up here when we have to FORCE_SCRIPT case, so we do manual URL construction
                    response['PostRunValidation'] = MAIN_URL + "/download/%u/validity_testscript/secret=%s" % (
                        sub.assignment.pk, JOB_EXECUTOR_SECRET)
                elif sub.state == Submission.TEST_FULL_PENDING or sub.state == Submission.CLOSED_TEST_FULL_PENDING:
                    response['Action'] = 'test_full'
                    # reverse() is messing up here when we have to FORCE_SCRIPT case, so we do manual URL construction
                    response['PostRunValidation'] = MAIN_URL + "/download/%u/full_testscript/secret=%s" % (
                        sub.assignment.pk, JOB_EXECUTOR_SECRET)
                else:
                    assert (False)
                # store date of fetching for determining jobs stucked at the executor
                sub.file_upload.fetched = timezone.now()
                sub.file_upload.save()
                # 'touch' submission so that it becomes sorted to the end of the queue if something goes wrong
                sub.modified = timezone.now()
                sub.save()
                return response
        # no feasible match in the list of possible jobs
        raise Http404

    elif request.method == "POST":
        # first check if this is just configuration data, and not a job result
        if request.POST['Action'] == 'get_config':
            machine = TestMachine.objects.get(pk=int(request.POST['MachineId']))
            machine.config = request.POST['Config']
            machine.save()
            return HttpResponse(status=201)

        # executor.py is providing the results as POST parameters
        sid = request.POST['SubmissionFileId']
        submission_file = get_object_or_404(SubmissionFile, pk=sid)
        sub = submission_file.submissions.all()[0]
        error_code = int(request.POST['ErrorCode'])
        if request.POST['Action'] == 'test_compile' and sub.state == Submission.TEST_COMPILE_PENDING:
            submission_file.test_compile = request.POST['Message']
            if error_code == 0:
                if sub.assignment.attachment_test_validity:
                    sub.state = Submission.TEST_VALIDITY_PENDING
                elif sub.assignment.attachment_test_full:
                    sub.state = Submission.TEST_FULL_PENDING
                else:
                    sub.state = Submission.SUBMITTED_TESTED
                    inform_course_owner(request, sub)
            else:
                sub.state = Submission.TEST_COMPILE_FAILED
            inform_student(sub, sub.state)
        elif request.POST['Action'] == 'test_validity' and sub.state == Submission.TEST_VALIDITY_PENDING:
            submission_file.test_validity = request.POST['Message']
            if error_code == 0:
                if sub.assignment.attachment_test_full:
                    sub.state = Submission.TEST_FULL_PENDING
                else:
                    sub.state = Submission.SUBMITTED_TESTED
                    inform_course_owner(request, sub)
            else:
                sub.state = Submission.TEST_VALIDITY_FAILED
            inform_student(sub, sub.state)
        elif request.POST['Action'] == 'test_full' and sub.state == Submission.TEST_FULL_PENDING:
            submission_file.test_full = request.POST['Message']
            if error_code == 0:
                sub.state = Submission.SUBMITTED_TESTED
                inform_course_owner(request, sub)
            else:
                sub.state = Submission.TEST_FULL_FAILED
                # full tests may be performed several times and are meant to be a silent activity
                # therefore, we send no mail to the student here
        elif request.POST['Action'] == 'test_full' and sub.state == Submission.CLOSED_TEST_FULL_PENDING:
            submission_file.test_full = request.POST['Message']
            sub.state = Submission.CLOSED
            # full tests may be performed several times and are meant to be a silent activity
            # therefore, we send no mail to the student here
        else:
            mail_managers('Warning: Inconsistent job state', str(sub.pk), fail_silently=True)
        submission_file.fetched = None  # makes the file fetchable again by executors, but now in a different state
        perf_data = request.POST['PerfData'].strip()
        if perf_data != "":
            submission_file.perf_data = perf_data
        else:
            submission_file.perf_data = None
        submission_file.save()
        sub.save()
        return HttpResponse(status=201)