ラベル requests の投稿を表示しています。 すべての投稿を表示
ラベル requests の投稿を表示しています。 すべての投稿を表示

2019年6月29日土曜日

DockerでPython3.7、requests、slackがインストールされたコンテナ(Alpine3.9ベース)を作成する

requestsとslackでネットワークにアクセスした結果に応じてslackの通知するようなプログラムを作成する事ができます。

1.イメージの作成
以下のコマンドとDockerfileでPython3.7、requests、slackがインストールされたコンテナを作成します。
docker build --no-cache -t slack-requests:1.0 .

Dockerfile
FROM python:3.7-alpine3.9
RUN apk --no-cache add libstdc++ \
  && apk --no-cache --virtual pydeps add gcc \
    g++ \
    python3-dev \
    musl-dev \
    cython \
    libffi-dev \
  && pip install requests \
  && pip install slackclient \
  && apk del --purge pydeps
CMD ["/bin/sh"]

2. 以下のサンプルプログラムでrequestsとslackを活用して簡単なURLの生死監視・エラーチェックを行うことができます。
下記monitor_urls.pyの他に監視したいURLを保持したurls.txt(1行に1URLを書いてください)と通知時のメッセージヘッダーを保持したheader.txtを同じフォルダに用意します。
Botsの登録などはあらかじめ行い、TOKENを控えてください。

monitor_urls.py
import os
import requests
from requests.exceptions import ConnectionError
import slack
import json

header = ""
with open(os.environ['HEADER']) as fheader:
  header = fheader.read()

with open(os.environ['URLS']) as furls:
  urls = furls.readlines()

errors=[]

for url in urls:
  url = url.rstrip('\n')
  try:
    result = requests.get(url, timeout=10)
    if result.status_code >= 400:
      errors.append({'status_code':result.status_code, 'reason':result.reason, 'url':url})
  except ConnectionError as err:
    errors.append({'status_code':-1, 'reason':'No response', 'url':url})

if len(errors) > 0:
  client = slack.WebClient(token=os.environ['SLACK_TOKEN'])
  response = client.chat_postMessage(
    channel=os.environ['SLACK_CHANNEL'],
    username=os.environ['SLACK_USER'], icon_emoji=os.environ['SLACK_ICON'],
    text=header + json.dumps(errors, indent=2))

実行は以下のコマンドを実行します。slackへのトークン情報やurlを格納したファイルなどの情報は環境変数を指定して渡します。
docker run -e SLACK_TOKEN='<slack token>' \
  -e SLACK_CHANNEL='#general' \
  -e SLACK_USER='mybot' \
  -e SLACK_ICON=':cat:' \
  -e URLS='/tmp/query.txt'
  -e HEADER='/tmp/header.txt'
  -v `pwd`:/tmp  -it slack-requests:1.0 /usr/local/bin/python3 /tmp/monitor_urls.py

2018年11月12日月曜日

Pythonで国立国会図書館サーチAPIで、図書を検索する

国立図書館サーチAPIで蔵書の情報を取得する事ができます。
以下のサンプルコードで、指定キーワードを含む蔵書を検索する事ができます。

〇サンプルコード
# coding: utf-8
from lxml import etree
import requests
from io import StringIO
import xml.etree.ElementTree as ET

query = 'title="ラズパイ" AND from="2012"'
baseuri='http://iss.ndl.go.jp/api/sru?operation=searchRetrieve&query='
uri = baseuri + query
headers = {'content-type': 'text/xml'}
response = requests.get(
  uri,
  headers=headers)

root = etree.fromstring(response.content)
for record in root.findall('.//recordData', root.nsmap):
  rec = etree.fromstring(record.text)
  print("title:" + str(rec.find('./{*}title').text))
  if rec.find(('./{*}creator')) is not None:
    print("creator:" + str(rec.find('./{*}creator').text))
  print("---------------")

○関連情報
・外部提供インタフェース(API)
http://iss.ndl.go.jp/information/api/

・requestsパッケージに関する他の記事はこちらを参照してください。

2018年11月5日月曜日

Pythonで路線・駅データを取得する

