亲宝软件园·资讯

展开

python,Django实现的淘宝客登录功能示例

人气:0

本文实例讲述了python,Django实现的淘宝客登录功能。分享给大家供大家参考,具体如下:

在整理python,django资料的时候,发现了这个东西,也许是当初某位网友或者朋友发过来参考或者一起探讨修改的东西,现在不记得了,也许taobao的接口都变了也有可能,但总体来说还是有参考价值的,主要是做淘宝客客或者返利网会用到taobao登录而用的.

参考代码如下:

#!/usr/bin/python
#coding:utf-8
import datetime, urllib, base64, random
from hashlib import md5
from django.conf import settings
from django.contrib import auth
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from app.taobao.backends import TaobaoBackend
from app.taobao.models import User as taobao_user
from app.taobao.forms import UserOnceChange
from pyapi.taobao.top import Request
def authenticated(request, template):
  if request.method == 'POST':
    form = UserOnceChange(request=request, data=request.POST)
    if form.is_valid():
      request.user.username = form.cleaned_data['username']
      password = form.cleaned_data.get('password', None)
      if password:
        request.user.set_password(form.cleaned_data)
      request.user.save()
      #更新应用用户绑定
      tb_user = request.user.taobao.all()[0]
      tb_user.has_bind_user=True
      tb_user.save()
      return HttpResponseRedirect(reverse('user'))
  top_session = request.GET.get('top_session', None)
  top_parameters = request.GET.get('top_parameters', None)
  top_sign = str(request.GET.get('top_sign', None))
  #解析 top parameters
  if top_parameters:
    back_parameters = base64.decodestring(urllib.unquote(top_parameters))
    infos = dict(k.split("=") for k in back_parameters.split("&"))
    username = infos.get('visitor_nick', None)
    visitor_id = infos.get("visitor_id", None)
    # validate sign 认证返回值中的签名
    local_sign_str = '%s%s%s%s' % (settings.TAOBAO_APP_KEY,
                    top_parameters,
                    top_session,
                    settings.TAOBAO_APP_SECRET)
    local_sign = base64.encodestring(md5(local_sign_str).digest())
    #注意 base64 encode后,字符串最后会有 \n 符, 因此需要清除才能验证
    if top_sign == local_sign.strip(): # 清除 \n
      # 创建/返回淘宝账户
      tb_user, tb_user_created = taobao_user.objects.get_or_create(id=int(visitor_id),
                     nick=username)
      #建立系统用户, 用户名存在则创建随机数扩展
      if tb_user.user_id is None:
        try:
          User.objects.get(username=username)
          django_user_username = username
          tb_user.has_bind_user = True
        except:
          django_user_username = '%s_%s' % (username, random.randint(1000, 10000))
        django_user, django_user_created = User.objects.get_or_create(username=django_user_username)
        if django_user_created:
          django_user.set_password(visitor_id)
          django_user.save()
        tb_user.user = django_user
      # 保存返回的信息:过期时间 token ts等
      tb_user.expires_in = datetime.datetime.now() + datetime.timedelta(seconds=int(infos.get("expires_in", 0)))
      tb_user.ts = infos.get("ts", '')
      tb_user.refresh_token = infos.get("refresh_token", '')
      tb_user.save()
      # update user profile in taobao auth backend
      user = auth.authenticate(id=tb_user.id, nick=tb_user.nick)
      if user:
        auth.login(request, user)
        #如果应用账户没有绑定系统用户,则用户第一次时可以修改用户名
        if not tb_user.has_bind_user:
          form = UserOnceChange(request=request,
                     initial={'username':tb_user.user.username,
                          'password':tb_user.id})
          return render(request, template, locals())
  return HttpResponseRedirect(settings.TAOBAO_AUTH_URL)

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论