インポート
import json
json形式のファイルの辞書型データへの読み込み
json形式を直接読み込んで、結果は辞書型データにな。
with open(filename, mode='r', encoding='utf-8') as file1:
json_file = json.load(file1)
読み込んだあとは辞書型データの処理を行う。
jsonから読み込んだ辞書型データの長さ
len(json_file['data'])
Since 2023/09/17
モジュールをインポートして実行するコマンドを説明
import json
json形式を直接読み込んで、結果は辞書型データにな。
with open(filename, mode='r', encoding='utf-8') as file1:
json_file = json.load(file1)
読み込んだあとは辞書型データの処理を行う。
len(json_file['data'])
C 標準で定義された数学関数へのアクセスを提供する。
複素数は扱えない。戻り値は全て浮動小数点数になる。
import math
平方根を返す。
math.sqrt(2) 1.4142135623730951
SMTP プロトコルクライアント。emailを送信できるモジュールである。この例ではsslモジュールとMIMETextモジュールも一緒に使用している。
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()
Python 3では主流ではなくなって、現在は以下が主流になっているらしい。
“import MysqlDB”でインポートできるようになっているので、MySQLdbを使っているつもりでも、mysqlclientが実行されている場合がある。
py -m pip install MySQL-Python
上記モジュールのインストールで、。”‘config-win.h’:No such file or directory”というエラーが出て失敗するときは、代わりに基本的なMySQLの機能だけを有効にする以下のモジュールをインストールするとよい。
py -m pip install PyMySQL
import MySQLdb
MySQLのオペレーションは7つのステップからなる。
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()
cursor.execute(sql)
cursor.fetchall()
cursor.close()
connect.close()
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()