/ app / profile /上的TypeError,' list' object不可调用handle_pageBegin args =()

时间:2017-03-10 11:42:46

标签: python django pdf unicode django-views

我想要一个按钮来创建一个PDF文件(使用Python 2.7,Django 1.8),但我不知道如何将其表达到机器上。

我开始阅读一些文章,试图向其他人学习如何做到这一点。

找到this handy link,将我重定向到以下链接:

因此,为了打印为PDF:

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\ 方法一:使用ReportLab ////////////////////////////// ///////////////////

pip install reportlab

ReportLab依赖于 Pillow ,它是第三方Python图像库。 如果您运行:

pip install Pillow

你会看到这样的事情:

Requirement already satisfied: Pillow in c:\pythonprojects\virtualenvs\apis\lib\site-packages
Requirement already satisfied: olefile in c:\pythonprojects\virtualenvs\apis\lib\site-packages (from Pillow)

在这个级别上似乎不需要其他任何东西,所以让我们首先确保我们在视图中拥有所需的一切。

------------------------------------------ 版本0.2 (代码错误)----------------------------------------- -

1。 代码

# views.py
from django.http import response
from django.core.files.storage import FileSystemStorage
from django.shortcuts import render, HttpResponse
from django.contrib.auth.decorators import login_required
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
import requests
import praw


def profile(request):
        #PDF
        doc = SimpleDocTemplate("test.pdf")
        styles = getSampleStyleSheet()
        Story = [Spacer(1, 2 * inch)]
        style = styles["Normal"]

        #Webpage
        parsedData = []
        userData = {}
        if request.method == 'POST':
        #Data
            sub = request.POST.get('subreddit')
            reddit = praw.Reddit(client_id='client_id',
                                 client_secret='client_secret',
                                 user_agent='user_agent')
            # assuming you have a Reddit instance bound to variable `reddit`
            subreddit = reddit.subreddit(sub)

            print('Master, this was the data retrieved that is going to be displayed:')
            print(subreddit.display_name)  # Output: redditdev
            print(subreddit.title)  # Output: reddit Development
            print(subreddit.description)  # Output: A subreddit for discussion of ...
            print('Tell me if you want more and I can give that to you, no problem-------------')

         #PDF
            print('Now, Im gonna create a PDF file with the same data...')
            subreddit_name = subreddit.display_name
            subreddit_title = subreddit.title
            subreddit_description = subreddit.description

            p = Paragraph(subreddit_name, subreddit_title, subreddit_description,  style)
            Story.append(p)
            Story.append(Spacer(1, 0.2 * inch))
            doc.build(Story)
            print('The file was created and can be accessed in the root of the Django project. The name is test.pdf')
            print('Tell me to stop if you dont like what Im doing-------------')        

        #Webpage
            print('OK. Time to give that to the user as well...')
            userData['subreddit_name'] = subreddit.display_name
            userData['title'] = subreddit.title
            userData['description'] = subreddit.description
        parsedData.append(userData)
        return render(request, 'app/profile.html', {'data': parsedData})

从插入#PDF下的代码开始,视图就不再相同了。

2。 错误

跟踪图像: enter image description here

跟踪文字:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/app/profile/

Django Version: 1.8
Python Version: 2.7.12
Installed Applications:
('frontend',
 'app',
 'blog',
 'suit',
 'suit_redactor',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')


Traceback:
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "C:\PythonProjects\reddit_development\demonstration\app\views.py" in profile
  69.         doc.build(Story)
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\reportlab\platypus\doctemplate.py" in build
  1213.         BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker)
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\reportlab\platypus\doctemplate.py" in build
  969.                     self.handle_flowable(flowables)
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\reportlab\platypus\doctemplate.py" in handle_flowable
  834.             if frame.add(f, canv, trySplit=self.allowSplitting):
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\reportlab\platypus\frames.py" in _add
  167.                 w, h = flowable.wrap(aW, h)
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\reportlab\platypus\paragraph.py" in wrap
  1191.         leftIndent = style.leftIndent

Exception Type: AttributeError at /app/profile/
Exception Value: 'unicode' object has no attribute 'leftIndent'

3。 我认为问题出在哪里?:

代码运行正常,直到此部分:

p = Paragraph(subreddit_name, subreddit_title, subreddit_description,  style)
Story.append(p)
Story.append(Spacer(1, 0.2 * inch))
doc.build(Story)

------------------------------------------ 版本0.3 ----------------------------------------------

根据他的消息中的Christoph Bluossthe documentation

