Skip to content

Instantly share code, notes, and snippets.

@trisgelar
Created February 28, 2023 15:01
Show Gist options
  • Save trisgelar/dec54e5157689f465ec4fa13f92d37c2 to your computer and use it in GitHub Desktop.
Save trisgelar/dec54e5157689f465ec4fa13f92d37c2 to your computer and use it in GitHub Desktop.
ILT_Snippets_Bangkit2023

Django on GCP

GC Dev CLI

curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-cli-419.0.0-linux-x86_64.tar.gz
tar -xf google-cloud-cli-419.0.0-linux-x86.tar.gz
./google-cloud-sdk/install.sh --help
./google-cloud-sdk/bin/gcloud init

Initiate

gcloud init

Screenshoot

Welcome! This command will take you through the configuration of gcloud.

Settings from your current configuration [default] are:
core:
  account: xyz@gmail.com
  disable_usage_reporting: 'True'
  project: ilt01-cc-bangkit2023-tg

Pick configuration to use:
 [1] Re-initialize this configuration [default] with new settings 
 [2] Create a new configuration
Please enter your numeric choice:  

1

Your current configuration has been set to: [default]

You can skip diagnostics next time by using the following flag:
  gcloud init --skip-diagnostics

Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.                                            
Reachability Check passed.
Network diagnostic passed (1/1 checks passed).

Choose the account you would like to use to perform operations for this 
configuration:
 [1] xyz@gmail.com
 [2] Log in with a new account
Please enter your numeric choice:  1


You are logged in as: [xyz@gmail.com].

Pick cloud project to use: 
 [1] decent-essence-335514
 [2] ilt01-cc-bangkit2023-tg
 [3] ilt4-gcf-fizzbuzz
 [4] Enter a project ID
 [5] Create a new project
Please enter numeric choice or text value (must exactly match list item):  
2


Your current project has been set to: [ilt01-cc-bangkit2023-tg].

Not setting default zone/region (this feature makes it easier to use
[gcloud compute] by setting an appropriate default value for the
--zone and --region flag).
See https://cloud.google.com/compute/docs/gcloud-compute section on how to set
default compute region and zone manually. If you would like [gcloud init] to be
able to do this for you the next time you run it, make sure the
Compute Engine API is enabled for your project on the
https://console.developers.google.com/apis page.

Your Google Cloud SDK is configured and ready to use!

* Commands that require authentication will use xyz@gmail.com by default
* Commands will reference project `ilt01-cc-bangkit2023-tg` by default
Run `gcloud help config` to learn how to change individual settings

This gcloud configuration is called [default]. You can create additional configurations if you work with multiple accounts and/or projects.
Run `gcloud topic configurations` to learn more.

Some things to try next:

* Run `gcloud --help` to see the Cloud Platform services you can interact with. And run `gcloud help COMMAND` to get help on any gcloud command.
* Run `gcloud topic --help` to learn about advanced features of the SDK like arg files and output formatting
* Run `gcloud cheat-sheet` to see a roster of go-to `gcloud` commands.

Do you want to configure a default Compute Region and Zone? (Y/n)?  y

Which Google Compute Engine zone would you like to use as project default?
If you do not specify a zone via a command line flag while working with Compute 
Engine resources, the default is assumed.
 [1] us-east1-b
 [2] us-east1-c

 56

List of Zones

gcloud compute zones list

Screenshoot

API [compute.googleapis.com] not enabled on project [561132442140]. Would you 
like to enable and retry (this will take a few minutes)? (y/N)?

