I use the Django site (1)-Sina Weibo login

Source: Internet
Author: User
Tags oauth

Sina Weibo third-party login using OAuth2.0, development premise has registered the developer account, is a developer.

About OAuth

Oauth:oauth (Open Licensing) is an open standard that allows users to authorize third-party websites to access information they store on other service providers without having to provide their usernames and passwords to third-party websites or to share all the content of their data.

Specific development Steps First step: preparation phase

Open the Weibo development platform and log in to your Sina Weibo account. Then click on "Micro Link"--"website access" on the navigation.



After you've created the app, you'll be able to get app key and app Secret in the basic information. In the development phase can be used directly, if the site needs to improve the level of information.


Weibo third-party login The general steps: First jump to the user login interface, agree to callback to fill in the callback page, or code code, through code code to get Access_token, which contains the user's unique representation UID.

The first step: specific development

    • Create a web App
      After the creation is complete, open the models.py file and write the model:
class Users(models.Model):    uid = models.CharField(max_length=64, null=True)  # 微博的关联uid    nickname = models.CharField(max_length=30, null=True)  # 用户昵称    head = models.CharField(max_length=100, null=True)  # 用户头像    sex = models.CharField(max_length=2, null=True)  # 性别    register_time = models.DateTimeField(‘保存日期‘)  # 注册时间    register_ip = models.CharField(max_length=30, null=True)  # 注册ip    last_time = models.DateTimeField(‘最后修改日期‘)  # 最后一次登录时间

The model is used to store the UID value returned by the microblog login. This UID is corresponding to Weibo one by one.
In the total URLs route, add the corresponding application route.

from django.contrib import adminfrom django.urls import include, pathurlpatterns = [    path(‘login/‘, include(‘login.urls‘)),  # 登录模块]

Open the corresponding application directory under the urls.py file, fill in the routing:

from django.urls import pathfrom . import viewsurlpatterns = [    path(‘oauth/weibo/login‘, views.weibo_login),  # 微博授权页面    path(‘weibo/connect/callback.php‘, views.weibo_get_code),  # 微博回调页面]

Oauth/weibo/login and weibo/connect/callback.php, respectively, are to open the authorization page and callback address.
The approximate step is to obtain the UID after authorization. Determine if the UID exists in the database. If it exists, it can be directly logged in to the corresponding user, and if it does not exist, obtain the Sina interface to obtain the user information and obtain the user information.

    • Developing login Modules
      1. Set constants in the project catalog settings.py
‘‘‘微博登录常量‘‘‘WEIBO_APP_ID = "App Key"WEIBO_APP_KEY = "App Secret"WEIBO_REDIRECT_URI = "回调地址"

2. Create the wb_oauth.py file under the corresponding app's folder and edit the wb_oauth.py file:

Import Requestsimport jsonclass oauthwb:def __init__ (self, client_id, Client_key, Redirect_uri): self.client_id = client_id Self.client_key = Client_key Self.redirect_uri = Redirect_uri def get_access_token (self, cod e): # Get user token and uid URL = "Https://api.weibo.com/oauth2/access_token" querystring = {"client_id            ": self.client_id," Client_secret ": Self.client_key," Grant_type ":" Authorization_code ", "Code": Code, "Redirect_uri": self.redirect_uri} response = Requests.request ("POST", URL, header  S=headers, params=querystring) Access_token_data = Json.loads (response.text) return Access_token_data def Get_user_info (self, access_token_data): #获取用户的信息 url = "Https://api.weibo.com/2/users/show.json" Querystrin        g = {"UID": access_token_data[' uid '], "Access_token": access_token_data[' Access_token '} Response = Requests. Request ("GET", url, headers=headers, params=querystring) return Json.loads (Response.text) 

3. Edit the corresponding app folder under the views.py file:

From. Wb_oauth Import oauthwbfrom django.conf Import Settings # Introduce constant def weibo_login (request): # Jump Authorization page return HTTPRESPO Nseredirect (' https://api.weibo.com/oauth2/authorize?client_id= ' + settings. weibo_app_id + ' &redirect_uri= ' + settings. Weibo_redirect_uri) def weibo_get_code (Request): "" "After login, you will be redirected here. You need to determine the code and state "" "Code = Request. Get.get (' Code ', None) Sina = OAUTHWB (settings. weibo_app_id, settings. Weibo_app_key, settings. Weibo_redirect_uri) User_info = Sina.get_access_token (code) Time.sleep (0.1) # to prevent a request to token to proceed to the next # by the UID to find out whether it is a new use Login Is_user_exist = models, the new user is registered.        Users.objects.filter (uid=user_info[' uid '). First () If Is_user_exist is not None: # There is a direct login pass else: #不存在获取用户信息 new_user_info = Sina.get_user_info (user_info) users_dict = {"UID": New_user_inf o[' id '], ' description ': new_user_info[' description ', ' head ': new_user_info[' Profile_imagE_url '], "nickname": new_user_info[' name '],} users_table_obj = models.    Users.objects.create (**users_dict). Id

Note: The interface to get an email address is an advanced permission that needs to be approved first and then applied in interface management in my app. The API test page provided by Sina.

I use the Django site (1)-Sina Weibo login

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.