urlfetchでPOSTする方法
urlfetchにはurl, method, payload, headersなどが指定できるらしい。
def index_v1(request):
import urllib2
import urllib
from google.appengine.api import urlfetch
try:
logging.debug('start')
reqtype = request.META['REQUEST_METHOD']
if reqtype == 'POST':
logging.debug('POST')
dict = request.POST
logging.debug('%s', dict)
else:
logging.error('Method Not Allowed')
raise
dict_ret = {}
for k, v in dict.iteritems():
dict_ret[k.encode('utf-8')] = v.encode('utf-8')
logging.debug('dict_ret:%s', dict_ret)
data = urllib.urlencode(dict_ret)
contentURL = "http://%s/hoge/" % HTTP_NEW_HOST
logging.debug('%s', contentURL)
result = urlfetch.fetch(url=contentURL, method=urlfetch.POST, payload=data)
if result.status_code != 200:
logging.error(' response:%s',result.status_code )
raise
logging.debug('end')
except:
logging.error('Occur Exception%s', sys.exc_info())
raise
※heardersは今回は使わなかったが
header_auth = { 'Authorization' : 'Basic ' + base64.b64encode('%s:%s' % ('YourTwitterID', 'YourTwitterPass')) }
とか使い方があるそうです。
参考サイト:
Google App EngineでtwitterにPostする
Dateutil導入
ここからdateutilをダウンロード
フォルダの直下にdateutilというフォルダがある
dateutilのフォルダを利用するプロジェクトの直下へ移動。
'from dateutil'で利用できる。
参考サイト:
全体的に思うこと
GAEについて全体的な考察はココにまとめました。
Ubuntu9.10へインストール
Pythonのインストール方法はココです。
Eclipseのインストール方法はココです。
Google App Engine(GAE)のインストールは以下のとおり。
GAEをGoogleのOfficial Siteからダウンロードする。
どこでもいいから置いて、dev_appserver.pyを実行すると以下のエラー。。。
#python google_appengine/dev_appserver.py
Traceback (most recent call last):
File "google_appengine/dev_appserver.py", line 50, in <module>
execfile(script_path, globals())
File "/home/google/google_appengine/google/appengine/tools/dev_appserver_main.py", line 338, in <module>
sys.exit(main(sys.argv))
File "/home/google/google_appengine/google/appengine/tools/dev_appserver_main.py", line 297, in main
server = MakeRpcServer(option_dict)
File "/home/google/google_appengine/google/appengine/tools/dev_appserver_main.py", line 259, in MakeRpcServer
host_override=option_dict[ARG_ADMIN_CONSOLE_HOST])
File "/home/google/google_appengine/appcfg.py", line 114, in __init__
File "/home/google/google_appengine/appcfg.py", line 319, in _GetOpener
AttributeError: 'module' object has no attribute 'HTTPSHandler'
Pythonをインストール時、./counfigure実行後に/home/XXX/download/Python-2.5.5/Modules/Setupファイルを修正
修正前
#SSL=/usr/local/ssl
#_ssl _ssl.c \
# -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
# -L$(SSL)/lib -lssl -lcrypto
修正後
SSL=/usr
_ssl _ssl.c \
-DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
-L$(SSL)/lib -lssl -lcrypto
makeを実行するとさらにエラー発生
./Modules/_ssl.c: In function 'init_ssl':
./Modules/_ssl.c:693: 警告: implicit declaration of function 'SSL_load_error_strings'
./Modules/_ssl.c:694: 警告: implicit declaration of function 'SSLeay_add_ssl_algorithms'
make: *** [Modules/_ssl.o] エラー 1
libssl-devをインストールする
apt-get install libssl-dev
make, make installを再度実行すればOK!!
Eclipse起動設定
Package Explorerのprojectを右クリック
Debug As
Debug Configurations..
Pydev Google App Engine Run
Main -> Main Moduleは/home/XXXX/download/google_appengine/dev_appserver.py
Argument -> Program Argumentsは${project_loc}を設定する。
管理画面
ローカルのデータストアを見る
http://localhost:8080/_ah/admin/datastore
参考サイト:Google Official Site
JSON Parser
GAEでのJSON Parserはsimplejsonが簡単simplejson.load()を呼ぶだけだ
以下の通りサンプル書きます。
# -*- coding: utf-8 -*-
from appengine_django.models import BaseModel
import sys
from django.utils.simplejson import loads
class ParseJsonModel(BaseModel):
def parse_loads(self, content):
dict = loads(content)
return dict
def conntents_search_v1(request):
#get Json
content = get_provider_result_content(base_url)
#json parser
m = ParseJsonModel()
dict = m.parse_loads(content)
Email送信
GAEを使ってE-mail送信するサンプルコードは以下の通り。
mail.send_mail(sender="xxx.xxx@gmail.com",
to="%s<%s>" % (nickname, Addr),
subject="Hello! My name is %s" % nickname,
body="""
Hi, My name is %s
Googdbye see you later.
""" % nickname)
参考サイト:Official Site
別の方法
参考サイト:メール中毒なアナタに.., GAE Blog
日本語を送信する
日本語はutf-8で送りましょう。
ファイルはutf-8フォーマットで保存して、ファイルの先頭に以下を追加します。
# -*- coding: utf-8 -*-
そうすると、日本語をベタで記載できます。mail.EmailMessageを使うパターンとmail.send_mailを使うパターンとありますが
同じなので今回はmail.send_mailを使います。
senderはapp engineに登録されたメールアドレスを使ってください。
→google app engine管理画面→administration→developersでメールアドレスを登録。
from google.appengine.api import mail
class HogeModel(BaseModel):
def send_email_address_to_self(self, body, url):
body = "おはようございます。\n"
body += "%sにメールを送ります。\n" % str(self.name)
sender = "name@gmail.com"
subject = "朝ですよー"
to = "%s <%s>" % (self.dispname, self.email)
mail.send_mail(sender, to, subject, body)
local:8080 のデータベースを消す
dev_appserver.py --clear_datastore
EcliposeでPydevを使う
pydevの設定はココに記載
DebugConfigurationの設定
プロジェクトのエクスプローラーを右クリック
Debug as→Debug configurations..
Mainタブ:Projectに使用するプロジェクト名を選択
Mainタブ:Main ModuleはC:\Program Files\Google\google_appengine\dev_appserver.py
Argumants:${project_loc} --port=8080
ログを取得する
ログを一気に取得する。
appcfg.py request_logs appname/ filename.txt
一回取得したファイルに定期的にログを追加していく
appcfg.py --severity=0 --append request_logs appname/ filename.txt
GAEデータをCSVファイルでダウンロードする
参考サイト