使用json在python/django中设置用户登录名,不知道从哪里开始 [英] setting up a user login in python / django using json and have no idea where to start

查看:97
本文介绍了使用json在python/django中设置用户登录名,不知道从哪里开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常模糊的问题,我不确定从哪里开始.

I have a very vague question that I'm not sure where to start from.

我需要使用python(Django REST调用)进行ajax登录

I need to make an ajax login using python (django REST calls)

jQuery从我的头开始可以使用.

jQuery is available from my end.

我得到了这个:

    import sys, base64
    import httplib, urllib, urlparse, json
    auth = 'Basic %s' % base64.encodestring('%s:%s' % (username, password)).strip()
    headers = {'Content-Type':'application/x-www-form-urlencoded', 'Authorization':auth}
    endpoint = "urlendpoint.com"
    url = "/login/"
    conn = httplib.HTTPSConnection(endpoint)
    conn.request("POST", url, "", headers)
    response = conn.getresponse()
    if response.status != httplib.OK: raise Exception("%s %s" % (response.status, response.reason))
    result = json.load(response)
    if "token" not in result: raise Exception("Unable to acquire token.")
    if "sessionid" not in result: raise Exception("Unable to acquire session ID.")
    print result["token"], result["sessionid"]
    conn.close()

我需要通过POST发送登录信息,然后设置一个cookie.

I need to send the login via POST and then set a cookie.

我绝对不知道从哪里开始这项任务.使用命令行,我可以设置/login.py文件,使用在上面的变量字段和VIOLA中硬编码的用户名和密码访问该文件-可以正常工作.但是,我不知道从哪里开始使用ajax来完成此任务.

I have absolutely no clue where to begin with this task. Using the command line, I'm able to set up a /login.py file, access said file with a username and password hard-coded in the above variable field and VIOLA - it works fine. However, I have no clue where to begin using ajax for this task.

这里的主要事情是,一旦该人登录,我需要在登录的用户和服务器之间建立一个会话ID,以便获得对REST(json)端点的访问权限,以便我可以开始添加数据(通过Ajax).

The main thing here is that I need to establish a session ID between the logged in user and the server once the person has logged in, in order to get access to the REST (json) endpoints so that I can start adding data (via Ajax).

任何帮助将不胜感激.

Any assistance would be much appreciated.

我希望有人

推荐答案

在常规视图中如何完成操作与在AJAX视图中如何完成操作在功能上没有区别;唯一的区别是您发送的回复是什么:

There's functionally no difference between how it's done for a regular view and how you'd do it for an AJAX view; the only difference is what response you send:

from django.contrib.auth import authenticate, login
from django.http import HttpResponse, HttpResponseBadRequest
from django.utils import simplejson

def ajax_login(request):
    if request.method == 'POST':
        username = request.POST.get('username', '').strip()
        password = request.POST.get('password', '').strip()
        if username and password:
            # Test username/password combination
            user = authenticate(username=username, password=password)
            # Found a match
            if user is not None:
                # User is active
                if user.is_active:
                    # Officially log the user in
                    login(self.request, user)
                    data = {'success': True}
                else:
                    data = {'success': False, 'error': 'User is not active'}
            else:
                data = {'success': False, 'error': 'Wrong username and/or password'}

            return HttpResponse(simplejson.dumps(data), mimetype='application/json')

    # Request method is not POST or one of username or password is missing
    return HttpResponseBadRequest()        

这篇关于使用json在python/django中设置用户登录名,不知道从哪里开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