灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
使用django调试工具栏。例如,它允许查看在呈现视图时执行的所有SQL查询,您还可以查看其中任何一个的堆栈跟踪。
其他回答
因为Django的“视图”只需要是返回HttpResponse的可调用对象,你可以很容易地创建基于类的视图,就像Ruby on Rails和其他框架中的那样。
有几种方法可以创建基于类的视图,下面是我最喜欢的:
from django import http
class RestView(object):
methods = ('GET', 'HEAD')
@classmethod
def dispatch(cls, request, *args, **kwargs):
resource = cls()
if request.method.lower() not in (method.lower() for method in resource.methods):
return http.HttpResponseNotAllowed(resource.methods)
try:
method = getattr(resource, request.method.lower())
except AttributeError:
raise Exception("View method `%s` does not exist." % request.method.lower())
if not callable(method):
raise Exception("View method `%s` is not callable." % request.method.lower())
return method(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
return http.HttpResponse()
def head(self, request, *args, **kwargs):
response = self.get(request, *args, **kwargs)
response.content = ''
return response
您可以在基本视图中添加各种其他东西,如条件请求处理和授权。
一旦你设置好了你的视图,你的urls.py将看起来像这样:
from django.conf.urls.defaults import *
from views import MyRestView
urlpatterns = patterns('',
(r'^restview/', MyRestView.dispatch),
)
PyCharm IDE是一个很好的编码环境,尤其是调试环境,内置了对Django的支持。
从settings.py中删除数据库访问信息
我在Django站点的settings.py中做的一件事是从/etc文件中加载数据库访问信息。这样,每台机器的访问设置(数据库主机、端口、用户名、密码)都是不同的,并且像密码这样的敏感信息不在我的项目存储库中。您可能希望以类似的方式限制对工作者的访问,即让他们使用不同的用户名连接。
您还可以通过环境变量传递数据库连接信息,甚至只是一个配置文件的键或路径,并在settings.py中处理它。
例如,下面是我如何拉入我的数据库配置文件:
g = {}
dbSetup = {}
execfile(os.environ['DB_CONFIG'], g, dbSetup)
if 'databases' in dbSetup:
DATABASES = dbSetup['databases']
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
# ...
}
}
不用说,你需要确保DB_CONFIG中的文件除了db管理员和Django本身外,其他用户都不能访问。默认情况下,Django应该参考开发人员自己的测试数据库。使用ast模块代替execfile可能还有更好的解决方案,但我还没有研究过。
我做的另一件事是为DB管理任务使用单独的用户。在我的manage.py中,我添加了以下序言:
# Find a database configuration, if there is one, and set it in the environment.
adminDBConfFile = '/etc/django/db_admin.py'
dbConfFile = '/etc/django/db_regular.py'
import sys
import os
def goodFile(path):
return os.path.isfile(path) and os.access(path, os.R_OK)
if len(sys.argv) >= 2 and sys.argv[1] in ["syncdb", "dbshell", "migrate"] \
and goodFile(adminDBConfFile):
os.environ['DB_CONFIG'] = adminDBConfFile
elif goodFile(dbConfFile):
os.environ['DB_CONFIG'] = dbConfFile
其中/etc/django/db_regular.py中的配置是针对只有SELECT, INSERT, UPDATE, DELETE权限的Django数据库用户,而/etc/django/db_admin.py中的配置是针对拥有CREATE, DROP, INDEX, ALTER, LOCK TABLES权限的用户。(迁移命令来自南方。)这在运行时为我提供了一些保护,防止Django代码弄乱我的模式,并限制了SQL注入攻击可能造成的损害(尽管您仍然应该检查和过滤所有用户输入)。
(摘自我对另一个问题的回答)
Django调试工具栏真的很棒。它实际上并不是一个工具栏,而是一个侧栏,告诉您是什么带来了您正在查看的页面的各种信息——DB查询、发送到模板的上下文变量、信号等等。
使用xml_models创建使用XML REST API后端(而不是SQL后端)的Django模型。这是非常有用的,特别是在对第三方api建模时——你会得到你习惯的所有相同的QuerySet语法。您可以从PyPI安装它。
来自API的XML:
<profile id=4>
<email>joe@example.com</email>
<first_name>Joe</first_name>
<last_name>Example</last_name>
<date_of_birth>1975-05-15</date_of_birth>
</profile>
现在在python中:
class Profile(xml_models.Model):
user_id = xml_models.IntField(xpath='/profile/@id')
email = xml_models.CharField(xpath='/profile/email')
first = xml_models.CharField(xpath='/profile/first_name')
last = xml_models.CharField(xpath='/profile/last_name')
birthday = xml_models.DateField(xpath='/profile/date_of_birth')
finders = {
(user_id,): settings.API_URL +'/api/v1/profile/userid/%s',
(email,): settings.API_URL +'/api/v1/profile/email/%s',
}
profile = Profile.objects.get(user_id=4)
print profile.email
# would print 'joe@example.com'
它还可以处理关系和集合。我们每天都在大量使用的产品代码中使用它,所以即使它是测试版,它也是非常有用的。它还有一组很好的存根,可以在测试中使用。
(免责声明:虽然我不是这个库的作者,但我现在是一个提交者,已经进行了一些小的提交)