apilecture for 2014/02/22 at shannonlab

115
Django×API ででで ででで

Upload: yutaka-kobayshi

Post on 28-May-2015

327 views

Category:

Technology


7 download

DESCRIPTION

lecture resume for 2/22

TRANSCRIPT

Page 1: Apilecture for 2014/02/22 at shannonlab

Django×API で遊ぶ

小林泰

Page 2: Apilecture for 2014/02/22 at shannonlab

タイムライン0. 自己紹介1 . API とは?2 . API の(具体的)使い方例3 .データ形式4. Python のターミナル上で動かしてみる5. Django にのせてみる

Page 3: Apilecture for 2014/02/22 at shannonlab

1 . API とは?

Page 4: Apilecture for 2014/02/22 at shannonlab

API の定義

Application programming Interface

直訳:アプリケーションをプログラムする時の接続

Page 5: Apilecture for 2014/02/22 at shannonlab

API がなければHello world! と表示されるためのプログラムでも

①Hello world という文字のドットデータを作る② そのデータをバッファに格納するプログラムを作る③ 格納されたデータが正しく出力されるようにグラフィックカー  ドに対するプログラムも作る

めんどくさい。

Page 6: Apilecture for 2014/02/22 at shannonlab

WEB API

今回扱うのは WEB API と呼ばれるもの

「 Http リクエストを送ったら、データを返してくれるようなもの」

Page 7: Apilecture for 2014/02/22 at shannonlab

ためしに。。。。今日使う API をブラウザーで叩いてみよう参照ホームページ  http://zip.cgis.biz

Page 8: Apilecture for 2014/02/22 at shannonlab

How to Use

Page 10: Apilecture for 2014/02/22 at shannonlab

TRY 1① ブラウザーを開く

Page 12: Apilecture for 2014/02/22 at shannonlab

TRY3

結果が返される

Page 13: Apilecture for 2014/02/22 at shannonlab

結果 xml 形式<ZIP_result><result name="ZipSearchXML"/><result version="1.01"/><result request_url="http%3A%2F%2Fzip.cgis.biz%2Fxml%2Fzip.php%3Fzn%3D1690075"/><result request_zip_num="1690075"/><result request_zip_version="none"/><result result_code="1"/><result result_zip_num="1690075"/><result result_zip_version="0"/><result result_values_count="1"/><ADDRESS_value><value state_kana=" トウキョウト "/><value city_kana=" シンジュクク "/><value address_kana=" タカダノババ "/><value company_kana="none"/><value state=" 東京都 "/><value city=" 新宿区 "/><value address=" 高田馬場 "/><value company="none"/></ADDRESS_value></ZIP_result>

Page 14: Apilecture for 2014/02/22 at shannonlab

csv の方もやってみようhttp://zip.cgis.biz/csv/zip.php?zn= 郵便番号

Page 15: Apilecture for 2014/02/22 at shannonlab

結果 csv 形式"ZipSearchXML","1.01","http://zip.cgis.biz/csv/zip.php?zn=1690075","1690075","none","1","1690075","0","1"" トウキョウト "," シンジュクク "," タカダノババ ","none"," 東京都 "," 新宿区 "," 高田馬場 ","none"

Page 17: Apilecture for 2014/02/22 at shannonlab

2 . Examples of APIs

Page 18: Apilecture for 2014/02/22 at shannonlab

WEB API 例Facebook api

Page 19: Apilecture for 2014/02/22 at shannonlab

WEB API 例Twitter api

Page 20: Apilecture for 2014/02/22 at shannonlab

twitterAPI を使っている例

Page 21: Apilecture for 2014/02/22 at shannonlab

3 .得られるデータ

Page 22: Apilecture for 2014/02/22 at shannonlab

得られるデータxmlcsvjsonExel シート

等が得られる

Page 23: Apilecture for 2014/02/22 at shannonlab

xml

Extensible Markup Languageタグを用いて論理構造などを表現

< 要素名 属性 =" 値 "> 内容 </ 要素名 >

Page 24: Apilecture for 2014/02/22 at shannonlab

