小编Den*_*din的帖子

Python Django Rest Framework UnorderedObjectListWarning

我从Django 1.10.4升级到1.11.1,突然间,当我运行测试时,我收到了大量的这些消息:

lib/python3.5/site-packages/rest_framework/pagination.py:208:
UnorderedObjectListWarning: 
Pagination may yield inconsistent results with an unordered object_list: 
<QuerySet [<Group: Requester>]>
paginator = self.django_paginator_class(queryset, page_size)
Run Code Online (Sandbox Code Playgroud)

我已经追溯到Django Pagination模块:https: //github.com/django/django/blob/master/django/core/paginator.py#L100

它似乎与我的queryset代码有关:

return get_user_model().objects.filter(id=self.request.user.id)
Run Code Online (Sandbox Code Playgroud)

如何找到有关此警告的更多详细信息?似乎我需要order_by(id)在每个过滤器的末尾添加一个,但我似乎无法找到需要添加order_by的代码(因为警告不会返回堆栈跟踪,所以它在我的测试期间随机发生跑).

谢谢!

编辑:

所以通过使用@KlausD.冗长的提示,我看了一个导致此错误的测试:

response = self.client.get('/api/orders/')

这样做OrderViewSet但get_queryset中的任何内容都不会导致它,并且序列化程序类中的任何内容都不会导致它.我有其他测试使用相同的代码来获取/ api/orders而那些不会导致它....在get_queryset之后DRF做了什么?

https://github.com/encode/django-rest-framework/blob/master/rest_framework/pagination.py#L166

如果我将回溯放入分页中,那么我会得到一大堆与django rest框架相关的内容,但没有任何内容可以指出我的哪些查询触发了订单警告.

python django django-rest-framework

64
推荐指数
5
解决办法
2万
查看次数

TypeScript 错误 - TS2340 公共方法可通过“super”关键字访问

我有一个很长的继承链,带有 Angular 5 中的抽象类和接口。它抛出了一个错误 error TS2340: Only public and protected methods of the base class are accessible via the 'super' keyword.

抽象父类的方法定义为:

public get text() {
    return this.el.attr('text/text').replace("\n", "");
} 
Run Code Online (Sandbox Code Playgroud)

子类的方法定义为:

public get text(): string {
  return super.text;
}
Run Code Online (Sandbox Code Playgroud)

如何让子类不抛出 TS2340 错误?

我创建了一个 stackblitz 来演示这个问题:

https://stackblitz.com/edit/ts2340-super-keywork-public?file=app%2Fnodes.ts

inheritance abstract-class typescript angular

9
推荐指数
2
解决办法
5131
查看次数

gunicorn 日志配置 access_log_format

我希望 gunicorn 在我的 docker 容器中记录 JSON。我想在配置文件中使用 --access-logformat 。试图添加formataccess_log_formataccess_logformat不配置该记录器。如何配置 access_log_format 以输出 JSON?

http://docs.gunicorn.org/en/stable/settings.html#access-log-format

gunicorn_logging.conf

[loggers]
keys=root, gunicorn.error, gunicorn.access

[handlers]
keys=console

[formatters]
keys=json

[logger_root]
level=INFO
handlers=console
access_log_format = '{"remote_ip":"%(h)s","request_id":"%({X-Request-Id}i)s","response_code":"%(s)s","request_method":"%(m)s","request_path":"%(U)s","request_querystring":"%(q)s","request_timetaken":"%(D)s","response_length":"%(B)s", "remote_addr": "%(h)s"}'

[logger_gunicorn.error]
level=ERROR
handlers=console
propagate=0
qualname=gunicorn.error

[logger_gunicorn.access]
level=DEBUG
handlers=console
propagate=0
qualname=gunicorn.access
access_log_format = '{"remote_ip":"%(h)s","request_id":"%({X-Request-Id}i)s","response_code":"%(s)s","request_method":"%(m)s","request_path":"%(U)s","request_querystring":"%(q)s","request_timetaken":"%(D)s","response_length":"%(B)s", "remote_addr": "%(h)s"}'

[handler_console]
class=StreamHandler
formatter=json
args=(sys.stdout, )

[formatter_json]
class=utils.jsonlogger.JSONWithTime
Run Code Online (Sandbox Code Playgroud)

