创建工作流和保存django凭据的简单应用程序
django-google-api的Python项目详细描述
安装
从pypi安装和执行一样简单:
pip install django-google-api
初始化
django google api是与django一起使用google api的库
步骤:-1
< >创建D.jango项目基址目录中的{{STR 1 } $凭据.JSON < /强>文件,其中您的{STR 1 } $管理.Py < /St>文件存在django-project├── django-project│ ├── __init__.py│ ├── settings.py│ ├── urls.py│ └── wsgi.py├── credentials.json├── manage.py└── requirements.txt
步骤:-2
将应用程序添加到INSTALLED_APPS设置中,作为默认orm:
INSTALLED_APPS=[...'django_google.apps.DjangoGoogleConfig',]
步骤:-3
google oauth凭据集GOOGLE_CLIENT_SECRET_FILE和GOOGLE_AUTH_SCOPES位于setting.py中您可以添加选择的范围
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',]
如果您使用的是javascript身份验证,那么将这一行也添加到您的项目中
GOOGLE_CLIENT_ID="xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"
用法:
执行命令
python manage.py makemigrations python manage.py migrate
在views.py中创建视图
在urls.py中创建视图
login.html您自己选择的google auth文件创建按钮fromdjango.shortcutsimportreverse,redirect,renderfromdjango_google.flowimportDjangoFlow,CLIENT_SECRET_FILE,SCOPESfromdjango.http.responseimportJsonResponsefromdjango.contrib.authimportget_user_modelfromdjango.confimportsettingsfromdjango_google.modelsimportGoogleAuthUser=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)defoAuthView(request):callback_url=reverse("oauth2callback")# callback Url (oAuth2CallBackView URL)returnredirect(flow.get_auth_url(request,callback_url=callback_url))# Google Authentication Call Back VIEW (Using Without Javascript)defoAuth2CallBackView(request):success_url="/dashboard/"# redirection URL on Success reverse() can b use herecreds=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'])exceptUser.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)exceptGoogleAuth.DoesNotExist:gauth=GoogleAuth.objects.create(user=user,creds=creds)# Return Response as you want or Redirect to some URLdefoAuthJavascriptView(request):ifrequest.is_ajax():ifrequest.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'])exceptUser.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)exceptGoogleAuth.DoesNotExist:gauth=GoogleAuth.objects.create(user=user,creds=creds)# return JSON Response with Status Code of 200 for success and 400 for errorsreturnJsonResponse({},status=200)else:context={"client_id":getattr(settings,'GOOGLE_CLIENT_ID',None),"scopes":" ".join(SCOPES)}# Render HTML page that havs Google Authentication Page with Javasccriptreturnrender(request,'login.html',context)
fromdjango.urlsimportpathfrom.viewsimportoAuthView,oAuth2CallBackView,oAuthJavascriptViewurlpatterns=[path('',oAuthJavascriptView,name="login"),path('auth/',oAuthView,name="auth"),path('oauth2callback/',oAuth2CallBackView,name="oauth2callback"),]
<scriptsrc="https://apis.google.com/js/api:client.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script><buttonid="g-auth-btn">Sign in with <b>Google</b></button><script>functionstartApp(){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>