Django开发BUG汇总

图片 8

阅读目录

使用版本知悉

limengjiedeMacBook-Pro:~ limengjie$ python --version

Python 3.6.4 :: Anaconda, Inc.

limengjiedeMacBook-Pro:~ limengjie$ python -m django --version

1.11.13 

工作需求是1.11.13(安装时,pip版本较低,2.0以下版本安装会超时,2.0以上版本安装正常)

当前系统环境的端口情况查看:

图片 1图片 2

# windows
# 查看8000端口
netstat -aon | findstr "8000"

# 假若此时8000端口被进程号为15312的进程占用,继续执行下面命令查看对应的进程:
tasklist | findstr "15312"

# 假若查看结果,是被test.py给占用了,如果不想这个程序继续占用,可以结束该进程:
taskkill /f /t /im test.py
或者直接根据进程号PID杀死该进程
taskkill /f /PID 15312


#mac
# 查看端口:
sudo lsof -i:8000

# 查看结果:
COMMAND PID      USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
python  934 limengjie    4u  IPv4 0xf90e8048abbcccff      0t0  TCP localhost:irdmi (LISTEN)

# 根据进程PID杀进程
sudo kill -9 934

查看系统端口情况

  1. django-debug-toolbar的配置
  2. Django
    logging的配置

目录

  1. mac环境下,安装Django 2.0
    以下版本报错
  2. 列表存进MySQL数据库后再读取时需转换类型
  3. 上传与下载
  4. Django调试工具:debug_toolbar

 

 

 

 

 

 

 

 

一、django-debug-toolbar的配置

一、mac环境下,安装Django 2.0以下版本报错

1、介绍

django-debug-toolbar
是一组可配置的面板,可显示有关当前请求/响应的各种调试信息,并在单击时显示有关面板内容的更多详细信息。

github地址

文档地址

使用pycharm安装异常截图

图片 3

2、安装

pip3 install django-debug-toolbar

使用命令行安装,异常如下

提示安装超时,并建议更新pip版本号

图片 4图片 5

Last login: Thu Jun 14 16:59:22 on ttys000
limengjiedeMacBook-Pro:~ limengjie$ pip install Django==1.11.13
Collecting Django==1.11.13
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x10ae0ebe0>, 'Connection to files.pythonhosted.org timed out. (connect timeout=15)')': /packages/25/4d/c8228419346a0e84aec202a43e181afc6572b861d38f8a0306dbce6abef0/Django-1.11.13-py2.py3-none-any.whl
  Downloading https://files.pythonhosted.org/packages/25/4d/c8228419346a0e84aec202a43e181afc6572b861d38f8a0306dbce6abef0/Django-1.11.13-py2.py3-none-any.whl (6.9MB)
    14% |████▊                           | 1.0MB 8.9kB/s eta 0:11:03Exception:
