小编wru*_*esh的帖子

Python类型:注释父类返回子类类型对象的最佳方式

我有一个如下的基类:

class BaseClass:
    @classmethod
    def create(cls, arg1: str) -> BaseClass:
        instance = cls(arg1)
        return instance
Run Code Online (Sandbox Code Playgroud)

还有一个像这样的派生类:

class DerivedClass(BaseClass):
    def __init__(self, arg: str) -> None:
        self.arg = arg 
Run Code Online (Sandbox Code Playgroud)

现在当我这样做时

data: DerivedClass = DerivedClass.create('first arg)
Run Code Online (Sandbox Code Playgroud)

mypy 给出以下错误:

"BaseClass" cannot be assigned to declared type "DerivedClass"
"BaseClass" is incompatible with "DerivedClass"
Run Code Online (Sandbox Code Playgroud)

我如何解决它是通过使用typing.cast

data: DerivedClass = cast(
    DerivedClass, 
    DerivedClass.get(derived_class_instance)
)
Run Code Online (Sandbox Code Playgroud)

我应该如何解决它而不使用typing.cast

python mypy python-typing

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

Django-model:在模型字段中保存计算值

我想用计算字段保存django模型,以便我可以对其进行搜索.

class TestModel(models.Model):
    x = models.CharField(max_length=16)
    z = models.CharField(max_length=16)

    # I want a field like below and also saves in databse
    # computed =  computed()

    def computed(self):
        result = self.x + self.y
        return result
Run Code Online (Sandbox Code Playgroud)

python django django-models

7
推荐指数
2
解决办法
4247
查看次数

带有 python subprocess.Popen 通信方法的 airodump-ng 输出

嗨,我正在尝试从airodump-ng mon0获得连续输出

出于这个原因,我试图在一段时间后使用 Popen.communicate读取airodump-ng mon0的输出,但仍然无法获得任何信息。

import subprocess

airodump = subprocess.Popen(['airodump-ng', 'mon0'],
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)
try:
    o_airodump, unused_stderr = airodump.communicate(timeout=15)
except subprocess.TimeoutExpired as e:
    airodump.kill()
    o_airodump, unused_stderr = airodump.communicate()
    print(o_airodump)
    print(unused_stderr)
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它会卡在:

o_airodump, unused_stderr = airodump.communicate()
Run Code Online (Sandbox Code Playgroud)

我现在完全被困住了。并且无法找到任何其他方式。请帮忙。

python subprocess aircrack-ng

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

为什么 kurento 媒体服务器与 ant-media 相比性能低?

我正在尝试为数千个并发调用扩展 kurento 媒体服务器。

我打算使用 OpenVidu Pro 进行缩放。

我还保留了一个替代方案来开发我自己的应用服务器和管理 kms 节点。

我关心的是与kms节点具有相同硬件容量的ant-media-server,与kms相比,它支持更多的并发调用。

以上信息来源

如果上述信息属实,kms 做了什么额外的工作以使用更多的硬件资源?

可以做些什么来优化公里数。

如果可能,请说明一些情况。

kurento ant-media-server-sdk

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

由 django 中的 prefetch_related 完成的烧瓶多对多连接

我在带有 Sql Alchemy ORM 的烧瓶中有以下组和联系人模型

group_contact = db.Table(
    'group_contact',
    db.Column('group_id', db.Integer, db.ForeignKey(
        'group.id')),
    db.Column('contact_id', db.Integer, db.ForeignKey(
        'contact.id')),
    db.PrimaryKeyConstraint('group_id', 'contact_id')
)


class Group(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))


