视图之间的Django会话无效

时间:2017-01-19 06:07:51

标签: python ajax django session

我无法在坐标函数中访问变量solo变量。 调试语句“solo used:”输出“none”。我需要做些什么来使其工作?非常感谢你的想法。

在views.py中

def go(request):
  print "go executing"
  lat = request.GET.get('latitude', None)
  lng = request.GET.get('longitude', None)
  if not lat or not lng:
    print "ERROR: BAD URL PARAMETERS"
  # call the dronekit module we wrote before
  solo = drone.drone()
  print "solo instantiated: ", solo
  solo.takeoff()
  solo.flyTo(lat,lng, 60)
  resp = "Arrived and landed. <br> <a href=/rtl>Return Home</a>"
  request.session['solo'] = "hello"
  return HttpResponse(resp)

def coordinates(request):
  #print "Request: ", request
  #if request.method == 'GET':
  solo = request.session.get('solo')
  print "solo used: ", solo

  # print "made it to views.py, and lat: ", solo.getlat(), ". lng: ", solo.getlng() 
  #print "lat: ", lat, ". lng: ", lng
  #lat1 = fly_drone.getlat()
  #lat2 = fly_drone.getlng()
  #print "lat1: ", lat1, ". lat2: ", lat2
  return HttpResponse('check')

请注意,我通过ajax:

从map.js调用坐标
function refreshData()
{
  x = 5;
  setTimeout(refreshData, x*1000);
  console.log("refreshing now");
  $.ajax({
    url: '/coordinates/',
    type: 'get',
    success: function(data){
      //alert(data);
    },
    failure: function(data){
      //alert('Got an error dude');
    }
  })

请注意,我在settings.py中打开了会话序列化程序:

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
...
MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]



 INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'skyway_app'
    ]

1 个答案:

答案 0 :(得分:0)

如有疑问,read the docs

  1. 确保django.contrib.sessions.middleware.SessionMiddleware 在您设置的MIDDLEWARE
  2. 确保您的会话引擎设置正确
    • 如果您使用的是数据库支持的会话,则必须确保设置中的django.contrib.sessions位于INSTALLED_APPS 并且迁移已经开始。