Log in using third-party qq Django project.

Log on the premise that the use of qq Web application has been created in the Internet qq official website and get to the APP ID QQ Internet in Web applications and APP KEY

1, built routing

#     qq登录
    path('loginQq/',qq.loginQq,name='loginQq/'),
    path('returns/',qq.returns,name='returns/'),

2, the front page write qq login link, this paper did not use icons to temporarily use a link request.

<a data-wow-delay=".5s" href="/blog/loginQq/"> »  QQ登录</a>

3, the application program created under the folder, and creates function.py utils for encapsulating function, a function for extracting the package OpenID (Tencent inside the database user id) from the return data

Function contents encapsulated as follows;

import re

def parse_jsonp(jsonp_str):
    try:
        return re.search('^[^(]*?\((.*)\)[^)]*$', jsonp_str).group(1)
    except:
        raise ValueError('无效数据!')

4, code-behind

from django.shortcuts Import the render, the redirect, the HttpResponse, HttpResponseRedirect
 from blog.models Import Member
 from the urllib Import the parse
 from the urllib Import Request AS REQ
 Import Re
 Import JSON
 Import Random
 from blog.utils Import function
 DEF loginQq (Request): 
    State = STR ( random.randrange (100000,999999)) # define a random status code, to prevent cross-domain forgery attacks. 
    makes request.session [ ' State ' ] = State  # Random status code stored Session, for verifying the authorization information is returned. 
    = client_id ' 101 716 344 '   # QQ Internet in Web applications APP ID. 
    # Callback address is encoded, users will agree that the authorization to call this link. 
    = parse.urlencode the callback ({ ' the redirect_uri ' : ' http://127.0.0.1:8000/blog/returns ' })    # the redirect_uri = HTTP%. 3A. 2F%%% 2Fblog 2F127.0.0.1% 3A8000% 2Freturns 
    # organizations third-party QQ login link 
    LOGIN_URL = ' https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=%s&%s&state=%s ' % (client_id, callback, State)
     return HttpResponseRedirect (LOGIN_URL)   #QQ login redirects to third-party authorization page 
DEF returns A (Request):
     IF request.session [ ' State ' ] == request.GET [ ' State ' ]:   # verification status code, prevent cross-domain forgery attacks. 
        = `` request.GET`` code [ ' code ' ]   # obtain user authorization code 
        client_id = ' 101 716 344 '   # the APP ID QQ interconnection Web applications. 
        = client_secret ' 7f42aaac69f866750078fbe1edd9d2a4 '   # APP Key QQ Internet in Web applications. 
        = parse.urlencode the callback ({ ' the redirect_uri ' :' Http://127.0.0.1:8000/blog/returns ' })
         # callback address is encoded, users will agree that the authorization to call this link. 
        = LOGIN_URL ' https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s&%s ' % (code, client_id, client_secret, the callback)   # tissue to obtain access token link 
        # return the HttpResponse (LOGIN_URL) 
        . Response = req.urlopen (LOGIN_URL) .read () decode ()   # open access token acquired links the access_token: 123456789 & 

        the access_token = re.split ( ' & ' , Response) [0]   # obtain access token the access_token: 123456789 

        RESReq.urlopen = ( ' https://graph.qq.com/oauth2.0/me? ' + The access_token) .read (). Decode ()   # open openid get links 

        openid = json.loads (function.parse_jsonp ( RES)) [ ' OpenID ' ]   # acquired from the return data 410225632333335556566 OpenID 

        UserInfo = req.urlopen ( ' https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s&%s ' % ( 
            client_id , openid, the access_token)). the Read (). decode ()   # open for a link to the user's information 
        # Print View acquired user information 
        Print (UserInfo) 
        UserInfoJson.loads = (UserInfo)   # user information returned data (JSON format) read as a dictionary. 
        = Member.objects.filter the User (member_qq_id = openid)   # query whether there is a user 
        IF  not the User:   # If there is no user 
            # Create a new user 
            member_obj = Member.objects.create (member_qq_id = openid, member_nickname = UserInfo [ ' the Nickname ' ], member_name UserInfo = [ ' Nickname ' ], member_photo UserInfo = [ ' figureurl_qq_1 ' ])
             # user Member = () Create a new user # 
            # user.member_qq_id = OpenID writing user information # 
            #user.member_nickname = userinfo [ 'nickname'] # write user information 
            # user.member_name UserInfo = [ 'Nickname'] to write user information # 
            # # user.gender UserInfo = [ 'Gender'] to write user information # 
            # User .member_photo = userinfo [ 'figureurl_qq_1'] # write user information 
            # user.save () # save or update the user 
            makes request.session [ ' member_id ' ] = member_obj.member_id   # user logged openid writing the Session 
            makes request.session [ ' member_name ' ] = UserInfo [ ' the Nickname ' ]
         #   return path to Home 
        return redirect ( '/blog/index/')
     The else :
         return HttpResponse ( ' Authorization failed! ' )

This article is qq login feature in a local test project, so the callback address qq official website of the Internet needs to be modified for the local address,

5, start function test project

 

6, view the database table members, membership information has been written.

done。

Guess you like

Origin www.cnblogs.com/nmsghgnv/p/11343711.html