PythonからElixir Reportのレポートサーバーにアクセスするサンプルコード
Rev. | 035502cd03efae53b90c7321f6989d16751f2a72 |
---|---|
Size | 3,173 bytes |
Time | 2014-12-03 18:18:41 |
Author | hylom |
Log Message | fix: typo in server_app.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urlparse
import urllib
import urllib2
import cookielib
class ReportServer:
def __init__(self, user, password, host, port=7001):
self.user = user
self.password = password
self.host = host
self.port = port
self.scheme = 'http'
self.cookies = None
self.opener = None
def open_path(self, path, param=None, method='POST'):
"指定したパスにリクエストを投げる"
if self.opener == None:
self.login()
url = self.path_to_url(path)
if param == None:
resp = self.opener.open(url)
else:
if method == 'POST':
p = urllib.urlencode(param)
resp = self.opener.open(url, p)
else:
p = urllib.urlencode(param)
url_get = url + '?' + p
resp = self.opener.open(url_get)
return resp
def repository(self):
"リポジトリ一覧を取得する"
path = '/repository?mode=xml'
resp = self.open_path(path)
if resp.code == 200:
return resp.read()
else:
return None
def data(self, path, params={}):
"データソースからデータをXML形式で取得する"
param = params.copy()
param["mime-type"] = "text/xml"
resp = self.open_path(path, param)
if resp.code == 200:
return resp.read()
else:
return None
def pdf(self, path, params={}):
"レポートをPDF形式で取得する"
param = params.copy()
param["mime-type"] = "application/pdf"
param["elx.disposition"] = "inline"
resp = self.open_path(path, param, 'GET')
if resp.code == 200:
return resp.read()
else:
return None
def login(self):
"ログイン処理を行う"
# 初めにCookieを取得する
if self.opener == None:
path = '/'
url = self.path_to_url(path)
req = urllib2.Request(url)
resp = urllib2.urlopen(req)
cookies = cookielib.CookieJar()
cookies.extract_cookies(resp, req)
self.cookies = cookies
# 取得したCookieを使用する
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookies))
# ログインリクエストを投げる
path = '/login.html'
param = {
"username": self.user,
"password": self.password
}
resp = self.open_path(path, param)
return resp.code
def logout(self):
"ログアウト処理を行う"
if self.opener == None:
return 200
path = '/logout.html'
resp = self.open_path(path)
return resp.code
def path_to_url(self, path):
"パスをURLに変換する"
t = (self.scheme,
'{0}:{1}'.format(self.host, self.port),
path,
'',
'',
'')
return urlparse.urlunparse(t)