Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

angular - Django Session Data Not Being Stored

I am trying to store some session data using Django and Angular2. I noticed something strange, or do not understand. I was stuck on this for a while on my project. Instead, I tried to test a simple example to understand what's happening. Finally, I was able to store the session data when I made the requests using POSTMAN, and the sessionId was recognized. However when I made the request through my Angular app, the session data saving was successful but it was unable to access the saved session data on the next request. I also noticed that when done with Angular, a new session is created on every request. So it's not recognizing the session and creating a new session each time. Any ideas on what might be causing this? Thank you for your help.

Django Views

class TestSaveSessionView(APIView):
    authentication_classes = (TokenAuthentication,)

    def post(self, request):
        # set new data
        request.session['user_id'] = 20
        request.session['team'] = 'Barcelona'
        return Response("Session Data Saved")


class TestAccessSessionView(APIView):
    authentication_classes = (TokenAuthentication,)

    def post(self, request):
        response = ""
        print("USER ID", request.session.get('user_id'))
        if request.session.get('user_id'):
            user_id = request.session.get('user_id')
            response += "User Id : {0} <br>".format(user_id)
        if request.session.get('team'):
            team = request.session.get('team')
            response += "Team : {0} <br>".format(team)

        if not response:
            return Response("No session data")
        else:
            return Response(response)

Angular Service

export class TestSessionService {
  constructor(private http: HttpClient) { }
  baseUrl: string = environment.apiURL;

  getAuthenticationHeaders() {
    const token = localStorage.getItem('token');
    const httpHeaders = new HttpHeaders(
      {
        'Content-Type': 'application/json; charset-utf-8', 'Authorization': 'Token ' + token
      }
    );
    return { headers: httpHeaders };
  }

  testSaveSession(): Observable<any> {
    const body = {
    };
    return this.http.post(this.baseUrl + 'checkout/test_save_session/', body, this.getAuthenticationHeaders());
  }

  testAccessSession(): Observable<any> {
    const body = {
    };
    return this.http.post(this.baseUrl + 'checkout/test_access_session/', body, this.getAuthenticationHeaders());
  }

}

Results w/ Postman

"Session Data Saved"
"User Id : 20 Team : Barcelona"

Results w/ Angular

"Session Data Saved"
"No Session Data"

I am using 'django.contrib.sessions' in INSTALLED_APPS. I noticed that when I make the request to access the session data over Chrome, Django is unable to find the Cookie called "sessionid". In the browser's development environment, Application --> Cookies. The sessionid is there.

class SessionMiddleware(MiddlewareMixin):
    # RemovedInDjango40Warning: when the deprecation ends, replace with:
    #   def __init__(self, get_response):

    def __init__(self, get_response=None):
        self._get_response_none_deprecation(get_response)
        self.get_response = get_response
        self._async_check()
        engine = import_module(settings.SESSION_ENGINE)
        self.SessionStore = engine.SessionStore

    def process_request(self, request):
        print("sessionid is ", request.COOKIES.get(settings.SESSION_COOKIE_NAME))
        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
        request.session = self.SessionStore(session_key)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...