小编Pur*_*ret的帖子

如何在上下文管理器中编写装饰器以包装参数?

我已经看到如何在装饰器中使用上下文管理器以及如何将装饰器中创建的对象传递给装饰函数以及带参数的python装饰器,我正在尝试将两者结合起来.但我正在努力让我的头围绕它.

@wrap如果可能的话,我宁愿使用func工具装饰器来执行此操作,因为我知道是否会保留doc字符串.

我想要做的是:

def pyro_opener(func,service,database,port,secret_key):
    def wrapper(params):
        with Pyro4.Proxy("PYRO:"+service+"@"+database+":"+port) as obj:
            obj.set_secret_key(secret_key)
            return obj.func(params)
    return wrapper


@pyro_opener(output_service, employee_db,port=9876,secret_key="h3llow0rld")
def get_employee_names(salary):
    return obj.return_employee_names(salary)  # obj is clearly not in scope here
                                              # but what else can I do?


get_employee_names(25000)

>>>> Bob, Jane, Mary
Run Code Online (Sandbox Code Playgroud)

我认为这不起作用,方法return_employee_names是在连接另一端的服务上.我应该只返回函数调用吗?如果是这样,我怎么通过params呢?

python decorator pyro python-2.7 python-decorators

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

序列化和反序列化Django Enum字段以接受数字和文本表示

我正在尝试在Django中创建一个枚举字段,在GET请求时将返回枚举的文本表示,并在POST或PATCH请求时将文本表示转换为相应的整数,然后保存.

transform_<field>()
Run Code Online (Sandbox Code Playgroud)

方法可以很好地将整数枚举值转换为相应的字符串,但我无法找到一种更好的方法将字符串转换为相应的整数而不是黑客攻击

validate_<field>()
Run Code Online (Sandbox Code Playgroud)

方法.

有没有更好的方法呢?请参阅下面的代码

模型文件

class Status(enum.Enum):
    RUNNING = 0
    COMPLETED = 1

    labels = {
         RUNNING: 'Running',
         COMPLETED: 'Completed'
    }

    translation = {v: k for k, v in labels.iteritems()}

class Job(models.Model):
    status = enum.EnumField(Status)
Run Code Online (Sandbox Code Playgroud)

串行

class JobSeralizer(serializers.ModelSerailzer):
    status = seralizers.CharField(max_length=32, default=Status.QUEUED)

    def transform_status(self, obj, value):
        return JobStatus.labels[value]

    def validate_status(self, attrs, source):
        """Allow status to take numeric or character representation of status
        """
        status = attrs[source]
        if status in JobStatus.translation:
            attrs[source] = JobStatus.translation[status]
        elif status.isdigit(): …
Run Code Online (Sandbox Code Playgroud)

python django django-rest-framework

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

混合Django Rest Framework中序列化器之间的公共字段

我有这个:

class GenericCharacterFieldMixin():
    attributes = serializers.SerializerMethodField('character_attribute')
    skills = serializers.SerializerMethodField('character_skill')

    def character_attribute(self, obj):
        character_attribute_fields = {}
        character_attribute_fields['mental'] = {str(trait_item.get()): trait_item.get().current_value
                                                for trait_item in obj.mental_attributes}
        character_attribute_fields['physical'] = {str(trait_item.get()): trait_item.get().current_value
                                                  for trait_item in obj.physical_attributes}
        character_attribute_fields['social'] = {str(trait_item.get()): trait_item.get().current_value
                                                for trait_item in obj.social_attributes}
        return character_attribute_fields

    def character_skill(self, obj):
        character_skill_fields = {}
        character_skill_fields['mental'] = {str(trait_item.get()): trait_item.get().current_value
                                            for trait_item in obj.mental_skills}
        character_skill_fields['physical'] = {str(trait_item.get()): trait_item.get().current_value
                                              for trait_item in obj.physical_skills}
        character_skill_fields['social'] = {str(trait_item.get()): trait_item.get().current_value
                                            for trait_item in obj.social_skills}
        return character_skill_fields


class MageSerializer(GenericCharacterFieldMixin, serializers.ModelSerializer):
    player = serializers.ReadOnlyField(source='player.username')
    arcana …
Run Code Online (Sandbox Code Playgroud)

python django mixins django-rest-framework

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

使用默认值来构建嵌套对象的更清洁方法?

我有一个嵌套的对象可能有缺少的东西:

const unreliableObject = {
    id: 10,
    nestedObject: { // may be missing
        id: 11 // may also be missing
    }
}
Run Code Online (Sandbox Code Playgroud)

现在说我想得到内心的id.我可以做以下事情

const { nestedObject: { id: key = -1 } = {key: -1} } = unreliableObject;
console.log(key);
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?我没有定义{key: -1}两次的东西,也没有使用空对象(我们有lint规则),在这种情况下我仍然想要默认密钥.

javascript destructuring

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

BASH - 使用正则表达式查找和过滤查找特定文件夹

我有一个文件夹,其中包含许多带有子文件夹 (/...) 的文件夹,其结构如下:

_30_photos/combined
_30_photos/singles
_47_foo.bar
_47_foo.bar/combined
_47_foo.bar/singles
_50_foobar
Run Code Online (Sandbox Code Playgroud)

使用命令将显示find . -type d -print | grep '_[0-9]*_'结构为** 的所有文件夹。但是我生成了一个仅捕获 */combined 文件夹的正则表达式: _[0-9]*_[a-z.]+/combined但是当我将它插入到 find 命令中时,不会打印任何内容。