Operation "operations/acf.p2-561132442140-bceedfe2-fe31-4c38-a040-413a6796091c" finished successfully.
NAME                       REGION                   STATUS  NEXT_MAINTENANCE  TURNDOWN_DATE
us-east1-b                 us-east1                 UP
us-east1-c                 us-east1                 UP
us-east1-d                 us-east1                 UP
us-east4-c                 us-east4                 UP
us-east4-b                 us-east4                 UP
us-east4-a                 us-east4                 UP
us-central1-c              us-central1              UP
us-central1-a              us-central1              UP
us-central1-f              us-central1              UP
us-central1-b              us-central1              UP
us-west1-b                 us-west1                 UP
us-west1-c                 us-west1                 UP
us-west1-a                 us-west1                 UP
europe-west4-a             europe-west4             UP
europe-west4-b             europe-west4             UP
europe-west4-c             europe-west4             UP
europe-west1-b             europe-west1             UP
europe-west1-d             europe-west1             UP
europe-west1-c             europe-west1             UP
europe-west3-c             europe-west3             UP
europe-west3-a             europe-west3             UP
europe-west3-b             europe-west3             UP
europe-west2-c             europe-west2             UP
europe-west2-b             europe-west2             UP
europe-west2-a             europe-west2             UP
asia-east1-b               asia-east1               UP
asia-east1-a               asia-east1               UP
asia-east1-c               asia-east1               UP
asia-southeast1-b          asia-southeast1          UP
asia-southeast1-a          asia-southeast1          UP
asia-southeast1-c          asia-southeast1          UP
asia-northeast1-b          asia-northeast1          UP
asia-northeast1-c          asia-northeast1          UP
asia-northeast1-a          asia-northeast1          UP
asia-south1-c              asia-south1              UP
asia-south1-b              asia-south1              UP
asia-south1-a              asia-south1              UP
australia-southeast1-b     australia-southeast1     UP
australia-southeast1-c     australia-southeast1     UP
australia-southeast1-a     australia-southeast1     UP
southamerica-east1-b       southamerica-east1       UP
southamerica-east1-c       southamerica-east1       UP
southamerica-east1-a       southamerica-east1       UP
asia-east2-a               asia-east2               UP
asia-east2-b               asia-east2               UP
asia-east2-c               asia-east2               UP
asia-northeast2-a          asia-northeast2          UP
asia-northeast2-b          asia-northeast2          UP
asia-northeast2-c          asia-northeast2          UP
asia-northeast3-a          asia-northeast3          UP
asia-northeast3-b          asia-northeast3          UP
asia-northeast3-c          asia-northeast3          UP
asia-south2-a              asia-south2              UP
asia-south2-b              asia-south2              UP
asia-south2-c              asia-south2              UP
asia-southeast2-a          asia-southeast2          UP
asia-southeast2-b          asia-southeast2          UP
asia-southeast2-c          asia-southeast2          UP
australia-southeast2-a     australia-southeast2     UP
australia-southeast2-b     australia-southeast2     UP
australia-southeast2-c     australia-southeast2     UP
europe-central2-a          europe-central2          UP
europe-central2-b          europe-central2          UP
europe-central2-c          europe-central2          UP
europe-north1-a            europe-north1            UP
europe-north1-b            europe-north1            UP
europe-north1-c            europe-north1            UP
europe-southwest1-a        europe-southwest1        UP
europe-southwest1-b        europe-southwest1        UP
europe-southwest1-c        europe-southwest1        UP
europe-west6-a             europe-west6             UP
europe-west6-b             europe-west6             UP
europe-west6-c             europe-west6             UP
europe-west8-a             europe-west8             UP
europe-west8-b             europe-west8             UP
europe-west8-c             europe-west8             UP
europe-west9-a             europe-west9             UP
europe-west9-b             europe-west9             UP
europe-west9-c             europe-west9             UP
me-west1-a                 me-west1                 UP
me-west1-b                 me-west1                 UP
me-west1-c                 me-west1                 UP
northamerica-northeast1-a  northamerica-northeast1  UP
northamerica-northeast1-b  northamerica-northeast1  UP
northamerica-northeast1-c  northamerica-northeast1  UP
northamerica-northeast2-a  northamerica-northeast2  UP
northamerica-northeast2-b  northamerica-northeast2  UP
northamerica-northeast2-c  northamerica-northeast2  UP
southamerica-west1-a       southamerica-west1       UP
southamerica-west1-b       southamerica-west1       UP
southamerica-west1-c       southamerica-west1       UP
us-east5-a                 us-east5                 UP
us-east5-b                 us-east5                 UP
us-east5-c                 us-east5                 UP
us-south1-a                us-south1                UP
us-south1-b                us-south1                UP
us-south1-c                us-south1                UP
us-west2-a                 us-west2                 UP
us-west2-b                 us-west2                 UP
us-west2-c                 us-west2                 UP
us-west3-a                 us-west3                 UP
us-west3-b                 us-west3                 UP
us-west3-c                 us-west3                 UP
us-west4-a                 us-west4                 UP
us-west4-b                 us-west4                 UP
us-west4-c                 us-west4                 UP

