Showing posts with label japanese. Show all posts
Showing posts with label japanese. Show all posts

November 2, 2009

pkg_resources の warning を抑制する

sitecustomize.py を site-packages 内に下記の内容で作成する

import warnings
warnings.filterwarnings('ignore',
  message=r'Module .*? is being added to sys\.path', append=True)

ここに書いてありました:
http://lucumr.pocoo.org/2008/2/19/sick-of-pkg-resources-warnings

August 31, 2009

Kay で pyjamas を使う

日本語の情報もできたのでちょっと変わり種をやります。

Python 版 GWT である pyjamas を Kay と組み合わせてみました.. と言っても jsonrpc の簡単なサンプルを動かしただけですが。

Pyjamas をインストールした場所を ${PYJAMAS_HOME} と、プロジェクトのディレクトリを ${PROJECT_DIR} として進めましょう。

${PYJAMAS_HOME}/examples/jsonrpc をいじって使います。public 以下は JSONRPCExample.html だけ必要みたい。


$ tree kay-pyjamas-sample
kay-pyjamas-sample
|-- JSONRPCExample.py
`-- public
`-- JSONRPCExample.html

1 directory, 2 files


JSONRPCExample.py を下記のように少しいじります。

import pyjd # dummy in pyjs

from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.TextArea import TextArea
from pyjamas.ui.Label import Label
from pyjamas.ui.Button import Button
from pyjamas.ui.HTML import HTML
from pyjamas.ui.VerticalPanel import VerticalPanel
from pyjamas.ui.HorizontalPanel import HorizontalPanel
from pyjamas.ui.ListBox import ListBox
from pyjamas.JSONService import JSONProxy

class JSONRPCExample:
def onModuleLoad(self):
self.TEXT_WAITING = "Waiting for response..."
self.TEXT_ERROR = "Server Error"
self.METHOD_ECHO = "Echo"
self.METHOD_REVERSE = "Reverse"
self.METHOD_UPPERCASE = "UPPERCASE"
self.METHOD_LOWERCASE = "lowercase"
self.methods = [self.METHOD_ECHO, self.METHOD_REVERSE, self.METHOD_UPPERCASE, self.METHOD_LOWERCASE]

self.remote_py = EchoServicePython()

self.status=Label()
self.text_area = TextArea()
self.text_area.setText("""{'Test'} [\"String\"]
\tTest Tab
Test Newline\n
after newline
""" + r"""Literal String:
{'Test'} [\"String\"]
""")
self.text_area.setCharacterWidth(80)
self.text_area.setVisibleLines(8)

self.method_list = ListBox()
self.method_list.setName("hello")
self.method_list.setVisibleItemCount(1)
for method in self.methods:
self.method_list.addItem(method)
self.method_list.setSelectedIndex(0)

method_panel = HorizontalPanel()
method_panel.add(HTML("Remote string method to call: "))
method_panel.add(self.method_list)
method_panel.setSpacing(8)

self.button_py = Button("Send to Python Service", self)

buttons = HorizontalPanel()
buttons.add(self.button_py)
buttons.setSpacing(8)

info = """

JSON-RPC Example


This example demonstrates the calling of server services with
JSON-RPC.


Enter some text below, and press a button to send the text
to an Echo service on your server. An echo service simply sends the exact same text back that it receives.

"""

panel = VerticalPanel()
panel.add(HTML(info))
panel.add(self.text_area)
panel.add(method_panel)
panel.add(buttons)
panel.add(self.status)

RootPanel().add(panel)

def onClick(self, sender):
self.status.setText(self.TEXT_WAITING)
method = self.methods[self.method_list.getSelectedIndex()]
text = self.text_area.getText()
id = -1
if method == self.METHOD_ECHO:
id = self.remote_py.echo(text, self)
elif method == self.METHOD_REVERSE:
id = self.remote_py.reverse(text, self)
elif method == self.METHOD_UPPERCASE:
id = self.remote_py.uppercase(text, self)
elif method == self.METHOD_LOWERCASE:
id = self.remote_py.lowercase(text, self)
if id<0:
self.status.setText(self.TEXT_ERROR)

def onRemoteResponse(self, response, request_info):
self.status.setText(response)

def onRemoteError(self, code, message, request_info):
self.status.setText("Server Error or Invalid Response: ERROR %d - %s" %
(code, message))


