52.md 10.2 KB
Newer Older
W
wizardforcel 已提交
1 2
{% raw %}

W
wizardforcel 已提交
3
# Flask 和登录验证
W
init  
wizardforcel 已提交
4 5 6 7 8

> 原文: [https://pythonspot.com/login-authentication-with-flask/](https://pythonspot.com/login-authentication-with-flask/)

![flask-logo](img/18374e2fa266165025a38238c3cdc35f.jpg)

W
wizardforcel 已提交
9
Flask 图标
W
init  
wizardforcel 已提交
10 11 12

在本教程中,您将学习如何使用 [Flask](https://pythonspot.com/en/python-flask-tutorials/) 和 Python 构建登录 Web 应用程序。

W
wizardforcel 已提交
13
### 建立一个 Flask 登录页面
W
init  
wizardforcel 已提交
14

W
wizardforcel 已提交
15
创建此 Python 文件并将其另存为`app.py`
W
init  
wizardforcel 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

```py
from flask import Flask
from flask import Flask, flash, redirect, render_template, request, session, abort
import os

app = Flask(__name__)

@app.route('/')
def home():
if not session.get('logged_in'):
return render_template('login.html')
else:
return "Hello Boss!"

@app.route('/login', methods=['POST'])
def do_admin_login():
if request.form['password'] == 'password' and request.form['username'] == 'admin':
session['logged_in'] = True
else:
flash('wrong password!')
return home()

if __name__ == "__main__":
app.secret_key = os.urandom(12)
app.run(debug=True,host='0.0.0.0', port=4000)

```

在此处创建了两条路由(您可以在浏览器 URL 栏中看到的路径):

```py
@app.route('/')
@app.route('/login', methods=['POST'])

```

第一个显示基于登录条件的登录屏幕或主屏幕。第二个路由在登录时验证登录变量。

W
wizardforcel 已提交
55
我们创建目录`/templates/`。 使用以下代码创建文件`/templates/login.html`
W
init  
wizardforcel 已提交
56 57

```py
W
wizardforcel 已提交
58 59
{% block body %};
{% if session['logged_in'] %};
W
init  
wizardforcel 已提交
60 61 62

You're logged in already!

W
wizardforcel 已提交
63
{% else %};
W
init  
wizardforcel 已提交
64 65 66 67 68
<form action="/login" method="POST">
  <input type="username" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Log in">
</form>
W
wizardforcel 已提交
69 70 71
{% endif %};
{% endblock %};
{% endraw %};
W
init  
wizardforcel 已提交
72 73 74 75 76 77 78 79 80 81

```

使用以下命令运行 Web 应用程序:

```py
$ python hello.py

```

W
wizardforcel 已提交
82
在您的网络浏览器中打开 [http://localhost:5000/](http://localhost:5000/) ,然后会出现登录屏幕。 登录凭据显示在`do_admin_login()`函数中。
W
init  
wizardforcel 已提交
83

W
wizardforcel 已提交
84
![Pythonspot.com Login Screen Python](img/00af7aae4e992d7feccf73ba2c75cb8f.jpg)
W
init  
wizardforcel 已提交
85

W
wizardforcel 已提交
86
Pythonspot.com 登录界面
W
init  
wizardforcel 已提交
87 88 89

### 使它看起来很棒

W
wizardforcel 已提交
90 91
功能正常时,登录屏幕看起来像 90 年代初期的用户界面(UI)。 我们从 [codepen.io](https://codepen.io) 中选择了一个随机登录模板。 我们使用文件`style.css`创建目录`/static/`

W
init  
wizardforcel 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

```py
* {
box-sizing: border-box;
}

*:focus {
outline: none;
}
body {
font-family: Arial;
background-color: #3498DB;
padding: 50px;
}
.login {
margin: 20px auto;
width: 300px;
}
.login-screen {
background-color: #FFF;
padding: 20px;
border-radius: 5px
}

.app-title {
text-align: center;
color: #777;
}

.login-form {
text-align: center;
}
.control-group {
margin-bottom: 10px;
}

input {
text-align: center;
background-color: #ECF0F1;
border: 2px solid transparent;
border-radius: 3px;
font-size: 16px;
font-weight: 200;
padding: 10px 0;
width: 250px;
transition: border .5s;
}

input:focus {
border: 2px solid #3498DB;
box-shadow: none;
}

.btn {
border: 2px solid transparent;
background: #3498DB;
color: #ffffff;
font-size: 16px;
line-height: 25px;
padding: 10px 0;
text-decoration: none;
text-shadow: none;
border-radius: 3px;
box-shadow: none;
transition: 0.25s;
display: block;
width: 250px;
margin: 0 auto;
}

.btn:hover {
background-color: #2980B9;
}

.login-link {
font-size: 12px;
color: #444;
display: block;
margin-top: 12px;
}

```

W
wizardforcel 已提交
175
`login.html`模板修改为:
W
init  
wizardforcel 已提交
176 177 178

```py
 	 	 	<link rel="stylesheet" href="/static/style.css" type="text/css">
W
wizardforcel 已提交
179
{% block body %};
W
init  
wizardforcel 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

<form action="/login" method="POST">
<div class="login">
<div class="login-screen">
<div class="app-title">
<h1>Login</h1>
</div>
<div class="login-form">
<div class="control-group">
				<input type="text" class="login-field" value="" placeholder="username" name="username">
<label class="login-field-icon fui-user" for="login-name"></label></div>
<div class="control-group">
				<input type="password" class="login-field" value="" placeholder="password" name="password">
<label class="login-field-icon fui-lock" for="login-pass"></label></div>
<input type="submit" value="Log in" class="btn btn-primary btn-large btn-block">

</div>
</div>
</div>
</form>
W
wizardforcel 已提交
200
{% endblock %};
W
init  
wizardforcel 已提交
201 202 203

```

W
wizardforcel 已提交
204
重新启动应用程序后,将出现以下屏幕:
W
init  
wizardforcel 已提交
205

W
wizardforcel 已提交
206
![Python login screen Flask](img/fb0c1e80aa99b4e5cdf8e4159b31d784.jpg)
W
init  
wizardforcel 已提交
207

W
wizardforcel 已提交
208
Python Flask 登录界面
W
init  
wizardforcel 已提交
209 210 211 212 213

很棒,不是吗? :-)

### 那么注销呢?

W
wizardforcel 已提交
214
如您所见,没有注销按钮或功能。 创建起来非常容易。 下面提出的解决方案只是众多解决方案之一。 我们创建一个新的路由`/logout`,它直接指向函数`logout()`。 此函数清除会话变量并返回登录屏幕。
W
init  
wizardforcel 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

```py
@app.route("/logout")
def logout():
session['logged_in'] = False
return home()

```

完整代码:

```py
from flask import Flask
from flask import Flask, flash, redirect, render_template, request, session, abort
import os

app = Flask(__name__)

@app.route('/')
def home():
if not session.get('logged_in'):
return render_template('login.html')
else:
return "Hello Boss!  <a href="/logout">Logout</a>"

@app.route('/login', methods=['POST'])
def do_admin_login():
if request.form['password'] == 'password' and request.form['username'] == 'admin':
session['logged_in'] = True
else:
flash('wrong password!')
return home()

@app.route("/logout")
def logout():
session['logged_in'] = False
return home()

if __name__ == "__main__":
app.secret_key = os.urandom(12)
app.run(debug=True,host='0.0.0.0', port=4000)

```

### 连接数据库

W
wizardforcel 已提交
261
如果要使用多用户登录系统,则应在应用程序中添加一个数据库层。Flask 没有现成的数据库支持。 如果要数据库支持,则必须使用第三方库。 在本教程中,我们将使用 SqlAlchemy。 如果您没有安装,请执行以下操作:
W
init  
wizardforcel 已提交
262 263 264 265 266 267 268 269

```py
$ sudo pip install Flask-SqlAlchemy

```

SQLAlchemy 是用于 Python 编程语言的 SQL 工具箱和对象关系映射器(ORM)。 它支持 MySQL,Microsoft SQL Server 和许多其他关系数据库管理系统。 如果您不熟悉所有这些术语,请继续阅读。

W
wizardforcel 已提交
270
创建文件`tabledef.py`
W
init  
wizardforcel 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

```py
from sqlalchemy import *
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref

engine = create_engine('sqlite:///tutorial.db', echo=True)
Base = declarative_base()

########################################################################
class User(Base):
""""""
__tablename__ = "users"

id = Column(Integer, primary_key=True)
username = Column(String)
password = Column(String)

#----------------------------------------------------------------------
def __init__(self, username, password):
""""""
self.username = username
self.password = password

# create tables
Base.metadata.create_all(engine)

```

使用以下命令执行:

```py
python tabledef.py

```

W
wizardforcel 已提交
309
该文件将创建数据库结构。在目录内,您将找到一个名为`tutorial.db`的文件。创建一个名为`dummy.py`的文件,其中将包含以下代码:
W
init  
wizardforcel 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345

```py
import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from tabledef import *

engine = create_engine('sqlite:///tutorial.db', echo=True)

# create a Session
Session = sessionmaker(bind=engine)
session = Session()

user = User("admin","password")
session.add(user)

user = User("python","python")
session.add(user)

user = User("jumpiness","python")
session.add(user)

# commit the record the database
session.commit()

session.commit()

```

执行:

```py
$ python dummy.py

```

W
wizardforcel 已提交
346
这会将伪数据放入数据库中。 最后,我们更新`app.py`
W
init  
wizardforcel 已提交
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369

## 使用 SqlAlchemy 验证登录凭据

下一步是编写验证数据库中存在的用户和密码的功能。 使用 SqlAlchemy 我们可以做到这一点(虚拟/伪代码):

```py
@app.route('/test')
def test():

POST_USERNAME = "python"
POST_PASSWORD = "python"

Session = sessionmaker(bind=engine)
s = Session()
query = s.query(User).filter(User.username.in_([POST_USERNAME]), User.password.in_([POST_PASSWORD]) )
result = query.first()
if result:
return "Object found"
else:
return "Object not found " + POST_USERNAME + " " + POST_PASSWORD

```

W
wizardforcel 已提交
370
我们使用 SqlAlchemys Oject 关系映射(ORM)。 我们将对象映射到关系数据库表,反之亦然。 定义(用户)在`tabledef.py`中给出。`s.query`函数是构建查询的地方。 我们有两个条件:用户名和密码必须匹配。 如果对象存在,`query.first()`返回`true`,否则返回`false`。 这给出了以下总代码:
W
init  
wizardforcel 已提交
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419

```py
from flask import Flask
from flask import Flask, flash, redirect, render_template, request, session, abort
import os
from sqlalchemy.orm import sessionmaker
from tabledef import *
engine = create_engine('sqlite:///tutorial.db', echo=True)

app = Flask(__name__)

@app.route('/')
def home():
if not session.get('logged_in'):
return render_template('login.html')
else:
return "Hello Boss!  <a href="/logout">Logout</a>"

@app.route('/login', methods=['POST'])
def do_admin_login():

POST_USERNAME = str(request.form['username'])
POST_PASSWORD = str(request.form['password'])

Session = sessionmaker(bind=engine)
s = Session()
query = s.query(User).filter(User.username.in_([POST_USERNAME]), User.password.in_([POST_PASSWORD]) )
result = query.first()
if result:
session['logged_in'] = True
else:
flash('wrong password!')
return home()

@app.route("/logout")
def logout():
session['logged_in'] = False
return home()

if __name__ == "__main__":
app.secret_key = os.urandom(12)
app.run(debug=True,host='0.0.0.0', port=4000)

```

现在,您可以使用数据库表中定义的任何用户登录。

### 那么安全性呢?

W
wizardforcel 已提交
420
我们在上面演示了一个简单的登录应用程序。 但是,正确保护它是您的工作。 有很多人会尝试闯入您的应用程序。
W
init  
wizardforcel 已提交
421

W
wizardforcel 已提交
422
[下载 Flask 示例](https://pythonspot.com/en/download-flask-examples/)
W
init  
wizardforcel 已提交
423

W
wizardforcel 已提交
424
最佳做法:
W
init  
wizardforcel 已提交
425 426 427 428 429 430 431 432 433 434

*   [散列数据库密码](https://en.wikipedia.org/wiki/Hash_function)。 不要将它们存储为纯文本格式。

*   使用 [HTTPS](https://en.wikipedia.org/wiki/HTTPS) 来保护连接。

*   记录失败的登录尝试。

*   使用验证码可以防止暴力破解登录。

*   其他? 在评论中写下它们。