python錯誤總結(常更)
阿新 • • 發佈:2018-11-10
- AttributeError: ‘set’ object has no attribute ‘items’
出錯原因是在http請求的header裡,應該用冒號而不是逗號
//wrong
headers={
'Content-Type', 'application/json'
}
//ok
headers={
'Content-Type': 'application/json'
}
2.TypeError: not enough arguments for format string
出錯原因是在佔位符替換時的替換物件,應該是一個元組
//wrong
key = '%s-%s-%s' % report_date[0:4], report_date[4:6], report_date[6:]
//ok
key = '%s-%s-%s' % (report_date[0:4], report_date[4:6], report_date[6:])
3.dict is an unmarshal type
出錯原因是 requests包的post請求data必須放一個json化好的資料,而不是資料本身
buf = {'username':'fw'} //wrong request.post('www.baidu.com',headers={'Content-Type':'application/json'},data=buf) //ok request.post('www.baidu.com',headers={'Content-Type':'application/json'},data=json.dumps(buf))
4.‘dict’ objectt has no attribute ‘x’
出錯原因: 平時寫go時,{}指代的就是物件,而python裡{}指代字典,字典的成員訪問不存在點.,只有物件可以通過點.訪問成員
obj = {'username':'fwe'}
# wrong
print(obj.username)
# ok
print(obj.get('username'))
print(obj.get('username',''))
print(obj['username'])
相比之下,python裡的物件長這樣:
class T: __init__(self,arg): this.arg =arg # 使用時 t = T('xxx') print(t.arg)
還有其他區別比如:
print(t)和print(obj)
前者輸出Object(T),後者輸出{‘username’:‘fwe’}
type(t)和type(obj)
這個輸出也是不同的,答案就不說了自己測測
5.關於時間型別的格式化失效的問題
正確的寫法和錯誤的寫法:
# wrong
print(datetime.today().strftime('%y-%m-%d %H:%m:%s'))
# ok
print(datetime.today().strftime('%Y-%m-%d %H:%M:%S'))
6.去除字串兩邊空格
# wrong
str.strip(' time ')
# ok
' time '.strip()
7.獲取body,param,query三種引數
@action(methods=('get',), detail=False, url_path='invite/relative')
def get_invite_relative(self, request, *args, **kwargs):
# query www.baidu.com?keyword=xxx
keyword = request.query_params.get('keyword', '')
# body {'name':'ft'}
name = request.data.get('name','')
# param invite/:id/relative
id = kwargs['id']
8.時間轉換:
# reg_time是date或者datetime型別
row.reg_time.strftime('%Y-%m-%d %H:%M:%S'),
# reg_time是string型別
parser.parse(reg_time).strftime('%Y-%m-%d %H:%M:%S')
9.整型除法和地板除法
print(2/8) # 0.25
print(2//8) # 0
-
execute() takes from 2 to 3 positional arguments but 5 were given
原因是 cursor.execute(sql, arg1,arg2,arg3) 這樣寫是錯誤的
應該寫成 cursor.execute(sql, [arg1, arg2, arg3]) -
打日誌:
import logging
import logging.config
...
logging.basicConfig(level=logging.DEBUG,
format='[%(asctime)s] %(levelname)s [%(funcName)s: %(filename)s, %(lineno)d] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filemode='a')
logging.error(info)
logging.info(msg)
- 通過反射拿到class內部欄位,如何區分函式和欄位
def IfFunc(obj):
return hasattr(obj,'__call__')