1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- import csv
- import json
- from datetime import datetime
- from pathlib import Path
- import requests
- import snowflake.connector
- url = "https://sq43047.eu-central-1.snowflakecomputing.com/oauth/token-request"
- login = {
- "user": "AxayPnlaAHtkZ9FuBbERcf0Wa8E=",
- "password": "RC18m4LHUwcDlxSInZ5FOlUOQ8J4ud5LMcq7ATZNgps=",
- }
- credentials = {
- "user": "1103",
- "account": "sq43047.eu-central-1",
- "authenticator": "oauth",
- "token": "256A1D8740C7AC1FE617BFF4B2C74E31789BE754",
- "database": "REISACHER",
- "schema": "EXTRAKTION",
- }
- sql = """
- select
- *
- from "01_EXTR_REISACHER_RSP_ACCOUNTCUSTOMERCARES" AS "T1"
- inner join "01_EXTR_REISACHER_RSP_ACCOUNTS_LEGALENTITYINFORMATION" AS "T2" ON "T1"."accountId" = "T2"."accountId"
- """
- def get_auth_code():
- payload = {
- "grant_type": "authorization_code",
- "code": credentials["token"],
- "redirect_uri": "https://localhost.com",
- }
- r = requests.post(
- url=url,
- auth=(*login.values(),),
- data=payload,
- )
- token = r.json()
- return token
- def get_access_token(token):
- payload = {
- "grant_type": "refresh_token",
- "refresh_token": token["refresh_token"],
- "redirect_uri": "https://localhost.com",
- }
- r = requests.post(
- url=url,
- auth=(*login.values(),),
- data=payload,
- )
- token = r.json()
- return token
- def snowflake_to_csv(csv_export_file):
- token_json = Path("token.json")
- if token_json.exists():
- token = json.load(token_json.open("r"))
- if datetime.now().timestamp() > token_json.stat().st_mtime + token["expires_in"]:
- token = token.update(get_access_token(token))
- json.dump(token, token_json.open("w"), indent=2)
- else:
- token = get_auth_code()
- json.dump(token, token_json.open("w"), indent=2)
- credentials["token"] = token["access_token"]
-
- with snowflake.connector.connect(**credentials) as conn:
- cur = conn.cursor()
- cur.execute(sql)
- with Path(csv_export_file).open("w", encoding="latin-1", newline="") as fwh:
- csv_export = csv.writer(fwh, delimiter=";")
- csv_export.writerow([i[0] for i in cur.description])
- csv_export.writerows(cur.fetchall())
- if __name__ == "__main__":
- snowflake_to_csv(Path(__file__).parent / "01_EXTR_REISACHER_RSP_ACCOUNTCUSTOMERCARES.csv")
-
|