GAP Create App

gcloud app create

Screenshoot

You are creating an app for project [ilt01-cc-bangkit2023-tg].
WARNING: Creating an App Engine application for a project is irreversible and the region
cannot be changed. More information about regions is at
<https://cloud.google.com/appengine/docs/locations>.

Please choose the region where you want your App Engine application located:

 [1] asia-east1    (supports standard and flexible)
 [2] asia-east2    (supports standard and flexible and search_api)
 [3] asia-northeast1 (supports standard and flexible and search_api)
 [4] asia-northeast2 (supports standard and flexible and search_api)
 [5] asia-northeast3 (supports standard and flexible and search_api)
 [6] asia-south1   (supports standard and flexible and search_api)
 [7] asia-southeast1 (supports standard and flexible)
 [8] asia-southeast2 (supports standard and flexible and search_api)
 [9] australia-southeast1 (supports standard and flexible and search_api)
 [10] europe-central2 (supports standard and flexible)
 [11] europe-west   (supports standard and flexible and search_api)
 [12] europe-west2  (supports standard and flexible and search_api)
 [13] europe-west3  (supports standard and flexible and search_api)
 [14] europe-west6  (supports standard and flexible and search_api)
 [15] northamerica-northeast1 (supports standard and flexible and search_api)
 [16] southamerica-east1 (supports standard and flexible and search_api)
 [17] us-central    (supports standard and flexible and search_api)
 [18] us-east1      (supports standard and flexible and search_api)
 [19] us-east4      (supports standard and flexible and search_api)
 [20] us-west1      (supports standard and flexible)
 [21] us-west2      (supports standard and flexible and search_api)
 [22] us-west3      (supports standard and flexible and search_api)
 [23] us-west4      (supports standard and flexible and search_api)
 [24] cancel
Please enter your numeric choice:  8

Creating App Engine application in project [ilt01-cc-bangkit2023-tg] and region
 [asia-southeast2]....done.                                                    
Success! The app is now created. Please use `gcloud app deploy` to deploy your first app.

Preparing Python Environment

git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git
cd python-docs-samples/appengine/standard_python3/django
python3 -V
python3 -m venv venv

### Screenshoot
```sh
The virtual environment was not created successfully because ensurepip is not
available.  On Debian/Ubuntu systems, you need to install the python3-venv
package using the following command.

    apt install python3.8-venv

You may need to use sudo with that command.  After installing the python3-venv
package, recreate your virtual environment.

Failing command: ['/home/dicoding/Projects/ilt-01-demo/python-docs-samples/appengine/standard_python3/django/venv/bin/python3', '-Im', 'ensurepip', '--upgrade', '--default-pip']

sudo apt-get install python3.8-venv
```sh

## Preparing Python Environment 2

python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt

### Screenshoot CLI
?  django git:(main) python3 -m venv venv
?  django git:(main) ls
app.yaml  manage.py  noxfile_config.py  README.md              requirements.txt
main.py   mysite     polls              requirements-test.txt  venv
?  django git:(main) source venv/bin/activate
(venv) ?  django git:(main) pip install --upgrade pip
Collecting pip
  Downloading pip-23.0.1-py3-none-any.whl (2.1 MB)
     |????????????????????????????????| 2.1 MB 2.7 MB/s 
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.0.2
    Uninstalling pip-20.0.2:
      Successfully uninstalled pip-20.0.2
