jak*_*ake 1 python django ajax rest jquery
我有一个非常模糊的问题,我不知道从哪里开始.
我需要使用python(django REST调用)进行ajax登录
jQuery可以从我这里获得.
我得到了这个:
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()
Run Code Online (Sandbox Code Playgroud)
我需要通过POST发送登录信息然后设置一个cookie.
我完全不知道从哪里开始这项任务.使用命令行,我可以设置一个/login.py文件,使用在上面的变量字段和VIOLA中硬编码的用户名和密码访问所述文件 - 它工作正常.但是,我不知道从哪里开始使用ajax执行此任务.
这里的主要内容是我需要在登录用户和服务器之间建立一个会话ID,以便访问REST(json)端点,以便我可以开始添加数据(通过Ajax ).
任何援助将不胜感激.
我希望有人
在常规视图中如何完成以及如何为AJAX视图执行操作在功能上没有区别; 唯一的区别是你发送的回复:
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2444 次 |
| 最近记录: |