utils.jsonlogger:

from pythonjsonlogger import jsonlogger
import time


class JSONWithTime(jsonlogger.JsonFormatter):
    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        t = time.strftime("%Y-%m-%dT%H:%M:%S", ct)
        s = "%s.%03dZ" …
Run Code Online (Sandbox Code Playgroud)

logging json python-2.7 gunicorn

8
推荐指数
0
解决办法
1750
查看次数

Rspec any_instance should_receive应该收到以下消息,但没有

我在与其中any_instance.should_receive抛出一个错误RSpec的支架试验的问题:故障/错误:无法找到回溯整整一个实例匹配行应该已收到以下消息(S),但没有:update_attributes方法

Rspec代码,使用FactoryGirl和strong_parameters:

describe "PUT update" do
   describe "with valid params" do
     it "updates the requested acquisition" do
       puts "starting updates the requested acquisition"
       acquisition = create(:acquisition)
       # Assuming there are no other acquisitions in the database, this
       # specifies that the Acquisition created on the previous line
       # receives the :update_attributes message with whatever params are
       # submitted in the request.
       Acquisition.any_instance.should_receive(:update_attributes).with(:acquisition =>    {:person_id => '10'})
      puts "before the put "
       put :update, :id => acquisition.id, :acquisition => { :person_id …
Run Code Online (Sandbox Code Playgroud)

rspec ruby-on-rails update-attributes

5
推荐指数
1
解决办法
4111
查看次数

Django Rest Framework Camel Case - 不使用解析器进行测试

我在 Django 中使用 rest_framework 有一个简单的 REST API。我添加了 djangorestframework-camel-case 插件并更新了我的 REST_FRAMEWORK 配置和 REST API 输出正确的驼峰案例。但是,当我使用 unittest ( python manage.py test app.test) 进行测试时,结果以 snake_case 而不是 camelCase 形式显示,并导致我的断言失败。

使用这个叉子:https : //github.com/rense/djangorestframework-camel-case

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.DjangoModelPermissions',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend', 'rest_framework.filters.OrderingFilter'),
    'DEFAULT_RENDERER_CLASSES': ('djangorestframework_camel_case.render.CamelCaseJSONRenderer',),
    'DEFAULT_PARSER_CLASSES': ('djangorestframework_camel_case.parser.CamelCaseJSONParser',),
    'TEST_REQUEST_RENDERER_CLASSES': ('djangorestframework_camel_case.render.CamelCaseJSONRenderer',),
    'TEST_REQUEST_PARSER_CLASSES': ('djangorestframework_camel_case.parser.CamelCaseJSONParser',),
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}
Run Code Online (Sandbox Code Playgroud)

我需要添加一些额外的配置吗?这是 djangorestframework 中的错误吗?在 djangorestframework-camel-case 中?

django django-rest-framework

5
推荐指数
1
解决办法
1445
查看次数

Angular 6 生产版本“无法绑定到‘disabled’,因为它不是‘div’的已知属性”

我的应用程序在使用 JIT 编译器时似乎可以工作,但是当我尝试使用 AOT 编译器时,ng build --prod它会抛出错误:

ERROR in : Can't bind to 'disabled' since it isn't a known property of 'div'. ("[ERROR ->]<div formButton></div>")

我如何找出这个错误来自哪里?

我只是添加了延迟加载的功能模块,而不是导入中的所有内容,app.module.ts并且我不知道是否需要导入FormButtonComponent到功能模块中?

我搜索了代码库,formButton除了button.

这是button.component.ts

import { Component, HostBinding, Input, OnChanges, SimpleChanges } from "@angular/core";

/**
 * Button with loading and disabled states
 */
