這個小項目的代碼是基於https://github.com/anfederico和https://github.com/xuweicn1兩位的工作,讓我可以幾天內從知道flask的概念到把網頁部署到阿里雲。感謝造輪子的大神。
整個小項目的代碼可以到https://github.com/zhangjipinggom/flask-sql下載
一、成品效果
首先登陸界面,註冊或登陸成功後將進入操作界面。可以編輯各項內容、計算得分、下載生成的文件。具體的內容需要看代碼
二、中途採坑及重點總結
1. 前端(html)和後端(.py)實現數據傳輸的方式:
以下面的代碼爲例。student_single這個函數可以被網頁通過url_for()調用,調用時候往這個函數傳入參數。最後的render_template()參數中,第一個爲要渲染的網頁,後面的參數可以向這個網頁傳遞這些參數。這網頁中通過{{變量名}}這樣的方式來引用。
@app.route('/student_single/<name_student>')
def student_single(name_student):
student_test = Student.query.filter_by(name=name_student).first()
todos_student = Todo.query.filter_by(student=student_test).all()
scores = {}
categories = Category.query.all()
score_all = 0
for category in categories:
score = 0
todos = Todo.query.filter_by(student=student_test, category=category)
for todo in todos:
score += todo.scoreweight.value
score_all += todo.scoreweight.value
scores[category.name] = score
scores["All"] = score_all
return render_template(
'student-single.html',
todos=todos_student,
categories=Category.query.all(),
student=student_test,
scoreweights=ScoreWeight.query.all(),
scores=scores
)
可以參考https://blog.csdn.net/weixin_41279532/article/details/84497881
2. 生成excel文件並下載:
如果在這個過程中提示Latin.....utf-8編碼錯誤。注意下面函數的參數:
response.headers["Content-Disposition"] = \ "attachment;" \ "filename*=UTF-8''{utf_filename}".format( utf_filename=quote(basename.encode('utf-8')) )
@app.route('/student_single/<name_student>/')
def student_download(name_student):
student_test = Student.query.filter_by(name=name_student).first()
dict_w = {}
categories = Category.query.all()
score_all = 0
length_max = 0
dict_w["姓名"] = [name_student]
for category in categories:
score = 0
content = []
todos = Todo.query.filter_by(student=student_test, category=category)
for todo in todos:
content += [todo.description]
score += todo.scoreweight.value
score_all += todo.scoreweight.value
dict_w[category.name] = content
dict_w["score_"+category.name] = [score]
length_max = max(length_max, len(content))
dict_w["ScoreAll"] = [score_all]
for key0 in dict_w.keys():
length0 = len(dict_w[key0])
if length0 < length_max:
dict_w[key0] += [""] * (length_max - length0)
df = pd.DataFrame(dict_w)
out = io.BytesIO()
writer = pd.ExcelWriter(out, engine="xlsxwriter")
df.to_excel(excel_writer=writer, index=False, sheet_name="{}".format(name_student))
writer.save()
writer.close()
response = make_response(out.getvalue())
basename = "{}.xlsx".format(name_student)
response.headers["Content-Disposition"] = \
"attachment;" \
"filename*=UTF-8''{utf_filename}".format(
utf_filename=quote(basename.encode('utf-8'))
)
return response
這裏可以參考https://blog.csdn.net/qq_35318838/article/details/101354968
https://www.cnblogs.com/gresstant/p/7943056.html
3. 將代碼部署到雲端,讓手機或者其他代碼也能訪問自己的網頁
(1)方式一:用python anywhere https://www.pythonanywhere.com/
這種方式最簡便。但是我部署的時候運行出來的結果和我自己在本地跑的不一致,現在也沒找到原因。不得不用第二種方法。
(2)服務器+nginx
網上教程太多,也折騰了好幾個。最後是下面這個博客最簡單的第三種方法實現的
https://www.jianshu.com/p/61d18009b657
總結起來也就幾步:
a. 安裝nginx(sudo apt-get install nginx)
b. 配置Nignx--(cd //etc/nginx/nginx.conf)
#只用nginx代理的配置
server {
listen 80;
server_name 47.106.218.225; # 阿里雲公網ip
location / {
proxy_pass http://127.0.0.1:5000; # 本機:啓動端口(此處端口與項目端口一致)
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
c. 重啓nginx:
nginx -s reload
如果出現報錯:nginx: [error] open() "/var/run/nginx.pid" failed (2: No such file or directory)
可能是nginx服務沒有啓動
systemctl start nginx # 啓動nginx
d. 在服務器上運行主程序。比如 python app.py
然後在其他電腦或手機輸入ip(比如http://47.106.218.225) 就可以訪問呈現運行的結果
4. db.create_all()加的地方要注意