创建工作流和保存django凭据的简单应用程序

django-google-api的Python项目详细描述


PyPI VersionGPL LicensePlatform & Version Support

安装

从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_FILEGOOGLE_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中创建视图

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)

urls.py中创建视图

fromdjango.urlsimportpathfrom.viewsimportoAuthView,oAuth2CallBackView,oAuthJavascriptViewurlpatterns=[path('',oAuthJavascriptView,name="login"),path('auth/',oAuthView,name="auth"),path('oauth2callback/',oAuth2CallBackView,name="oauth2callback"),]

login.html您自己选择的google auth文件创建按钮

<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>

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java为什么只为字符数组重载println方法,而不为字符串、整数等其他数组重载?   java将快速线程返回到池中,而不是等待慢速线程   创建jar文件时java SwingWorker不工作   java如何将依赖注入RabbitListener   java如何在gradle任务中通过scp复制目录?   java在MySql数据库中创建表时,遇到NullPointerException   java HTTP Status 500 Servlet执行引发异常   在JAVA中对arraylist使用继承时出错   java PowerMockito未完成存根异常   如果没有错误/警告增加到某个极限,java是否停止在eclipse中构建项目或使用maven?   java Robolectric如何测试DateFormat。getBestDateTimePattern()   google云平台GCP数据存储Java API,构建一个空值实体   VerifyListener和FocusListener之间的java冲突   安卓是否可以在Java中的另一个方法内部强制调用一个方法?   JavaWindows7、JDK1.8、SpringBoot应用程序JAR在方法安全性方面占用了大量时间。getProviders()返回   Bean提供程序的java错误消息   java Slick动画每帧必须有一个持续时间   java无法在Trie中设置isLeaf标志   java为什么JVM不能创建包含main方法的类的对象,以便从该类访问main方法,如果它具有该类的名称?   java Apache Camel+CXF端点身份验证