Valuebai / awesome-python-io

Python十分钟入门指南/技术图谱,持续更新收集整理中,期待你的参与
MIT License
8 stars 1 forks source link

【Bug】常见报错Bug-Python, Django, Flask #24

Open Valuebai opened 3 years ago

Valuebai commented 3 years ago

Django 常见报错,比较难找到原因的

if request.method == 'POST':
报错
return None

一般是请求路由URL中少了/,比如
/mail/send   ——报错❌
/mail/send/  ——正常✔️
Valuebai commented 3 years ago

Mac执行正常,但是在windows上执行报错的,原因:%Y-%m-%d-%H:%M:%S这里的:引起的,改为- 就正常了

        # 获取当前时间
        current_time = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
        final_file = r'./data/merged_file_{}.txt'.format(current_time)
        print(final_file)

        # 2个文本合并后的路径,需要考虑放在哪里,暂时以w_file 或当前路径下/data/文件夹中
        w_file = open(final_file, "wb")
Valuebai commented 3 years ago

【问题】django 执行python manage.py migrate 报错

Applying django_celery_results.0001_initial...Traceback (most recent call last): ... django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 1000 bytes')

【原因】在数据库中创建的表是MyISAM,而不是InnoDB

  1. mysql -u root -p 登录后
  2. show databases;
  3. use django_数据库
  4. show table status;

【解决】将表设置为InnoDB

DATABASES['default']['ENGINE'] = 'django.db.backends.mysql'
DATABASES['default']['OPTIONS'] = {
    "init_command": "SET default_storage_engine=INNODB;"
}

或者
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', '
sqlite3' or 'oracle'.
        'OPTIONS':{
            "init_command": "SET default_storage_engine=INNODB;"
        },
        'NAME': 'mydb',                      # Or path to database file if using sqlite3.
        'USER': 'mmog',                      # Not used with sqlite3.
        'PASSWORD': 'mmog',                  # Not used with sqlite3.
        'HOST': '/data/mysqldata/mysql.sock',                      # Set to empty string for localh
ost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}
Valuebai commented 3 years ago

为什么使用django_redis存储string,用redis可视化工具或者命令获取key值,显示十六进制的内容??

如:
# timeout为过期时间,单位:秒,timeout=0为立即过期, timeout为None永不超时
            set_flag = cache.set(self.redis_key, token_value, timeout=self.expire_time)

查看值:
\x80\x04\x95\x16\x00\x00\x00\x00\x00\x00\x00}\x94\x8c\x09mip_token\x94\x8c\x03123\x94s.

原因:django_redis对set的key进行的picke序列化和base64encode操作
python3.6/site-packages/django/core/cache/backends/db.py 的140行

            if num > self._max_entries:
                self._cull(db, cursor, now)
            pickled = pickle.dumps(value, self.pickle_protocol)
            # The DB column is expecting a string, so make sure the value is a
            # string, not bytes. Refs #19274.
            b64encoded = base64.b64encode(pickled).decode('latin1')

【总结】使用Django_redis时,存储的值会有pickle和base64encode,其他应用要用看或者redis可视化工具查看会不方便,如想其他应用也用到django的redis值,需要自己使用redis库进行封装,https://www.runoob.com/w3cnote/python-redis-intro.html