1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

郵便番号情報をダウンロードしてSupabaseに登録する Python(Google Colaboratory)

Last updated at Posted at 2023-01-03

手順

  1. supabaseのプロジェクトの作成
    • supabaseの下記のデータベース接続情報をメモする
      • Host
      • Database name
      • Port
      • User
      • Password
  2. Pythonプログラム(Google Colaboratory)の作成
    • supabaseの接続情報をconfig.ymlに設定する
      • 日本郵政の郵便番号データベースのダウンロード先も設定しておく
    • Pythonプログラム作成
config.yml
SUPABASE:
  SUPABASE_PROJECT_URL: https://xxxxxx.supabase.co/
  Host: db.xxxxxxxx.supabase.co
  Databasename: xxxxx
  Port: xxxx
  User: xxxxx
  Password: xxxxxx
Postcode:
  CSV_URL: https://www.post.japanpost.jp/zipcode/dl/kogaki/zip/ken_all.zip

supabaseの管理画面でのテーブルの作成

SQL Editorを使う

create table postcode (
  id serial  primary key,
  postcode varchar(8),
  ken varchar(6),
  address1 varchar(50),
  address2 varchar(50),
  updated_at timestamp with time zone not null default now()
);

create index on postcode (postcode);

Pythonプログラム

PythonからPostgreSQLに接続する為のライブラリをインストール

pip install psycopg2

Pythonプログラム本体

import yaml
# configはGoogleドライブに保存
CONST_CONFIG_FILENAME = "./drive/MyDrive/colaboratory/postcode_to_supabase/config.yml"

# configの読込
config = None
with open(CONST_CONFIG_FILENAME, 'r') as yml:
	config = yaml.safe_load(yml)
	print(config)

# 郵便番号情報のダウンロード
import os
import requests

url = config['Postcode']['CSV_URL']
r = requests.get(url, allow_redirects=True)
saveZipFileName = "postcode.zip"
if os.path.isfile(saveZipFileName):
	os.remove(saveZipFileName)

open(saveZipFileName, 'wb').write(r.content)

# 解凍
import shutil
out_dir_name = saveZipFileName.split(".")[0]
shutil.unpack_archive(saveZipFileName, out_dir_name)

# データベース接続
import psycopg2
from psycopg2 import extras

connection = psycopg2.connect(host=config['SUPABASE']['Host'],
user=config['SUPABASE']['User'],
password=config['SUPABASE']['Password'],
database=config['SUPABASE']['Databasename'])

# 一括登録する関数を定義
def insertPostcodeDatas(values):
	with connection:
		with connection.cursor() as cursor:
			cursor.execute("truncate table postcode")
			sql = "insert into postcode (postcode , ken , address1, address2) values %s"
			extras.execute_values(cursor, sql, values)
	
			# # コミットしてトランザクション実行
			connection.commit()
			
			# 終了処理
			cursor.close()


# CSVを読込DBにINSERT

CSV_FILE_NAME = "KEN_ALL.CSV"
csv_file_path = os.path.join(out_dir_name,CSV_FILE_NAME)

import csv
datas = []
with open(csv_file_path, "r", encoding="Shift_JIS") as csv_file:
	f = csv.reader(csv_file)
	for row in f:
		postcode = row[2]
		ken = row[6]
		address1 = row[7]
		address2 = row[8]
		datas.append([postcode, ken, address1, address2])

insertPostcodeDatas(datas)

データベースへの登録に3分ぐらいかかる

その他

supabaseでテーブル(postcode)にRLSを設定して、アプリケーションから利用する

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?