@Component({
    moduleId: module.id,
    selector: '[formButton]',
    templateUrl: 'button.component.html'
})
export class FormButtonComponent implements OnChanges {
    @Input() loading? = false;
    @Input() disabled? …
Run Code Online (Sandbox Code Playgroud)

angular

5
推荐指数
1
解决办法
7821
查看次数

Pyspark 可为空的 uuid 类型 uuid 但表达式的类型为字符变化

给定一个具有不可空 uuid列和可空 uuid列的表设计,如何使用带有 Pyspark 2.4.3 数据帧和 postgresql-42.2.18.jar 驱动程序的 python 3.7.9 进行插入?

table_df = spark.read.format('jdbc) \
                     .option('driver', 'org.postgresql.Driver') \
                     .option('dbtable', 'example_table') \
                     .load()

table_df.printSchema()

root
 |-- id: string (nullable = false)
 |-- created: timestamp (nullable = true)
 |-- modified: timestamp (nullable = true)
 |-- example_uuid: string (nullable = true)


from pyspark.sql.functions import when, lit, col

from pyspark.sql.types import NullType, StringType

def replace(column, value):
  return when (column == value, lit(None).cast(NullType())).otherwise(column.cast(StringType()))

example_df = tasklog_df.withColumn("example_uuid", replace(col("example_uuid"), "NULL"))

example_df.write.mode('append').format('jbdc') \
                .option('driver', 'org.postgresql.Driver')\ …
Run Code Online (Sandbox Code Playgroud)

python postgresql apache-spark pyspark

5
推荐指数
1
解决办法
2173
查看次数

Django Rest 框架选择字段序列化器

使用 Django Rest Framework 3.6.3,我的模型中有一个选择 CharField:

# models.py
class User(AbstractUser):
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )

    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

# viewsets.py
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
Run Code Online (Sandbox Code Playgroud)

我正在发布到端点:

 { 'gender': 'M' }
Run Code Online (Sandbox Code Playgroud)

当我获取端点时,我希望它显示:

{ 'gender': 'Male' }
Run Code Online (Sandbox Code Playgroud)

使用以下序列化程序,它显示选择的显示值(男性)而不是值(M),但它不保存:

# serializers.py 
class UserSerializer(serializers.ModelSerializer):
    # for some reason on save, gender is None??
    gender = serializers.SerializerMethodField()

    class Meta:
        model = User