下一步是为每个组合文件夹(在我的硬盘上的某处)创建一个文件夹,并将组合文件夹的内容复制到新文件夹中。新文件夹名称应与子文件夹的父名称相同,例如 _47_foo.bar。搜索后可以使用 xargs 命令来实现吗?

regex bash

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

IE 8及更低版本的渐变支持

我为朋友正在制作的页面找到了一个很棒的CSS 渐变代码生成器,但是下面有一些评论让我担心:

/* For Internet Explorer 5.5 - 7 */
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#cccccc, endColorstr=#ffffff);
        /* For Internet Explorer 8 */
        -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#cccccc, endColorstr=#ffffff)";    
        background-color: #CCC;
Run Code Online (Sandbox Code Playgroud)

并作出回应:

我强烈建议不要这些!它们的行为不同,受到限制,性能受损,并且可能导致布局问题.简单地说,因为IE不支持渐变(以及许多其他CSS功能本身,没有过滤器),要么使用图像获得相同的效果(背景图像),要么让客户说服IE用户获得较少的体验(严重关心渐变) vs疯狂的'设计师'之外的单色?)因为他们的浏览器与我们开发人员想要的不匹配.它被称为优雅降级,IE不应该是任何例外.

所以我不知道的是:我是否应该建议他们不使用这些代码?是否让IE使用此代码无用/无望?

css internet-explorer gradient

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

非法块大小异常当使用填充密码解密时,输入长度必须是16的倍数

在我的应用程序中,我使用secretKey加密和解密数据.为此,我使用AES算法.但我在解密时遇到异常,使用密钥在三个已经加密的值中有一个值.

例外情况是:

Illegal Block Size Exception Input length must be multiple of 16 when decrypting with padded cipher.
Run Code Online (Sandbox Code Playgroud)

以下是我的代码:

功能来加强价值

public static String symmetricEncrypt(String text, String secretKey) {
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] raw;
    String encryptedString;
    SecretKeySpec skeySpec;
    BASE64Encoder bASE64Encoder = new BASE64Encoder();
    byte[] encryptText = text.getBytes();
    Cipher cipher;
    try {
        raw = decoder.decodeBuffer(secretKey);
        skeySpec = new SecretKeySpec(raw, "AES");
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        encryptedString = bASE64Encoder.encode(cipher.doFinal(encryptText));
    } 
    catch (Exception e) {
        e.printStackTrace();
        return "Error";
    }
    return encryptedString;
} …
Run Code Online (Sandbox Code Playgroud)

java security encryption-symmetric

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

为什么在此函数定义中使用'window.angular'如此?

我正在尝试理解我需要用来与Django集成的angularjs文件,它有一个我不熟悉的奇怪语法(记住我是一个初级开发者,所以这可能是你的面包和黄油) ...

它类似于:

(function(angular, undefined){
    'use script';
    var djng_forms_module = angular.module('ng.django.forms', []);
    funtion hasCode(s){
        return .....
    }
    var foo = .....
}(window.angular));
Run Code Online (Sandbox Code Playgroud)

我已经看到关于窗口的javascript概念,它显示该window部分是浏览器在加载页面时创建的顶级(?)级别对象.

跑步console.log(window.angular)打印出一堆内部角度的东西.所以我猜这是AngularJS的内部胆量......?

但是为什么这个奇怪的封装作为一个函数(与JavaScript作为'功能'语言有关)?

完整的脚本在这里,我无法弄清楚它window.angular在这个函数定义中使用的原因(与正常的处理方式相反).看起来这个设置意味着当我通过script标签导入它时,它不能用于我的应用程序.

javascript functional-programming angularjs

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

VSCode中未发现的Python单元测试

我写了一个名为蟒蛇测试文件scraping_test.py,用一个单一的测试类,使用unittest,称为TestScrapingUtils

"""Tests for the scraping app"""
import unittest

from bs4 import BeautifulSoup as bs4

from mosque_scraper.management.commands import scraping_utils
from mosque_scraper.selectors import MOSQUE_INFO_ROWS_SELECTOR

class TestScrapingUtils(unittest.TestCase):
    """Test scraping_utils.py """
    def setup(self):
        """Setup McSetupface."""
        pass
    def test_get_keys_from_row(self):
        """ Test that we extract the correct keys from the supplied rows."""
        test_page_name = "test_page.html"
        with open(test_page_name) as test_page_file:
            test_mosque = bs4(test_page_file, 'html.parser')
            rows = test_mosque.select(MOSQUE_INFO_ROWS_SELECTOR)
            field_dict = scraping_utils.get_fields_from_rows(rows)
            self.assertDictEqual(field_dict, {})
Run Code Online (Sandbox Code Playgroud)

我对单元测试的设置是:

{
    "python.unitTest.unittestEnabled": true,
    "python.unitTest.unittestArgs": [
        "-v",
        "-s",
        ".",
        "-p", …
Run Code Online (Sandbox Code Playgroud)

python python-unittest visual-studio-code

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

Visual Studio代码CMD.EXE以上述路径作为当前目录启动。不支持 UNC 路径。默认为 Windows 目录

我是 javaScript 新手,正在尝试设置 Visual Studio Code。我已经安装了 NodeJs 和 Visual Studio Code,以及 Windows Powershell。

在 Visual Studio > 终端中,如果我run npm view命令我收到以下错误

CMD .EXE 以上述路径作为当前目录启动。
不支持 UNC 路径。默认为 Windows 目录。
npm 错误!无效的包裹

任何人都可以看一下这个问题吗?这是因为公司系统的限制吗?

npm visual-studio-code

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