本指南介紹如何使用 Google ArtifactRegistry 將共享 Python 程式碼作為套件進行管理。這種方法消除了 Cloud Functions 和伺服器之間的程式碼重複。
為您的共享邏輯建立一個新的 Python 套件(例如 common_logic)。
common_logic/ ├── setup.py ├── common_logic/ │ ├── __init__.py
在 setup.py 檔案中定義你的套件配置:
common_logic/ ├── setup.py ├── common_logic/ │ ├── __init__.py
from setuptools import setup, find_packages setup( name="common_logic", version="0.1.0", packages=find_packages(), install_requires=[ "pandas>=1.3.0", ], author="Your Name", author_email="your.email@example.com", description="Common logic for app", )
gcloud services enable artifactregistry.googleapis.com
gcloud artifacts repositories create python-packages \ --repository-format=python \ --location=us-central1 \ --description="Python packages repository"
gcloud iam service-accounts create artifact-publisher \ --description="Service account for publishing to Artifact Registry"
gcloud artifacts repositories add-iam-policy-binding python-packages \ --location=us-central1 \ --member="serviceAccount:artifact-publisher@${PROJECT_ID}.iam.gserviceaccount.com" \ --role="roles/artifactregistry.writer"
gcloud iam service-accounts keys create key.json \ --iam-account=artifact-publisher@${PROJECT_ID}.iam.gserviceaccount.com
pip install build twine
python -m build
cat > ~/.pypirc << EOL [distutils] index-servers = common-logic-repo [common-logic-repo] repository: https://us-central1-python.pkg.dev/${PROJECT_ID}/python-packages/ username: _json_key_base64 password: $(base64 -w0 key.json) EOL
twine upload --repository common-logic-repo dist/*
--index-url https://pypi.org/simple --extra-index-url https://oauth2accesstoken:${ARTIFACT_REGISTRY_TOKEN}@us-central1-python.pkg.dev/${PROJECT_ID}/python-packages/simple/ common-logic==0.1.0
from common_logic import ... def cloud_function(request): # Your cloud function code using the imported functions pass
--index-url https://pypi.org/simple --extra-index-url https://oauth2accesstoken:${ARTIFACT_REGISTRY_TOKEN}@us-central1-python.pkg.dev/${PROJECT_ID}/python-packages/simple/ common-logic==0.1.0
from common_logic import ... # Your server code using the imported functions
以上是GCP 在生產中發布 python 包的詳細內容。更多資訊請關注PHP中文網其他相關文章!