小编Sha*_*ang的帖子

python:我怎么知道发生了什么类型的异常?

我有一个主程序调用的函数:

try:
    someFunction()
except:
    print "exception happened!"
Run Code Online (Sandbox Code Playgroud)

但是在函数执行过程中它会引发异常,因此会跳转到该except部分.

我怎样才能确切地看到发生了什么someFunction()导致异常发生?

python exception

200
推荐指数
7
解决办法
16万
查看次数

python/zip:如果提供文件的绝对路径,如何消除zip存档中的绝对路径?

我在两个不同的目录中有两个文件,一个是'/home/test/first/first.pdf',另一个是'/home/text/second/second.pdf'.我使用以下代码来压缩它们:

import zipfile, StringIO
buffer = StringIO.StringIO()
first_path = '/home/test/first/first.pdf'
second_path = '/home/text/second/second.pdf'
zip = zipfile.ZipFile(buffer, 'w')
zip.write(first_path)
zip.write(second_path)
zip.close()
Run Code Online (Sandbox Code Playgroud)

我打开我创建的zip文件后,我有一个home在它的文件夹,然后有两个子文件夹在里面,firstsecond,则PDF文件.我不知道如何只包含两个pdf文件,而不是将完整路径压缩到zip存档中.我希望我的问题清楚,请帮忙.谢谢.

python zip absolute-path zipfile

53
推荐指数
4
解决办法
3万
查看次数

新手问题:c ++ const到非const转换

const这些天我对关键词非常恼火,因为我对它并不熟悉.我有一个存储所有const指针的向量vector<const BoxT<T> *> *Q_exclude,并且在另一个类的构造函数中,我需要将此队列中的一个元素作为参数传入并将其分配给非const成员.我的问题是:

如何将const变量分配给非const变量?我知道这没有意义,因为毕竟const是一个const,不应该被改变.但是在这个过程中必须改变那个恼人的成员变量REALLY!我也可能会将向量中的数据类型更改为非const,但这样做太多了.或者有谁知道如何避免这种情况?

c++ const

45
推荐指数
3
解决办法
10万
查看次数

django:我如何根据GenericForeignKey的字段进行查询?

我是使用GenericForeignKey的新手,我无法使它在查询语句中工作.表格大致如下:

class Ticket(models.Model):
    issue_ct = models.ForeignKey(ContentType, related_name='issue_content_type')
    issue_id = models.PositiveIntegerField(null=True, blank=True)
    issue = generic.GenericForeignKey('issue_ct', 'issue_id')

class Issue(models.Model):
    scan = models.ForeignKey(Scan)
Run Code Online (Sandbox Code Playgroud)

扫描会产生一个问题,一个问题会产生一些故障单,我将问题作为Ticket表的外键.现在我有一个Scan对象,我想查询与此扫描相关的所有故障单.我先试了一下:

tickets = Tickets.objects.filter(issue__scan=scan_obj)
Run Code Online (Sandbox Code Playgroud)

这不起作用.然后我尝试了这个:

issue = Issue.objects.get(scan=scan_obj)
content_type = ContentType.objects.get_for_model(Issue)
tickets = Tickets.objects.filter(content_type=content_type, issue=issue)
Run Code Online (Sandbox Code Playgroud)

仍然无法正常工作.我需要知道如何在django中进行这些查询?谢谢.

django generic-foreign-key

45
推荐指数
2
解决办法
2万
查看次数

python:raise child_exception,OSError:[Errno 2]没有这样的文件或目录

我使用subprocess.popen()函数在python中执行命令,如下所示:

omp_cmd = 'cat %s | omp -h %s -u %s -w %s -p %s -X -' %(temp_xml, self.host_IP, self.username, self.password, self.port)
xmlResult = Popen(omp_cmd, stdout=PIPE, stderr=STDOUT)
Run Code Online (Sandbox Code Playgroud)

在shell中它运行正常没有错误,但在python我得到:

  File "/home/project/vrm/apps/audit/models.py", line 148, in sendOMP
    xmlResult = Popen(omp_cmd, stdout=PIPE, stderr=STDOUT)
  File "/usr/local/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/local/lib/python2.7/subprocess.py", line 1228, in _execute_child
    raise child_exception
  OSError: [Errno 2] No such file or directory
Run Code Online (Sandbox Code Playgroud)

我搜索了错误,但没有一个解决了我的问题.有谁知道这个问题的原因是什么?谢谢.

python popen

18
推荐指数
1
解决办法
4万
查看次数

Django ModelForm Imagefield上传

我是Django的新手,我遇到了使用ModelForm处理图像上传的问题.我的模型如下:

class Project(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=2000)
    startDate = models.DateField(auto_now_add=True)
    photo = models.ImageField(upload_to="projectimg/", null=True, blank=True)
Run Code Online (Sandbox Code Playgroud)

模型形式如下:

class AddProjectForm(ModelForm):
    class Meta:
        model = Project
        widgets = {
            'description': Textarea(attrs={'cols': 80, 'rows': 50}),
        }
        fields = ['name', 'description', 'photo']
Run Code Online (Sandbox Code Playgroud)

而View功能是:

def addProject(request, template_name):
if request.method == 'POST':
    addprojectform = AddProjectForm(request.POST,request.FILES)
    print addprojectform
    if addprojectform.is_valid():
        newproject = addprojectform.save(commit=False)
        print newproject
        print request.FILES
        newproject.photo = request.FILES['photo']
        newproject.save()
        print newproject.photo