    def get_gender(self, obj):
        return obj.get_gender_display()
Run Code Online (Sandbox Code Playgroud)

如果我添加一个to_internal_value方法,那么它可以正常工作(显示性别选择显示值,但也保存:

# serializers.py 
class UserSerializer(serializers.ModelSerializer):
    gender = serializers.SerializerMethodField()

    class …
Run Code Online (Sandbox Code Playgroud)

python django-rest-framework

4
推荐指数
1
解决办法
1万
查看次数

Open3.popen3 函数打开 bz、gz 和 txt 文件时出现“没有此类文件或目录”或“未打开读取”错误?

我正在尝试编写一个实用程序函数来打开三种不同类型的文件:.bz2、.gz 和.txt。我不能只是使用File.read,因为它给我压缩文件带来了垃圾。我正在尝试使用,Open3.popen3以便可以给它一个不同的命令,但我收到以下代码的“没有这样的文件或目录”错误:

def file_info(file)
  cmd = ''
  if file.match("bz2") then
    cmd = "bzcat #{file}"# | head -20"
  elsif file.match("gz") then
    cmd = "gunzip -c #{file}"
  else
    cmd = "cat #{file}"
  end

  puts "opening file #{file}"
  Open3.popen3("#{cmd}", "r+") { |stdin, stdout, stderr|
    puts "stdin #{stdin.inspect}"
    stdin.read {|line|
      puts "line is #{line}"
      if line.match('^#') then
      else
        break
      end
    }
  }
end


> No such file or directory - cat /tmp/test.txt
Run Code Online (Sandbox Code Playgroud)

该文件确实存在。我尝试使用cmd而不是#{cmd}popen3 cmd. …

ruby gzip ruby-on-rails bzip

2
推荐指数
1
解决办法
2160
查看次数

d3 v4 TypeScript 绝对类型化的 Angular2 线,X 轴上有 ScaleTime

我正在 angular2 组件中实现以下块(一个简单的折线图):https ://bl.ocks.org/d3noob/6f082f0e3b820b6bf68b​​78f2f7786084

我弄完了: npm install d3 --save npm install @types/d3 --save

我已经加载了 d3.min.js 和 d3.node.js vi SystemJS。我在下面包含了我的 component.ts 文件。

import { Component, Input, ElementRef, OnInit } from '@angular/core';
import { TimelineChartConfig } from "./timeline";
import * as D3 from 'd3';


@Component({
  moduleId: module.id,
  selector: 'timeline',
  templateUrl: 'timeline.component.html',
  styles: [`
    :host {
        width: 100%;
        display:block;
    }
    :host .axis path,
    :host .axis line {
        fill: none;
        stroke: rgba(0, 0, 0, 0.2);
        color: rgba(0, 0, 0, 0.2);
        shape-rendering: crispEdges;
    } …
Run Code Online (Sandbox Code Playgroud)

javascript d3.js typescript definitelytyped angular

2
推荐指数
1
解决办法
1851
查看次数

单击事件类型上的TypeScript jQuery

我在角度打字稿文件中有一些代码:

$('.dashboard-table').on('click', 'tbody tr', 
      function(event: JQueryEventObject) {   // changing this to any removes TS error
          const test: Test = <Test>$('.dashboard-table').DataTable().row(this).data();
          self.openTest(test.id, event);
      }
);

openTest(id: number, $event: MouseEvent|JQueryEventObject) {
    let target = $event.srcElement || $event.target as HTMLElement;
    if (target.tagName.toLowerCase() == 'a'
        || $(target).parents('a').length
        || target.tagName.toLowerCase() == 'button'
        || $(target).parents('button').length) {
        return;
    }
    this.router.navigate([this.urls.paths.test(id)]);
}
Run Code Online (Sandbox Code Playgroud)

它抛出了一个TypeScript错误:

error TS2345: Argument of type '"click"' is not assignable to parameter of type 
'PlainObject<false | EventHandler<HTMLElement, 
(this: HTMLElement, event: JQueryEventObject) => vo...'.`.  
Run Code Online (Sandbox Code Playgroud)

如何ng serve …

typescript

2
推荐指数
1
解决办法
2937
查看次数

使用 flake8 和 pytest 进行 Python 测试会导致 AttributeError: 'Application' object has no attribute 'parse_preliminary_options_and_args'

当我今天运行测试时,出现以下错误:

    return self._hookexec(self, self.get_hookimpls(), kwargs)
ve/lib/python2.7/site-packages/pluggy/manager.py:93: in _hookexec
    return self._inner_hookexec(hook, methods, kwargs)
ve/lib/python2.7/site-packages/pluggy/manager.py:87: in <lambda>
    firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
ve/lib/python2.7/site-packages/_pytest/runner.py:123: in pytest_runtest_call
    item.runtest()
ve/lib/python2.7/site-packages/pytest_flake8.py:126: in runtest
    self.statistics)
ve/lib/python2.7/site-packages/py/_io/capture.py:150: in call
    res = func(*args, **kwargs)
ve/lib/python2.7/site-packages/pytest_flake8.py:191: in check_file
    app.parse_preliminary_options_and_args(args)
E   AttributeError: 'Application' object has no attribute 'parse_preliminary_options_and_args'
Run Code Online (Sandbox Code Playgroud)

我在用着

        'pytest',
        'pytest-cov',
        'pytest-flake8',
        'pytest-flask',
        'pytest-watch',

Run Code Online (Sandbox Code Playgroud)

库的版本增加:pytest (4.6.9 -> 4.6.10)、pyflakes (2.1.1 -> 2.2.0)、pycodestyle (2.5.0 -> 2.6.0) 和 flake8 (3.7.9 - > 3.8.0)。变更日志中没有任何关于该parse_preliminary_options_and_args属性的内容。我猜这与 flake8 弃用 setuptools 集成有关: python setup.py flake8 (setuptools integration) …

python flake8

2
推荐指数
1
解决办法
4675
查看次数

django-scheduler找不到静态文件

我是Django的新手.我按照自述文件中的说明进行操作,然后找不到有关如何使用调度程序的任何进一步说明,因此我将django-scheduler-sample项目中的fullcalendar.html复制到我的项目中.但是,在collectstatic或bower安装后,它找不到任何所需的css或js文件.是否有关于如何将django-scheduler添加到应用程序的详细教程?为什么没有将fullcalendar.css添加到staticfiles?我正在使用Django 1.10.5,Nginx和Gunicorn.

django django-scheduler

1
推荐指数
1
解决办法
281
查看次数