Home >Backend Development >Python Tutorial >GCP publish python package in production
This guide explains how to use Google Artifact Registry to manage shared Python code as a package. This approach eliminates code duplication between your Cloud Functions and server.
Create a new Python package for your shared logic (e.g., common_logic).
common_logic/ ├── setup.py ├── common_logic/ │ ├── __init__.py
Define your package configuration in a setup.py file:
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
The above is the detailed content of GCP publish python package in production. For more information, please follow other related articles on the PHP Chinese website!