Open12

pythonを触る

kodukakoduka
main.py
import sys

def main():
    args = sys.argv
    print(args)

main()
出力
# python main.py aaa bbbb dddd eeeee=aaa
['main.py', 'aaa', 'bbbb', 'dddd', 'eeeee=aaa']
kodukakoduka

https://tonari-it.com/python-for-dictionary-keys-values-items/

辞書型のFor文。

main.py
for data in table.datas:
    print(data)
    for key, value in data.items():
        print("key: {}, value: ".format(key, value))
出力
# python main.py /python/assets/test.csv
[{'1': 'aaa', '2': 'bbb', '3': 'ccc', '4': 'ddd', '5': 'eee', '6': 'fff'}, {'1': 'aaa', '2': 'bbb', '3': 'ccc', '4': 'ddd', '5': 'eee', '6': 'fff'}]
{'1': 'aaa', '2': 'bbb', '3': 'ccc', '4': 'ddd', '5': 'eee', '6': 'fff'}
key: 1, value: 
key: 2, value: 
key: 3, value: 
key: 4, value: 
key: 5, value: 
key: 6, value: 
kodukakoduka

csvの値が[table].fieldの場合、DB接続して、そのテーブルのカラムの値を取得する。
だから、文字列が[table].fieldの場合に、[]で囲んだtableを取り出したい。

まず、[table].fieldのような形式であるかをチェックをして、
OKなら、パース処理を行う。
NGなら、ただの文字列として処理を続ける。

kodukakoduka

csvの値が[table].fieldの場合、DB接続して、そのテーブルのカラムの値を取得する。
だから、文字列が[table].fieldの場合に、[]で囲んだtableを取り出したい。

上記、ChatGPTに聞いて、以下を採用!

import re

text = "[table].field"
match = re.match(r'\[([^]]+)\]\.field', text)

if match:
    table_name = match.group(1)
    print(table_name)
else:
    print("マッチしませんでした。")
kodukakoduka
main.py
self.connection = psycopg2.connect("host={} dbname={} user={} password={}".format(
    os.environ.get('DB_HOST', 'localhost'),
    os.environ.get('POSTGRES_USER', 'docker'),
    os.environ.get('POSTGRES_USER', 'docker'),
    os.environ.get('POSTGRES_PASSWORD', 'password'),
))
出力
...
psycopg2.OperationalError: connection to server at "host.docker.internal" (192.168.65.254), port 5432 failed: Connection refused
        Is the server running on that host and accepting TCP/IP connections?

うまくないなー。

kodukakoduka
# docker-compose logs postgres
csv-filler-postgres-1  | bash: warning: setlocale: LC_ALL: cannot change locale (ja_JP.UTF-8)
csv-filler-postgres-1  | bash: warning: setlocale: LC_ALL: cannot change locale (ja_JP.UTF-8)
csv-filler-postgres-1  | The files belonging to this database system will be owned by user "postgres".
csv-filler-postgres-1  | This user must also own the server process.
csv-filler-postgres-1  | 
csv-filler-postgres-1  | 
csv-filler-postgres-1  | initdb: error: invalid locale settings; check LANG and LC_* environment variables
Dockefile
FROM postgres

ENV TZ Asia/Tokyo
ENV LANG ja_JP.UTF-8
ENV LANGUAGE ja_JP:ja
ENV LC_ALL ja_JP.UTF-8

環境変数の設定がダメそうなのはわかるけど、解決法がわからない。

kodukakoduka
Dockerfile
RUN apt-get update && apt-get install -y locales \
    && rm -rf /var/lib/apt/lists/* \
    && localedef -i ja_JP -c -f UTF-8 -A /usr/share/locale/locale.alias ja_JP.UTF-8

↑を追加する。
Dockerイメージのpostgresベースイメージは、
デフォルトでen_US.utf8のロケールを使用しているため、
initdbを実行する前にロケールデータを追加する必要があるらしい。

kodukakoduka

テストしたいから、DBにモックデータを簡単に入れるツールを探す必要があるな。