记录#
- 最近这两周状态不好、事情太多导致这个学习计划耽误太多了。今天开始补上!
- 今天的练习是写一个私人的博客页面,具有登录功能和发布功能。
- 这个练习的遇到的问题不少:
- redirect 的时候是 return
- 向 db 中存入数据的时候,如果值 = “” ,因为有引号的包裹,所以会被当作字符串存储。所以存入 json 格式的时候,最外面一定不能有引号。
- 循环或 if 后面的代码的缩进要正确,对 for 循环的理解有待加强。
CODE#
main.py#
from flask import Flask, request, redirect, session
from replit import db
import os
from datetime import datetime
app = Flask(__name__)
app.secret_key = os.environ['sission_key']
@app.route('/', methods=['GET'])
def index():
#db['user'] = {'name': 'reno', 'pass': '123'}
if session.get('name'):
text1 = ""
f = open("index.html", "r")
page = f.read()
f.close()
for key in db.keys():
if key and key != "user":
name = db[key]
text = f"""
</hr>
<h2>{name["title"]}</h2>
<p>{key}</p>
<p>{name["text"]}</p>
"""
text1 += text
page = page.replace("{text}", text1)
return page
else:
return redirect('/log')
@app.route('/', methods=["POST"])
def submit():
text = request.form
ttime = datetime.now()
title = text["title"]
text = text["text"]
db[ttime] = {"title": title, "text": text}
return redirect('/')
@app.route('/log1')
def log1():
return f"page{session.get('name')}"
@app.route('/log')
def log():
f = open("login.html", "r")
page = f.read()
f.close()
return page
@app.route('/login', methods=["POST"])
def login():
user = request.form
vuser = db['user']
if vuser['name'] == user["name"] and vuser['pass'] == user["pass"]:
session["name"] = vuser['name']
print("--")
print(session.get('name'))
print("--")
return redirect("/")
else:
return "NAME OR PASS ERROR!"
app.run(host='0.0.0.0', port=81)
index.html#
<html>
<head>
<title>MY BLOG</title>
</head>
<body>
<h1>MY BLog</h1>
<hr />
<form method="post" action="/">
<p>Title: <input type="text" name="title"></p>
<p>Text: <input type="text" name="text"></p>
<button>submit</button>
</form>
<p>{text}</p>
</body>
</html>
login.html#
<form method="post" action="/login">
<p>Name: <input name="name" type="text" ></p>
<p>Pass: <input name="pass" type="text" ></p>
<p><button name="submit" value="submit">submit</button></p>
</form>