Xml 例:さっきのやつ<ZIP_result><result name="ZipSearchXML"/><result version="1.01"/><result request_url="http%3A%2F%2Fzip.cgis.biz%2Fxml%2Fzip.php%3Fzn%3D1690075"/><result request_zip_num="1690075"/><result request_zip_version="none"/><result result_code="1"/><result result_zip_num="1690075"/><result result_zip_version="0"/><result result_values_count="1"/><ADDRESS_value><value state_kana="トウキョウト"/><value city_kana="シンジュクク"/><value address_kana="タカダノババ"/><value company_kana="none"/><value state="東京都"/><value city="新宿区"/><value address="高田馬場"/><value company="none"/></ADDRESS_value></ZIP_result>

Page 25: Apilecture for 2014/02/22 at shannonlab

csv

Comma-separated values字義通り、カンマで値を区切る形式

例:さっきのやつ" トウキョウト "," シンジュクク "," タカダノババ ","none"," 東京都 "," 新宿区 "," 高田馬場 "

Page 26: Apilecture for 2014/02/22 at shannonlab

json

JavaScript Object NotationJavascript のオブジェクト記述をベースにしている

{"name": "John Smith", "age": 33}

☞python の辞書形式にかなり近い

Page 27: Apilecture for 2014/02/22 at shannonlab

Json  を返してくれる API の例http://www.ekidata.jp/api/api_line.php

Page 28: Apilecture for 2014/02/22 at shannonlab

加工

データそのままでは使えないので、それを切り出す操作が必要になる。 →それを行うためのモジュールがある

Page 29: Apilecture for 2014/02/22 at shannonlab

Xml の場合・ Element Tree ( python 標準装備)・ xml.dom.minidom・ lxml・ Beautifulsoup・ xml.parsers.expatネットにいっぱい落ちています。

Page 30: Apilecture for 2014/02/22 at shannonlab

Element Tree

Xml データそのままでは使えないので、 pythonで使えるように変更する必要がある。Element 型という形

例:import xml.etree.ElementTree as ETdata = ET.fromstring   (response.read())

Page 31: Apilecture for 2014/02/22 at shannonlab

Practice:element tree

<window width="1920"><title font="large"

color="red">sample</title><buttonbox>

<button>OK</button><button>Cancel</button>

</buttonbox></window>

Page 32: Apilecture for 2014/02/22 at shannonlab

Step1: 文字列からString = <window width="1920”><title font="large" color="red">sample</title><buttonbox><button>OK</button><button>Cancel</button></buttonbox></window>

elem = fromstring(String)

Page 33: Apilecture for 2014/02/22 at shannonlab

Step1: ファイルからdata = parse(“sample.xml”)elem = data.getroot()

Page 34: Apilecture for 2014/02/22 at shannonlab

elem ← この中にデータを格納した!!     取り出してみよう

Page 35: Apilecture for 2014/02/22 at shannonlab

tag 名<window width="1920">

<title font="large" color="red">sample</title>

<buttonbox><button>OK</button><button>Cancel</button>

</buttonbox></window>

Page 36: Apilecture for 2014/02/22 at shannonlab

attribute

<window width="1920"><title font="large"

color="red">sample</title><buttonbox>

<button>OK</button><button>Cancel</button>

</buttonbox></window>

Page 37: Apilecture for 2014/02/22 at shannonlab

Attribute の value

<window width="1920"><title font="large"

color="red">sample</title><buttonbox>

<button>OK</button><button>Cancel</button>

</buttonbox></window>

Page 38: Apilecture for 2014/02/22 at shannonlab

value

<window width="1920"><title font="large"

color="red">sample</title><buttonbox>

<button>OK</button><button>Cancel</button>

</buttonbox></window>

Page 39: Apilecture for 2014/02/22 at shannonlab

Tag の名前の取り出しprint elem.tag

Result:window

Page 40: Apilecture for 2014/02/22 at shannonlab

Attribute を指定して value 取得print elem.get(“width”)

Result:1920

Page 41: Apilecture for 2014/02/22 at shannonlab

Attribute 名のリスト取得print elem.keys()

Result:[‘width’]

Page 42: Apilecture for 2014/02/22 at shannonlab

