import time
from django.core import signing
import hashlib
from django.core.cache import cache
# alg使用的算法
HEADER = {'typ': 'JWP', 'alg': 'default'}
TOKEN_KEY = 'solomon_world_token'
TOKEN_SALT = '[email protected]'
TIME_OUT = 30 * 60
# 加密
def encrypt(obj):
value = signing.dumps(obj, key=TOKEN_KEY, salt=TOKEN_SALT)
value = signing.b64_encode(value.encode()).decode()
return value
# 解密
def decrypt(src):
src = signing.b64_decode(src.encode()).decode()
raw = signing.loads(src, key=TOKEN_KEY, salt=TOKEN_SALT)
print(type(raw))
return raw
# 生成token信息
def create_token(username, password):
# 1. 加密头信息
header = encrypt(HEADER)
# 2. 构造Payload
payload = {
"username": username,
"password": password,
"iat": time.time()
}
payload = encrypt(payload)
# 3. 生成签名
md5 = hashlib.md5()
md5.update(("%s.%s" % (header, payload)).encode())
signature = md5.hexdigest()
token = "%s.%s.%s" % (header, payload, signature)
# 4.存储到缓存中
cache.set(username, token, TIME_OUT)
return token
def get_payload(token):
payload = str(token).split('.')[1]
payload = decrypt(payload)
return payload
# 通过token获取用户名
def get_username(token):
payload = get_payload(token)
return payload['username']
pass
def check_token(token):
username = get_username(token)
print('username', username)
last_token = cache.get(username)
if last_token:
return last_token == token
return False
class RegisterForm(forms.Form):
# 为生成的验证码图片,以及输入框.
# captcha = CaptchaField(error_messages={'invalid': '验证码输入有误'})
captcha = CaptchaField()
def get_captcha(request):
# 生成验证码表单
register_form = RegisterForm()
return render(request, 'index.html', {'register_form': register_form})
在HTML中
<div>
<form action='.' method='POST'>
{% csrf_token %}
{{ register_form.captcha }}
<input type="submit" />
<button class='js-captcha-refresh'>刷新图片</button>
</form>
</div>
urlpatterns += [
path('captcha/', include('captcha.urls')),
]
# 找出没有被测试过的函数和代码行
from django.test import TestCase
from api.models import User
from django.urls import reverse
# 测试User表正常工作
class TestUserModel(TestCase):
def setUp(self) -> None:
# 测试前的准备工作
user = User(username='solomon', password='147258Wang.')
user.save()
def test_user_model(self):
# 使用被测试提供的类进行一定操作
result = User.objects.get(username='solomon')
self.assertEqual(result.password, '147258Wang.')
class TestBlogIndex(TestCase):
def test_blog_get(self):
response = self.client.get(reverse('api:blog'))
print('response code > ', response.status_code)
self.assertEqual(response.status_code, 200)
def test_blog_post(self):
response = self.client.post(reverse('api:blog'), data={
'title': 'Django by example 2',
'author': 'solomon wang',
'description': 'learning django framework',
})
self.assertEqual(response.status_code, 200)
在HTML中使用Form
<div>
<form action="" method="post">
{% csrf_token %}
<p>
<label>title</label>
<input type="text" name="title">
</p>
<p>
<label>author</label>
<input type="text" name="author">
</p>
<p>
<label>description</label>
<input type="text" name="description">
</p>
<input type="submit" value="save">
</form>
</div>
在Django视图中
def HelloBlog(request):
if request.method == 'GET':
return render(request, 'blog.html')
elif request.method == 'POST':
title = request.POST.get('title')
author = request.POST.get('author')
description = request.POST.get('description')
blog_object = models.Blog(title=title, author=author, description=description)
blog_object.save()
return JsonResponse({'code': 100100, 'message': '数据成功保存'}, status=200)
else:
return JsonResponse({'code': 100101, 'message': '请求方法出错'}, status=404)