小编nia*_*loc的帖子

De Morgan的法则是Pythonic吗?

以下哪个if语句更像Pythonic?

if not a and not b:
    do_something
Run Code Online (Sandbox Code Playgroud)

要么

if not ( a or b ):
    do something
Run Code Online (Sandbox Code Playgroud)

它不是谓词逻辑所以我应该使用Python关键词,因为它更具可读性吗?

在后面的解决方案比另一个更优化?(我不相信.)

这有什么PEP-8指南吗?

这两种方法的字节代码(如果重要):

In [43]: def func1():
    if not a and not b:
        return
   ....:     
   ....:     

In [46]: def func2():
    if not(a or b):
        return
   ....:     
   ....:     

In [49]: dis.dis(func1)
  2           0 LOAD_GLOBAL              0 (a)
              3 UNARY_NOT           
              4 JUMP_IF_FALSE           13 (to 20)
              7 POP_TOP             
              8 LOAD_GLOBAL              1 (b)
             11 UNARY_NOT           
             12 JUMP_IF_FALSE            5 (to 20)
             15 POP_TOP             

  3          16 LOAD_CONST               0 …
Run Code Online (Sandbox Code Playgroud)

python pep8 demorgans-law

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

'User'Object没有attribude is_authenticated

我为我的django应用程序创建了一个User模型

class User(Model):
    """
    The Authentication model. This contains the user type.  Both Customer and
    Business models refer back to this model.
    """
    email = EmailField(unique=True)
    name = CharField(max_length=50)
    passwd = CharField(max_length=76)
    user_type = CharField(max_length=10, choices=USER_TYPES)
    created_on = DateTimeField(auto_now_add=True)
    last_login = DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.email

    def save(self, *args, **kw):
        # If this is a new account then encrypt the password.
        # Lets not re-encrypt it everytime we save.
        if not self.created_on:
            self.passwd = sha256_crypt.encrypt(self.passwd)
        super(User, self).save(*args, **kw)
Run Code Online (Sandbox Code Playgroud)

我还创建了一个身份验证中间件来使用这个模型.

from …
Run Code Online (Sandbox Code Playgroud)

django middleware django-middleware django-authentication

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

使用内部werkzeug开发服务器进行烧瓶部署

为什么不建议在生产中使用flask/werkzeug内部开发网络服务器?会出现什么样的问题?

我问,因为在工作中我被迫这样做并使用make shift cron每天重新运行服务!

python deployment werkzeug flask

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

尝试并最终在python中

def connect(self):
    ok = False
    try:
        conn = ftplib.FTP(self.hostname, self.user, self.password)
        ok = True
        return conn
    finally:
        if not ok:
            logging.error('Failed to connect to %s for %s' % (self.hostname, self.user))
Run Code Online (Sandbox Code Playgroud)

我假设如果在finally块中发生了某些事情,那么在try块内返回并不是一个好主意.我只是想确定执行的顺序,然后才会抨击某人的头!

python try-finally

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