Successfully installed pip-23.0.1

(venv) ?  django git:(main) pip install -r requirements.txt 
Ignoring Django: markers python_version < "3.8" dont match your environment
Collecting Django==4.0.4
  Downloading Django-4.0.4-py3-none-any.whl (8.0 MB)
     ???????????????????????????????????????? 8.0/8.0 MB 3.8 MB/s eta 0:00:00
Collecting django-environ==0.9.0
  Downloading django_environ-0.9.0-py2.py3-none-any.whl (17 kB)
Collecting psycopg2-binary==2.9.5
  Downloading psycopg2_binary-2.9.5-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.0 MB)
     ???????????????????????????????????????? 3.0/3.0 MB 3.5 MB/s eta 0:00:00
Collecting google-cloud-secret-manager==2.12.0
  Downloading google_cloud_secret_manager-2.12.0-py2.py3-none-any.whl (98 kB)
     ???????????????????????????????????????? 98.2/98.2 kB 3.5 MB/s eta 0:00:00
Collecting sqlparse>=0.2.2
  Downloading sqlparse-0.4.3-py3-none-any.whl (42 kB)
     ???????????????????????????????????????? 42.8/42.8 kB 3.6 MB/s eta 0:00:00
Collecting asgiref<4,>=3.4.1
  Downloading asgiref-3.6.0-py3-none-any.whl (23 kB)
Collecting backports.zoneinfo
  Downloading backports.zoneinfo-0.2.1-cp38-cp38-manylinux1_x86_64.whl (74 kB)
     ???????????????????????????????????????? 74.0/74.0 kB 3.5 MB/s eta 0:00:00
Collecting grpc-google-iam-v1<1.0.0dev,>=0.12.4
  Downloading grpc_google_iam_v1-0.12.6-py2.py3-none-any.whl (26 kB)
Collecting proto-plus<2.0.0dev,>=1.15.0
  Downloading proto_plus-1.22.2-py3-none-any.whl (47 kB)
     ???????????????????????????????????????? 47.9/47.9 kB 4.0 MB/s eta 0:00:00
Collecting google-api-core[grpc]!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,<3.0.0dev,>=1.32.0
  Downloading google_api_core-2.11.0-py3-none-any.whl (120 kB)
     ??????????????????????????????????????? 120.3/120.3 kB 4.2 MB/s eta 0:00:00
Collecting protobuf<4.0.0dev,>=3.19.0
  Downloading protobuf-3.20.3-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl (1.0 MB)
     ???????????????????????????????????????? 1.0/1.0 MB 3.0 MB/s eta 0:00:00
Collecting googleapis-common-protos<2.0dev,>=1.56.2
  Downloading googleapis_common_protos-1.58.0-py2.py3-none-any.whl (223 kB)
     ??????????????????????????????????????? 223.0/223.0 kB 3.6 MB/s eta 0:00:00
Collecting requests<3.0.0dev,>=2.18.0
  Downloading requests-2.28.2-py3-none-any.whl (62 kB)
     ???????????????????????????????????????? 62.8/62.8 kB 2.6 MB/s eta 0:00:00
Collecting google-auth<3.0dev,>=2.14.1
  Downloading google_auth-2.16.1-py2.py3-none-any.whl (177 kB)
     ??????????????????????????????????????? 177.2/177.2 kB 3.9 MB/s eta 0:00:00
Collecting grpcio-status<2.0dev,>=1.33.2
  Downloading grpcio_status-1.51.3-py3-none-any.whl (5.1 kB)
Collecting grpcio<2.0dev,>=1.33.2
  Downloading grpcio-1.51.3-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.8 MB)
     ???????????????????????????????????????? 4.8/4.8 MB 2.8 MB/s eta 0:00:00
Collecting six>=1.9.0
  Downloading six-1.16.0-py2.py3-none-any.whl (11 kB)
