搜尋
首頁後端開發Python教學用Python實現web端用戶登入和註冊功能

用Python實現web端用戶登入和註冊功能

Apr 09, 2018 pm 05:28 PM
pythonweb註冊

這篇文章主要介紹了用Python實現web端用戶登入和註冊功能的教程,需要的朋友可以參考下

用戶管理是絕大部分Web網站都需要解決的問題。用戶管理涉及用戶註冊和登入。

用戶註冊相對簡單,我們可以先透過API把用戶註冊這個功能實現了:

_RE_MD5 = re.compile(r'^[0-9a-f]{32}$')

@api
@post('/api/users')
def register_user():
 i = ctx.request.input(name='', email='', password='')
 name = i.name.strip()
 email = i.email.strip().lower()
 password = i.password
 if not name:
  raise APIValueError('name')
 if not email or not _RE_EMAIL.match(email):
  raise APIValueError('email')
 if not password or not _RE_MD5.match(password):
  raise APIValueError('password')
 user = User.find_first('where email=?', email)
 if user:
  raise APIError('register:failed', 'email', 'Email is already in use.')
 user = User(name=name, email=email, password=password, image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email).hexdigest())
 user.insert()
 return user

注意用戶口令是客戶端傳遞的經過MD5計算後的32位元Hash字串,所以伺服器端並不知道用戶的原始口令。

接下來可以建立一個註冊頁面,讓使用者填寫註冊表單,然後,提交資料到註冊用戶的API:

{% extends '__base__.html' %}

{% block title %}注册{% endblock %}

{% block beforehead %}