Traceback (most recent call last):
  File "/anaconda3/lib/python3.6/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 232, in _error_catcher
    yield
  File "/anaconda3/lib/python3.6/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 314, in read
    data = self._fp.read(amt)
  File "/anaconda3/lib/python3.6/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 60, in read
    data = self.__fp.read(amt)
  File "/anaconda3/lib/python3.6/http/client.py", line 449, in read
    n = self.readinto(b)
  File "/anaconda3/lib/python3.6/http/client.py", line 493, in readinto
    n = self.fp.readinto(b)
  File "/anaconda3/lib/python3.6/socket.py", line 586, in readinto
    return self._sock.recv_into(b)
  File "/anaconda3/lib/python3.6/ssl.py", line 1009, in recv_into
    return self.read(nbytes, buffer)
  File "/anaconda3/lib/python3.6/ssl.py", line 871, in read
    return self._sslobj.read(len, buffer)
  File "/anaconda3/lib/python3.6/ssl.py", line 631, in read
    v = self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/anaconda3/lib/python3.6/site-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/anaconda3/lib/python3.6/site-packages/pip/commands/install.py", line 335, in run
    wb.build(autobuilding=True)
  File "/anaconda3/lib/python3.6/site-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/anaconda3/lib/python3.6/site-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/anaconda3/lib/python3.6/site-packages/pip/req/req_set.py", line 620, in _prepare_file
    session=self.session, hashes=hashes)
  File "/anaconda3/lib/python3.6/site-packages/pip/download.py", line 821, in unpack_url
    hashes=hashes
  File "/anaconda3/lib/python3.6/site-packages/pip/download.py", line 659, in unpack_http_url
    hashes)
  File "/anaconda3/lib/python3.6/site-packages/pip/download.py", line 882, in _download_http_url
    _download_url(resp, link, content_file, hashes)
  File "/anaconda3/lib/python3.6/site-packages/pip/download.py", line 603, in _download_url
    hashes.check_against_chunks(downloaded_chunks)
  File "/anaconda3/lib/python3.6/site-packages/pip/utils/hashes.py", line 46, in check_against_chunks
    for chunk in chunks:
  File "/anaconda3/lib/python3.6/site-packages/pip/download.py", line 571, in written_chunks
    for chunk in chunks:
  File "/anaconda3/lib/python3.6/site-packages/pip/utils/ui.py", line 139, in iter
    for x in it:
  File "/anaconda3/lib/python3.6/site-packages/pip/download.py", line 560, in resp_read
    decode_content=False):
  File "/anaconda3/lib/python3.6/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 357, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/anaconda3/lib/python3.6/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 324, in read
    flush_decoder = True
  File "/anaconda3/lib/python3.6/contextlib.py", line 99, in __exit__
    self.gen.throw(type, value, traceback)
  File "/anaconda3/lib/python3.6/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 237, in _error_catcher
    raise ReadTimeoutError(self._pool, None, 'Read timed out.')
pip._vendor.requests.packages.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out.
You are using pip version 9.0.1, however version 10.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

pip install django==1.11.13
报错源码

3、配置

  1. settings.py中

将 debug_toolbar 添加到 INSTALL_APPS 中

INSTALLED_APPS = [
    …
    'debug_toolbar',
]
  1. urls.py中

    from django.conf import settings
    from django.conf.urls import include, url

    if settings.DEBUG:

     import debug_toolbar
     urlpatterns = [
         url(r'^__debug__/', include(debug_toolbar.urls)),
     ] + urlpatterns
    
  2. settings.py中

在中间件中加入DebugToolbarMiddleware

MIDDLEWARE = [
    # ...
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    # ...
]
  1. 如果是本机调试,还在将127.0.0.1加入 INTERNAL_IPS

在settings.py中加入以下配置项:

INTERNAL_IPS = [‘127.0.0.1’, ]

5.  配置jQuery的URL

django-debug-toolbar 默认使用的是Google的地址,默认配置如下:

JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'

国内用不了的话可以在settings.py中配置一下,例如(我这里特意选用了和原作者相同版本的jQuery):

DEBUG_TOOLBAR_CONFIG = {
    "JQUERY_URL": '//cdn.bootcss.com/jquery/2.2.4/jquery.min.js',
}

或者你如果在Django项目中使用了jquery的话就可以直接将这一项置为空,那么django-debug-toolbar
就会使用你项目中用到的jquery:

DEBUG_TOOLBAR_CONFIG = {
    "JQUERY_URL": '',
}

解决方案:

You are using pip version 9.0.1, however version 10.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

按照提示,更新pip版本后,安装正常

limengjiedeMacBook-Pro:~ limengjie$ pip install --upgrade pip
Collecting pip
  Downloading https://files.pythonhosted.org/packages/0f/74/ecd13431bcc456ed390b44c8a6e917c1820365cbebcb6a8974d1cd045ab4/pip-10.0.1-py2.py3-none-any.whl (1.3MB)
    100% |████████████████████████████████| 1.3MB 23kB/s 
