我想用它在我的自定义中间件类的process_exception()方法中生成html日志文件,例如:
我知道Django能够为这些异常发送电子邮件,但我宁愿不使用它.我正在使用JSON开发一个RESTful应用程序,所以返回一个json字符串表示错误500然后将html放在其他地方感觉更合适.
提前致谢.
对不起,也许我需要澄清一下:我不想创建自己的500.html,我想使用当Debug = True时django使用的那个.即生成错误文件并将其放在日志文件夹中.
感谢Mark的帮助 - 这是我对任何感兴趣的人的解决方案:
import logging
import os
import settings
import sys
import datetime
from response import get_json_response
from django.views.debug import ExceptionReporter
logging.config.dictConfig(settings.LOGGING)
LOGGER = logging.getLogger('console_logger')
class LoggingMiddleware(object):
def process_exception(self,request,exception):
exc_type, exc_value, exc_traceback = sys.exc_info()
er = ExceptionReporter(request, exc_type, exc_value, exc_traceback)
time = str(datetime.datetime.now())
file_path = os.path.join(settings.LOG_FOLDER, "{}.html".format(time))
LOGGER.error("Writing error 500 traceback to %s" % file_path)
file_handle = open(file_path,'w')
file_handle.write(er.get_traceback_html())
file_handle.close()
return get_json_response(500,"HTTP Error 500: Internal Server Error")
Run Code Online (Sandbox Code Playgroud)
代码拦截任何异常,使用sys模块和djangos默认错误模板生成格式良好的回溯/异常信息页面,然后在返回JSON对象之前将其放在日志文件夹中,表明存在http错误500.
django django-templates django-middleware django-views django-errors
我的目标是在Django 1.5中创建自定义用户模型
# myapp.models.py
from django.contrib.auth.models import AbstractBaseUser
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
db_index=True,
)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
company = models.ForeignKey('Company')
...
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['company']
Run Code Online (Sandbox Code Playgroud)
由于公司字段(models.ForeignKey('Company')(python manage.py createsuperuser),我
无法创建超级用户.我的问题:如何在没有公司的情况下为我的应用程序创建超级用户.我试图制作自定义MyUserManager但没有任何成功:
class MyUserManager(BaseUserManager):
...
def create_superuser(self, email, company=None, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(
email,
password=password,
)
user.save(using=self._db)
return user
Run Code Online (Sandbox Code Playgroud)
或者我是否必须为此用户创建虚假公司?谢谢
为什么我的应用程序中出现以下错误
Caught TypeError while rendering: 'ModelNameHere' object is not iterable
Run Code Online (Sandbox Code Playgroud)
但是当我从shell执行它时,我不明白它?
我的表单中只有一个自定义字段,它继承自forms.ModelForm
custom_serving_size = forms.ChoiceField(
ServingSize.objects.all(),
widget=forms.Select(attrs={'class':'ddl'})
)
Run Code Online (Sandbox Code Playgroud)
编辑
这是我的表格类
class RecipeIngredientForm(forms.ModelForm):
serving_size = forms.ChoiceField(choices=ServingSize.objects.all())
Run Code Online (Sandbox Code Playgroud)
ServingSize.objects.all()上发生错误
我知道django测试用例是用DEBUG = False和TEMPLATE_DEBUG = False完成的,并且我可以使用特定函数将其更改为True,
from django.test.utils import override_settings
@override_settings(DEBUG=True)
def test_one_function(self):
# This test should be failing and is not.
# If I did not test manually I would'nt know !
pass
Run Code Online (Sandbox Code Playgroud)
但也许有一种更好,更通用的解决方案可以同时应用于eveything?
我的模板中有错误:我包含了另一个模板,链接已损坏.如果我用DEBUG = True手动检查我得到TemplateDoesNotExist错误.但是在我的测试用例中,url是在没有破坏包含的情况下呈现的,它不会抛出错误,http_status是200.我已经在其他地方测试了非常通用的包含模板,所以我不想添加测试来查看是否什么是内部正确呈现.但我希望看到渲染失败,这就是我的测试!
我试图将TEMPLATE_STRING_IF_INVALID设置为异常(在此处找到),但它似乎不适用于破坏的包含.
有没有办法在测试期间使所有渲染错误引发异常,而不破坏django在调试中不运行测试的设计原则?
我正在尝试使用pip在一个隔离(--no-site-package)virtualenv中安装pycups,我得到了这个回溯.我无法弄清楚我做错了什么.任何的想法?
谢谢,
$ pip install pycups下载/解压缩pycups运行setup.py egg_info获取包pycups
安装收集的软件包:pycups运行setup.py install for pycups构建'cups'扩展gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -DVERSION ="1.9.66" -I/usr/include/python2.7 -c cupsmodule.c -o build/temp.linux-x86_64-2.7/cupsmodule.o cupsmodule.c:23:23:致命错误:cups/cups.h:El fitxer o导演没有existeix编译终止.错误:命令'gcc'失败,退出状态1完成输出命令/ home/jmartin/workspace/trytond/bin/python -c"import setuptools; file ='/ home/jmartin/workspace/trytond/build/pycups/setup .py'; exec(compile(open(file).read().replace('\ r \n','\n'),file,'exec'))"install --record/tmp/pip-NbMOAM -record/install-record.txt --single-version-external-managed --install-headers /home/jmartin/workspace/trytond/include/site/python2.7:running install
运行构建
运行build_ext
建立'杯子'延伸
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -DVERSION ="1.9.66"-I/usr/include/python2.7 -c cupsmodule.c -o建立/ temp.linux-x86_64-2.7/cupsmodule.o
cupsmodule.c:23:23:致命错误:cups/cups.h:El fitxer o directori no existeix
编译终止.
错误:命令'gcc'失败,退出状态为1
Command/home/jmartin/workspace/trytond/bin/python -c"import setuptools; …
我有一个模特:
class Discount(models.Model):
code = models.CharField(max_length=14, unique=True, null=False, blank=False)
email = models.EmailField(unique=True)
discount = models.IntegerField(default=10)
Run Code Online (Sandbox Code Playgroud)
在我的shell中,当我尝试保存没有输入的Discount对象时,它不会引发错误.我究竟做错了什么?
> e = Discount()
> e.save()
Run Code Online (Sandbox Code Playgroud) 所以我想安装需要pychart的openerp 7.0.406,它的唯一链接似乎在pip中被破坏了.
No distributions at all found for pychart in ./env/lib/python2.7/site-packages (from openerp-core==7.0.406->-r picdyn_openerp_conf/requirements (line 11))
Run Code Online (Sandbox Code Playgroud)
在日志中我们有:
URLs to search for versions for pychart in ./env/lib/python2.7/site-packages (from openerp-core==7.0.406->-r picdyn_openerp_conf/requirements (line 15)):
* https://pypi.python.org/simple/pychart/
Analyzing links from page https://pypi.python.org/simple/pychart/
Skipping link http://www.hpl.hp.com/personal/Yasushi_Saito/pychart (from https://pypi.python.org/simple/pychart/); not a file
Not searching http://www.hpl.hp.com/personal/Yasushi_Saito/pychart (from https://pypi.python.org/simple/pychart/) for files because external urls are disallowed.
Could not find any downloads that satisfy the requirement pychart in ./env/lib/python2.7/site-packages (from openerp-core==7.0.406->-r picdyn_openerp_conf/requirements (line 15))
Run Code Online (Sandbox Code Playgroud)
检查uri时,它返回404未找到.所以我从其他地方下载了pychart(http://download.gna.org/pychart/),我试图安装它(在我的virtualenv中).
pip install …Run Code Online (Sandbox Code Playgroud) 我正在尝试遍历包含测试用例的类的各种实例的数组。数组应具有each根据RubyDoc 的功能:
像所有包含Enumerable模块的类一样,Array具有each方法,该方法定义应迭代哪些元素以及如何对其进行迭代。
以下代码有效:
@array = []
(0..20).to_a.each{ |i|
@array.push(i)
}
@array.each { |i|
puts i
}
Run Code Online (Sandbox Code Playgroud)
但这不是:
@violation_array = []
(0..2).to_a.each{ |i|
@violation_array.push(Violation.new("violation#{i}"))
}
@violation_array.each { |violation|
puts violation
}
Run Code Online (Sandbox Code Playgroud)
并产生此错误:
NoMethodError: undefined method `each ' for #<Array:0x007f3aa232ece8>
Run Code Online (Sandbox Code Playgroud)
@violation_array.inspect之前的值each是:
[#<Violation:0x007f71e4965e30 @key="violation0">, #<Violation:0x007f71e4965bb0 @key="violation1">, #<Violation:0x007f71e49657f0 @key="violation2">]
Run Code Online (Sandbox Code Playgroud)
关于这个数组为什么缺少each功能的任何想法?
编辑:我在多个设置(python,ruby,markdown)中遇到了这个问题。2年后,我终于明白了:我总是space在按住AltGr需要输入的前一个或后一个字符的同时键入内容。这样就形成了不可分割的空间,请参阅如何使用altgr + space禁用不间断空间以获取解决方案)。
我的目标是使用具有默认值的哈希作为类常量.为此,在我看来,我必须在一行中初始化Hash作为具有预定义值和默认值的常量.
根据Ruby文档,我可以用两种方式设置默认值:
在构造函数中,然后通过添加值如下:
MY_HASH = Hash.new(-1)
MY_HASH[1] = 0
MY_HASH[2] = 42
Run Code Online (Sandbox Code Playgroud)首先添加值,然后再设置默认值:
MY_HASH = {
1=>0,
2=>42,
}
MY_HASH.default = -1
Run Code Online (Sandbox Code Playgroud)我尝试在这样的一行中做到这一点,但它不起作用:
MY_HASH = {
1=>0,
2=>42,
}.default = -1
#It's the same as :
MY_HASH = -1
Run Code Online (Sandbox Code Playgroud)
有没有办法在一行中声明一个默认值的哈希?
我正在尝试为一些仅在调试中设置的 URL 设置测试。它们没有设置,因为显然我的设置文件和 urls.py 之间的 DEBUG 值更改为 False。我以前从未遇到过这个问题,而且我不记得做过任何涉及 DEBUG 值的特别花哨的事情。
这是我的 urls.py :
from django.conf import settings
from my_views import dnfp
print "settings.DEBUG in url: {}".format(settings.DEBUG)
if settings.DEBUG:
urlpatterns += [url(r'^dnfp/$', dnfp, name="debug_not_found_page"...
Run Code Online (Sandbox Code Playgroud)
这是我的设置文件:
DEBUG=True
print "DEBUG at the end of the settings: {}".format(DEBUG)
Run Code Online (Sandbox Code Playgroud)
在我的测试中失败的内容:
reverse("debug_not_found_page"),
Run Code Online (Sandbox Code Playgroud)
这是测试的输出:
DEBUG at the end of the settings: True
settings.DEBUG in url: False
Creating test database for alias 'default'...
.E
(...)
NoReverseMatch: Reverse for 'debug_not_found_page' with arguments '()' and keyword arguments '{}' not found. …Run Code Online (Sandbox Code Playgroud) django ×6
python ×4
ruby ×2
testing ×2
virtualenv ×2
arrays ×1
django-views ×1
each ×1
foreign-keys ×1
hash ×1
linux ×1
openerp ×1
pip ×1
pychart ×1
python-2.7 ×1
templates ×1