Installation
Installing from PyPI is as easy as doing:
pip install django-google-api
Intigration
django-google-api is a library to use Google API with Django
step:- 1
create credentials.json file on DJango project Base Directory where your manage.py file exist
django-project├── django-project│ ├── __init__.py│ ├── settings.py│ ├── urls.py│ └── wsgi.py├── credentials.json├── manage.py└── requirements.txt
step:- 2
Add the application to INSTALLED_APPS setting, for default ORM:
INSTALLED_APPS = [
...
'django_google.apps.DjangoGoogleConfig',
]
step:- 3
Google OAuth credentials set GOOGLE_CLIENT_SECRET_FILE and GOOGLE_AUTH_SCOPES in setting.py you can add scope of your choices
GOOGLE_CLIENT_SECRET_FILE = os.path.join(BASE_DIR, 'credentials.json')
GOOGLE_AUTH_SCOPES = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
]
if you’re using javascript authentication then add this line to your project also
GOOGLE_CLIENT_ID = "xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"
Usage:
execute commands
python manage.py makemigrations
python manage.py migrate
Create Views in views.py
from django.shortcuts import reverse, redirect, render
from django_google.flow import DjangoFlow,CLIENT_SECRET_FILE, SCOPES
from django.http.response import JsonResponse
from django.contrib.auth import get_user_model
from django.conf import settings
from django_google.models import GoogleAuth
User = get_user_model()
flow = DjangoFlow.from_client_secrets_file(client_secrets_file=CLIENT_SECRET_FILE, scopes=SCOPES)
# Auto Redirect to Google Authentication URL (Using Without Javascript)
def oAuthView(request):
callback_url=reverse("oauth2callback") # callback Url (oAuth2CallBackView URL)
return redirect(flow.get_auth_url(request, callback_url=callback_url))
# Google Authentication Call Back VIEW (Using Without Javascript)
def oAuth2CallBackView(request):
success_url = "/dashboard/" # redirection URL on Success reverse() can b use here
creds = flow.get_credentails_from_response_url(response_url=request.build_absolute_uri())
userinfo = flow.get_userinfo(creds=creds)
try:
user = User.objects.get(email=userinfo['email'])
except User.DoesNotExist:
user = User.objects.create(email=userinfo['email'],
username=userinfo['email'],
first_name=userinfo['given_name'],
last_name=userinfo['family_name']
)
finally:
try:
gauth = GoogleAuth.objects.get(user=user)
except GoogleAuth.DoesNotExist:
gauth = GoogleAuth.objects.create(user=user, creds=creds)
# Return Response as you want or Redirect to some URL
def oAuthJavascriptView(request):
if request.is_ajax():
if request.method == "POST":
code = request.POST.get('code')
flow = DjangoFlow.from_client_secrets_file(client_secrets_file=CLIENT_SECRET_FILE, scopes=SCOPES)
creds = flow.get_credentials_from_code(code=code, javascript_callback_url="https://example.org")
userinfo = flow.get_userinfo(creds=creds)
try:
user = User.objects.get(email=userinfo['email'])
except User.DoesNotExist:
user = User.objects.create(email=userinfo['email'],
username=userinfo['email'],
first_name=userinfo['given_name'],
last_name=userinfo['family_name']
)
finally:
try:
gauth = GoogleAuth.objects.get(user=user)
except GoogleAuth.DoesNotExist:
gauth = GoogleAuth.objects.create(user=user, creds=creds)
# return JSON Response with Status Code of 200 for success and 400 for errors
return JsonResponse({}, status=200)
else:
context = {
"client_id": getattr(settings, 'GOOGLE_CLIENT_ID', None),
"scopes": " ".join(SCOPES)
}
# Render HTML page that havs Google Authentication Page with Javasccript
return render(request, 'login.html', context)
Create Views in urls.py
from django.urls import path
from .views import oAuthView, oAuth2CallBackView, oAuthJavascriptView
urlpatterns = [
path('', oAuthJavascriptView, name="login"),
path('auth/', oAuthView, name="auth"),
path('oauth2callback/', oAuth2CallBackView, name="oauth2callback"),
]
login.html file create Button of your own choice for google auth
<script src="https://apis.google.com/js/api:client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<button id="g-auth-btn">Sign in with <b>Google</b></button>
<script>
function startApp() {
gapi.load('auth2', function(){
auth2 = gapi.auth2.init({
client_id: '{{ client_id }}',
cookiepolicy: 'single_host_origin',
});
});
}
$(document).on("click", "#g-auth-btn", ()=>{
auth2.grantOfflineAccess({
prompt:"consent",
scope: '{{ scopes }}'
}).then((signInCallback)=>{
$.ajax({
type:'post',
data:signInCallback,
cache: false,
headers: {"X-CSRFToken": $.cookie('csrftoken')},
success: function (response) {
console.log(response);
if(!!response.redirect){
window.location = response.redirect
}
},
error: function (error) {
console.log(error);
if(!!error.responseJSON.redirect){
window.location = error.responseJSON.redirect
}
}
});
});
});
startApp();
</script>
Metadata
Release files for django-google-api 1.0.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| django-google-api-1.0.1.tar.gz | 9.2 kB | Without provenance | Details for django-google-api-1.0.1.tar.gz |
Release files / django-google-api-1.0.1.tar.gz
| Download URL | django-google-api-1.0.1.tar.gz |
|---|---|
| Size | 9.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7f4b999ee8a192f680652e38ddfe3f97e696066e44e1cdadc49e503b5fdf7266
|
|
BLAKE2b-256 checksum How to use checksums |
4fd7f1d05b57b74dad22eeab5d32b036c3f0d2ac7647946171564bf8b7363e55
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.34.0 CPython/3.7.3
|
Security for django-google-api 1.0.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.