1. 在vs code中創(chuàng)建以下目錄:
www
│ server.py
├─imgs
└─templates
base.html
column.html
index.html
login.html
server.py 是服務(wù)器文件置逻,templates文件夾放置html模板,imgs放置圖片备绽,不要改變文件夾名稱券坞。
2. server.py
from flask import Flask,render_template,url_for,redirect,request
from wtforms import Form,TextField,PasswordField
from wtforms.validators import Required
app = Flask(__name__)
class LoginForm(Form):
username = TextField('username',[Required()])
password = PasswordField('password',[Required()])
@app.route("/")
def index():
return render_template('index.html',message=["hello","world"])
@app.route('/login',methods=["GET","POST"])
def login():
myForm = LoginForm(request.form)
if request.method == "POST":
if myForm.username.data == 'jack' and myForm.password.data == "123" and myForm.validate():
return redirect(url_for('column'))
else:
return render_template('login.html',ticks='賬戶密碼錯誤鬓催!',form=myForm)
return render_template('login.html',form=myForm)
@app.route('/column')
def column():
return render_template("column.html")
if __name__ == '__main__':
app.run(host='0.0.0.0',debug=True)
3. base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<a href="{{ url_for('index')}}"> index </a>
<a href="{{ url_for('login')}}"> login </a>
<hr>
{% block content %}
{% endblock %}
<div>
copyright superexpo ,all right recived!
</div>
</body>
</html>
4. index.html
{% extends "base.html" %}
{% block content %}
<h1>首頁</h1>
{% if ticks %}{{ticks}}{% endif %}
{% for m in message%}
{{m}}<br>
{% endfor %}
{% endblock %}
5. login.html
{% extends "base.html" %}
{% block content%}
<h1>登錄界面</h1>
<form method="post">
username{{ form.username}}<br>
password{{ form.password}}<br>
<input type="submit" name="submit">
<input type="reset"><br>
{% if ticks %}{{ticks}}{% endif %}<br>
</form>
{% endblock %}
6. column.html
{% extends "base.html" %}
{% block content%}
<h1>驗證通過!</h1>
{% endblock %}
小結(jié):
- 手寫html是非常費時費力的工作恨锚,好在我們有emmet工具宇驾,html:5 語法可以生成html框架,配合其他語法可以像寫公式一樣快速的寫出大段html猴伶;
- 用wtform 插件取代硬寫表單课舍;
- 用 app.run(host='0.0.0.0',debug=True) 參數(shù)可以實現(xiàn)局域網(wǎng)內(nèi)訪問。