どっちも欲しい!!print elem.items()

Result:[(‘width’,’1920’)]

Page 43: Apilecture for 2014/02/22 at shannonlab

条件にマッチする要素を返すfor e in elem.findall(“.//button”): print e.tag

Result:buttonbutton

Page 44: Apilecture for 2014/02/22 at shannonlab

全部ほしいfor e in elem.getiterator(): print e.tag

Result:windowtitlebuttonboxbuttonbutton

Page 45: Apilecture for 2014/02/22 at shannonlab

特定のものだけ欲しいfor in elem.getiterator(“button”):

print e.tag

Result:buttonbutton

Page 46: Apilecture for 2014/02/22 at shannonlab
Page 47: Apilecture for 2014/02/22 at shannonlab

csv

csv (という標準装備のモジュールがある)

例 :reader さえ使えればなんとかなるlist =[]f = csv.reader(FILE)for row in f:

list.append(row)print list

Page 48: Apilecture for 2014/02/22 at shannonlab

json

json (標準装備)Simplejson  

例>>> import json>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]>>> json.loads('"\\"foo\\bar"')u'"foo\x08ar’

Page 49: Apilecture for 2014/02/22 at shannonlab

Practice( 変換だけですが )

{'Python':'python.org’, 'SearchEngine':('gogle.co.jp','yahoo.co.jp')}

これをデコードして辞書型に変換しましょう。デコードしたものから key ごとに取り出せるかも見てみましょう

Page 50: Apilecture for 2014/02/22 at shannonlab

そのまえに encode してみるimport json

data = さっきのencoded = json.dumps(data)Print type(encoded)

Page 51: Apilecture for 2014/02/22 at shannonlab

Decode してみようdecoded = json.loads(encoded)

print decodedprint type(decoded)

Page 52: Apilecture for 2014/02/22 at shannonlab

取り出し

print decoded[‘Python’]print decoded[‘SearchEngine’]

Page 53: Apilecture for 2014/02/22 at shannonlab
Page 54: Apilecture for 2014/02/22 at shannonlab

3 .ターミナルで動かす

Page 55: Apilecture for 2014/02/22 at shannonlab

郵便番号プログラム

さっきの郵便番号から住所を得る API を使うプログラムを書いて、結果を表示してみましょう。

Page 56: Apilecture for 2014/02/22 at shannonlab

例題1:データを得てそのまま表示

手順:

 ①アクセスする url 文字列を作成 ② urllib2 モジュールで、作った url 文字列を使   用して、 http レスポンスを得る ③得たレスポンスを print で表示

Page 57: Apilecture for 2014/02/22 at shannonlab

① アクセスする url を作るヒント:

・ input を使う・固定部分  url = “http://zip.cgis.biz/xml/zip.php?zn=“ 追加する部分(郵便番号)= input url = url + 郵便番号

※ 型は string

Page 58: Apilecture for 2014/02/22 at shannonlab

②urllib2 でレスポンスを得るヒント:

レスポンスオブジェクトは

response = urllib2.urlopen(url)

で得られます

Page 59: Apilecture for 2014/02/22 at shannonlab

③ レスポンスを表示ヒント:

オブジェクトprint response で ok

Page 60: Apilecture for 2014/02/22 at shannonlab

例題1:解答例#!/usr/bin/env python# -*- coding: utf-8 -*-

import urllib2import xml.etree.ElementTree as ET

if __name__=='__main__':num = input('address number?')url = 'http://zip.cgis.biz/xml/zip.php?zn='address = str(num)response = urllib2.urlopen(url+address)

data = response.read()print data

Page 61: Apilecture for 2014/02/22 at shannonlab

例題2:加工して表示得たデータを

都道府県 値市町村 値住所 値

という形に表示しよう。

Page 62: Apilecture for 2014/02/22 at shannonlab

手順①response オブジェクトを加工可能な形に変換  → element.tree を使う② 変換したものを python 辞書型に落とし込む③ それを表示

Page 63: Apilecture for 2014/02/22 at shannonlab

①response オブジェクトを加工ヒント

まずはパースすること→ elementtree 型にする

参考: http://docs.python.jp/2/library/xml.etree.elementtree.htmlあとは先ほどのスライド

Page 64: Apilecture for 2014/02/22 at shannonlab

②python 辞書型に変換ヒント今回の郵便番号 API は value でなくてattributeとして結果を返している

<value state=" 東京都 "/>

赤字が欲しい!!  elem.items ???

Page 65: Apilecture for 2014/02/22 at shannonlab

③ 表示ヒント

辞書をプリントするので、キーを指定してプリントすれば ok

Page 66: Apilecture for 2014/02/22 at shannonlab

解答例前半#!/usr/bin/env python# -*- coding: utf-8 -*-

import sysimport urllib2from xml.etree.ElementTree import *import xml.etree.ElementTree as ET

def api(a):url = 'http://zip.cgis.biz/xml/zip.php?zn='address = str(a)response = urllib2.urlopen(url+address)return response

Page 67: Apilecture for 2014/02/22 at shannonlab

解答例後半if __name__=='__main__':

num = input('address number?')response = api(num)data = response.read()root = ET.fromstring(data)data = {}for value in root.iter('value'):for k,v in value.attrib.items():#print k , vnome = kbasho = vdata.update({nome:basho})

Page 68: Apilecture for 2014/02/22 at shannonlab

<ZIP_result><result name="ZipSearchXML"/><result version="1.01"/><result request_url="http%3A%2F%2Fzip.cgis.biz%2Fxml%2Fzip.php%3Fzn%3D1690075"/><result request_zip_num="1690075"/><result request_zip_version="none"/><result result_code="1"/><result result_zip_num="1690075"/><result result_zip_version="0"/><result result_values_count="1"/><ADDRESS_value><value state_kana=" トウキョウト "/><value city_kana=" シンジュクク "/><value address_kana=" タカダノババ "/><value company_kana="none"/><value state=" 東京都 "/><value city=" 新宿区 "/><value address=" 高田馬場 "/><value company="none"/></ADDRESS_value></ZIP_result>

Page 69: Apilecture for 2014/02/22 at shannonlab

解答例最後    state = data['state']

city = data['city']address = data['address']print stateprint cityprint address

Page 70: Apilecture for 2014/02/22 at shannonlab

4 . Django で動かす

Page 71: Apilecture for 2014/02/22 at shannonlab

Django復習https://www.djangoproject.com

Page 72: Apilecture for 2014/02/22 at shannonlab

Django とは『 python 用の web フレームワーク』

※ フレームワーク  web アプリケーションの鋳型 根本的な部分はフレームワークに任せられる

Page 73: Apilecture for 2014/02/22 at shannonlab

おおまかな構造

view

MODEL

URL

Page 74: Apilecture for 2014/02/22 at shannonlab

おおまかな構造

view

MODEL

URL

HTTP リクエスト

Page 75: Apilecture for 2014/02/22 at shannonlab

おおまかな構造

view

MODEL

URL

HTTP リクエスト

命令振り分け

Page 76: Apilecture for 2014/02/22 at shannonlab

おおまかな構造

MODEL

URL

HTTP リクエスト

view処理!!

データやり取り

Page 77: Apilecture for 2014/02/22 at shannonlab

おおまかな構造

view処理!!

Django

HTTP レスポンスオブジェクト

Result

Page 78: Apilecture for 2014/02/22 at shannonlab

view

ページの表示にかかわる部分。アプリケーションの処理部分を書く

Page 79: Apilecture for 2014/02/22 at shannonlab

MODEL

アプリケーションに欠かせないデータの保管に関係する部分

Page 80: Apilecture for 2014/02/22 at shannonlab

URL

作成するアプリケーションの別々のページの間の関係、 URL まわりの設定をする

Page 81: Apilecture for 2014/02/22 at shannonlab

Django プロジェクトを立ち上げる

ダウンロードしていない人はする

Page 82: Apilecture for 2014/02/22 at shannonlab

startproject

適当なディレクトリでdjango-admin.py startproject mysite を実行

Page 83: Apilecture for 2014/02/22 at shannonlab

ディレクトリができているはず

Page 84: Apilecture for 2014/02/22 at shannonlab

自動的にディレクトリの中身も

Page 85: Apilecture for 2014/02/22 at shannonlab

startapp するpython manage.py startapp finda

Page 86: Apilecture for 2014/02/22 at shannonlab

自動的に finda が作成される

Page 87: Apilecture for 2014/02/22 at shannonlab

データベースを使えるようにする

python manage.py syncdb

→ 上手く動かない。 settings.py を変更

Page 88: Apilecture for 2014/02/22 at shannonlab

settings.py

Page 89: Apilecture for 2014/02/22 at shannonlab

settings.py MODEL設定

Page 90: Apilecture for 2014/02/22 at shannonlab

settings.py MODEL設定

Page 91: Apilecture for 2014/02/22 at shannonlab

改めて syncdb

Page 92: Apilecture for 2014/02/22 at shannonlab

foo ができている

Page 93: Apilecture for 2014/02/22 at shannonlab

フローを考える《住所表示アプリケーション》① トップページにアクセス② トップページの郵便番号欄に打ち込む③ 送信④結果表示

Page 94: Apilecture for 2014/02/22 at shannonlab

① トップページにアクセス機能・ top ページ url にリクエストを送ると、郵便番号  記入するフォームが現れる

・ view に書き込む  index クラス

Page 95: Apilecture for 2014/02/22 at shannonlab

②③ 送信機能・送信すると、 view 内の他の関数が働いて、入  力された数字を加工して、 api に送信、データ を受け取る

これも view に書く

Page 96: Apilecture for 2014/02/22 at shannonlab

④結果表示機能・②③のデータ処理と同じところに入れるor・②③の結果をモデルに入れて、そこから引き 出して使う

サンプルプログラムは前者です

Page 97: Apilecture for 2014/02/22 at shannonlab

① いきなりはわからない

Page 98: Apilecture for 2014/02/22 at shannonlab

Page 99: Apilecture for 2014/02/22 at shannonlab

①finda/urls.py

Page 100: Apilecture for 2014/02/22 at shannonlab

Page 101: Apilecture for 2014/02/22 at shannonlab

①mysite/urls.py

Page 102: Apilecture for 2014/02/22 at shannonlab

①mysite/urls.py

Page 103: Apilecture for 2014/02/22 at shannonlab

runserver

Page 104: Apilecture for 2014/02/22 at shannonlab

結果

Page 105: Apilecture for 2014/02/22 at shannonlab

template の利用

Page 106: Apilecture for 2014/02/22 at shannonlab

finda/templates/finda/index.html

Page 107: Apilecture for 2014/02/22 at shannonlab

view の書き換え

Page 108: Apilecture for 2014/02/22 at shannonlab

template の読み込み

Page 109: Apilecture for 2014/02/22 at shannonlab

結果

Page 110: Apilecture for 2014/02/22 at shannonlab

template に値を入れて表示したい時

html{{listall}}

viewlist = listcontext = {‘listall’:list}return render(request,'finda/index.html',context)

Page 111: Apilecture for 2014/02/22 at shannonlab

Django で動かすここまでで view の作り方がわかりました

・値は html の form で得るといいでしょう。・得たものを url 文字列に整形します 初めの方に作ったプログラムを流用します・先ほどのプログラムで辞書型データを作成・ template に値を与えて表示

Page 112: Apilecture for 2014/02/22 at shannonlab

手順例① プロジェクトを作る 済②app を作る 済③syncdb  済④settings.py の設定 済⑤urls.py の設定  result クラスの url設定⑥ビューの作成  result クラスを作る⑦テンプレートの作成

Page 113: Apilecture for 2014/02/22 at shannonlab

やってみましょう参考 url:チュートリアルhttps://docs.djangoproject.com/en/1.6/intro/tutorial01/posts 送信されたデータの受け取りhttp://www.djangoproject.jp/doc/ja/1.0/ref/request-response.htmlhttp://stackoverflow.com/questions/12518517/request-post-getsth-vs-request-poststh-difference

Page 114: Apilecture for 2014/02/22 at shannonlab

やってみましょう