<script>
function check_form() {
 $(&#39;#password&#39;).val(CryptoJS.MD5($(&#39;#password1&#39;).val()).toString());
 return true;
}
</script>

{% endblock %}

{% block content %}

<p class="uk-width-2-3">
 <h1 id="欢迎注册">欢迎注册!</h1>
 <form id="form-register" class="uk-form uk-form-stacked" onsubmit="return check_form()">
  <p class="uk-alert uk-alert-danger uk-hidden"></p>
  <p class="uk-form-row">
   <label class="uk-form-label">名字:</label>
   <p class="uk-form-controls">
    <input name="name" type="text" class="uk-width-1-1">
   </p>
  </p>
  <p class="uk-form-row">
   <label class="uk-form-label">电子邮件:</label>
   <p class="uk-form-controls">
    <input name="email" type="text" class="uk-width-1-1">
   </p>
  </p>
  <p class="uk-form-row">
   <label class="uk-form-label">输入口令:</label>
   <p class="uk-form-controls">
    <input id="password1" type="password" class="uk-width-1-1">
    <input id="password" name="password" type="hidden">
   </p>
  </p>
  <p class="uk-form-row">
   <label class="uk-form-label">重复口令:</label>
   <p class="uk-form-controls">
    <input name="password2" type="password" maxlength="50" placeholder="重复口令" class="uk-width-1-1">
   </p>
  </p>
  <p class="uk-form-row">
   <button type="submit" class="uk-button uk-button-primary"><i class="uk-icon-user"></i> 注册</button>
  </p>
 </form>
</p>

{% endblock %}
Try

這樣我們就把用戶註冊的功能完成了:

2015430102634859.jpg (560×753)

用戶登入比用戶註冊複雜。由於HTTP協議是一種無狀態協議,而伺服器要追蹤使用者狀態,就只能透過cookie實現。大多數Web框架提供了Session功能來封裝保存使用者狀態的cookie。

Session的優點是簡單易用,可以直接從Session中取出使用者登入資訊。

Session的缺點是伺服器需要在記憶體中維護一個映射表來儲存使用者登入訊息,如果有兩台以上伺服器,就需要對Session做集群,因此,使用Session的Web App很難擴展。

我們採用直接讀取cookie的方式來驗證使用者登錄,每次使用者造訪任意URL,都會對cookie進行驗證,這種方式的好處是保證伺服器處理任意的URL都是無狀態的,可以擴展到多台伺服器。

由於登入成功後是由伺服器產生一個cookie傳送給瀏覽器,所以,要確保這個cookie不會被客戶端偽造出來。

實現防偽造cookie的關鍵是透過單向演算法(例如MD5),舉例如下:

當用戶輸入了正確的口令登入成功後,伺服器可以從資料庫取到用戶的id,並且依照以下方式計​​算出一個字串:

"使用者id" "過期時間" MD5("使用者id" "使用者口令" "過期時間" "SecretKey")

#當瀏覽器發送cookie到伺服器端後,伺服器可以拿到的資訊包括:

  •     使用者id

  • ##    過期時間

  •     MD5值

如果未到過期時間,伺服器就依照使用者id找出使用者口令,並計算:

MD5("使用者id" "使用者口令" "過期時間" "SecretKey")

並與瀏覽器cookie中的MD5進行比較,如果相等,則表示使用者已登錄,否則,cookie就是偽造的。

這個演算法的關鍵在於MD5是一種單向演算法,即可以透過原始字串計算出MD5,但無法透過MD5反推出原始字串。

所以登入API可以實現如下:

@api
@post(&#39;/api/authenticate&#39;)
def authenticate():
  i = ctx.request.input()
  email = i.email.strip().lower()
  password = i.password
  user = User.find_first(&#39;where email=?&#39;, email)
  if user is None:
    raise APIError(&#39;auth:failed&#39;, &#39;email&#39;, &#39;Invalid email.&#39;)
  elif user.password != password:
    raise APIError(&#39;auth:failed&#39;, &#39;password&#39;, &#39;Invalid password.&#39;)
  max_age = 604800
  cookie = make_signed_cookie(user.id, user.password, max_age)
  ctx.response.set_cookie(_COOKIE_NAME, cookie, max_age=max_age)
  user.password = &#39;******&#39;
  return user

# 计算加密cookie:
def make_signed_cookie(id, password, max_age):
  expires = str(int(time.time() + max_age))
  L = [id, expires, hashlib.md5(&#39;%s-%s-%s-%s&#39; % (id, password, expires, _COOKIE_KEY)).hexdigest()]
  return &#39;-&#39;.join(L)

对于每个URL处理函数,如果我们都去写解析cookie的代码,那会导致代码重复很多次。

利用拦截器在处理URL之前,把cookie解析出来,并将登录用户绑定到ctx.request对象上,这样,后续的URL处理函数就可以直接拿到登录用户:

@interceptor(&#39;/&#39;)
def user_interceptor(next):
  user = None
  cookie = ctx.request.cookies.get(_COOKIE_NAME)
  if cookie:
    user = parse_signed_cookie(cookie)
  ctx.request.user = user
  return next()

# 解密cookie:
def parse_signed_cookie(cookie_str):
  try:
    L = cookie_str.split(&#39;-&#39;)
    if len(L) != 3:
      return None
    id, expires, md5 = L
    if int(expires) < time.time():
      return None
    user = User.get(id)
    if user is None:
      return None
    if md5 != hashlib.md5(&#39;%s-%s-%s-%s&#39; % (id, user.password, expires, _COOKIE_KEY)).hexdigest():
      return None
    return user
  except:
    return None
Try

#這樣,我們就完成了使用者註冊和登入的功能。


相關推薦:

python字串連接的幾種方式總結

python中的sort的方法使用詳解

以上是用Python實現web端用戶登入和註冊功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
2小時的Python計劃:一種現實的方法2小時的Python計劃:一種現實的方法Apr 11, 2025 am 12:04 AM

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python:探索其主要應用程序Python:探索其主要應用程序Apr 10, 2025 am 09:41 AM

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

您可以在2小時內學到多少python?您可以在2小時內學到多少python?Apr 09, 2025 pm 04:33 PM

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

如何在10小時內通過項目和問題驅動的方式教計算機小白編程基礎?如何在10小時內通過項目和問題驅動的方式教計算機小白編程基礎?Apr 02, 2025 am 07:18 AM

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

如何在使用 Fiddler Everywhere 進行中間人讀取時避免被瀏覽器檢測到?如何在使用 Fiddler Everywhere 進行中間人讀取時避免被瀏覽器檢測到?Apr 02, 2025 am 07:15 AM

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

Python 3.6加載Pickle文件報錯"__builtin__"模塊未找到怎麼辦?Python 3.6加載Pickle文件報錯"__builtin__"模塊未找到怎麼辦?Apr 02, 2025 am 07:12 AM

Python3.6環境下加載Pickle文件報錯:ModuleNotFoundError:Nomodulenamed...

如何提高jieba分詞在景區評論分析中的準確性?如何提高jieba分詞在景區評論分析中的準確性?Apr 02, 2025 am 07:09 AM

如何解決jieba分詞在景區評論分析中的問題?當我們在進行景區評論分析時,往往會使用jieba分詞工具來處理文�...

如何使用正則表達式匹配到第一個閉合標籤就停止?如何使用正則表達式匹配到第一個閉合標籤就停止?Apr 02, 2025 am 07:06 AM

如何使用正則表達式匹配到第一個閉合標籤就停止?在處理HTML或其他標記語言時,常常需要使用正則表達式來�...

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境