駅データ.jpのAPIを使用して、路線や駅の情報を取得する事ができます。
以下のサンプルコードで、指定都道府県内の路線名、指定した路線内の駅情報・緯度経度を取得する事ができます。

〇都道府県内の路線を取得するサンプルコード
# coding: utf-8
from lxml import etree
import requests

pref = '11' # Saitama
baseuri='http://www.ekidata.jp/api/p/'
uri = baseuri + pref + '.xml'
headers = {'content-type': 'text/xml'}
response = requests.get(
  uri,
  headers=headers)
root = etree.fromstring(response.content)
for line in root.xpath('//line'):
  print("line_cd:"+line.findtext('line_cd'))
  print("line_name:"+line.findtext('line_name'))

〇路線内の駅を取得するサンプルコード
# coding: utf-8
from lxml import etree
import requests

line_cd = '21004'
baseuri='http://www.ekidata.jp/api/l/'
uri = baseuri + line_cd + '.xml'
headers = {'content-type': 'text/xml'}
response = requests.get(
  uri,
  headers=headers)
root = etree.fromstring(response.content)
for station in root.xpath('//station'):
  print("station_cd:"+station.findtext('station_cd'))
  print("station_name:"+station.findtext('station_name'))
  print("longitude:"+station.findtext('lon'))
  print("latitude:"+station.findtext('lat'))
  print("----------")

○関連情報
・駅データ.jpのAPI情報
http://www.ekidata.jp/api/

・requestsパッケージに関する他の記事はこちらを参照してください。

2018年10月29日月曜日

Pythonで不動産取引価格情報を取得する

国土交通省の不動産取引価格情報取得APIを使用して、指定した市区町村・四半期の不動産取引情報を取得する事ができます。
以下のサンプルコードを使用して、不動産取引のタイプ、市区町村名、地区名、面積(平方メートル)、取引金額、建築年(建物などの場合)を取得する事ができます。

〇サンプルコード
# coding: utf-8
import pprint
import json
import requests

city = '11214' # Kasukabe city
from_quarter = '20181' # 2018Q1 = 2018-01 to 2-18-03
to_quarter = '20182' # 2018Q2 = 2018-04 to 2-18-06
baseuri='http://www.land.mlit.go.jp/webland/api/TradeListSearch?'
uri = baseuri + 'city=' + city + "&from=" + from_quarter + "&to=" + to_quarter
headers = {'content-type': 'application/json'}
response = requests.get(
  uri,
  headers=headers)
for trans in response.json()['data']:
  print("type:" + trans['Type'])
  print("municipality:" + trans['Municipality'])
  print("district name:" + trans['DistrictName'])
  print("area(m2):" + trans['Area'])
  print("trade price:" + trans['TradePrice'])
  if "BuildingYear" in trans:
    print("building year:" + trans['BuildingYear'])
  print("-----------------------------------")
#pprint.pprint(response.json())

○関連情報
・国土交通省:土地総合情報
http://www.land.mlit.go.jp/webland/api.html

・requestsパッケージに関する他の記事はこちらを参照してください。

2018年10月22日月曜日

Pythonで市区町村名称を取得する

都道府県内市区町村一覧取得APIを使用して、Pythonで指定した都道府県内の市区町村名称の日本語名称・英語名称を取得する事ができます。

〇指定都道府県内の市区町村名称を取得するサンプルコード
# coding: utf-8
import pprint
import json
import requests

pref='11' # 11:saitama
baseuri='http://www.land.mlit.go.jp/webland/api/CitySearch'
uri = baseuri + '?area=' + pref
headers = {'content-type': 'application/json'}
response = requests.get(
  uri,
  headers=headers)
for city in response.json()['data']:
    print("id:" + city['id'])
    print("name:" + city['name'])
    print("-----------------------------------")
#pprint.pprint(response.json())

〇指定都道府県内の市区町村英語名称を取得するサンプルコード
# coding: utf-8
import pprint
import json
import requests

pref='11' # 11:saitama
baseuri='http://www.land.mlit.go.jp/webland_english/api/CitySearch'
uri = baseuri + '?area=' + pref
headers = {'content-type': 'application/json'}
response = requests.get(
  uri,
  headers=headers)
