最近学习了一下flask,想着自己做一个简单的服务器框架来练手
文件目录:
/__init__.py
/templates
/404_refresh.html
/image.html
/login.html
/static
/images
/pig.jpg
__init__.py:
from flask import Flask,redirect,url_for,request,render_template,abort,session,make_response
import os
app = Flask("hp",static_folder = "static",template_folder = "templates")#设置flask设置
app.config["SECRET_KEY"] = os.urandom(24)#设置密钥
@app.route("/success/<name>")
def success(name):
return render_template("image.html",name = name)#调用图片模板
@app.errorhandler(404)
def error_date(error):
return render_template("404_refresh.html"),404#返回404错误
@app.route("/")
def index():
if "password" in session:#获取会话数据
user = session["username"]
return redirect(url_for("success",name = user))#重定向验证成功页面
else:
return redirect(url_for("login"))#自动重定向至登入页面
@app.route("/login")
def login():
return render_template("login.html")#调用登入模板
@app.route("/logout")
def logout():
resp = make_response("")
resp.delete_cookie("hhcgchpspk")
session.pop("username",None)
session.pop("password",None)
return redirect(url_for("login"))
#注销用户记录
@app.route("/handle",methods = ["GET","POST"])
def handle():
if request.method == "POST":
if request.form["password"] == "123456":#密码正确
user = request.form["username"]#获取用户名
session["username"] = request.form["username"]#设置会话用户名
session["password"] = request.form["password"]#设置会话密码
resp = make_response("")
resp.set_cookie("hhcgchpspk","123456",max_age = 3600)#设置cookie
return redirect(url_for('success',name = user))#重定向验证成功页面
else:
abort(401)#身份未验证:
else:
return redirect(url_for("login"))#返回登入界面
if __name__ == "__main__":
app.run(host = "0.0.0.0",port = 8080,debug = True)
login.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset = "UTF-8">
<title>Login</title>
</head>
<body>
<form action = "http://localhost:8080/handle" method = "POST">
<h1>Pigtou</h1>
<br>
</br>
<strong>登录页面</strong>
<p> 输入用户名 <input type = "text" name = "username"/></p>
<p> 输入密码 <input type = "text" name = "password"/></p>
<p> <input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
image.html:
<!DOCTYPE html>
<html>
<head>
<title>Pigtou</title>
</head>
<body>
<hr />
<ul>
<li>hello {{name}}</li>
</ul>
<p><img alt="Pigtou" src="{{ url_for('static', filename='images/pig.jpg') }}" width = 300 height = 200></p>
<br>
<p> <a href = "/logout">点击此处注销</a> </p>
</br>
</body>
</html>
404_refresh.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv = "refresh" content = "1,/login">
<title>404_refresh</title>
</head>
<body>
<p>loading...</p>
</html>
附赠图片:
效果如下:
目前为止,框架在本地服务器还可以运行,但想放在公网上,还需要用到如cpolar等内网穿透服务,这里就不细说了(因为自己也不了解)