我們都知道驗證碼是一張圖片,這樣程序自動識別的難度大,安全性高。
設計到圖片,先來看一下img標簽里的src屬性,也是實現驗證碼的一個小原理
我們都知道src屬性可以直接把圖片拿過來:
比如說拿到本地的圖片
就在直接可以顯示在頁面上
那它是怎么實現的呢?
其實src屬性同樣像服務端發送了一個請求,Django服務端接收到之后,自動把本地文件讀取并返回給了客戶端,就實現了上面的效果
下面來自己實現一下:
html:
#src屬性是一個url,
對應處理函數:
def
tu2
(
request
)
:
f
=
open
(
"static/timg.jpg"
,
"rb"
)
data
=
f
.
read
(
)
f
.
close
(
)
return
HttpResponse
(
data
)
如此就能發現兩者效果相同。
下面開始講驗證碼:
先貼上借鑒的博客,內含需要的文件:
https://blog.csdn.net/weixin_42100915/article/details/80851474
先生成驗證碼效果:
后臺處理函數:
def
yanzhengma
(
request
)
:
f
=
BytesIO
(
)
#創建生成一個內存地址
img
,
code
=
create_validate_code
(
)
#生成驗證碼, code是驗證碼文字內容,img是驗證碼對象
print
(
code
)
img
.
save
(
f
,
"PNG"
)
#把驗證碼寫入內存地址
return
HttpResponse
(
f
.
getvalue
(
)
)
#把驗證碼從內存中讀出來并返回給客戶端
def
register
(
request
)
:
return
render
(
request
,
"register.html"
)
HTML
<
body
>
<
form
action
=
"
"
>
form
>
<
p
>
用戶名
<
input
type
=
"
text
"
placeholder
=
"
請輸入用戶名
"
>
p
>
<
p
>
密碼
<
input
type
=
"
text
"
placeholder
=
"
請輸入密碼
"
>
p
>
<
p
>
確認密碼
<
input
type
=
"
text
"
placeholder
=
"
請確認密碼
"
>
p
>
<
p
>
驗證碼
<
input
type
=
"
text
"
placeholder
=
"
請輸入驗證碼
"
>
<
img
src
=
"
/yanzhengma
"
alt
=
"
"
>
p
>
body
>
下面上完整代碼:帶驗證功能和點擊刷新功能
處理函數:
def
yanzhengma
(
request
)
:
'''生成驗證碼'''
f
=
BytesIO
(
)
#創建生成一個內存地址
img
,
code
=
create_validate_code
(
)
#生成驗證碼, code是驗證碼文字內容,img是驗證碼對象
print
(
code
)
img
.
save
(
f
,
"PNG"
)
#把驗證碼寫入內存地址
request
.
session
[
"check_code"
]
=
code
#對應驗證用的
return
HttpResponse
(
f
.
getvalue
(
)
)
#把驗證碼從內存中讀出來并返回給客戶端
def
register
(
request
)
:
"""業務函數"""
if
request
.
method
==
"GET"
:
return
render
(
request
,
"register.html"
)
else
:
check
=
request
.
POST
.
get
(
"check"
,
None
)
check_code
=
request
.
session
[
"check_code"
]
if
check
==
check_code
:
return
HttpResponse
(
"注冊成功"
)
HTML
<
html
lang
=
"
en
"
>
<
head
>
<
meta
charset
=
"
UTF-8
"
>
<
title
>
Title
title
>
head
>
<
body
>
<
form
action
=
"
/register/
"
method
=
"
post
"
>
{% csrf_token %}
<
p
>
用戶名
<
input
type
=
"
text
"
placeholder
=
"
請輸入用戶名
"
>
p
>
<
p
>
密碼
<
input
type
=
"
text
"
placeholder
=
"
請輸入密碼
"
>
p
>
<
p
>
確認密碼
<
input
type
=
"
text
"
placeholder
=
"
請確認密碼
"
>
p
>
<
p
>
驗證碼
<
input
type
=
"
text
"
placeholder
=
"
請輸入驗證碼
"
name
=
"
check
"
>
<
img
src
=
"
/yanzhengma/
"
alt
=
"
"
id
=
"
check
"
>
p
>
<
input
type
=
"
submit
"
value
=
"
注冊
"
>
form
>
<
script
>
document
.
getElementById
(
"check"
)
.
onclick
=
function
(
)
{
this
.
src
=
this
.
src
+
"?"
//點一次就加一個問號,會重新發送一次請求
}
script
>
body
>
html
>
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
