python django接入小程序处理session认证问题

**

微信前端

**
html页面(text.html)

发送session认证
获取session

cookie页面(cookie.js)

const key = "cookie"
//服务器取出cookie
function getSessionIDFromResponse(res){
  var cookie = res.header["Set-Cookie"]
  console.log(cookie)
  return cookie
}
//存入cookie
function setCookieToStorage(cookie){
  try{
  wx.setStorageSync(key, cookie)
  console.log("存入成功")
  }catch(e){
    console.log(e)
  }
}
//storage取出cookie
function getCookieFromStorage(){
  var value = wx.getStorageSync(key)
  return value
}
//导出
module.exports = {
  setCookieToStorage: setCookieToStorage,
  getCookieFromStorage: getCookieFromStorage,
  getSessionIDFromResponse: getSessionIDFromResponse
}

js页面(text.js)

const cookies = require(“cookie.js”)
//向服务器发起请求获取session 存入小程序storage
users:function(){
wx.request({
url: ‘http://127.0.0.1:8000/users’,
method:‘POST’,
data:{
},
success:function(res){
console.log(“ok”)
var cookie = cookies.getSessionIDFromResponse(res)
cookies.setCookieToStorage(cookie)
}
})
},
//从小程序storage取出session 发送给服务器认证用户
shopcart:function(){
wx.request({
url: ‘http://127.0.0.1:8000/shopcart’,
header: {
‘Set-Cookie’: cookies.getCookieFromStorage()
},
method:‘POST’,
data:{
},
success:function(res){
console.log(“ok”)
}
})
}

django后端

urls页面

from users.views import UsersView,shopcart

urlpatterns = [
path(‘xadmin/’, xadmin.site.urls),
path(‘users’, UsersView),
path(‘shopcart’, shopcart)
]

modls页面

from django.db import models

class User(models.Model):

userid = models.CharField(max_length=32,unique=True)

views页面

from django.shortcuts import HttpResponse
import base64
import re
import pymysql.cursors
from users.models import User
#建立mysql连接

conn = pymysql.connect(host=‘localhost’,
user=‘root’,
password=‘redhat’,
db=‘lks’,
charset=‘utf8’)
cursor = conn.cursor()

#收到前端请求后处理
def UsersView(request):

try:
    response = {}

    if 1:
        request.session['userid'] = 1
        request.session['code'] = 200
        response['code'] = 200
        return HttpResponse(response)
except Exception as e:
    return None

def shopcart(request):
sessionid = request.META[‘HTTP_SET_COOKIE’]
res = re.findall(‘sessionid=(.*?);’,sessionid)[0]

# 获取前端session 解密认证用户
sql = "select * from django_session where session_key ="+"'"+res+"'"
s = cursor.execute(sql)
data = cursor.fetchall()
session_data = data[0][1]
user_data = base64.b64decode(session_data)
p = re.findall(":(.*?)'",str(user_data))
p = str(p).strip("'[]")
p = eval(p)
userid=p['userid']
User.objects.filter(userid=userid)
print(userid)

你可能感兴趣的:(python django接入小程序处理session认证问题)