今回の肝は、自作した URLOpener というクラスである。
こいつは setCookie と open という二つのメソッドを持つ。
setCookie で「ログインページのURL」と「ログインID」と「パスワード」をセットすると URLOpener のインスタンスはログイン状態になり、open でログインが必要なページを取得することができる。
helloworld.py
# -*- coding: utf-8 -*-
import cgi
import os
import urllib
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
#
# URLオープナー
#
class URLOpener(object):
def setCookie(self, login_url, login_id = None, password = None):
# パラメータはサイトに合わせて編集が必要。
params = urllib.urlencode({
"login_id" : login_id,
"password" : password
})
f = urlfetch.fetch(
login_url,
payload=params,
method=urlfetch.POST,
headers={}
)
self.cookie = f.headers['Set-Cookie'].replace("path=/,", "").replace("path=/", "")
def open(self, url, charset = "utf-8"):
f = urlfetch.fetch(
url,
payload = "",
method=urlfetch.POST,
headers={"Cookie" : self.cookie,
"content-type" : "text/html"}
)
return unicode(f.content, charset, "ignore")
#
# メインハンドラ
#
class MainHandler(webapp.RequestHandler):
def get(self):
LOGIN_URL = 'http://ログインページのURL'
URL = 'http://ログインが必要なページのURL'
LOGIN_ID = "hoge"
PASSWORD = "0123456789"
CHARSET = "shift_jis"
urlopener = URLOpener()
urlopener.setCookie(LOGIN_URL, LOGIN_ID, PASSWORD)
content = urlopener.open(URL, CHARSET)
template_values = {"content" : content}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
application = webapp.WSGIApplication([('/', MainHandler)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
index.html
<html>
<head>
<meta content='text/html; charset=UTF-8' http-equiv='Content-Type'/>
</head>
<body>
<h2>読み込んだページ</h2>
<blockquote>{{ content }}</blockquote>
</body>
</html>
これを使えば、「ログインは必要ないけど、一度アクセスしてCookieを取得しないとページを見られない」というサイトにも対応できる。たまに見るよね、そういうサイト。
ここはひとつポチっとよろしく。
プログラミング Google App Engine
posted with amazlet at 11.06.03
Dan Sanderson
オライリージャパン
売り上げランキング: 40082
オライリージャパン
売り上げランキング: 40082
【GAE for Pythonの最新記事】
- GAE/Pでmemcacheを利用してデ..
- PythonでJST日付をUTC(GMT..
- BeautifulSoupオブジェクトを..
- GAE/Pで詳細なエラーログ(トレース情..
- Pythonでオブジェクトのlistをソ..
- GAE/PでAspyctを使ってAOP(..
- GAE/Pでカスタムタグを作って日付をU..
- GAE/PでBeautifulSoupを..
- GAE/Pでファイルアップロード。
- GAE/Pでリクエストデータの扱い方。
- GAE/PでCRONを使ったスケジュール..
- GAE/PでModelをJSON変換する..
- GAE/P向け統合開発環境 Eclips..
- GAE/PとjQueryでJSONデータ..
- GAE+Pythonの標準モジュールだけ..
- GAE+Pythonでテンプレートの共通..
- GAEアプリをアップロードする方法。
- GAE+Pythonでテンプレートエンジ..
- GAE+Pythonでデータストアを操作..
- webappフレームワークを使ったフォー..