class Contact(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    phone = db.Column(db.String(15), nullable=False, unique=True)
    groups = db.relationship(
        "Group", secondary=group_contact, backref='contacts')
Run Code Online (Sandbox Code Playgroud)

现在我需要查询与组的联系:

contacts = Contact.query.join(Group, Contact.groups).all()
for contact in contacts:
    print(contact.groups)
Run Code Online (Sandbox Code Playgroud)

这里的问题是当我执行上面的代码时,SQL 查询的数量随着联系数量的增加而增加。

Django ORM 具有 prefetch_related() 和 queryset,它根据 django docs执行以下操作。

另一方面,prefetch_related 对每个关系进行单独的查找,并在 Python 中进行“连接”。除了 select_related 支持的外键和一对一关系之外,这允许它预取使用 select_related 无法完成的多对多和多对一对象。

现在我正在尝试通过以下代码对 Sql Alchemy 做同样的事情:

contacts …
Run Code Online (Sandbox Code Playgroud)

python postgresql sqlalchemy

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

Vuejs'beforeunload'事件未按预期触发

我已经在vue路由器的路由所使用的组件的已创建钩子上注册了“ beforeunload”事件。

我想调用此事件处理程序,以删除浏览器选项卡关闭或浏览器选项卡刷新或浏览器关闭上的用户。

在ComponentA上

created (){    
    window.addEventListener('beforeunload', () => {

        this.removeUser()

        return null
     })
}
Run Code Online (Sandbox Code Playgroud)

嘲笑ComponentB

created (){    
    window.addEventListener('beforeunload', () => {

        this.removeUser()

        return null
     })
}
Run Code Online (Sandbox Code Playgroud)

还有我的router.js

{
  path: '/staff/call/:session_key',
  name: 'Staff Call',
  component: ComponentA,
  meta: {auth: true}
},
{
  path: '/consumer/call/:session_key',
  name: 'Consumer Call',
  component: ComponentB
},
Run Code Online (Sandbox Code Playgroud)

在这里,“ beforeunload”事件处理程序是随机触发的。那有时是触发它,有时却没有触发。我认为在触发时会发现任何模式,而在没有触发时会发现。

我在这里想念什么?

javascript-events addeventlistener vue.js vue-router vuejs2

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

python方法()只需要1个参数(给定2个)

我在django app views.py中有这样的课程

from dms.models import Folder, File, FileTag

class GetFamily:

    def getFathers(folder_id):
        if folder_id == None:
            rev_fathers=None
        else:
            fathers=[]
            rev_fathers=[]
            father=Folder.objects.get(id=folder_id)
            fathers.append(father)
            while father.parent_folder_id != None:
                father=Folder.objects.get(id=father.parent_folder_id)
                fathers.append(father)
            rev_fathers=reversed(fathers)
        return rev_fathers

    def getChildrenFolders(folder_id):
        folders=Folder.objects.filter(parent_folder_id=folder_id)
        return folders  

    def getChildrenFiles(folder_id):
        files=File.objects.filter(folder_id=folder_id)
        return files
Run Code Online (Sandbox Code Playgroud)

当我用id调用getFathers(folder_id)方法时,它给getFathers()取1个参数(给定2个)

请帮助我

python django

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

文件没有缓冲区接口

我在views.py中有一个功能.就是这样

from django.core.files.uploadedfile import SimpleUploadedFile
def get_file(self, url):
    # pdb.set_trace()
    result = urllib.urlretrieve(url)
    fi = open(result[0])
    fi_name = os.path.basename(url)
    suf = SimpleUploadedFile(fi_name, fi)
    return suf
Run Code Online (Sandbox Code Playgroud)

在创建SimpleUploadedFile对象时,我得到错误说

TypeError: file doesnot have buffer interface
Run Code Online (Sandbox Code Playgroud)

我尝试将打开模式更改为'rb'.但仍然得到相同的错误Plz帮助我

python django

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

Django AttributeError'ModelFormOptions'对象没有属性'concrete_fields'

我得到AttributeError说 'ModelFormOptions' object has no attribute 'concrete_fields'。我的代码如下:

我的模型是这样的:

class OrderReceiving(models.Model):
    user = models.ForeignKey(User)
    po = models.ForeignKey(Order)
    datetime = models.DateTimeField(default=timezone.now)
    product = models.ForeignKey(Product)
    quantity = models.IntegerField(default=0)
    building = models.ForeignKey(BuildingNumber)
    isele_abc = models.ForeignKey(IseleAbc)
    isele_num = models.ForeignKey(IseleNum)
    isele_floor = models.ForeignKey(IseleFloor)
Run Code Online (Sandbox Code Playgroud)

我的ModelForm是这样的:

class OrderReceivingForm(ModelForm):

    class Meta:
        model = OrderReceiving
        exclude = ['user', 'datetime']
        labels = {
            'po': _('Vendor PO ID'),
        }
Run Code Online (Sandbox Code Playgroud)

我的看法是:

class OrderReceivingView(View):
    template = 'poreceiving/po_receive.html'

    def get(self, request, *args, **kwargs):
        context = {}
        form = OrderReceivingForm()
        context['form'] = form
        return render_to_response(self.template, …
Run Code Online (Sandbox Code Playgroud)

python django django-forms

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