for city in response.json()['data']:
    print("id:" + city['id'])
    print("name:" + city['name'])
    print("-----------------------------------")
#pprint.pprint(response.json())

○関連情報
・国土交通省:土地総合情報
http://www.land.mlit.go.jp/webland/api.html

・requestsパッケージに関する他の記事はこちらを参照してください。

2018年10月15日月曜日

Pythonでアメリカ地質調査所(USGS)の地震情報を取得する

アメリカ地質研究所(USGS)のAPIを使用して、地震情報を取得する事ができます。
以下のサンプルコードを使用して、地震名称、マグニチュード、日次、緯度、経度を取得する事ができます。

〇サンプルコード
# coding: utf-8
import pprint
import json
import requests
from datetime import datetime

baseuri='https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson'
startdate = '2018-09-27'
enddate = '2018-09-28'
uri = baseuri + '&starttime=' + startdate + '&endtime=' + enddate
headers = {'content-type': 'application/json'}
response = requests.get(
  uri,
  headers=headers)
print(datetime.utcnow().timestamp())
for earthquake in response.json()['features']:
    print("title:" + earthquake['properties']['title'])
    print("magnitude:" + str(earthquake['properties']['mag']))
    print("datetime:" + str(datetime.fromtimestamp(earthquake['properties']['time']/1000)))
    print("longitude:" + str(earthquake['geometry']['coordinates'][0]))
    print("latitude:" + str(earthquake['geometry']['coordinates'][1]))
    print("-----------------------------------")
#pprint.pprint(response.json())

○関連情報
・API Documentation - Earthquake Catalog
https://earthquake.usgs.gov/fdsnws/event/1/

・requestsパッケージに関する他の記事はこちらを参照してください。

2018年10月8日月曜日

Pythonで直近5回のロケット打ち上げ予定の情報を取得する

Launchlibrary.netのAPIを使用してロケット打ち上げ予定情報を取得する事ができます。
以下のサンプルコードで、直近5回の打ち上げ予定の打上予定名、予定時間、場所、使用ロケットの情報を取得する事ができます。

〇サンプルコード
# coding: utf-8
import pprint
import json
import requests

uri = 'https://launchlibrary.net/1.3/launch/next/5'
headers = {'content-type': 'application/json'}
response = requests.get(
  uri,
  headers=headers)
for launch in response.json()['launches']:
    print("launch name:" + launch['name'])
    print("window:" + launch['windowstart'] + " - " + launch['windowend'])
    print("location:" + launch['location']['pads'][0]['name'])
    print("rocket:" + launch['rocket']['name'])
    print("-----------------------------------")
#pprint.pprint(response.json())

○関連情報
・Launch Library Reading API Overview
https://launchlibrary.net/docs/1.3/api.html

・requestsパッケージに関する他の記事はこちらを参照してください。

2018年10月2日火曜日

DockerでJupyter Notebook、folium、requests、postgresqlがインストールされたコンテナのイメージを作成する

Jupyter Notebookと地図を描画できるパッケージfolium、HTTPリクエストを簡素化するrequests、postgresqlにアクセスするpsycopg2とPostgreSQLがインストールされたコンテナのイメージを作成するには、以下の手順を実行します。

〇foliumで描画した地図


○構築方法
以下の手順で、Jupyter Notebookとfolium, requests, psycopg2のコンテナを構築・実行します。
1. folium, requests, psycopg2を追加したJupyter Notebookイメージの作成(Dockerfileがあるフォルダで実行)
docker build -t scipy-notebook-requests-folium-pg .

Dockerfile
FROM jupyter/scipy-notebook
ENV TZ=Asia/Tokyo
USER root
RUN apt-get update \
  && apt-get -y install libpq-dev python-dev \
  && pip install psycopg2-binary \
  && pip install requests \
  && pip install folium \
  && apt-get clean
USER $NB_UID

2. Jupyter Notebookの構築・実行(docker-compose.ymlがあるフォルダで実行)
docker-compose up -d

