西维蜀黍

【Python】魔术方法(Magic Methods)

Python的魔术方法一般以__methodname__的形式命名,如:__init__(构造方法)、 __getitem__、 __setitem__、__delitem__(调用del obj[key]时对应触发的函数)、 __len__(对类实例调用len(…)时对应触发的函数)等。

魔术方法具体有:

  • __init__(self):构造方法
  • __del__ :析构函数,释放对象时使用
  • __getitem__(self,key):返回键对应的值(按照索引获取值)
  • __setitem__(self,key,value):设置给定键的值(按照索引赋值)
  • __delitem__(self,key):删除给定键对应的元素
  • __len__():对类实例调用len(…)时对应触发的函数
  • __cmp_: 比较运算
  • __call_:调用
  • __add__:加运算
  • __sub__:减运算
  • __mul__:乘运算
  • __div__:除运算
  • __mod__:求余运算
  • __pow__:幂

需要注意的是,这些成员里面有些是方法,调用时要加括号,有些是属性,调用时不需要加括号。

  ...


【Python】import 问题排查

解决思路

1

使用pip list查看本项目或者系统中已经安装了未找到的模块,这里具体又分为使用了 virenv 和未使用的情况。

2

直接在 terminal 中进入到当前工作文件夹(cd <your target folder>),测试以下 import:

$ python
Python 2.7.17 (default, Oct 24 2019, 12:57:47)
[GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.33.8)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>import <your target module name>
  ...


【Python】pytest - 运行错误

  ...


【Python】单元测试框架 - pytest

一个实例

# content of test_sample.py
 
def func(x):
    return x+1
 
def test_func():
    assert func(3) == 5

再一个实例

当需要编写多个测试样例的时候,我们可以将其放到一个测试类当中,如:

# content of test_class.py

class TestClass:
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

我们可以通过执行测试文件的方法,执行上面的测试:

$ py.test -q test_class.py
.F                                                                                                                                                  [100%]
======================================================================== FAILURES =========================================================================
___________________________________________________________________ TestClass.test_two ____________________________________________________________________

self = <testAA.TestClass instance at 0x10dd68d40>

    def test_two(self):
        x = "hello"
>       assert hasattr(x, 'check')
E       AssertionError: assert False
E        +  where False = hasattr('hello', 'check')

testAA.py:8: AssertionError
1 failed, 1 passed in 0.05 seconds
  ...


【Django】Django ORM - 文档整理

DB Doc

Index for DB: https://docs.djangoproject.com/en/2.2/topics/db/

API Doc

QuerySet API reference:https://docs.djangoproject.com/en/1.11/ref/models/querysets/

Performance and optimization - https://docs.djangoproject.com/en/1.11/topics/performance/

  ...


【Django】Django ORM - 性能优化

你可以使用 python manage.py shell 来让 ORM 执行查询以玩耍:

$ python manage.py shell
>>> from core import models
>>> a = models.User.objects[0:5]
...

如果你使用 MySQL,还可以结合General Log来实时查看 MySQL的 SQL 执行日志以进行验证(Visit 【MySQL】日志记录 for more details)。

最重要的原则: Work at the appropriate level

意思就是说要在对应的 level (M V C) 做对应的事。e.g. 如果计算 court, 在最低的数据库 level 里是最快的(如果只需要知道此记录是否存在的话,用 exists() 会更快)。 但要 注意 : queryset 是 lazy 的,所以有时候在 higher level (例如模板)里控制 queryset 是否真的执行,说不定会更高效。

下面这段代码很好的解释了不同 level 的意思:

# QuerySet operation on the database
# fast, because that's what databases are good at
my_bicycles.count()

# counting Python objects
# slower, because it requires a database query anyway, and processing
# of the Python objects
len(my_bicycles)

# Django template filter
# slower still, because it will have to count them in Python anyway,
# and because of template language overheads
\{\{ my_bicycles|length \}\}
  ...


【Django】Django ORM - 使 DB Schema 生效

当通过 Model 声明完表结构后,Django 可以自动将 Model 声明转换成DB Schema,进而自动写入 DB 中。

在>=1.7 的 Django 中,可以使用以下方法来生成 DB schema:

$ python manage.py makemigrations
$ python manage.py migrate

The makemigrations command looks at all your available models and creates migrations for whichever tables don’t already exist. migrate runs the migrations and creates tables in your database, as well as optionally providing much richer schema control.

在 1.7 之前的版本,使用:

$ python manage.py syncdb
  ...


【Django】使用 Template

在复杂的 Django Project 中,可以会存在多个 Django App,如果科学地管理我们的 HTML页面非常重要。

  ...


【MySQL】日志(Logs)

MySQL 日志文件有一下几种:

  • 错误日志(error logs):It contains information about errors that occur while the server is running (also server start and stop)
  • 一般日志(general logs):This is a general record of what mysqld is doing (connect, disconnect, queries)
  • 慢查询日志(slow query logs):Ιt consists of “slow” SQL statements (as indicated by its name).
  • 二进制日志(binlog)
  • 重做日志(Redo Logs)
  • 回滚日志(Undo Logs)
  • Relay Logs
  ...


【Python】枚举

  ...