else:
    addprojectform = AddProjectForm()

newProposalNum = projectProposal.objects.filter(solved=False).count()
return render(request, template_name, {'addprojectform':addprojectform,
                                       'newProposalNum':newProposalNum})
Run Code Online (Sandbox Code Playgroud)

模板是: …

python django modelform

18
推荐指数
1
解决办法
2万
查看次数

类型对象'X'没有属性'对象'

我正在使用Django和Django Rest Framework 2.4.0

我收到属性错误 type object 'Notification' has no attribute 'objects'

models.py

class Notification(models.Model):
    NOTIFICATION_ID = models.AutoField(primary_key=True)
    user = models.ForeignKey(User, related_name='user_notification')
    type = models.ForeignKey(NotificationType)
    join_code = models.CharField(max_length=10, blank=True)
    requested_userid = models.CharField(max_length=25, blank=True)
    datetime_of_notification = models.DateTimeField()
    is_active = models.BooleanField(default=True)
Run Code Online (Sandbox Code Playgroud)

serializers.py:

class NotificationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Notification
        fields = (
            'type',
            'join_code',
            'requested_userid',
            'datetime_of_notification'
        )
Run Code Online (Sandbox Code Playgroud)

api.py:

class Notification(generics.ListAPIView):
    serializer_class = NotificationSerializer
    def get_queryset(self):
        notifications = Notification.objects.all()
        return notifications
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我解决这个问题吗?它失败api.pynotifications = Notification.objects.all()

django django-rest-framework

18
推荐指数
2
解决办法
3万
查看次数

git:重命名本地分支失败

我不知道为什么我重命名本地分支的尝试失败了.我基本上克隆了项目,然后我在项目中也有一个子模块,我也下载了子模块代码.但是,当我git branch在子模块中使用时,我有:

* (no branch)
  master
Run Code Online (Sandbox Code Playgroud)

代码看起来像我在另一个分支,但输出显示它没有名称.然后我在网上搜索找到如何重命名本地分支,我得到了这个:

git branch -m <newname>
Run Code Online (Sandbox Code Playgroud)

运行此命令后,git给了我这个错误:

error: refname refs/heads/HEAD not found
fatal: Branch rename failed
Run Code Online (Sandbox Code Playgroud)

谁知道为什么会这样?谢谢.

git branch rename

14
推荐指数
6
解决办法
1万
查看次数

django foreignkey包含查询

我有以下型号

class Command(models.Model):
    server = models.ForeignKey(Server)
    user_login = models.CharField(max_length=100)
    user_run = models.CharField(max_length=100)
    host = models.CharField(max_length=100)
    ip = models.CharField(max_length=100)
    session = models.CharField(max_length=100)
    command = models.TextField()
    ts = models.DateTimeField(auto_now_add=True)
    version = models.CharField(max_length=100)
    type = models.CharField(max_length=100)
Run Code Online (Sandbox Code Playgroud)

我有以下搜索查询

cmds = Command.objects.filter(Q(user_login__contains=form.cleaned_data['loguser']),
                              Q(user_run__contains=form.cleaned_data['runuser']),
                              Q(host__contains=form.cleaned_data['loghost']),
                              Q(command__contains=form.cleaned_data['command']),
                              Q(server__contains=form.cleaned_data['host']),
                              Q(session__contains=form.cleaned_data['session'])) \
                      .order_by('-id')[:100]
Run Code Online (Sandbox Code Playgroud)

我需要通过以下字符串搜索server.host

如果我尝试添加以下内容,则会收到错误消息

Q(server__contains=form.cleaned_data['host']),

Exception Type:     TypeError
Exception Value:    

Related Field has invalid lookup: contains

Exception Location:     /usr/lib/python2.5/site-packages/django/db/models/fields/related.py in get_db_prep_lookup, line 156
Run Code Online (Sandbox Code Playgroud)

form.cleaned_data ['host']将包含主机名的文本字符串.

django contains

10
推荐指数
1
解决办法
8591
查看次数

Django:POST方法显示重新发布警告后重定向到当前页面

我对这个问题很困惑,我希望有人可以指出我的错误.

我在views.py中有一个方法,它绑定到一个包含表单的模板.代码如下所示:

def template_conf(request, temp_id):
    template = ScanTemplate.objects.get(id=int(temp_id))
    if request.method == 'GET':
        logging.debug('in get method of arachni.template_conf')    
        temp_form = ScanTemplateForm(instance=template))
        return render_response(request, 'arachni/web_scan_template_config.html', 
                               {
                                'template': template,
                                'form': temp_form,
                               })
    elif request.method == 'POST':
        logging.debug('In post method')
        form = ScanTemplateForm(request.POST or None, instance=template)
        if form.is_valid():
            logging.debug('form is valid')
            form.save()
            return HttpResponseRedirect('/web_template_conf/%s/' %temp_id)
Run Code Online (Sandbox Code Playgroud)

这个页面的行为是这样的:当我按下"提交"按钮时,程序进入POST分支,并成功执行分支中的所有内容.然后HttpResponseRedirect唯一重定向到当前页面(该url是当前url,我认为应该等于.).GET自从我重定向到当前页面后,该分支被执行后,页面确实成功返回.但是,如果我此时刷新页面,浏览器会返回一个确认警告:

The page that you're looking for used information that you entered. 
Returning to that page might cause any action you …
Run Code Online (Sandbox Code Playgroud)

django post redirect

10
推荐指数
2
解决办法
2万
查看次数