Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Managed VMs Django Example #152

Merged
merged 1 commit into from
Jan 5, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,6 @@ coverage.xml
nosetests.xml
python-docs-samples.json
__pycache__
*db\.sqlite3
managed_vms/django_tutorial/static/*
**/migrations/*
20 changes: 20 additions & 0 deletions managed_vms/django_tutorial/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
.dockerignore
Dockerfile
db.sqlite3
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add .dockerignore and Dockerfile at the top here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

__pycache__
*.pyc
*.pyo
*.pyd
.Python
env
pip-log.txt
pip-delete-this-directory.txt
.tox
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
*.log
.git
41 changes: 41 additions & 0 deletions managed_vms/django_tutorial/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Copyright 2015, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# [START docker]

# The Google App Engine python runtime is Debian Jessie with Python installed
# and various os-level packages to allow installation of popular Python
# libraries. The source is on github at:
# https://github.com/GoogleCloudPlatform/python-docker
FROM gcr.io/google_appengine/python

# Create a virtualenv for the application dependencies.
# # If you want to use Python 3, add the -p python3.4 flag.
RUN virtualenv /env

# Set virtualenv environment variables. This is equivalent to running
# source /env/bin/activate. This ensures the application is executed within
# the context of the virtualenv and will have access to its dependencies.
ENV VIRTUAL_ENV /env
ENV PATH /env/bin:$PATH

# Install dependencies.
ADD requirements.txt /app/requirements.txt
RUN /env/bin/pip install -r /app/requirements.txt

# Add Application code
ADD . /app

CMD gunicorn -b :$PORT mysite.wsgi
# [END docker]
114 changes: 114 additions & 0 deletions managed_vms/django_tutorial/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# Getting started with Django on Google Cloud Platform

This repository is an example of how to run a [Django](https://www.djangoproject.com/)
app on Google Managed VMs. It uses the [Writing your first Django app](https://docs.djangoproject.com/en/1.9/intro/tutorial01/) as the example app to deploy.


## Setup the database

This tutorial assumes you are setting up Django using a SQL database, which is the easiest way to run Django. If you have an existing SQL database running, you can use that, but if not, these are the instructions for creating a managed MySQL instance using CloudSQL.


* Create a [CloudSQL instance](https://console.cloud.google.com/project/_/sql/create)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These instructions go out of date so quickly. Do you think it would be better to provide the gcloud commands instead? You could mention that it's possible through the console.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The creation of instance and allowed networks can be done through gcloud, which I added as an option. The creation of the database and user is currently available in the API but not implemented in the gcloud tool, so instead I mention you can alternatively do the steps using your MySQL client.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks.


* In the instances list, click your Cloud SQL instance.

* Click Access Control.

* In the IP address subsection, click Request an IPv4 address to enable access to the Cloud SQL instance through an
IPv4 address. It will take a moment to initialize the new IP address.

* Also under Access Control, in the Authorization subsection, under Allowed Networks, click the add (+) button .

* In the Networks field, enter 0.0.0.0/0. This value allows access by all IP addresses.

* Click Save.

Note: setting allowed networks to 0.0.0.0/0 opens your SQL instance to traffic from any computer. For production databases, it's highly recommended to limit the authorized networks to only IP ranges that need access.

* Alternatively, the instance can be created with the gcloud command line tool as follows, substituting `your-root-pw
with a strong, unique password.

`gcloud sql instances create <instance_name> --assign-ip --authorized-networks=0.0.0.0/0 set-root-password=your-root-pw`

* Create a Database And User

* Using the root password created in the last step to create a new database, user, and password using your preferred MySQL client. Alternatively, follow these instructions to create the database and user from the console.
* From the CloudSQL instance in the console, click New user.
* Enter a username and password for the application. For example, name the user "pythonapp" and give it a randomly
generated password.
* Click Add.
* Click Databases and then click New database.
* For Name, enter the name of your database (for example, "polls"), and click Add.

Once you have a SQL host, configuring mysite/settings.py to point to your database. Change `your-database-name`,
`your-database-user`, `your-database-host` , and `your-database-password` to match the settings created above. Note the
instance name is not used in this configuration, and the host name is the IP address you created.

## Running locally

First make sure you have Django installed. It's recommended you do so in a
[virtualenv](https://virtualenv.pypa.io/en/latest/). The requirements.txt
contains just the Django dependency.

`pip install -r requirements.txt`

Once the database is setup, run the migrations.

`python manage.py migrate`

If you'd like to use the admin console, create a superuser.

`python manage.py createsuperuser`

The app can be run locally the same way as any other Django app.

`python manage.py runserver`

Now you can view the admin panel of your local site at

`http://localhost:8080/admin`

## Deploying

Since the Django development server is not built for production, our container uses the Gunicorn server. Since Gunicorn doesn't serve static content,
the static content is instead served from Google Cloud Storage.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like this is slightly overkill for a basic sample. I'm super happy you did it, though.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Slight overkill, but the alternative is that our sample was using the development server. Maybe once bookshelf gets done we can think about changing this back, but for now with just 1 or 2 samples I think showing how to setup gunicorn is worth it.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SGTM.


First, make a bucket and make it publically readable, replacing <your-gcs-bucket> with a bucket name, such as your project id:

`gsutil mb gs://<your-gcs-bucket>`
`gsutil defacl set public-read gs://<your-gcs-bucket>`

Next, gather all the static content locally into one folder using the Django `collectstatic` command

`python manage.py collectstatic`

Then upload it to CloudStorage using the `gsutil rsync` command

`gsutil rsync -R static/ gs://<your-gcs-bucket>/static`

Now your static content can be served from the following URL:

`http://storage.googleapis.com/<your-gcs-bucket/static/`

Make sure to replace <your-cloud-bucket> within `mysite/settings.py` to set STATIC_URL to the correct value to serve static content from, and
uncomment the STATIC_URL to point to the new URL.

The app can be deployed by running

`gcloud preview app deploy app.yaml --set-default --version=1 --promote`

which deploys to version 1, and `promote` makes version 1 the default version.

Now you can view the admin panel of your deployed site at

`https://<your-app-id>.appspot.com/admin`

## Contributing changes

* See [CONTRIBUTING.md](CONTRIBUTING.md)


## Licensing

* See [LICENSE](LICENSE)
Empty file.
14 changes: 14 additions & 0 deletions managed_vms/django_tutorial/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# This file specifies your Python application's runtime configuration
# including URL routing, versions, static file uploads, etc. See
# https://developers.google.com/appengine/docs/python/config/appconfig
# for details.

# TODO: Enter your application id below. If you have signed up
# using cloud.google.com/console use the "project id" for your application
# id.
# [START runtime]
runtime: custom
vm: true

# [END runtime]

24 changes: 24 additions & 0 deletions managed_vms/django_tutorial/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/usr/bin/env python
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

from django.core.management import execute_from_command_line

execute_from_command_line(sys.argv)
Empty file.
113 changes: 113 additions & 0 deletions managed_vms/django_tutorial/mysite/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'pf-@jxtojga)z+4s*uwbgjrq$aep62-thd0q7f&o77xtpka!_m'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls'
)

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

# [START dbconfig]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '<your-database-name>',
'USER': '<your-database-user>',
'PASSWORD': '<your-database-password>',
'HOST': '<your-database-host>',
'PORT': '3306',
}
}
# [END dbconfig]

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

# [START staticurl]
# Fill in your cloud bucket and switch which one of the following 2 lines
# is commented to serve static content from GCS
# STATIC_URL = 'https://storage.googleapis.com/<your-cloud-bucket>/static/'
STATIC_URL = '/static/'
# [END staticurl]

STATIC_ROOT = 'static/'
19 changes: 19 additions & 0 deletions managed_vms/django_tutorial/mysite/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls)]
22 changes: 22 additions & 0 deletions managed_vms/django_tutorial/mysite/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

application = get_wsgi_application()
Empty file.
Loading