class EchoServicePython(JSONProxy):
def __init__(self):
JSONProxy.__init__(self, "/json", ["echo", "reverse", "uppercase", "lowercase"])

if __name__ == '__main__':
# for pyjd, set up a web server and load the HTML from there:
# this convinces the browser engine that the AJAX will be loaded
# from the same URI base as the URL, it's all a bit messy...
pyjd.setup("http://127.0.0.1/examples/jsonrpc/public/JSONRPCExample.html")
app = JSONRPCExample()
app.onModuleLoad()
pyjd.run()


そしたらそのディレクトリに入ってコンパイルします。今回はターゲットを直
接 ${PROJECT_DIR}/media にしてしまいます。


$ cd kay-pyjamas-sample
$ ${PYJAMAS_HOME}/bin/pyjsbuild -o ${PROJECT_DIR}/media JSONRPCExample.py


成功すると ${PROJECT_DIR}/media/JSONRPCExample.html が出来ます。
http://localhost:8080/media/JSONRPCExample.html で画面が出ていればまあ成功です。

サーバーサイドは下記の通りにします。myapp はアプリケーション名に読み換
えてくださいね。

${PROJECT_DIR}/myapp/urls.py

# -*- coding: utf-8 -*-
# myapp.urls


from werkzeug.routing import (
Map, Rule, Submount,
EndpointPrefix, RuleTemplate,
)
import myapp.views

def make_rules():
return [
EndpointPrefix('myapp/', [
Rule('/', endpoint='index'),
Rule('/json', endpoint='json_rpc'),
]),
]

all_views = {
'myapp/index': myapp.views.index,
'myapp/json_rpc': myapp.views.json_rpc,
}


最後に view です。

${PROJECT_DIR}/myapp/views.py

# -*- coding: utf-8 -*-
# myapp.views
# ... 省略

import simplejson

# ... 省略

def json_uppercase(args):
return [args[0].upper()]

def json_echo(args):
return [args[0]]

def json_reverse(args):
return [args[0][::-1]]

def json_lowercase(args):
return [args[0].lower()]

def json_rpc(request):
if request.method:
args = simplejson.loads(request.data)
method_name = 'json_%s' % args[u"method"]
json_func = globals().get(method_name)
json_params = args[u"params"]
json_method_id = args[u"id"]
result = json_func(json_params)
args.pop(u"method")
args["result"] = result[0]
args["error"] = None
return Response(simplejson.dumps(args), content_type="application/json")
else:
return Response('Error')



適当な作りですが、まあこれで動きます。興味があれば色々工夫してみてくだ
さい。

今日はここでおしまいです。

August 4, 2009

Kay framework を使ってみる

Kay framework を 7/7 にリリースしたわけですが、日本語での情報が無いので少しずつ書いていくことにしようと思います。

始め方


必要なものは下記の通りです。

  • Python-2.5
  • App Engine SDK Python
  • Kay framework


macports を使って python25 を入れた場合は、他に下記もインストールしましょう。

  • py25-hashlib
  • py25-socket-ssl
  • py25-pil
  • py25-ipython


Kay のリリース版を使う場合は、下記のダウンロードページから tar ball を落として使います。リポジトリを追いかける場合は、mercurial で clone してください。

ダウンロードページ: http://code.google.com/p/kay-framework/downloads/list

clone するには:

$ hg clone https://kay-framework.googlecode.com/hg/ kay


プロジェクトを始める


kay の manage.py スクリプトでプロジェクトディレクトリを作る事ができます。

