python错误总结(常更)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fwhezfwhez/article/details/82110385
  1. 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
  1. execute() takes from 2 to 3 positional arguments but 5 were given
    原因是 cursor.execute(sql, arg1,arg2,arg3) 这样写是错误的
    应该写成 cursor.execute(sql, [arg1, arg2, arg3])

  2. 打日志:

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)
  1. 通过反射拿到class内部字段,如何区分函数和字段
def IfFunc(obj):
    return hasattr(obj,'__call__')

猜你喜欢

转载自blog.csdn.net/fwhezfwhez/article/details/82110385