p = Paragraph("Some string", style)

了解这一点,

1。 代码

一个。创建了3个类

Story1 = [Spacer(1, 2 * inch)]

Story2 = [Spacer(1, 2 * inch)]

Story3 = [Spacer(1, 2 * inch)]

湾创建了3个新变量

p1 = Paragraph(subreddit_name,  style)

p2 = Paragraph(subreddit_title, style)

p3 = Paragraph(subreddit_description, style)

℃。将所有变量附加​​到不同的类中

Story1.append(p1)
Story1.append(Spacer(1, 0.2 * inch))

Story2.append(p2)
Story2.append(Spacer(1, 0.2 * inch))

Story3.append(p3)
Story3.append(Spacer(1, 0.2 * inch))

d。有一个带有这些变量的doc.buil。

doc.build(Story1, Story2, Story3)

2。 错误

跟踪图像: enter image description here

跟踪文字:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/app/profile/

Django Version: 1.8
Python Version: 2.7.12
Installed Applications:
('frontend',
 'app',
 'blog',
 'suit',
 'suit_redactor',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')


Traceback:
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "C:\PythonProjects\reddit_development\demonstration\app\views.py" in profile
  77.         doc.build(Story1, Story2, Story3)
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\reportlab\platypus\doctemplate.py" in build
  1213.         BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker)
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\reportlab\platypus\doctemplate.py" in build
  966.                 self.clean_hanging()
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\reportlab\platypus\doctemplate.py" in clean_hanging
  554.             self.handle_flowable(self._hanging)
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\reportlab\platypus\doctemplate.py" in handle_flowable
  828.             f.apply(self)
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\reportlab\platypus\doctemplate.py" in apply
  153.             annotateException("\nhandle_%s args=%s"%(action,ascii(args)))
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\reportlab\lib\utils.py" in annotateException
  1390.     rl_reraise(t,v,b)
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\reportlab\platypus\doctemplate.py" in apply
  146.             getattr(doc,arn)(*args)
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\reportlab\platypus\doctemplate.py" in handle_pageBegin
  1189.         self._handle_pageBegin()
File "C:\PythonProjects\virtualenvs\apis\lib\site-packages\reportlab\platypus\doctemplate.py" in handle_pageBegin
  579.         self.pageTemplate.onPage(self.canv,self)

Exception Type: TypeError at /app/profile/
Exception Value: 'list' object is not callable
handle_pageBegin args=()

3。 我认为问题在哪里

代码运行正常,直到此部分:

 p1 = Paragraph(subreddit_name,  style)
 p2 = Paragraph(subreddit_title, style)
 p3 = Paragraph(subreddit_description, style)
 Story1.append(p1)
 Story1.append(Spacer(1, 0.2 * inch))
 Story2.append(p2)
 Story2.append(Spacer(1, 0.2 * inch))
 Story3.append(p3)
 Story3.append(Spacer(1, 0.2 * inch))
 doc.build(Story1, Story2, Story3)

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\ 方法二:使用WeasyPrint ////////////////////////////// ///////////////////

如果我们无法解决过去的方法,这似乎是一个很好的协议。

2 个答案:

答案 0 :(得分:3)

回答您的最新问题(第0.3版) 根据文档http://www.reportlab.com/docs/reportlab-userguide.pdf(第68页):

  

BaseDocTemplate.build(self,flowables,filename = None,canvasmaker = canvas.Canvas)

     

假设文档实例已正确设置构建   方法以流动性列表的形式呈现故事(   flowables参数)并循环遍历列表强制流动   一次一个通过格式化机制

另一方面,你只是用一些列表来调用build()。实际上,我甚至不知道你为什么要使用3个单独的列表,而不仅仅是单个列表这样的话。

story = [Spacer(1, 2 * inch)]
story.append(Paragraph(subreddit_name,  style))
story.append(Spacer(1, 2 * inch))
story.append(Paragraph(subreddit_title, style))
story.append(Spacer(1, 2 * inch))
story.append(Paragraph(subreddit_description, style))
doc.build(story)

工作正常。 (尽管用python3测试过)

答案 1 :(得分:1)

查看the Paragraph() documentation,第二个参数是段落样式。您正在提供subreddit_title,这是一个常规的unicode字符串,但不起作用。

您的代码应如下所示:

p = Paragraph("Some string", style)

而我的2个主题是关于pdf生成的主题。 我发现http://weasyprint.org/更方便使用。没有许可证的Reportlab很难与之合作。