json

インポート

import json

json形式のファイルの辞書型データへの読み込み

json形式を直接読み込んで、結果は辞書型データにな。

with open(filename, mode='r', encoding='utf-8') as file1:
            json_file = json.load(file1)

読み込んだあとは辞書型データの処理を行う。

jsonから読み込んだ辞書型データの長さ

len(json_file['data'])

math

C 標準で定義された数学関数へのアクセスを提供する。

複素数は扱えない。戻り値は全て浮動小数点数になる。

インポート

import math

ルート(平方根)

平方根を返す。

math.sqrt(2)
1.4142135623730951

smtplib

SMTP プロトコルクライアント。emailを送信できるモジュールである。この例ではsslモジュールとMIMETextモジュールも一緒に使用している。

標準ライブラリー

smtplib — SMTP プロトコルクライアント

インポート

smtplib以外のものも一緒に記載している。

import smtplib
from email.mime.text import MIMEText
import ssl

メッセージの送信

msg = MIMEText('xxxxxxxx', "html")
msg['Subject'] = 'AWS_lambda_autosendmail ---- '
msg['From'] = userid+'@'+smtp_server+'(AWS_lambda_autosendmail)'
msg['To'] = to_address

server = smtplib.SMTP_SSL(smtp_server, smtp_port, context=ssl.create_default_context())
server.login(userid, password)
server.send_message(msg)
server.quit()

MySQLdb

MySQLdb User’s Guide

MySQLdb User’s Guide

インストール

py -m pip install MySQL-Python

上記モジュールのインストールで、。”‘config-win.h’:No such file or directory”というエラーが出て失敗するときは、代わりに基本的なMySQLの機能だけを有効にする以下のモジュールをインストールするとよい。

py -m pip install PyMySQL

インポート

import MySQLdb

オペレーションフロー

MySQLのオペレーションは7つのステップからなる。

  1. Create connection
  2. Create cursor
  3. Create Query string
  4. Execute the query
  5. Commit to the query
  6. Close the cursor
  7. Close the connection

データベース接続

connect = MySQLdb.connect(
    host = 'localhost',    # Pythonを実行するPCのアドレス(localhost)
    port = 10022,    # 上記で指定したlocalhostの適当なPort
    user = RDS_MySQL_userID,
    db = RDS_database_name,
    passwd = RDS_database_password,
    local_infile = 1    # "LOADDATA IN FILE" for CSV Import
)
cursor = connect.cursor()
  • データーベースのエンドポイントは、すでにSSHTunnelForwarderでパラメーターとして指定しているので、dbにはデーターベース名だけを指定する。

クエリの実行

cursor.execute(sql)

クエリ実行結果取得

cursor.fetchall()

データベースを閉じる

cursor.close()
  • Connectを閉じると自動的にデータベースが閉じるという説もある。

MySQLの接続を閉じる

connect.close()
  • Cursorを閉じた後に実行する。

sshtunnel

SSHトンネルでサーバーにSSH接続を行う。

踏み台にするEC2サーバーと、接続するRDSのエンドポイントとポートを指定する。

公式ドキュメント

Welcome to sshtunnel’s documentation!

インストール

py -m pip install sshtunnel

インポート

from sshtunnel import SSHTunnelForwarder

サーバー設定

ec2_server = SSHTunnelForwarder(
        (EC2_instabnce_globalIP, 22),
        ssh_host_key = None,
        ssh_username = 'user-id',
        ssh_password = None,
        ssh_pkey = 'D:\xxxxxxxx',
        remote_bind_address = (RDS_database_endpoint, 3306),
        local_bind_address = ('localhost', 10022)    # Pythonを実行するPCのアドレス(localhost=127.0.0.0))と適当なPort
)

サーバーの開始

ec2_server.start()

サーバーの停止

ec2_server.stop()