Installing collected packages: pip
  Found existing installation: pip 9.0.1
    Uninstalling pip-9.0.1:
      Successfully uninstalled pip-9.0.1
Successfully installed pip-10.0.1
limengjiedeMacBook-Pro:~ limengjie$ pip install Django==1.11.13
Collecting Django==1.11.13
  Downloading https://files.pythonhosted.org/packages/25/4d/c8228419346a0e84aec202a43e181afc6572b861d38f8a0306dbce6abef0/Django-1.11.13-py2.py3-none-any.whl (6.9MB)
    100% |████████████████████████████████| 7.0MB 30kB/s 
Requirement already satisfied: pytz in /anaconda3/lib/python3.6/site-packages (from Django==1.11.13) (2017.3)
Installing collected packages: Django
  Found existing installation: Django 2.0.6
    Uninstalling Django-2.0.6:
      Successfully uninstalled Django-2.0.6
Successfully installed Django-1.11.13

安装成功验证:

方法一:

>>> import django
>>> print django.VERSION # Python2的格式  
>>> print(django.VERSION) # python3版本
(1, 11, 13, 'final', 0)

方法二:(也是通过查看版本号,python -m django –version)

limengjiedeMacBook-Pro:~ limengjie$ python -m django --version
1.11.13

图片 6

 


 

4、使用

访问具体路径的时候在页面右侧有各项配置面板,点击即可查看各种调试信息。

二、列表存进MySQL数据库后再读取需重新转换为列表

二、Django logging配置

做开发开不开日志,以下是Django项目常用的logging配置。

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'
                      '[%(levelname)s][%(message)s]'
        },
        'simple': {
            'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
        },
        'collect': {
            'format': '%(message)s'
        }
    },
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],  # 只有在Django debug为True时才在屏幕打印日志
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'default': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自动切
            'filename': os.path.join(BASE_LOG_DIR, "xxx_info.log"),  # 日志文件
            'maxBytes': 1024 * 1024 * 50,  # 日志大小 50M
            'backupCount': 3,
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
        'error': {
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自动切
            'filename': os.path.join(BASE_LOG_DIR, "xxx_err.log"),  # 日志文件
            'maxBytes': 1024 * 1024 * 50,  # 日志大小 50M
            'backupCount': 5,
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
        'collect': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件,自动切
            'filename': os.path.join(BASE_LOG_DIR, "xxx_collect.log"),
            'maxBytes': 1024 * 1024 * 50,  # 日志大小 50M
            'backupCount': 5,
            'formatter': 'collect',
            'encoding': "utf-8"
        }
    },
    'loggers': {
       # 默认的logger应用如下配置
        '': {
            'handlers': ['default', 'console', 'error'],  # 上线之后可以把'console'移除
            'level': 'DEBUG',
            'propagate': True,
        },
        # 名为 'collect'的logger还单独处理
        'collect': {
            'handlers': ['console', 'collect'],
            'level': 'INFO',
        }
    },
}

附:Python logger流示图

图片 7 

 用法:

import logging  #调用日记模块

# 生成一个以当前文件名命名的logger实例
logger = logging.getLogger(__name__)
# 生成一个名为collect的logger实例
collect_logger = logging.getLogger("collect")
# 用法与日记模块一样

logger.info("又来了,小伙子!")
collect_logger.info("多多来洗脚!")

 

问题截图

图片 8

此处功能部分源码:

关键是使用eval()函数实现str类型和list,tuple或dict之间的转换

class UploadFile(View):

    def get(self, request):
        file_list = models.FileObj.objects.all()
        # 将数据库中的str对象转为list对象
        for file_obj in file_list:
            file_obj.fileMsg = eval(file_obj.fileMsg)
        return render(
            request,
            "upload_file.html",
            {"file_list": file_list}
        )

    def post(self, request):
        pass