記錄#
- 最近這兩週狀態不好、事情太多導致這個學習計劃耽誤太多了。今天開始補上!
- 今天的練習是寫一個私人的部落格頁面,具有登錄功能和發布功能。
- 這個練習的遇到的問題不少:
- 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>