docker-compose.yml
version: "2"
services:
  scipy-notebook:
    image: scipy-notebook-requests-folium-pg
    container_name: "scipy-notebook-requests-folium-pg"
    volumes:
      - "scipy-notebook-data:/home/jovyan/work"
    ports:
      - "8888:8888"
    environment:
      JUPYTER_TOKEN: jupyter
      JUPYTER_ENABLE_LAB: 1
    depends_on:
      - db
  db:
    image: postgres:10.5-alpine
    container_name: "test-db"
    ports:
      - "5432:5432"
    volumes:
      - "db-data:/var/lib/postgresql/data"
    environment:
        POSTGRES_DB: test
        POSTGRES_PASSWORD: test
volumes:
  db-data:
    driver: local
  scipy-notebook-data:
    driver: local

3.ブラウザから以下のURLにアクセス
http://<Dockerホスト名またはIP>:8888/?token=jupyter

〇動作確認用コード
import folium

fm = folium.Map(location=[35.856999, 139.648849], zoom_start=10)

folium.Marker(location=[35.861729,139.645482], popup='さいたま市').add_to(fm)
folium.Marker(location=[35.975198, 139.752301], popup='春日部市').add_to(fm)
    
fm


○関連情報
・requestsパッケージに関する他の記事はこちらを参照してください。

・psycopg2に関する他の記事はこちらを参照してください。

2018年10月1日月曜日

PyPIのパッケージ情報を取得する

PyPIのJSON APIでパッケージ情報を取得する事ができます。
以下のサンプルコードでパッケージのホームページ、サマリ、説明、リリースバージョンの情報を取得することができます。

〇サンプルコード
# coding: utf-8
import pprint
import json
import requests

project_name = 'wbdata'
uri = 'https://pypi.org/pypi/' + project_name + '/json'
headers = {'content-type': 'application/json'}
response = requests.get(
  uri,
  headers=headers)
print("home page:" + response.json()['info']['home_page'])
print("summary:" + response.json()['info']['summary'])
print("description:" + response.json()['info']['description'])
for release in response.json()['releases']:
  print(release)
#pprint.pprint(response.json())


○関連情報
・PyPIのAPIリファレンスのJSON APIページ
https://warehouse.readthedocs.io/api-reference/json/

・requestsパッケージに関する他の記事はこちらを参照してください。

2018年8月28日火曜日

Jupyterで日本の人口推移データをグラフ化する

Jupterでe-statsから人口データをダウンロードしてグラフ表示するには、以下のコードを実行します

〇コード
%matplotlib inline
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import requests
import re
import pandas

#※データ取得ページ
#組織 厚生労働省 人口動態調査_人口動態統計_確定数_人口_年次_2016年 1_年次・性別人口
#http://www.data.go.jp/data/dataset/mhlw_20171204_0015/resource/53d97e92-5f10-4fcf-ab3b-a08c898f09c1

# download data and cleansing
url = "http://www.e-stat.go.jp/SG1/estat/GL08020103.do?_csvDownload_&fileId=000008018753&releaseCount=1"
table = False
rows = []
for line in requests.get(url).iter_lines():
  # SJISとして読み込む
  row = line.decode('SJIS')
  # 「総数」含まれている行から実データ
  if '総数' in row:
    table = True
  # ヘッダー1列目を「year」に修正
  row = re.sub('^,.*', 'year,total,male,female', row)
  # 西暦上2桁を修正
  row = re.sub('^ ', '19', row)
  # その他の位置の全角スペースを消す
  row = re.sub(' ', '', row)
  # 空行を除く
  if len(row) == 0:
    continue
  if table == True:
    rows.append(row)

filename = "population-data.csv"
with open(filename, mode='w') as outfile:
  outfile.write("\n".join(rows))

df = pandas.read_csv(filename)
df2 = df.loc[:,['year','male','female']]
ax = df2.set_index('year').plot()
ax.get_yaxis().set_major_formatter(
    ticker.FuncFormatter(lambda y, p: format(int(y), ',')))
plt.legend(loc='best')
plt.show()

〇出力画像



○関連情報
・requestsパッケージに関する他の記事はこちらを参照してください。