Archive for 2月 11th, 2011

GAE/PythonでDjango1.2.5を使う方法

2月 11th, 2011 by admin

本日リリースのApp Engine SDK 1.4.2から、新しいバージョンのDjangoを利用できるようになっているので、早速使ってみた。

ソースコード

templateをインポートする前に、user_libraryでdjangoのバージョンを指定するだけでよい。

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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from google.appengine.ext import webapp
from google.appengine.dist import use_library
use_library('django', '1.2')
from google.appengine.ext.webapp import util, template

class MainHandler(webapp.RequestHandler):
    def get(self):
        params = {
          'message': u'テンプレートエンジンで表示しています。',
          'version': str(template.django.VERSION)
        }
        print_with_template(self, "index.html", params)

def print_with_template(self, view, params = {}):
    fpath = os.path.join(os.path.dirname(__file__), 'templates', view)
    html = template.render(fpath, params)
    self.response.out.write(html)

def main():
    application = webapp.WSGIApplication([('/', MainHandler)], debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()

テンプレートファイル。(/template/index.html)

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
<head>
    <title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></title>
</head>
<body>
{{message}}<br>
バージョン:{{version}}
</body>
</html>

実行結果

プレリリース版のリリースノートには1.2.4と記載されていたが、どうやら1.2.5が搭載されているようだ。

1
2
テンプレートエンジンで表示しています。
バージョン:(1, 2, 5, 'final', 0)

まとめ

pyファイルの先頭に2行付け加えるだけでDjangoのバージョンを0.96から1.2.5にアップデートできた。

参考記事
Google AppEngine で Django 1.1 を使う

GAE/Pでテンプレートエンジン使ってみた。

2月 11th, 2011 by admin

GAE/Python標準付属のテンプレートエンジンであるDjangoを使ってみました。

テンプレート

以下のファイルを、 /template/index.html に保存しました。{{message}}の部分が、渡された変数に置換されます。

1
2
3
4
5
6
7
8
9
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
<head>
<title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></title>
</head>
<body>
{{message}}
</body>
</html>

プログラム本体

プログラムはこんな感じになります。DjangoはGAEでは標準で組み込まれているので、importするだけで使えます。google.appengine.ext.webappからtemplateモジュールをインポートしましょう。

template.renderにテンプレートのPathと変数のディクショナリを渡すことで、テンプレートに変数を埋め込めます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util, template

class MainHandler(webapp.RequestHandler):
    def get(self):
        params = {'message':u'テンプレートエンジンで表示しています。'}
        fpath = os.path.join(os.path.dirname(__file__), 'templates','index.html')
        html = template.render(fpath, params)
        self.response.out.write(html)

def main():
    application = webapp.WSGIApplication([('/', MainHandler)], debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()

テンプレートを適用の処理を関数にまとめるとこうなります。get関数がシンプルになりました。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util, template

class MainHandler(webapp.RequestHandler):
    def get(self):
        params = {'message':u'テンプレートエンジンで表示しています。'}
        print_with_template(self, "index.html", params)

def print_with_template(self, view, params = {}):
    fpath = os.path.join(os.path.dirname(__file__), 'templates', view)
    html = template.render(fpath, params)
    self.response.out.write(html)

def main():
    application = webapp.WSGIApplication([('/', MainHandler)], debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()

まとめ

テンプレートエンジンを使うと、ロジックとデザインを分離でき見通しのよいプログラムになります。大規模なアプリ開発には必須のテクニックです。

GAE-Cron

2月 11th, 2011 by admin

GoogleAppEngine/Pythonを使って、CRONサービスを提供するサービスがあったので、参加してみた。

試しに1環境設置。ユーザ数の上限は50で、一人当たりの設定数の上限は5にしている。
http://gaecron-pystudy.appspot.com/

Cronの設定ができないサーバでWebサービスを提供する方の手助けになればなーと思ってます。

Twitterの検索機能はJS必須?

2月 11th, 2011 by admin

Twitterクライアントに、ハッシュタグ投稿機能を実装しました。

ハッシュタグを付けて発言しているときは、TLにハッシュタグの検索結果が表示されるのが自然ですよね?で、実装しようとしたんですが、無理でした。

Tweetの検索APIは認証不要です。認証不要のAPIは、1つのIPから1時間あたり一定(150?)回しかコールできません。GAEでは、同一IPを数多くのアプリが共有しているため、高頻度でAPIの利用制限に関するエラーが発生してしまいました。他のTwitterクライアントはどう処理しているのか気になりhootsuiteの通信を確認してみたのですが、通常のTLはhootsuite.comと通信していましたが、検索結果(ハッシュタグ)のTLはtwitter.comと直接通信していました。

JavaScriptでクライアントを実装すれば解決するのですが、本ブログの趣旨とずれてくるので、どうしようか悩んでいるところです。

まとめ

Twitterの検索機能は、API利用制限があるため、サーバサイドからは利用できない。検索結果を表示するにはJavaScriptなどクライアントサイドの開発が必要。

GAEのSDK 1.4.2リリース文

2月 11th, 2011 by admin

GoogleAppEnigneの新しいバージョンのSDKが公開された。正式版のリリース文はまだ公開されていないようだが、プレリリース版のリリース文があったので簡単に翻訳してみた。使ったことがない機能は変な訳になってしまっているかもしれない。また、Java向けのリリースは省略した。

原文
http://groups.google.com/group/google-appengine/msg/49354dd8552b60a6

Hey everyone, I just wanted to post that the prerelease SDKs for 1.4.2 are now available for early testing:

http://code.google.com/p/googleappengine/downloads/list

→1.4.2のベータ版リリースするよ。

Highlights of this release:
- Lots of XMPP improvements
- Prospective Search API (formerly known as Matcher API) now available to everyone
- Lots of improvements to task queues
- vacuum_indexes in Java SDK

注目ポイント
-XMPPの大幅な改善
-”Prospective Search API”(以前はMatcher APIと呼ばれていた)がすべてのユーザに提供されます
-task queueの大幅な改善
-Java SDK の vacuum_indexes

Full release notes are below. As a reminder, the backend portions of 1.4.2
have not been pushed yet, so they won’t likely work (though vacuum_indexes
for Java should be working). Download and enjoy!
まだ動かないかもしれないけどつかってみてね。(訳注: βリリース時のリリースノートの訳です、すでに正式版がリリースされているので、正しく動作するはずです。)

Python
————-

- The XMPP API was updated to include presence and allow subscriptions.

XMPP API に presence と allow subscriptionsを追加しました。

- The Task Queue now supports programmatic deleting of tasks.

http://code.google.com/p/googleappengine/issues/detail?id=2588

Task Queue: 作成したタスクをAPI経由で削除できるようになりました。

- The maximum rate per queue at which tasks are processed has been increased to 100 tasks per second.

1秒間に処理可能なタスクの数が100に増えました。

- The maximum number of concurrent requests for a single queue can be specified
in the application’s queue.yaml. This provides an additional easy-to-use form of rate limiting. The current number of running tasks is also displayed in
the Admin Console.

1つのQueue内の最大同時実行リクエスト数を指定できるようになりました。queue.yamlを使って簡単に設定できるようになりました。

- Metadata queries in the Datastore now support cursors.

DataStore: メタデータのクエリでカーソルをサポートしました。

- Admin Console logs viewer now displays time as YYYY-MM-DD HH:MM:SS.mmm.

Admin Consoleのログの時間表記がYYYY-MM-DD HH:MM:SS.mmm形式になりました。

- Added a warning when an admin tries to upload a queue.yaml where the number of new queues and the number of disabled queues exceeds 100.

新しいQueueの数と無効化したQueueの数が100を超えているqueue.yamlをデプロイしようとした際に警告するようになりました。

- Django 1.2.4 is available via use of the use_library() declaration. This version of Django has also been added to the Python SDK.

use_library()でDjango1.2.4を利用できるようになりました。

- The Prospective Search API (formerly named the Matcher API) is available for use by all applications. Applications will be limited to a maximum of 1000 subscriptions during the experimental release.

Prospective Search API がすべてのアプリケーションで利用できるようになりました。テストリリース期間中は購読数が1000件までに制限されます。

- Added builtin support for the deferred library.

deferredライブラリをビルトインサポートしました。

- If Python Precompilation fails, an error will be printed but the app will still be uploaded.

プリコンパイルに失敗した場合、エラーメッセージは表示されるが、デプロイ自体は実行されるようになりました。

- Added a -disable_sdk_update_check command line flag to the dev_appserver.

コマンドラインオプション -disable_sdk_update_check をdev_appserverに追加しました。

- The Mail API added KML and KMZ files as allowed attachments.

Mail API: KLMとLMZを添付ファイルとして許可しました。

- Fixed an issue where the datastore copy functionality did not work if writes were disabled on the source application.

datastore copy: コピー元のDataStoreに書き込み権限がない場合に動作しないという不具合を修正しました。

- Fixed an issue where mail from @appid.appspotmail.com did not work when sending mail to app admins.

@appid.appspotmail.comからアプリケーション管理者にメールが送信されない不具合を修正しました。

- Fixed an issue where the dev_appserver URLFetch API limit was 16MB. It is now 32 MB to match production.

dev_appserver上でのURLFetchの上限を16MBから32MBに変更しました。

- Fixed a zipimport issue on Windows which was not working due to path separators.
http://code.google.com/p/googleappengine/issues/detail?id=2086

zipimport: Windows上で発生していたPathの区切り文字に関する問題を修正しました。

- Fixed an issue where the SDK did not enforce the 100 task limit for the Task Queue.
http://code.google.com/p/googleappengine/issues/detail?id=3296

TaskQueueの上限100を正しく適用するようになりました。

- Fixed an issue where Query.order() was broken for properties with the ‘name’ attribute.
http://code.google.com/p/googleappengine/issues/detail?id=3693

Query.order() をname属性に対して使用した場合の問題を解消しました。

- Fixed an unhelpful error message in the Python namespace_manager.
http://code.google.com/p/googleappengine/issues/detail?id=3931

namespace_managerの、意味不明なエラーメッセージを修正しました。

Java
———
以下省略

まとめ

主にバグフィックスと、細かな機能追加が行われたようだ。サーバ側の実行環境を選択できないので(常に最新版が使われる)、開発版を最新のリリースにアップデートしない理由はない。特別な理由がない限り、速やかに、最新版をダウンロードしインストールしましょう。

本日の実装

2月 11th, 2011 by admin

今日はhttp://nisetwitter.appspot.com/を少し改良しました。

改良点

  • URL自動リンクの正規表現に穴があったので修正
  • Tweet内容をDBに保存する機能を実装

明日から3連休なので、気合入れなおしてがんばります!!