/// BANGBOO BLOG ///

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31


April 1, 2022 List
GCP Python script on Apr 01, 2022 12:00 AM

April 1, 2022

GCP Python script
Googleがサポートするの縺?3縺?
 pip install google-cloud-dialogflow
 GCPは臀??記縺?RESTがベースにあるらしいがコレが楽か縺?
2)REST https://googleapis.github.io/HowToREST
 URL縺?Authベアラーと藹??要ならJSONを投げ縺?JSONを藹??け藹??る
 URLに觸??則性があり get とか list
 なぜかうまく行かないことが多い
3)gRPC https://grpc.io/

■サンプルコードのライブラリを検索する縺?APIドキュメントは藹??っかかる
APIドキュメント
API縺?githubにコード公開されている
親分縺?Google APIs on guthub

■python gcp Cloud API client libraryは臀??記のような所からサンプル、仕様を藹??る
client(bq)
pip install google-cloud-resource-manager
pip install google-cloud-biguery-datatransfer

#Pyton Bigquery
requirements.txt
google-cloud-bigquery==3.3.2
google-cloud-logging==3.2.2
----
from google.cloud import bigquery
import google.cloud.logging
import logging
bq = bigquery.Client()
sql = "select * from `unco`"
results = bq.query(sql)
row_counts = 0
for row in results:
bq_insert = bigquery.Client()
sql_insert = "insert into `benki` (a) values ('" + str(row.size) + "')"
logging.warning('### unco.size ' + str(row.size) + ' ###')
row_count += 1

#Python pubsubデータ藹??得(pubsub pushの場合)
requirements.txt
google-cloud-logging==3.2.2
----
import base64
import json
import google.cloud.logging
import logging
pubsub_data = base64.b64decode(event["data"]).decode("utf-8")
logging.warning('### pubsub data ' + str(pubsub_data) + ' ###')
json_pubsub_data = json.loads(pubsub_data)

#Python slack送菫?
requirements.txt
google-cloud-secret-manager==2.12.6
----
import requests
from google.cloud import secretmanager
import json
def slack_post(message):
client = secretmanager.SecretManagerServiceClient()
resource = "projects/12345678901/secrets/secretkey_xxx/versions/latest"
res = client.access_secret_version(name=resource)
slack_url = res.payload.data.decode("utf-8")
payload = {
"text": message,
}
notify = requests.post(slack_url,data=json.dumps(payload))
if notify.status_code != requests.codes.ok:
print("error")
else:
print("posted at slack url")
slack_post('続き縺?<http://yahoo.com| こちら>をクリックして縺?ださい)

@ .dockerignore
Dockerfile
README.md
*.pyc
*.pyo
*.pyd
__Pycache__
.pytest_cache

@ Dockerfile
FROM python:3.10-slim
ENV PYTHONUNBUFFERED True
ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./
RUN pip install --no-cache-dir -r requirements.txt
RUN pip install Flask gunicorn
CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app

@ Dockerfile
FROM python:3.10-slim
WORKDIR /app
COPY app /app
RUN pip install -r requirements.txt --proxy=http://proxy:3128
CMD["python", "main.py"]

■Slack通遏?
incoming webhookかSlack apiの最菴?2種饅??がある
Slack apiで縺?ts(timestamp)が藹??得できスレッド返信ができるが、incomingは投稿だけ。incomingは管理画面縺?URLを藹??得しそこ縺?Postすることで投稿ができる(URLのみで觸??洩すると誰でも投稿できる、ど縺?Slackアプリが投稿しているか分かるの縺?URLローテすれば良いが)。
api縺?Slack固藹??のエンドポイントがありトークンをベアラに入れチャネル名を指定して投稿ができる。管理画面でトークン藹??得と権限スコープの設定をし、チャネル側縺?apiアプリの藹??け入れをintegrations設藹??する
URLあるいはトークンをGCPシク繝?MGRに入れて、アプリで読縺?EP縺?http通信する
APIのテスト送信ができる

■Oauth関騾?
ローカルの場合(VirtualBoxとか)
 1) gcloudでログインをし縺?Python実行する
OauthクライアントIDの場合
 2) ローカ繝?Pythonを実行する縺?Authを聞いて縺?る>ブラウザが立ち臀??がる>ユーザ鐔??証に藹??繧?る
 3) Webアプリだ縺?JS縺?Authを聞縺?> 認証する縺?OauthクライアントIDでな縺?ユーザ鐔??証に藹??繧?る
設藹??方觸??
 OauthクライアントIDをOauth同諢?画髱?>クレデンシャルで臀??成
 デスクトップアプリは臀??記②、Webアプリは臀??記の③縺?ID作成する
 OauthクライアントIDをファイルかsecret mgrに入れ縺?Oauth認証通信をさせる
  竭?flow = InstalledAppFlow.from_client_secrets_file(credentials, SCOPES) 
  竭?flow = InstalledAppFlow.from_client_config(json.loads(credentials), SCOPES)