Collecting rsa<5,>=3.1.4
  Downloading rsa-4.9-py3-none-any.whl (34 kB)
Collecting pyasn1-modules>=0.2.1
  Downloading pyasn1_modules-0.2.8-py2.py3-none-any.whl (155 kB)
     ??????????????????????????????????????? 155.3/155.3 kB 3.3 MB/s eta 0:00:00
Collecting cachetools<6.0,>=2.0.0
  Downloading cachetools-5.3.0-py3-none-any.whl (9.3 kB)
Collecting grpcio-status<2.0dev,>=1.33.2
  Downloading grpcio_status-1.51.1-py3-none-any.whl (5.1 kB)
  Downloading grpcio_status-1.50.0-py3-none-any.whl (14 kB)
  Downloading grpcio_status-1.49.1-py3-none-any.whl (14 kB)
  Downloading grpcio_status-1.48.2-py3-none-any.whl (14 kB)
Collecting idna<4,>=2.5
  Downloading idna-3.4-py3-none-any.whl (61 kB)
     ???????????????????????????????????????? 61.5/61.5 kB 3.9 MB/s eta 0:00:00
Collecting certifi>=2017.4.17
  Downloading certifi-2022.12.7-py3-none-any.whl (155 kB)
     ??????????????????????????????????????? 155.3/155.3 kB 3.4 MB/s eta 0:00:00
Collecting charset-normalizer<4,>=2
  Downloading charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (195 kB)
     ??????????????????????????????????????? 195.4/195.4 kB 3.2 MB/s eta 0:00:00
Collecting urllib3<1.27,>=1.21.1
  Downloading urllib3-1.26.14-py2.py3-none-any.whl (140 kB)
     ??????????????????????????????????????? 140.6/140.6 kB 1.8 MB/s eta 0:00:00
Collecting pyasn1<0.5.0,>=0.4.6
  Downloading pyasn1-0.4.8-py2.py3-none-any.whl (77 kB)
     ???????????????????????????????????????? 77.1/77.1 kB 2.3 MB/s eta 0:00:00
Installing collected packages: pyasn1, charset-normalizer, urllib3, sqlparse, six, rsa, pyasn1-modules, psycopg2-binary, protobuf, idna, grpcio, django-environ, certifi, cachetools, backports.zoneinfo, asgiref, requests, proto-plus, googleapis-common-protos, google-auth, Django, grpcio-status, google-api-core, grpc-google-iam-v1, google-cloud-secret-manager
Successfully installed Django-4.0.4 asgiref-3.6.0 backports.zoneinfo-0.2.1 cachetools-5.3.0 certifi-2022.12.7 charset-normalizer-3.0.1 django-environ-0.9.0 google-api-core-2.11.0 google-auth-2.16.1 google-cloud-secret-manager-2.12.0 googleapis-common-protos-1.58.0 grpc-google-iam-v1-0.12.6 grpcio-1.51.3 grpcio-status-1.48.2 idna-3.4 proto-plus-1.22.2 protobuf-3.20.3 psycopg2-binary-2.9.5 pyasn1-0.4.8 pyasn1-modules-0.2.8 requests-2.28.2 rsa-4.9 six-1.16.0 sqlparse-0.4.3 urllib3-1.26.14


## Cloud SQL 
gcloud auth application-default login

