低レベルAPI とその他のレシピ

□未翻訳

□翻訳中

□翻訳完了(Omi Chiba)

■レビュー(Yota Ichino)

低レベル API とその他のレシピ

simplejson

JSON

simplejson

web2pyにはBob Ippolitoが開発したgluon.contrib.simplejsonがあります。このモジュールは最も標準的なPython-JSONのエンコーダ・デコーダを提供します。

web2py includes gluon.contrib.simplejson, developed by Bob Ippolito. This module provides the most standard Python-JSON encoder-decoder.

SimpleJSONは二つの機能から構成されています:

SimpleJSON consists of two functions:

  • gluon.contrib.simplesjson.dumps(a)はPythonオブジェクトaをJSONにエンコードします。

  • gluon.contrib.simplejson.loads(b) はJavaScriptオブジェクトbをPtyhonオブジェクトにデコードします。

    • gluon.contrib.simplesjson.dumps(a) encodes a Python object a into JSON.

    • gluon.contrib.simplejson.loads(b) decodes a JavaScript object b into a Python object.

シリアライズされるオブジェクト型には基本型、リスト、辞書があります。複合的なオブジェクトはユーザ定義クラスを除きシリアライズできます。

Object types that can be serialized include primitive types, lists, and dictionaries. Compound objects can be serialized with the exception of user defined classes.

これは低レベルAPIを使った曜日を含むPythonリストをシリアライズする簡単なアクション(例:コントローラー"default.py")です:

Here is a sample action (for example in controller "default.py") that serializes the Python list containing weekdays using this low level API:

1.

2.

3.

4.

5.

def weekdays():

names=['Sunday','Monday','Tuesday','Wednesday',

'Thursday','Friday','Saturday']

import gluon.contrib.simplejson

return gluon.contrib.simplejson.dumps(names)

以下はAjaxリクエストを上記のアクションに送信し、JSONメッセージを受信しリストを対応するJavaScript変数に保存するHTMLのサンプルです。

Below is a sample HTML page that sends an Ajax request to the above action, receives the JSON message and stores the list in a corresponding JavaScript variable:

1.

2.

3.

4.

5.

{{extend 'layout.html'}}

<script>

$.getJSON('/application/default/weekdays',

function(data){ alert(data); });

</script>

このコードはAjaxの実行、応答時に、ローカルJavaScript変数dataにある曜日の名称を保存してその変数をコールバック関数に返す働きをする$.getJSONというjQuery関数を使用しています。この例ではコールバック関数が訪問者にデータが受信されたことを知らせます。

The code uses the jQuery function $.getJSON, which performs the Ajax call and, on response, stores the weekdays names in a local JavaScript variable data and passes the variable to the callback function. In the example the callback function simply alerts the visitor that the data has been received.

PyRTF

PyRTF

RTF

ウェブサイトでよく必要になる他の機能としてWordで読み込むことができるテキスト文書の作成があります。一番簡単な方法はRich Text Format (RTF) を使うことです。このフォーマットはMicrosoftによって発明されて、それからは標準のフォーマットになりました。

Another common need of web sites is that of generating Word-readable text documents. The simplest way to do so is using the Rich Text Format (RTF) document format. This format was invented by Microsoft and it has since become a standard.

web2pyにはSimon Cusackによって開発されGrant Edwardsによって改良されたgluon.contrib.pyrtfがあります。このモジュールは色付きのテキストや画像を含むRTF文書をプログラム的に作成することができます。

web2py includes gluon.contrib.pyrtf, developed by Simon Cusack and revised by Grant Edwards. This module allows you to generate RTF documents programmatically including colored formatted text and pictures.

次の例では二つの標準的なRTFクラスDocumentとSectionをインスタンス化し、後者を前者に追加し後者にダミーテキストを挿入しています。

In the following example we instantiate two basic RTF classes, Document and Section, append the latter to the former and insert some dummy text in the latter:

1.

2.

3.

4.

5.

6.

7.

8.

9.

def makertf():

import gluon.contrib.pyrtf as q

doc=q.Document()

section=q.Section()

doc.Sections.append(section)

section.append('Section Title')

section.append('web2py is great. '*100)

response.headers['Content-Type']='text/rtf'

return q.dumps(doc)

Documentの最後はq.dumps(doc)によってシリアライズされます。RTF文書を返す前にヘッダーにcontent-typeを指定する必要があることに注意してください、そうしないとブラウザーはファイルをどのように処理していいか分かりません。

In the end the Document is serialized by q.dumps(doc). Notice that before returning an RTF document it is necessary to specify the content-type in the header else the browser does not know how to handle the file.

ブラウザの設定によって、ファイルを保存するかテキストエディタで開くかを聞かれます。

Depending on the configuration, the browser may ask you whether to save this file or open it using a text editor.

ReportLab and PDF

ReportLab

PDF

web2pyは"ReportLab"73という追加ライブラリでPDFドキュメントを作成することもできます。

web2py can also generate PDF documents, with an additional library called "ReportLab"73 .

ソースからweb2pyを実行しているのであれば、ReportLabが既にインストールされている可能性が高いです。Windowsバイナリディストリビューションの場合は、ReportLabを"wb2py/"フォルダに解凍する必要があります。Macバイナリディストリビューションの場合は、以下のフォルダに解凍する必要があります。

If you are running web2py from source, it is sufficient to have ReportLab installed. If you are running the Windows binary distribution, you need to unzip ReportLab in the "web2py/" folder. If you are running the Mac binary distribution, you need to unzip ReportLab in the folder:

1.

web2py.app/Contents/Resources/

ReportLabがインストールされてweb2pyがそれを実行できる状態であるとします。PDFドキュメントを作成する"get_me_a_pdf"という簡単な関数を作成して行きましょう:

From now on we assume ReportLab is installed and that web2py can find it. We will create a simple action called "get_me_a_pdf" that generates a PDF document.

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

17.

18.

19.

20.

21.

22.

23.

24.

25.

26.

27.

28.

from reportlab.platypus import *

from reportlab.lib.styles import getSampleStyleSheet

from reportlab.rl_config import defaultPageSize

from reportlab.lib.units import inch, mm

from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER, TA_JUSTIFY

from reportlab.lib import colors

from uuid import uuid4

from cgi import escape

import os

def get_me_a_pdf():

title = "This The Doc Title"

heading = "First Paragraph"

text = 'bla '* 10000

styles = getSampleStyleSheet()

tmpfilename=os.path.join(request.folder,'private',str(uuid4()))

doc = SimpleDocTemplate(tmpfilename)

story = []

story.append(Paragraph(escape(title),styles["Title"]))

story.append(Paragraph(escape(heading),styles["Heading2"]))

story.append(Paragraph(escape(text),styles["Normal"]))

story.append(Spacer(1,2*inch))

doc.build(story)

data = open(tmpfilename,"rb").read()

os.unlink(tmpfilename)

response.headers['Content-Type']='application/pdf'

return data

tmpfilenameという仮のファイル名でPDFを作成し、そのファイルから作成されたPDFを読み込み削除している点に注意してください。

Notice how we generate the PDF into a unique temporary file, tmpfilename, we read the generated PDF from the file, then we deleted the file.

ReportLab APIについての詳細はReportLabドキュメントを参照してください。ParagraphSpacerなどを利用できるReportLabのPlatypus APIはお勧めです。

For more information about the ReportLab API, refer to the ReportLab documentation. We strongly recommend using the Platypus API of ReportLab, such as Paragraph, Spacer, etc.