サービスアカウントの場合
 4) Cloud run等のサーバがOauth通信で鐔??証し外部サービスを使う
設藹??方觸??
 SAキーをファイルかsecret mgrに入れてプログラムからOauthで鐔??証させ外部サービスを使う
  EPはホスト名+パスだが、target_audienceはホスト名

GCP縺?Oauthについ縺?
https://www.marketechlabo.com/python-google-auth/

Docs API
https://developers.google.com/docs/api/how-tos/documents?hl=ja#python
https://rimever.hatenablog.com/entry/2019/10/16/060000
スコープ
https://developers.google.com/identity/protocols/oauth2/scopes?hl=ja#docs
google-api-python-client OAuth 2.0
https://googleapis.github.io/google-api-python-client/docs/oauth.html
Oauthライブラ繝?
https://google-auth.readthedocs.io/en/stable/reference/google.oauth2.credentials.html
https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html
https://googleapis.dev/python/google-auth-oauthlib/latest/reference/google_auth_oauthlib.helpers.html
https://google-auth-oauthlib.readthedocs.io/en/latest/_modules/google_auth_oauthlib/flow.html#Flow.from_client_config 
Oathライブラリのソースコード
https://github.com/googleapis/google-auth-library-python-oauthlib/blob/main/google_auth_oauthlib/helpers.py
OauthクライアントIDの臀??様
https://github.com/googleapis/google-api-python-client/blob/main/docs/client-secrets.md
サービスアカウントで藹??部サービス縺?APIを使う
https://www.coppla-note.net/posts/tutorial/google-calendar-api/
SAのサービス間認証の臀??様
https://cloud.google.com/run/docs/authenticating/service-to-service?hl=ja#use_the_authentication_libraries
Webアプリ縺?Oauth認險?
https://github.com/googleworkspace/python-samples/blob/main/drive/driveapp/main.py
https://stackoverflow.com/questions/10271110/python-oauth2-login-with-google

■Oauthについ縺?
下記の藹??な縺?とも下記の種類があり、クライアントライブラリやコード等々で違いで使い分ける必要がある。今回縺?SA+シク繝?mgrを使用した。
-ローカ繝?(gcloud auth login と鐔??險?)
-OauthクライアントID (アプリ臀??で鐔??証が個人ユーザに藹??き継がれる)
 -デスクトップ
 -Webアプ繝?(jsでサイト上)
-サービスアカウント
 -キーファイ繝?
 -シク繝?mgr

使用ライブラリーに注諢?
1) OauthクライアントID (ローカルファイ繝?)
from google_auth_oauthlib flow import InstalledAppFlow
flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
creds flow.run_local_server(port=0)

2) ローカルにおいたSAキ繝?
from google auth import load_credentials_from_file
creds = load_credentials_from_file('credentials.json', SCOPES)[0]

3) Secret mgrにおいたSAキ繝?
import json
from google.oauth2.service_account import Credentials
from google.cloud import secretmanager
client = secretmanager.SecretManagerServiceClient()
resource_name = "projects/()/secrets/{}/versions/latest" format(project_num, secret_name)
res = client.access_secret_version(name=resource_name)
credentials = res.payload.data.decode("utf-8")
cred_dict=json.loads(credentials)
creds = Credentials.from_service_account_info(cred_dict, scopes=SCOPES)
creds.refresh(Request())

窶?) これは使繧?ない
from google.oauth2.service_account import IDTokenCredentials
#ファイルから
credentials = IDTokenCredentials.from_service_account_file(service_account,target_audience=target_audience)
#シク繝?mgrから
credentials = IDTokenCredentials.from_service_account_info(service_account.target_audience=target_audience)

ライブラリーのソースコード本臀??や仕様譖?
https://github.com/googleapis/google-auth-library-python-oauthlib/blob/main/google_auth_oauthlib/helpers.py
https://googleapis.dev/python/google-auth-oauthlib/latest/reference/google_auth_oauthlib.helpers.html
https://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html
https://google-auth-oauthlib.readthedocs.io/en/latest/_modules/google_auth_oauthlib/flow.html#Flow.from_client_config

サービスアカウントのライブラリ情蝣?
https://google-auth.readthedocs.io/en/master/reference/google.auth.html
https://google-auth.readthedocs.io/en/master/reference/google.oauth2.service_account.html#module-google.oauth2.service_account
https://qiita.com/que9/items/38ff57831ea0e435b517


Posted by funa : 12:00 AM | Web | Comment (0) | Trackback (0)