17.04.2017       Выпуск 174 (17.04.2017 - 23.04.2017)       Статьи

Как генерировать ODT документы с Secretary

Короткая статья о библиотеки для геренации ODT файлов

Читать>>



Экспериментальная функция:

Ниже вы видите текст статьи по ссылке. По нему можно быстро понять ссылка достойна прочтения или нет

Просим обратить внимание, что текст по ссылке и здесь может не совпадать.

Sometimes due to the needs of a project, we need to create odt documents to represent information that we have in our application. This task can be light using the Secretary library.

What is Secretary?

Secretary is a library that allows you to use documents in ODT format to render documents usingdjango

Secretary uses the semantics of jinja2 templates  and most of its functionalities can be used in the generation of these documents, some very important as "variable printing,filters andflow control''. 

Installation

 

pip install secretary

To show the use of this library, we create a model that contains people with 3 data (name, surname and email). The idea is to generate a document that contains a table with the data of all the people. We started!

1º We add a new url in urls.pyto associate our new view that will generate the document.

from django.conf.urls import url
from . import views

urlpatterns = [
   url(r'^generate/document/$', views.generate_document,name='generate_document')
  ]

2º We created a very simple view to render and create the http response in our views.py. To reduce logic in the view, we create a classwith a static method where the rendering of the document is performed and theHTTP response is created.

# views.py
from .models import Person
from .logic import ReportGenerator

def generate_document(request):
   # Model data
   people = Person.objects.all().order_by('last_name')

   return ReportGenerator().create_report(people)
# logic.py
from secretary import Renderer
from django.http import HttpResponse
import os, tempfile


class ReportGenerator():
   """ Class ReportGenerator """

   @staticmethod
   def create_report(data):
       engine = Renderer()
       root = os.path.dirname(__file__)
       document = root + '/templates/bedjango/template.odt'
       result = engine.render(document, data=data)

       response = HttpResponse(content_type='application/vnd.oasis.opendocument.text; charset=UTF-8')
       response['Content-Disposition'] = 'inline; filename=people.odt'
       with tempfile.NamedTemporaryFile() as output:
           output.write(result)
           output.flush()
           output = open(output.name, 'r')
           response.write(output.read())

       return response

3º We create an odt document that will serve as a template to render information of the people of our application. I remember that we should use Jinja2 syntax.

Selection_041.png

 

4º We check the result.

Selection_042.png

 

As you can see, we have generated a very fast document odt with the data of the people of our application. I hope you liked this post. Do not hesitate to ask!

https://github.com/christopher-ramirez/secretary


Regards!



Лучшая Python рассылка

Нас поддерживает


Python Software Foundation



Разместим вашу рекламу

Пиши: mail@pythondigest.ru

Нашли опечатку?

Выделите фрагмент и отправьте нажатием Ctrl+Enter.

Система Orphus