Create a Django Application in the Google App Engine Standard Environment

  1. Install Python 3
  2. Install Django
  3. Create a basic Django project
  4. Create the following files in the same directory as manage.py
# app.yaml
runtime: python38
# main.py
from hpwg.wsgi import application
app = application

Optionally, add a requirements.txt file with the contents Django==3.1.4, using whichever version you installed.

You will also need to update your settings.py file to allow the application to be accessed in a browser. ALLOWED_HOSTS = ['{PROJECT_ID}.uc.r.appspot.com', '127.0.0.1', 'localhost'] should suffice for now.

Lastly, run gcloud app deploy to deploy the application. The output will show you the progress of your build and deploy before presenting you with a URL at which you can view your stock application.

Adding an API server application

What we've just created and configured is a Django project. Django projects are umbrella structures, under which one or more applications can run. For example, you could have a web server and a Web Sockets server in the same project to facilitate the hosting of a chat application or some high performance, progressively loaded data visualization thing... 🤔

In the same directory as manage.py, run python manage.py startapp api_server. This will create an api_server directory to house our API calls, which looks very similar to the directory that was created when the project was initialized.

One file the new directory has is views.py. Replace its contents with the following code to create the simplest possible view.

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello from the API server.")

Next add a urls.py file to the api_server directory with the contents below. This will map the base URL to the view you just created.

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

Lastly, include the new URLs in your project's root urls.py and nest them under api/. This means navigating to /api will activate the index route above, and any paths will be matched against the segment after /api.

urlpatterns = [
    path('api/', include('api_server.urls')),
    path('admin/', admin.site.urls),
]

Run python manage.py runserver to verify your changes locally, or run gcloud app deploy to publish a new version to your public URL. If you navigate to the /api path of your server you should see Hello from the API server. in your browser.

Resources

app.yaml reference documentation