Django开发实用技巧与部署指南
立即解锁
发布时间: 2025-08-22 01:25:46 阅读量: 1 订阅数: 2 


Django Web开发实战秘籍
### Django开发实用技巧与部署指南
在Django开发过程中,有许多实用的技巧和方法可以帮助我们提高开发效率、优化性能以及更好地部署项目。下面将详细介绍一些常见的应用场景及操作步骤。
#### 1. 切换Django调试工具栏的可见性
在Django开发中,我们常常需要检查当前模板上下文、衡量SQL查询性能或查看缓存使用情况。Django调试工具栏(Django Debug Toolbar)可以帮助我们实现这些功能。它是一组可配置的面板,能显示有关当前请求和响应的各种调试信息。我们可以通过书签小工具(bookmarklet)设置的cookie来切换调试工具栏的可见性。
##### 准备工作
- 安装Django调试工具栏到虚拟环境:
```sh
(myproject_env)$ pip install django-debug-toolbar==1.2.1
```
- 在设置中,将`debug_toolbar`添加到`INSTALLED_APPS`中。
##### 操作步骤
1. 在`settings.py`文件中添加以下设置:
```python
#myproject/settings.py
MIDDLEWARE_CLASSES = (
# ...
"debug_toolbar.middleware.DebugToolbarMiddleware",
)
DEBUG_TOOLBAR_CONFIG = {
"DISABLE_PANELS": [],
"SHOW_TOOLBAR_CALLBACK": "utils.misc.custom_show_toolbar",
"SHOW_TEMPLATE_CONTEXT": True,
}
DEBUG_TOOLBAR_PANELS = [
"debug_toolbar.panels.versions.VersionsPanel",
"debug_toolbar.panels.timer.TimerPanel",
"debug_toolbar.panels.settings.SettingsPanel",
"debug_toolbar.panels.headers.HeadersPanel",
"debug_toolbar.panels.request.RequestPanel",
"debug_toolbar.panels.sql.SQLPanel",
"debug_toolbar.panels.templates.TemplatesPanel",
"debug_toolbar.panels.staticfiles.StaticFilesPanel",
"debug_toolbar.panels.cache.CachePanel",
"debug_toolbar.panels.signals.SignalsPanel",
"debug_toolbar.panels.logging.LoggingPanel",
"debug_toolbar.panels.redirects.RedirectsPanel",
]
```
2. 在`utils`模块中创建`misc.py`文件,并添加以下函数:
```python
#utils/misc.py
# -*- coding: UTF-8 -*-
def custom_show_toolbar(request):
return "1" == request.COOKIES.get("DebugToolbar", False)
```
3. 打开Chrome或Firefox浏览器,进入书签管理器,创建两个新的JavaScript链接:
- 第一个链接用于显示工具栏:
- 名称:Debug Toolbar On
- URL:`javascript:(function(){document.cookie="DebugToolbar=1; path=/";location.href=location.href;})();`
- 第二个链接用于隐藏工具栏:
- 名称:Debug Toolbar Off
- URL:`javascript:(function(){document.cookie="DebugToolbar=0; path=/";location.href=location.href;})();`
##### 工作原理
`DEBUG_TOOLBAR_PANELS`设置定义了工具栏中要显示的面板。`DEBUG_TOOLBAR_CONFIG`设置字典定义了工具栏的配置,包括用于检查是否显示工具栏的函数路径。默认情况下,浏览项目时Django调试工具栏不会显示。当点击“Debug Toolbar On”书签小工具时,`DebugToolbar` cookie将被设置为1,页面会刷新,此时可以看到带有调试面板的工具栏。
#### 2. 使用ThreadLocalMiddleware
`HttpRequest`对象包含有关当前用户、语言、服务器变量、cookie、会话等有用信息。`ThreadLocalMiddleware`中间件可以将当前`HttpRequest`对象存储到全局可访问的Python线程中,这样我们就可以从模型方法、表单、信号处理程序等之前无法直接访问`HttpRequest`对象的地方获取它。
##### 准备工作
创建`utils`应用,并将其添加到设置中的`INSTALLED_APPS`中。
##### 操作步骤
1. 在`utils`应用中添加`middleware.py`文件,内容如下:
```python
#utils/middleware.py
# -*- coding: UTF-8 -*-
from threading import local
_thread_locals = local()
def get_current_request():
""" returns the HttpRequest object for this thread """
return getattr(_thread_locals, "request", None)
def get_current_user():
""" returns the current user if it exists or None otherwise """
request = get_current_request()
if request:
return getattr(request, "user", None)
class ThreadLocalMiddleware(object):
""" Middleware that adds the HttpRequest object to thread local storage """
def process_request(self, request):
_thread_locals.request = request
```
2. 在设置中,将此中间件添加到`MIDDLEWARE_CLASSES`中:
```python
#myproject/settings.py
MIDDLEWARE_CLASSES = (
# ...
"utils.middleware.ThreadLocalMiddleware",
)
```
##### 工作原理
`ThreadLocalMiddleware`处理每个请求,并将当前`HttpRequest`对象存储在当前线程中。Django中的每个请求 - 响应周期是单线程的。有两个函数`get_current_request`和`get_current_user`,可以从任何地方使用它们来获取当前`HttpRequest`对象或当前用户。例如,可以创建并使用`CreatorMixin`,将当前用户保存为模型的创建者:
```python
#utils/models.py
class CreatorMixin(models.Model):
"""
Abstract base class with a creator
"""
creator = models.ForeignKey(
"auth.User",
verbose_name=_("creator"),
editable=False,
blank=True,
null=True,
)
def save(self, *args, **kwargs):
from utils.middleware import get_current_user
if not self.creator:
self.creator = get_current_user()
super(CreatorMixin, self).save(*args, **kwargs)
save.alters_data = True
class Meta:
abstract = True
```
#### 3. 缓存方法值
如果在请求 - 响应周期中多次调用具有大量计算或数据库查询的同一模型方法,视图的性能可能会非常慢。我们可以使用一种模式来缓存方法的值,以便后续重复使用。这里不使用Django缓存框架,而是使用Python默认提供的功能。
##### 准备工作
选择一个包含耗时方法的模型的应用,该方法将在同一请求 - 响应周期中重复使用。
##### 操作步骤
在模型中使用以下模式来缓存方法值:
```python
#someapp/models.py
# -*- coding: UTF-8 -*-
from django.db import models
class SomeModel(models.Model):
# ...
def some_expensive_function(self):
if not hasattr(self, "_expensive_value_cached"):
# do some heavy calculations...
# ... and save the result to result variable
self._expensive_value_cached = result
return self._expensive_value_cached
```
##### 工作原理
该方法检查模型实例是否存在`_expensive_value_cached`属性。如果不存在,则进行耗时的计算,并将结果分配给这个新属性。方法结束时,返回缓存的值。如果有多个耗时方法,需要使用不同的属性名来保存每个计算值。可以在模板的头部和底部使用`{{ object.some_expensive_function }}`,耗时的计算只会进行一次。也可以在`if`条件中使用该函数来检查值是否存在,并在模板中打印该值:
```html
{% if object.some_expensive_function %}
<span class="special">{{ object.some_expensive_function }}</span>
{% endif %}
```
#### 4. 通过电子邮件获取详细的错误报告
Django使用Python的内置日志模块进行系统日志记录。默认的Django配置似乎相当复杂。我们可以对其进行调整,以便在发生错误时发送包含完整HTML的错误电子邮件,就像Django在DEBUG模式下提供的那样。
##### 准备工作
定位虚拟环境中的Django安装位置。
##### 操作步骤
1. 在文本编辑器中打开`myproject_env/lib/python2.7/site-packages/django/utils/log.py`文件,将`DEFAULT_LOGG
0
0
复制全文
相关推荐