$ python kay/manage.py startproject myproject
$ tree myproject
myproject
|-- app.yaml
|-- kay -> /Users/tmatsuo/work/tmp/kay/kay
|-- manage.py -> /Users/tmatsuo/work/tmp/kay/manage.py
|-- settings.py
`-- urls.py

1 directory, 4 files


シンボリックリンクをサポートしているプラットフォームでは kay ディレクトリと manage.py へのシンボリックリンクが作成されます。後で kay の場所を動かすときっと動かなくなるのですが、そんな時はリンクを張り直してください。

アプリケーションを作る


出来たばかりの myproject ディレクトリに cd して、早速アプリケーションを作りましょう。

$ cd myproject
$ python manage.py startapp myapp
$ tree myapp
myapp
|-- __init__.py
|-- models.py
|-- templates
| `-- index.html
|-- urls.py
`-- views.py

1 directory, 5 files


こうして作成した myapp を動作させるにはもうひと手間必要です。settings.py の INSTALLED_APPS に登録します。必要なら APP_MOUNT_POINTS も登録します。下記の例では、アプリケーションをルート URL にマウントする例です。APP_MOUNT_POINTS を設定しない場合は、/myapp というようにアプリケーション名 URL にマウントされます。

settings.py

#$/usr/bin/python
#..
#..

INSTALLED_APPS = (
'kay.sessions',
'myapp',
)

APP_MOUNT_POINTS = {
'myapp': '/',
}


見れば分かると思いますが、INSTALLED_APPS はタプルで、APP_MOUNT_POINTS は dict になっています。

アプリケーションを動かす


作ったアプリケーションを動かしてみましょう。下記のコマンドで開発サーバが起動する筈です。

$ python manage.py runserver
INFO 2009-08-04 05:48:21,339 appengine_rpc.py:157] Server: appengine.google.com
...
...
INFO 2009-08-04 05:48:21,448 dev_appserver_main.py:465] Running application myproject on port 8080: http://localhost:8080

この状態で http://localhost:8080/ にアクセスすると、「Hello」又は「こんにちは」と表示される筈です。

GAE にアップロードする


GAE にアップロードするには、対象の appid を app.yaml の application に設定してから、下記のコマンドを使用します。

$ python manage.py appcfg update


成功すると、http://your-appid.appspot.com/ でアクセスできるようになります。

今日はここまでにしますね。けっこう簡単に始められる事がお分かりいただけたでしょうか。次回はモデル定義とか、フォームの自動生成などについてお話しする予定です。

当分このシリーズを続けるつもりなので、取り上げて欲しいトピックなどがあればコメントください。

May 14, 2009

Google App Engine で Werkzeug のデバッガを使う

Werkzeug という Python Web Framework があります。Werkzeug のデバッガはなかなかすぐれもので Web アプリでエラーが出るとインライン console が使えたりします。

このデバッガを GAE の dev server で使う方法を作者の方が書いているのですが、この通りやるとインライン console が使えなかったりします。

ちょっと調べてみたら意外と簡単に使えました。GAE の dev server だとリクエスト毎に DebuggedApplication のインスタンスが作り直されてしまうので、これを module global のシングルトンにしてやればオッケイでした。



_debugged_app = None
app = ... build your wsgi app ...

def main():
# Only run the debugger in development.
import os, sys
if 'SERVER_SOFTWARE' in os.environ and os.environ['SERVER_SOFTWARE'].startswith('Dev'):
# use our debug.utils with Jinja2 templates
import debug.utils
sys.modules['werkzeug.debug.utils'] = debug.utils

# don't use inspect.getsourcefile because the imp module is empty
import inspect
inspect.getsourcefile = inspect.getfile

# wrap the application
from werkzeug import DebuggedApplication
global _debugged_app
if _debugged_app is None:
_debugged_app = app = DebuggedApplication(app, evalex=True)
else:
app = _debugged_app

October 11, 2008

GeoPt Property 用のカスタムウィジェット

こないだ Maps API hack-a-thon Tokyo に参加してきました。その時作ったのが Google App Engine の GeoPt Property をとても扱いやすくするためのユーティリティクラスです。

この記事では、そのクラスを使って geopoint データを datastore に保存するサンプルコードをお見せします。始めるまえに、こちらのdjangoforms に関する記事を読んでおくとコードがすぐ理解できるでしょう。

まずはこの記事用のディレクトリを作ります。そして拙作の my_geopt.py をその中にコピーし、さらに新しく3つのファイルを作ります。app.yaml, main.py と index.html です。

ファイルを作成したら、開発用サーバーを機動して localhost にアクセスします。すると Google Map をクリックするだけで特定の GeoPt が指定できる事がわかります。

また ライブデモもあります(少し複雑になってますが、基本は同じです)。

Happy coding :-)

app.yaml
application: geotest
version: 1
runtime: python
api_version: 1

handlers:
- url: /.*
  script: main.py


main.py
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import os
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext.db import djangoforms
import my_geopt

class Place(db.Model):
  name = db.StringProperty()
  description = db.StringProperty()
  geopoint = db.GeoPtProperty()
  date = db.DateTimeProperty(auto_now=True)

class PlaceForm(djangoforms.ModelForm):
  class Meta:
    model = Place

class MainPage(webapp.RequestHandler):
  def post(self):
    data = PlaceForm(data=self.request.POST)
    if data.is_valid():
      # Save the data, and redirect to the view page
      entity = data.save(commit=False)
      entity.put()
      self.redirect('/')
    else:
      # Reprint the form
      contents = {'form': data}
      path = os.path.join(os.path.dirname(__file__), 'index.html')
      self.response.out.write(template.render(path, contents))
  def get(self):
    contents = {'form': PlaceForm()}
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, contents))

application = webapp.WSGIApplication(
  [('/', MainPage),],
  debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()


index.html (Please replace 2 YOURAPIKEYs with your Maps API Key)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>GeoPtWidgets Example</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=YOURAPIKEY"
type="text/javascript"></script>
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=YOURAPIKEY"
type="text/javascript"></script>
<script src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js"
type="text/javascript"></script>
<style type="text/css">
@import url("http://www.google.com/uds/css/gsearch.css");
@import url("http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css");
</style>
</head>

<body onunload="GUnload()">
<h1>GeoPtWidgets Example</h1>
<form method="post" action="/">
{{ form.as_p }}
<input type="submit" value="register"/>
</form>
</body> </html>

June 3, 2008

App Engine の SMS verification

I/O で一般公開された(はずの) Google App Engine ですが、日本のみなさんは SMS の verification がなかなかできずに困っているのではないでしょうか。

Verify のページでは「We are currently experiencing issues with DoCoMo and KDDI phones.」と表示されており、どうやら Docomo と KDDI では SMS が受け取れないようですし、私の持っている softbank 携帯でも SMS が受け取れませんでした。ちなみに嫁の softbank 携帯だと受け取る亊が出来ました。

嫁は昔から softbank (Jフォン時代から)ひとすじで、私は昔 Docomo だったのを MNP で softbank に乗り換えたクチですが、それが関係してるのかな?

ちなみに softbank 携帯に SMS を送った時は、Country and Carrier には「Other」を選び、Mobile Numberに「+81 90xxxxxxxx」(xは番号です)というように国番号「+81」の次に、始めの「0」は無しで電話番号を入力すれば送る亊ができました。参考になればと思い書いておきます。

しかし、そろそろ Developper Day が開催するので、それまでにはなるべく多くの人が App Engine を使えるようになると良いのですが...

May 30, 2008

Google I/O が終わりました

終わってしまいました。 Guido のセッションがものすごく High Level だったのが意外でした。 High Level というのは 「 core では無い」という意味ですが。

全体的な感想ですが、今回は主な興味の対象である App Engine のセッションを中心に見てきまして、 App Engine についていろいろあやふやだった点がはっきりしてきました。とても有意義なセッション達でした。

ところで今回同行した a2c さんが面白い亊を言っていました。興味の無いテクノロジーのセッションを聞くのも意外と楽しい...と。そういうものかもしれません。発見する亊はそもそも楽しいですからね。

そうそう。以前のポストで書いた App Engine 用のソフトウェアがだいたい完成しましたので、URL を書いときます。
http://internovel.appspot.com/

まだ説明とか全然足りないので、多分正体や使い方も皆目分からないと思います。それらは日本に帰ってからおいおい書くつもりです。

今日はとりあえずこんなところで。

May 25, 2008

Google I/O前夜

Google I/O が近づいて来ましたので準備をはじめました。まずはプログラムのスケジュールをダウンロードして印刷しておきます。これを飛行機の中で眺めておけば、参加したいプログラムをある程度しぼれるでしょう。荷物は少なめです。いつも使っているトラベルバッグに収まりそう。

Google I/O 自体は 5/28, 5/29 の2日間なのですが、私自身は 5/27 のうちに San Francisco に到着予定です。この日の夕食をどうするか悩んでいたのですが、何人かの Googler がホストしてくれる亊になったので気が楽になりました :-)

私個人として、今一番注目しているテクノロジーは App Engine です。Google のインフラを使って Web アプリが動かせるのですから、冗長化の面でもスケーラビリティの面でも大きなメリットがあります。それに python だし。 python は私のお気に入りです。

そうそう。まだ内容は内緒ですが、 App Engine で動く Web アプリを作っている最中なのです。もう少しでプロトタイプが完成しそうなので、飛行機の中で書き終えられたら良いなと思っています。とりあえず動くものが完成したら App Engine Group にポストしてみるつもりです。(5/26追記) グループにポストするよりも Applications Gallery に登録する方が良さそうですね。