### Screenshoot
```sh
(venv) ?  django git:(main) gcloud auth application-default login
Your browser has been opened to visit:
    https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2F&scope=openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fsqlservice.login+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Faccounts.reauth&state=5InhEOWdQnkCQEGUyZCowbq45klh99&access_type=offline&code_challenge=U-IDH329ppbpN_s6Ow2xIgsdnoe5dXex30snuh0hXps&code_challenge_method=S256
Credentials saved to file: [/home/dicoding/.config/gcloud/application_default_credentials.json]

These credentials will be used by any library that requests Application Default Credentials (ADC).

Quota project "ilt01-cc-bangkit2023-tg" was added to ADC which can be used by Google client libraries for billing and quota. Note that some services may still bill the project owning the resource.

Cloud SQL Proxy

curl -o cloud-sql-proxy
https://storage.googleapis.com/cloud-sql-connectors/cloud-sql-proxy/v2.0.0/cloud-sql-proxy.linux.amd64

chmod +x cloud-sql-proxy

Cloud SQL Initiation

export INSTANCE_NAME="ilt01-cc-bangkit2023-tg-sql" export PROJECT_ID="ilt01-cc-bangkit2023-tg" export DATABASE_USERNAME="ilt01-cc-bangkit2023-tg-user" export DATABASE_NAME="ilt01-cc-bangkit2023-tg-db" export DATABASE_PASSWORD="xyz" export REGION="asia-southeast2" export PROJECT_ID_MEDIA_BUCKET="ilt01-cc-bangkit2023-tg-bucket"

gcloud sql instances create $INSTANCE_NAME
--project $PROJECT_ID
--database-version POSTGRES_13
--tier db-f1-micro
--region $REGION

gcloud sql databases create $DATABASE_NAME
--instance $INSTANCE_NAME

gcloud sql users create $DATABASE_USERNAME
--instance $INSTANCE_NAME
--password $DATABASE_PASSWORD

echo DATABASE_URL=postgres://$DATABASE_USERNAME:$DATABASE_PASSWORD@//cloudsql/$PROJECT_ID:$REGION:$INSTANCE_NAME/$DATABASE_NAME > .env echo GS_BUCKET_NAME=$PROJECT_ID_MEDIA_BUCKET >> .env echo SECRET_KEY=$(cat /dev/urandom | LC_ALL=C tr -dc '[:alpha:]'| fold -w 50 | head -n1) >> .env

Screenshoot

export INSTANCE_NAME="ilt01-cc-bangkit2023-tg-sql"
export PROJECT_ID="ilt01-cc-bangkit2023-tg"
export DATABASE_USERNAME="ilt01-cc-bangkit2023-tg-user"
export DATABASE_NAME="ilt01-cc-bangkit2023-tg-db"
export DATABASE_PASSWORD="xyz"
export REGION="asia-southeast2"
export PROJECT_ID_MEDIA_BUCKET="ilt01-cc-bangkit2023-tg-bucket"

(venv) ?  django git:(main) gcloud sql instances create $INSTANCE_NAME \
    --project $PROJECT_ID \
    --database-version POSTGRES_13 \
    --tier db-f1-micro \
    --region $REGION
API [sqladmin.googleapis.com] not enabled on project [561132442140]. Would you 
like to enable and retry (this will take a few minutes)? (y/N)?  y

Enabling service [sqladmin.googleapis.com] on project [561132442140]...
Operation "operations/acat.p2-561132442140-834286d5-037e-4abe-bf19-d8083706cffe" finished successfully.
Creating Cloud SQL instance for POSTGRES_13...?                                
Creating Cloud SQL instance for POSTGRES_13...?                                
Creating Cloud SQL instance for POSTGRES_13...done.                            
Created [https://sqladmin.googleapis.com/sql/v1beta4/projects/ilt01-cc-bangkit2023-tg/instances/ilt01-cc-bangkit2023-tg-sql].
NAME                         DATABASE_VERSION  LOCATION           TIER         PRIMARY_ADDRESS  PRIVATE_ADDRESS  STATUS
ilt01-cc-bangkit2023-tg-sql  POSTGRES_13       asia-southeast2-a  db-f1-micro  34.101.177.210   -                RUNNABLE


(venv) ?  django git:(main) gcloud sql databases create $DATABASE_NAME \
    --instance $INSTANCE_NAME
Creating Cloud SQL database...done.                                            
Created database [ilt01-cc-bangkit2023-tg-db].
instance: ilt01-cc-bangkit2023-tg-sql
name: ilt01-cc-bangkit2023-tg-db
project: ilt01-cc-bangkit2023-tg


(venv) ?  django git:(main) gcloud sql users create $DATABASE_USERNAME \
    --instance $INSTANCE_NAME \
    --password $DATABASE_PASSWORD
Creating Cloud SQL user...done.                                                
Created user [ilt01-cc-bangkit2023-tg-user].


(venv) ?  django git:(main) echo DATABASE_URL=postgres://$DATABASE_USERNAME:$DATABASE_PASSWORD@//cloudsql/$PROJECT_ID:$REGION:$INSTANCE_NAME/$DATABASE_NAME > .env
echo GS_BUCKET_NAME=$PROJECT_ID_MEDIA_BUCKET >> .env
echo SECRET_KEY=$(cat /dev/urandom | LC_ALL=C tr -dc '[:alpha:]'| fold -w 50 | head -n1) >> .env


(venv) ?  django git:(main) cat .env
DATABASE_URL=postgres://ilt01-cc-bangkit2023-tg-user:NNv9F3zSewY7JJR@//cloudsql/ilt01-cc-bangkit2023-tg:asia-southeast2:ilt01-cc-bangkit2023-tg-sql/ilt01-cc-bangkit2023-tg-db
GS_BUCKET_NAME=ilt01-cc-bangkit2023-tg-bucket
SECRET_KEY=jyjYPKAitJVNFbDzImozFVNxJrvTFgoZSnLIrHZykcVuaGoXAH

Cloud SQL Secret Initiation

gcloud secrets create django_settings --data-file .env

gcloud secrets describe django_settings
gcloud secrets versions access latest --secret django_settings

rm .env

gcloud secrets add-iam-policy-binding django_settings \
    --member serviceAccount:$PROJECT_ID@appspot.gserviceaccount.com \
    --role roles/secretmanager.secretAccessor

cloud-sql-proxy $PROJECT_ID:$REGION:$INSTANCE_NAME

Screenshoot

(venv) ?  django git:(main) gcloud secrets create django_settings --data-file .env
API [secretmanager.googleapis.com] not enabled on project [561132442140]. Would 
you like to enable and retry (this will take a few minutes)? (y/N)?  y

Enabling service [secretmanager.googleapis.com] on project [561132442140]...
Operation "operations/acat.p2-561132442140-5d19cc6f-030e-489e-b84d-ac44bed35ea1" finished successfully.
Created version [1] of the secret [django_settings].

(venv) ?  django git:(main) gcloud secrets describe django_settings
gcloud secrets versions access latest --secret django_settings
createTime: '2023-02-28T14:05:50.941756Z'
etag: '"15f5c317d6ea3c"'
name: projects/561132442140/secrets/django_settings
replication:
  automatic: {}
DATABASE_URL=postgres://ilt01-cc-bangkit2023-tg-user:NNv9F3zSewY7JJR@//cloudsql/ilt01-cc-bangkit2023-tg:asia-southeast2:ilt01-cc-bangkit2023-tg-sql/ilt01-cc-bangkit2023-tg-db
GS_BUCKET_NAME=ilt01-cc-bangkit2023-tg-bucket
SECRET_KEY=jyjYPKAitJVNFbDzImozFVNxJrvTFgoZSnLIrHZykcVuaGoXAH


(venv) ?  django git:(main) gcloud secrets add-iam-policy-binding django_settings \
    --member serviceAccount:$PROJECT_ID@appspot.gserviceaccount.com \
    --role roles/secretmanager.secretAccessor
Updated IAM policy for secret [django_settings].
bindings:
- members:
  - serviceAccount:ilt01-cc-bangkit2023-tg@appspot.gserviceaccount.com
  role: roles/secretmanager.secretAccessor
etag: BwX1wx3Dlwo=
version: 1
(venv) ?  django git:(main) 


(venv) ?  django git:(main) cloud-sql-proxy $PROJECT_ID:$REGION:$INSTANCE_NAME
2023/02/28 21:07:50 Authorizing with Application Default Credentials
2023/02/28 21:07:51 [ilt01-cc-bangkit2023-tg:asia-southeast2:ilt01-cc-bangkit2023-tg-sql] Listening on 127.0.0.1:5432
2023/02/28 21:07:51 The proxy has started successfully and is ready for new connections!


Django Local Initiation

export GOOGLE_CLOUD_PROJECT=$PROJECT_ID export USE_CLOUD_SQL_AUTH_PROXY=true python manage.py makemigrations python manage.py makemigrations polls python manage.py migrate python manage.py collectstatic python manage.py runserver 8080 python manage.py createsuperuser python manage.py runserver

Screenshot

(venv) ? django git:(main) export GOOGLE_CLOUD_PROJECT=$PROJECT_ID (venv) ? django git:(main) export USE_CLOUD_SQL_AUTH_PROXY=true

(venv) ? django git:(main) python manage.py makemigrations

No changes detected (venv) ? django git:(main) python manage.py makemigrations polls

Migrations for 'polls': polls/migrations/0001_initial.py - Create model Question - Create model Choice (venv) ? django git:(main) python manage.py migrate

Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_alter_user_first_name_max_length... OK Applying polls.0001_initial... OK Applying sessions.0001_initial... OK (venv) ? django git:(main) python manage.py collectstatic

128 static files copied to '/home/dicoding/Projects/ilt-01-demo/python-docs-samples/appengine/standard_python3/django/static'. (venv) ? django git:(main) ? python manage.py runserver 8080

Performing system checks...

System check identified no issues (0 silenced). February 28, 2023 - 14:11:02 Django version 4.0.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8080/ Quit the server with CONTROL-C. [28/Feb/2023 14:11:07] "GET / HTTP/1.1" 200 81 [28/Feb/2023 14:11:07] "GET /favicon.ico HTTP/1.1" 404 179 ^C% (venv) ? django git:(main) ? python manage.py createsuperuser

Username (leave blank to use 'dicoding'): admin Email address: admin@admin.com Password: Password (again): Superuser created successfully. (venv) ? django git:(main) ?

Deploy to gcloud

gcloud app deploy

(venv) ?  django git:(main) ? gcloud app deploy
Services to deploy:

descriptor:                  [/home/dicoding/Projects/ilt-01-demo/python-docs-samples/appengine/standard_python3/django/app.yaml]
source:                      [/home/dicoding/Projects/ilt-01-demo/python-docs-samples/appengine/standard_python3/django]
target project:              [ilt01-cc-bangkit2023-tg]
target service:              [default]
target version:              [20230228t211603]
target url:                  [https://ilt01-cc-bangkit2023-tg.et.r.appspot.com]
target service account:      [App Engine default service account]


Do you want to continue (Y/n)?  y

Beginning deployment of service [default]...
??????????????????????????????????????????????????????????????
?? Uploading 150 files to Google Cloud Storage              ??
??????????????????????????????????????????????????????????????
File upload done.
Updating service [default]...done.                                             
Setting traffic split for service [default]...done.                            
Deployed service [default] to [https://ilt01-cc-bangkit2023-tg.et.r.appspot.com]

You can stream logs from the command line by running:
  $ gcloud app logs tail -s default

To view your application in the web browser run:
  $ gcloud app browse
(venv) ?  django git:(main) ? 
env_variables:
    APPENGINE_URL: https://PROJECT_ID.uc.r.appspot.com
gcloud app deploy

Browse Django

gcloud app browse

gcloud app describe --format "value(defaultHostname)"

PRODUCTION READY

export DATABASE_USERNAME_PROD="ilt01-cc-bangkit2023-tg-prod" export DATABASE_PASSWORD_PROD="xyz"

gcloud sql connect $INSTANCE_NAME --user postgres

CREATE USER $DATABASE_USERNAME_PROD WITH PASSWORD $DATABASE_PASSWORD_PROD;

GRANT ALL PRIVILEGES ON DATABASE $DATABASE_NAME TO $DATABASE_USERNAME_PROD;

\q

Reference

https://cloud.google.com/python/django/appengine#gcloud

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment