原文: http://www.catonlinepy.tech/
声明: 原创不易,未经许可,不得转载
1. 你将学会什么
今天的教程主要给大家介绍,如何在Flask应用中添加个人主页以及在个人主页中如何上传用户头像。教程中的代码都会托管到github上,猫姐一如既往的强调,在学习本课内容时一定要亲自动手实现代码,遇到问题再到github上查看代码,如果实在不知道如何解决,可以在日志下方留言。
2. 个人主页的实现
2.1 项目目录的创建
在创建个人主页之前,先来创建今天的项目目录,猫姐直接将第5天的day5目录复制后改成day6,然后程序里面的userauth_demo目录改成userprofile_demo目录,并将代码中的userauth_demo改为userprofile_demo。在此基础上,我们还需要创建如下文件和目录:
# 注意:以下所有的操作都必须在虚拟环境中进行
# 在userprofile_demo新建文件utils.py文件,此文件用来保存一些功能独立的小函数
(miao_venv) maojie@Thinkpad:~/flask-plan/flask-course-primary/day6/userprofile_demo$ touch utils.py
# 在userprofile_demo目录下新建static目录,此目录用来保存css,js及图片文件
(miao_venv) maojie@Thinkpad:~/flask-plan/flask-course-primary/day6/userprofile_demo$ mkdir static
# cd到static目录
(miao_venv) maojie@Thinkpad:~/flask-plan/flask-course-primary/day6/userprofile_demo$ cd static
# 在static目录中新建profile目录,用户上传的头像图片将保存到该目录
(miao_venv) maojie@Thinkpad:~/flask-plan/flask-course-primary/day6/userprofile_demo/static$ mkdir profile
# 在templates目录中新建account.html文件
(miao_venv) maojie@Thinkpad:~/flask-plan/flask-course-primary/day6/userprofile_demo/templates$ touch account.html
最终,我们得到今天项目的目录结构如下(使用tree命令得到):
(miao_venv) maojie@Thinkpad:~/flask-plan/flask-course-primary$ tree day6
day6
├── run.py
└── userprofile_demo
├── config.py
├── database.db
├── forms.py
├── __init__.py
├── models.py
├── routes.py
├── static
│ └── profile
│ └── default.jpg
├── templates
│ ├── account.html
│ ├── index.html
│ ├── layout.html
│ ├── login.html
│ └── register.html
└── utils.py
2.2 为个人主页添加入口链接
通常,在用户登录后,在主页导航栏中会有一个用户名的超链接,当用户点击这个超链接时,就会跳转到用户的个人主页。下面,我们在layout.html文件的导航栏中添加个人主页的入口:
<html>
<head>
{% if title %}
<title>{
{ title }}-喵星在线</title>
{% else %}
<title>喵星在线</title>
{% endif %}
{% block js %}
{% endblock js%}
</head>
<header>
<div>
<a href="{
{ url_for('index') }}">主页</a>
{% if current_user.is_authenticated %}
<a href="{
{ url_for('logout') }}">注销</a>
<a href="#">{
{current_user.username}}</a>
{% else %}
<a href="{
{ url_for('login') }}">登陆</a>
{% endif %}
</div>
</header>
<body>
<!-- 渲染flash消息 -->
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{
{ category }}">
{
{ message }}
</div>