我编写了一个小的独立 python 脚本,它调用我基于 django 的后端,并且在登录和调用需要身份验证等的视图时一切正常。
一点代码
def dostuff():
session = login(username, password)
license = add_license(session)
def _helper(self, url, cookie=None):
http = httplib2.Http()
if cookie:
headers = { "Cookie" : cookie }
else:
headers = {}
response, content = http.request(host + url, "GET", headers=headers, body="")
return response, content
def login(self, username, password):
url = "/license/login?username=%s&password=%s" % (username, password)
response, content = self._helper(url)
sessioncookie = response["set-cookie"]
customer_id = re.search("id=(?P<id>\d+)", content)
if response["status"] == "200":
return sessioncookie, customer_id.group("id")
def add_license(self, session):
cookie = session[0]
customer_id = int(session[1])-1
url = "/license/add_license?customer_id=%s" % customer_id
response, content = self._helper(url, cookie)
content = content[1:-1]
if response["status"] == "200": #ok
data = json.loads(content)
return data["fields"]
如果我将“GET”更改为“POST”,我会遇到 Django CSRF 错误页面(CSRF 验证失败)作为回报。如何将 POST 数据发送到 Django?
我在 Django 中的登录视图,我需要做任何特别的事情来添加 csrf 令牌吗?我的计划是在一切正常后重写它以发送 json。
def my_login(request):
done, username = get_input(request, "username")
if not done:
return username
done, password = get_input(request, "password")
if not done:
return password
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponse("Done, id=%s" % user.pk)
else:
return HttpResponse("User disabled")
else:
return HttpResponse("Invalid login")