Last active
December 23, 2018 22:04
-
-
Save acokikoy/79867001723a71c8c52cbd2e2b9d2894 to your computer and use it in GitHub Desktop.
Pythonの勉強した履歴をログに残す。ログデータはDataAPI経由でMTに保存する。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# mt.py | |
import json | |
import requests | |
class DataAPI: | |
def __init__(self): | |
self.base_url = '' | |
self.site_id = 1 | |
self.contenttype_id = 1 | |
self.username = '' | |
self.password = '' | |
self.client_id = '' | |
self.access_token = '' | |
# コンテンツデータの一覧を取得(GET) | |
# GET /v4/sites/:site_id/contentTypes/:content_type_id/data?limit=N | |
def list_contents(self, limit=1): | |
# url_list_contents = 'http://YourDomain/MT_Path/mt-data-api.cgi/v4/sites/1/contentTypes/2/data?limit=1' | |
url_list_contents = self.base_url + '/sites/' + str(self.site_id) + '/contentTypes/' + str(self.contenttype_id) + '/data?limit=' + str(limit) | |
# レスポンス取得 | |
r = requests.get(url_list_contents) | |
return r.status_code, r.json() | |
# コンテンツデータ1件取得(GET) | |
# GET /v4/sites/:site_id/contentTypes/:content_type_id/data/:content_id | |
def get_content(self, contentdata_id): | |
# url_get_content = 'http://YourDomain/MT_Path/mt-data-api.cgi/v4/sites/1/contentTypes/2/data/XX' | |
url_get_content = self.base_url + '/sites/' + str(self.site_id) + '/contentTypes/' + str(self.contenttype_id) + '/data/' + str(contentdata_id) | |
headers = {} | |
if self.access_token: | |
auth = 'MTAuth accessToken=' + self.access_token | |
headers = {'X-MT-Authorization': auth } | |
# レスポンス取得 | |
r = requests.get(url_get_content, headers=headers) | |
return r.status_code, r.json() | |
# 認証(POST) | |
# POST /v4/authentication | |
def authenticate(self): | |
# url_authentication = 'http://YourDomain/MT_Path/mt-data-api.cgi/v4/authentication' | |
url_authentication = self.base_url + '/authentication' | |
headers = {'Content-Type': 'application/x-www-form-urlencoded'} | |
params = { | |
'username': self.username, | |
'password': self.password, | |
'remenber': 1, | |
'clientId': self.client_id | |
} | |
# レスポンス取得 | |
r = requests.post(url_authentication, params, headers=headers) | |
self.access_token = r.json()['accessToken'] | |
return r.status_code, r.json() | |
# コンテンツデータ投稿(POST) | |
# POST /v4/sites/:site_id/contentTypes/:content_type_id/data | |
def create_content(self, content_data): | |
''' | |
# url_create_content = 'http://YourDomain/MT_Path/mt-data-api.cgi/v4/sites/1/contentTypes/2/data' | |
Args: | |
content_data(dict): { | |
'data': [ | |
{'data': '2018-12-17 23:00:00', 'id': '7', 'label': 'log_id'}, | |
{'data': '383問中、333問修了', 'id': '8', 'label': 'progress'}, | |
{'data': 'テスト投稿', 'id': '9', 'label': 'body'}], | |
'label': '2018-12-17 23:00:00', | |
'status': 'Publish' | |
} | |
''' | |
url_create_content = self.base_url + '/sites/' + str(self.site_id) + '/contentTypes/' + str(self.contenttype_id) + '/data' | |
auth = 'MTAuth accessToken=' + self.access_token | |
headers = {'Content-Type': 'application/x-www-form-urlencoded', 'X-MT-Authorization': auth } | |
r = requests.post(url_create_content, headers=headers, data='content_data='+json.dumps(content_data)) | |
return r.status_code, r.json() | |
# データ整形 - コンテンツデータ1個分 | |
def fitem(item): | |
''' | |
コンテンツデータ1件分から使うデータだけ取り出し、 | |
扱い易い形に整形して返す | |
''' | |
content = {} | |
content['id'] = item['id'] | |
content['author_name'] = item['author']['displayName'] | |
content['basename'] = item['basename'] | |
content['blog_id'] = item['blog']['id'] | |
content['createdDate'] = item['createdDate'] | |
content['modifiedDate'] = item['modifiedDate'] | |
content['date'] = item['date'] | |
content['label'] = item['label'] | |
content['status'] = item['status'] | |
content['updatable'] = item['updatable'] | |
# contentdata | |
for cd in item['data']: | |
label = cd['label'] | |
content[label] = cd['data'] | |
return content | |
# データ整形 - コンテンツ一覧 | |
def fitems(r_json): | |
''' | |
get_contentsのレスポンス(json)を、各コンテンツデータが扱い易い形に整形して返す | |
Args: | |
r_json (dict): list_contents取得値 | |
Returns: | |
total_items (int): 総データ数 | |
cnt_items: 今回取得したデータ数 | |
contents[id] (list): コンテンツデータ詳細 | |
''' | |
# # レスポンスの結果を解析する | |
total_items = r_json['totalResults'] # 全コンテンツ数 | |
items = r_json['items'] #コンテンツデータ詳細 | |
cnt_items = len(items) # 今回取得したコンテンツ数 | |
# コンテンツデータ値を扱いやすい形に再編 | |
contents = [] | |
for item in items: | |
contents.append(fitem(item)) | |
return (total_items, cnt_items, contents) | |
if __name__ == '__main__': | |
api = mt.DataAPI(base_url, site_id, contenttype_id) | |
api.base_url = 'http://YourDomain/MT_Path/mt-data-api.cgi/v4' | |
api.site_id = 1 | |
api.contenttype_id = 2 | |
api.username = 'MTユーザ名' | |
api.password = 'Webサービスパスワード' | |
api.client_id = 'my_pylog' #なんでもいい | |
# r_status_code, r_json = api.list_contents() | |
# r_status_code, r_json = api.get_content(2) | |
# r_status_code, r_json = api.authenticate() | |
api.authenticate() | |
r_status_code, r_json = api.create_content() | |
if r_status_code == 200: | |
print('OK:', r_status_code) | |
else: | |
print('NG:', r_status_code) | |
print(api.access_token) | |
print(r_json) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# my_pylog.py | |
# Pythonの勉強履歴。ログデータはDataAPI経由でMTに保存する。 | |
from datetime import datetime | |
import re | |
import mt | |
def show_log(log:dict): | |
'''取得したログを整形して表示''' | |
log_date = log['log_id'] | |
body = log['body'] | |
progress = log['progress'] | |
if progress: | |
progress = '[[' + progress + ']], ' | |
print(f'{log_date} -- {progress}{body}') | |
# DataAPIの準備 | |
api = mt.DataAPI() | |
api.base_url = 'http://YourDomain/MT_Path/mt-data-api.cgi/v4' | |
api.site_id = 1 #対象サイトのID | |
api.contenttype_id = 2 #対象コンテンツタイプのID | |
api.username = 'MTユーザ名' | |
api.password = 'Webサービスパスワード' | |
api.client_id = 'my_pylog' #なんでもいい | |
# DataAPI: 直前のログ1件を取得 | |
r_status_code, r_json = api.list_contents(limit=1) | |
if r_status_code == 200: | |
# 取得した直前のログを、整形して表示 | |
content = mt.fitems(r_json)[2][0] | |
print('last log:') | |
show_log(content) | |
else: | |
print('NG:', r_status_code) | |
# 新しいログを入力 | |
# 書式: [[progress]], body ※[[progress]], は省略可能 | |
i = input("input new log:\n ") | |
i.strip() | |
m = re.match('(\[\[(.+?)\]\],\s*)*(.+)$', i) | |
body = m.group(3) | |
progress = m.group(2) | |
if progress == None: | |
progress = '' | |
#現在日時を取得してstr_nowにセット | |
dt = datetime.now() | |
str_now = datetime.strftime(dt, '%Y-%m-%d %H:%M:%S') | |
# DataAPI: 投稿 | |
content_data = { | |
'data': [ | |
{'data': str_now, 'id': '7', 'label': 'log_id'}, | |
{'data': progress, 'id': '8', 'label': 'progress'}, | |
{'data': body, 'id': '9', 'label': 'body'}], | |
'label': str_now, | |
'status': 'Publish' | |
} | |
api.authenticate() | |
r_status_code, r_json = api.create_content(content_data) | |
# 結果表示: レスポンスを整形して表示する | |
if r_status_code == 200: | |
print('logged:') | |
show_log(mt.fitem(r_json)) | |
else: | |
print('NG:', r_status_code) | |
# 'done'と表示しておしまい | |
print('done') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment