Skip to content

Instantly share code, notes, and snippets.

@gbozee
Created December 29, 2017 19:35
Show Gist options
  • Save gbozee/87cedf1fdd3c768bf4629ab9cc04aee2 to your computer and use it in GitHub Desktop.
Save gbozee/87cedf1fdd3c768bf4629ab9cc04aee2 to your computer and use it in GitHub Desktop.
Django app that makes api call to the graphql service
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body {
margin: 0;
padding: 0;
font-family: sans-serif;
</style>
{% for css_file in styles %}
<link rel="stylesheet" href="{{css_file}}">
{% endfor %}
{% autoescape off %}
{{css}}
{% endautoescape %}
</head>
<body>
{% autoescape off %}
<div id="root">
{{html}}
</div>
{% endautoescape %}
<script type="text/javascript" src="https://unpkg.com/@umds/[email protected]/object-assign.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/[email protected]/dist/preact.min.js"></script>
<script src="https://unpkg.com/[email protected]/prop-types.js"></script>
<script type="text/javascript" src="https://unpkg.com/[email protected]/dist/preact-compat.min.js"></script>
<script>
window.React = preactCompat;
window.ReactDOM = preactCompat;</script>
<script type="text/javascript" src="https://unpkg.com/[email protected]/umd/react-router-dom.min.js"></script>
{% for script in scripts %}
<script src="{{ script }}"></script>
{% endfor %}
<script>window.main()</script>
</body>
</html>
# helper library to help us make graphql queries in python.
import requests
import json
def remove_spaces(string):
return string.lstrip().rstrip()
def to_graphql(string):
string_as_array = [remove_spaces(x) for x in string.splitlines()
if remove_spaces(x)]
return "\n".join(string_as_array) + "\n"
class GraphQLClient:
def __init__(self, endpoint):
self.endpoint = endpoint
self.token = None
def execute(self, query, variables=None, operationName=None):
return self._send(query, variables, operationName)
def inject_token(self, token):
self.token = token
def _send(self, query, variables, operationName):
data = {'query': to_graphql(query),
'operationName': operationName,
'variables': variables}
headers = {'Accept': 'application/json',
'Content-Type': 'application/json'}
if self.token is not None:
headers['Authorization'] = 'Bearer %s' % self.token
req = requests.post(
self.endpoint, data=json.dumps(data), headers=headers)
req.raise_for_status()
return req.json()
"""
Django settings for django_ssr project.
Generated by 'django-admin startproject' using Django 2.0.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '%iv^g#rb)%@e-@6n*dqw!!$+=n43b^r#!p@ha^(**%*f8-8@99'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['node','localhost']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'django_ssr.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'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 = 'django_ssr.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/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/2.0/howto/static-files/
STATIC_URL = '/static/'
GRAPHQL_ENDPOINT = 'http://node:3000/graphql' # graphql endpoint assuming running in docker container if running locally, it is http://localhost:3000/graphiql
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache', # caching backend so that we don't make calls everytime to the graphql endpoint for result already fetched
'LOCATION': 'my_cache_table',
}
}
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
os.getenv('NODE_ASSETS', '') # environmental variable that points to the location of the cra assets
)
from django.contrib import admin
from django.urls import path, re_path
from django.http import JsonResponse
from .gql import GraphQLClient
from django.conf import settings
from django.core.cache import cache
from django.shortcuts import render
def get_result(route):
inst = GraphQLClient(settings.GRAPHQL_ENDPOINT)
query = """
query getRoute($path:String) {
route(path:$path){
html
css
scripts
styles
}
}
"""
print(route)
return inst.execute(query, {"path":f"/${route}"},"getRoute")
def get_query(route, from_cache=True):
if from_cache:
result = cache.get(route)
if not result:
result = get_result(route)
cache.set(route,result,timeout=3600)
else:
result = get_result(route)
return result
def all_urls(request, path=''):
print(path)
result = get_query(path,False)
print(result)
return render(request, 'base.html',result['data']['route'])
# return JsonResponse(result)
urlpatterns = [
path('', all_urls),
# re_path('^.*$', all_urls, name='index'),
re_path(r'^(?P<path>.*)/$', all_urls),
path('admin/', admin.site.urls),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment