一、个人学期总结
通过一学期的学习,我学会了使用Flask框架搭建一个web service,并在其中加上一些简单的css,js,html等。为数18周的信息管理系统的学习让我感受颇深,每学一点新内容,老师都发布作业给我们完成,这对于我们是一种知识巩固的好方法,让我们及时发现没有理解的地方,并及时问老师和同学,及时掌握好新内容。学习过程中我也会自己通过网络学习简单的css的设计,一点一点修改自己页面的样式等等。
二、总结Python+Flask+MysqL的web建设技术过程
1、使用软件
Python3.5+mysql5.7+pycharm2017.2
2、数据库
(1)、连接数据库
import os SQLALCHEMY_DATABASE_URI=‘mysql+pymysql://root:@127.0.0.1:3306/hog?charset=utf8‘ SQLALCHEMY_TRACK_MODIFICATTONS = False SECRET_KEY = os.urandom(24)
(2)、创建数据库
app = Flask(__name__) app.config.from_object(config) db = SQLAlchemy(app) #创建用户模型 class User(db.Model): __tablename__ = ‘user‘ id = db.Column(db.Integer,primary_key=True,autoincrement=True) username = db.Column(db.String(20),nullable=False) _password = db.Column(db.String(200), nullable=False) #内部使用 @property def password(self):#外部使用,取值 return self._password @password.setter def password(self, row_password): self._password = generate_password_hash(row_password) def check_password(self, row_password):#外部使用,赋值 result = check_password_hash(self._password, row_password) return result class Question(db.Model): __tablename__ = ‘question‘ id = db.Column(db.Integer, primary_key=True, autoincrement=True) question = db.Column(db.String(100), nullable=False) questionDetail = db.Column(db.Text, nullable=False) creat_time = db.Column(db.DateTime, default=datetime.now) author_id = db.Column(db.Integer, db.ForeignKey(‘user.id‘)) author = db.relationship(‘User‘, backref=db.backref(‘question‘))#User类添加question属性,定义反向关系,这一属性可以访问Question模型 class Comment(db.Model): _tablename_=‘comment‘ id=db.Column(db.Integer,primary_key=True,autoincrement=True) author_id=db.Column(db.Integer,db.ForeignKey(‘user.id‘)) question_id=db.Column(db.Integer,db.ForeignKey(‘question.id‘)) detail=db.Column(db.Text,nullable=False) creat_time=db.Column(db.DateTime,default=datetime.now) question=db.relationship(‘Question‘,backref=db.backref(‘comments‘,order_by=creat_time.desc)) author=db.relationship(‘User‘,backref=db.backref(‘comments‘)) db.create_all()
3、页面设计
(1)注册&登录界面
js文件: onclick函数return True时才提交表单,return False时不提交表单。
html文件:
- <form>中设置 action和method="post"
- <input> 中设置 name
- onclick="return fnLogin()"
主py文件中:
- from flask import request, redirect, url_for
- @app.route(‘/regist/‘, methods=[‘GET‘, ‘POST’])
- 设置`SECRET_KEY`
- `session`:增加用户名`session[‘username‘]=`username
主要代码:
html:
<div class="box"> <h3>欢迎注册</h3> <form action="{{ url_for("sign_in") }}" method="post"> <div class="input_box"> 输入用户名: <input id="name" name="username" type="text" placeholder="请输入用户名" class="b1"> </div> <div class="input_box"> 输入密码: <input id="password" name="password" type="password" placeholder="请输入密码" class="b1"> </div> <div class="input_box"> 确认密码: <input id="passwordagain" name="passwordagain" type="password" placeholder="请确认密码" class="b1"> </div> <div id="error_box" class="error_box"><br></div> <div class="button"> <button class="login" onclick="fnLogin()">登录</button> <button class="cancel" onclick=window.alert("是否确认离开,您输入的数据可能不会被保存")>取消</button></div> </div> <div class="box"> <h3>欢迎登陆</h3> <form action="{{ url_for(‘sign_up‘) }}" method="post"> <div class="input_box"> 用户名: <input id="name" name=‘username‘ type="text" placeholder="请输入用户名" class="b1"> </div> <div class="input_box"> 密码: <input id="password" name="password" type="password" placeholder="请输入密码" class="b1"> </div> <div id="error_box" class="error_box"><br></div> <div class="button"> <button class="login" onclick="fnLogin()">登录</button> <button class="cancel" onclick=window.alert("是否确认离开,您输入的数据可能不会被保存")>取消</button> </div> </div>
js:
function fnLogin() { var uname=document.getElementById("name"); var upassword=document.getElementById("password"); var uError=document.getElementById("error_box"); var upasswordagain = document.getElementById("passwordagain"); var isError = true; uError.innerHTML="<br>"; if(uname.value.length<6||uname.value.length>20){ uError.innerHTML="用户名的长度需为6-20位"; isError = false; return isError; }else if((uname.value.charCodeAt(0)>=48)&&(uname.value.charCodeAt(0)<=57)){ uError.innerHTML="首字母不能是数字。"; isError = false; return isError; }else for(var i=0;i<uname.value.length;i++){ if((uname.value.charCodeAt(i)<48||uname.value.charCodeAt(i)>57)&&(uname.value.charCodeAt(i)<97||uname.value.charCodeAt(i)>122)){ uError.innerHTML="只能包含字母或数字。"; isError = false; return isError; } } if (upassword.value.length<6||upassword.value.length>20){ uError.innerHTML="密码的长度需为6-20位"; isError = false; return isError; } if(upasswordagain.value!=upassword.value){ uError.innerHTML="输入密码不一致。"; isError = false; return isError; }else if(upasswordagain.value==""){ uError.innerHTML="未确认密码。"; isError = false; return isError; } return isError; window.alert("登录成功!") }
py:
@app.route(‘/sign_up/‘,methods=[‘GET‘,‘POST‘])#登录 def sign_up(): if request.method == "GET": return render_template("sign_up.html") else: username = request.form.get("username") password = request.form.get("password") user = User.query.filter(User.username == username).first() if user: if user.check_password(password): session[‘user‘] = username session[‘userid‘] = user.id session.permanent = True return redirect(url_for(‘first‘)) else: return ‘password error‘ else: return ‘username is not existed‘ @app.route(‘/sign_in/‘,methods=[‘GET‘,‘POST‘])#注册 def sign_in(): if request.method == "GET": return render_template("sign_in.html") else: username = request.form.get("username") password = request.form.get("password") user = User.query.filter(User.username == username).first() if user: return ‘username existed.‘ else: user = User(username=username, password=password) db.session.add(user) db.session.commit() return redirect(url_for(‘sign_up‘))
(2)父模板,首页
主要代码:
html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}Hogwarts</title> <base target="_blank"> <link rel="stylesheet" type="text/css" href="{{ url_for(‘static‘,filename=‘css/base.css‘) }}"> <script src="{{ url_for(‘static‘,filename=‘js/base.js‘) }}"></script> {% block head %} {% endblock %} </head> <body class="body" id="myBody"> <header> <nav class="nav"> <ul> <li><img id="on_off" onclick="mySwitch()" src="{{ url_for(‘static‘,filename=‘images/bulboff.jpg‘) }}" width="40px"></li> <li><a href="{{ url_for(‘first‘) }}">首页</a></li> <li><a href="">校园新闻</a></li> <li><a href="{{ url_for(‘question‘) }}">讨论交流</a></li> <form action="{{ url_for(‘search‘) }}" method="get"> <li><input type="text"id="search" class="form-control" name="search"placeholder="请输入搜索内容" ></li> <li><button id="button1"type="submit">搜索</button></li> </form> {% if username %} <li>[<a href="{{ url_for(‘usercenter‘,user_id =session.get(‘userid‘),tag=1) }}" id="aaa">{{ username }}</a>·<a href="{{ url_for(‘logout‘) }}">注销</a>]</li> {% else %} <li>[<a href="{{ url_for(‘sign_up‘) }}">登录</a>·<a href="{{ url_for(‘sign_in‘) }}">注册</a>]</li> {% endif %} </ul> </nav> </header> <div class="title"> <h1>霍格沃兹论坛</h1> <h2>Hogwarts‘BBS</h2> </div> {% block main %} {% endblock %} <div id="bottom"> <a href="">联系我们</a> <a href="">加入我们</a> <a href="">校长室</a> <a href="">帮助中心</a> <a href="">合作伙伴</a> </div> <div class="copyright"> <p>Copyright © 2017. Created by <a href="#" target="_blank">Judy_L</a></p> </div> </body> </html> <p class="slogan">欢迎你,{{username}}</p> {% for foo in question %} <ul class="list-group" > <li class="list-group-item"> <span class="glyphicon glyphicon-leaf" aria-hidden="true"></span> <a href="{{ url_for(‘usercenter‘,user_id = foo.author_id,tag=1) }}">id:{{ foo.author.username }}</a> <br> <a href="{{ url_for(‘question_detail‘ ,question_id=foo.id)}}">标题:{{ foo.question }}</a> <br> <a >详情:{{ foo.questionDetail }}</a> <br> <span class="badge">{{ foo.creat_time }}</span> </li> </ul>
py:
@app.route(‘/‘) def first(): context = { ‘question‘: Question.query.order_by(‘creat_time‘).all() } return render_template(‘first.html‘,**context)
(3)登陆后更新导航条
- 用上下文处理器app_context_processor定义函数
- 获取session中保存的值
- 返回字典
- 在父模板中更新导航,插入登录状态判断代码。
- 注意用{% ... %}表示指令。
- {{ }}表示变量
- 完成注销功能。
- 清除session
- 跳转
html:
{% if username %} <li>[<a href="{{ url_for(‘usercenter‘,user_id =session.get(‘userid‘),tag=1) }}" id="aaa">{{ username }}</a>·<a href="{{ url_for(‘logout‘) }}">注销</a>]</li> {% else %} <li>[<a href="{{ url_for(‘sign_up‘) }}">登录</a>·<a href="{{ url_for(‘sign_in‘) }}">注册</a>]</li> {% endif %}
py:
@app.context_processor def mycontext(): usern=session.get(‘user‘) if usern: return {‘username‘:usern} else: return {} @app.route(‘/logout/‘) def logout(): session.clear() return render_template("first.html")
(4)发布功能 并在首页显示
- 编写要求登录的装饰器
from functools import wraps
def loginFirst(func): #参数是函数
@wraps(func)
def wrapper(*args, ** kwargs): #定义个函数将其返回
#要求登录
return func(*args, ** kwargs)
return wrapper #返回一个函数
- 应用装饰器,要求在发布前进行登录,登录后可发布。
@app.route(‘/question/‘,methods=[‘GET‘,‘POST‘])
@loginFirst
def question():
- 建立发布内容的对象关系映射。
class Question(db.Model):
- 完成发布函数。
保存到数据库。
重定向到首页:
- 在首页添加显示问答的列表,并定义好相应的样式。
- 用字典向index.html传递参数。
html:
<p class="slogan">欢迎你,{{username}}</p> {% for foo in question %} <ul class="list-group" > <li class="list-group-item"> <span class="glyphicon glyphicon-leaf" aria-hidden="true"></span> <a href="{{ url_for(‘usercenter‘,user_id = foo.author_id,tag=1) }}">id:{{ foo.author.username }}</a> <br> <a href="{{ url_for(‘question_detail‘ ,question_id=foo.id)}}">标题:{{ foo.question }}</a> <br> <a >详情:{{ foo.questionDetail }}</a> <br> <span class="badge">{{ foo.creat_time }}</span> </li> </ul> <div class="box1" > <form action="{{ url_for(‘question‘) }}" method="post"> <h3 > 发帖</h3> <div class="TT"> <label for="question">标题:</label><br> <textarea id="question" name="question" cols="100" rows="1"></textarea><br> <label for="questionDetail">内容:</label><br> <textarea id="questionDetail" name="questionDetail" cols="100" rows="10"></textarea> </div> <br> <div class="ja"> <button class="sent" onclick="fnchat">发布</button> </div> </div>
py:
def loginFirst(func): #参数是函数 @wraps(func) def wrapper(*args, **kwargs): #定义个函数将其返回 if session.get(‘user‘): return func(*args, **kwargs) else: return redirect(url_for(‘sign_up‘)) return wrapper #返回一个函数 @app.route(‘/question/‘, methods=[‘GET‘ , ‘POST‘]) @loginFirst def question(): if request.method == ‘GET‘: return render_template(‘question.html‘) else: question = request.form.get(‘question‘) questionDetail = request.form.get(‘questionDetail‘) author_id = User.query.filter(User.username == session.get(‘user‘)).first().id question = Question(question = question, questionDetail = questionDetail, author_id = author_id) db.session.add(question) #保存数据库 db.session.commit() #提交 return redirect(url_for(‘first‘))
(5)、首页链接到问答详情页
主PY文件写视图函数,带id参数。
@app.route(‘/question_detail/<question_id>‘) def question_detail(question_id): quest = Question.query.filter(Question.id == question_id).first() return render_template(‘question_detail.html‘,ques=quest)
首页标题的标签做带参数的链接。
{{ url_for(‘question_detail‘ ,question_id=foo.id)}}
在详情页将数据的显示在恰当的位置。
<div class="detail"> <div class="detail_left"> <h3>{{ ques.question }}</h3> <a href="{{ url_for(‘usercenter‘,user_id=session.get(‘userid‘),tag=1) }}" style="font-size: 18px">{{ ques.author.username }} <span class="badge">{{ ques.creat_time }}</span></a> <hr> <a>{{ ques.questionDetail }}</a> <hr> <form action="{{ url_for(‘comment‘) }}" method="post"> <textarea name="new_comment" class="form-control1" rows="3" id="new_comment" placeholder="请写下你的评论..."></textarea> <input name="question_id" type="hidden" value="{{ ques.id }}"/> <br><button type="submit" class="btn-default">发布</button> </form> <h4>评论:({{ ques.comments|length }})</h4> <ul class="list-group"> {% for foo in ques.comments %} <li class="list-group-item"> <span class="glyphion-heart-empty" aria-hidden="true"></span> ?<a href="{{ url_for(‘usercenter‘,user_id=session.get(‘userid‘),tag=1) }}">{{ foo.author.username }}</a> <span class="badge">{{ foo.creat_time }}</span> <p class="comdetail">{{ foo.detail }}</p> </li>
(6)完成评论功能
定义评论的视图函数
@app.route(‘/comment/‘,methods=[‘POST‘])
def comment():
读取前端页面数据,保存到数据库中
@app.route(‘/comment/‘, methods=[‘POST‘]) @loginFirst def comment(): comment = request.form.get("new_comment") question_id = request.form.get("question_id") author_id = User.query.filter(User.username == session.get(‘user‘)).first().id comm = Comment(author_id=author_id,question_id=question_id,detail=comment) db.session.add(comm) db.session.commit() context = { ‘question‘: Question.query.order_by(‘creat_time‘).all(), ‘comments‘: Comment.query.order_by(‘creat_time‘).all() } question = Question.query.filter(Question.id == question_id).first() return render_template(‘question_detail.html‘, ques=question, **context)
用<input type="hidden" 方法获取前端的"question_id"
<input name="question_id" type="hidden" value="{{ ques.id }}"/>
显示评论次数
<h4>评论:({{ ques.comments|length }})</h4>
要求评论前登录
@loginFirst
尝试实现详情页面下的评论列表显示
<ul class="list-group"> {% for foo in ques.comments %} <li class="list-group-item"> <span class="glyphion-heart-empty" aria-hidden="true"></span> ?<a href="{{ url_for(‘usercenter‘,user_id=session.get(‘userid‘),tag=1) }}">{{ foo.author.username }}</a> <span class="badge">{{ foo.creat_time }}</span> <p class="comdetail">{{ foo.detail }}</p> </li> {% endfor %} </ul>
(7)个人中心
新页面userbase.html,用<ul ><li role="presentation"> 实现标签页导航。
<ul class="nav nav-tabs">
<li role="presentation"><a href="#">Home</a></li>
<li role="presentation"><a href="#">Profile</a></li>
<li role="presentation"><a href="#">Messages</a></li>
</ul>
<ul class="nav_ul"> <h4>{{ user.username }}‘s zone</h4> <li role="presentation"><a href="{{ url_for(‘usercenter‘,user_id=user.id,tag=1) }}">全部问答</a> </li> <li role="presentation"><a href="{{url_for(‘usercenter‘,user_id=user.id,tag=2) }}">全部评论</a> </li> <li role="presentation"><a href="{{url_for(‘usercenter‘,user_id=user.id,tag=3) }}">个人信息</a> </li> <br><br><br><br><br> </ul> {% block user %} {% endblock %}
制作个人中心的三个子页面,重写userbase.html中定义的user块,分别用于显示问答、评论、个人信息
<div class="col-md-8 column" style="margin:0 auto;width:1000px;height:auto;border-style:groove; background-color:black; opacity: 0.7;"> <h3><span class="glyphicon glyphicon-user" aria-hidden="true"></span>{{username}} 发布的问题<span class="badge"></span> </h3> <ul class="list-unstyled"> {% for foo in questions %} <li class="list-group-item" style="list-style: none;"> <br><p>文章标题:<a href="{{ url_for(‘question_detail‘,question_id=foo.id)}}">{{ foo.question}}</a></p> <p>主要内容:{{ foo.questionDetail }}</p> <small><a>{{ foo.author.username }}</a></small> <span class="badge">{{foo.creat_time}}</span> <hr> </li> {% endfor %} </ul> </div> <div class="col-md-8 column" style="margin:0 auto;width:1000px;height:auto;border-style:groove; background-color:black; opacity: 0.7;"> <h3><span class="glyphicon glyphicon-user" aria-hidden="true"></span> {{username}} 发布的评论<span class="badge"></span> </h3> <ul class="list-unstyled"> {% for foo in comments %} <li class="list-group-item"> <span class="glyphicon glyphicon-heart-empty" aria-hidden="true"></span> <a href="#">{{foo.author.username }}</a> <span class="badge">{{foo.creat_time}}</span> <p style="">{{foo.detail}}</p> <br> </li> {% endfor %} </ul> </div> <div class="col-md-8 column"style="margin:0 auto;width:1000px;height:auto;border-style:groove; background-color:black; opacity: 0.7;" > <h3><span class="glyphicon glyphicon-user" aria-hidden="true"></span> {{username}}<small>个人信息<span class="badge"></span> </small></h3> <ul class="list-unstyled" > <li class="list-group-item">用户:{{username}}<a href="{{ url_for(‘ModifyPassword‘) }}">修改密码</a></li> <li class="list-group-item">文章篇:{{ user.question|length }}</li> <li class="list-group-item">评论数:{{ user.comments|length }}</li> </ul> </div>
py定义视图函数
@app.route(‘/usercenter/<user_id>/<tag>‘) @loginFirst def usercenter(user_id,tag): user=User.query.filter(User.id==user_id).first() mycontext={ ‘user‘:user, ‘questions‘: user.question, ‘comments‘: user.comments, } if tag == ‘1‘: return render_template(‘user1.html‘,**mycontext) elif tag == ‘2‘: return render_template(‘user2.html‘, **mycontext) else: return render_template(‘user3.html‘, **mycontext)
(8)搜索功能
- 准备视图函数search() 完成视图函数search()
- 获取搜索关键字q = request.args.get(‘q’)
- 条件查询qu = Question.query.filter(Question.title.contains(q)).order_by(‘-creat_time’)
- 加载查询结果:return render_template(‘index.html‘, question=qu)
@app.route(‘/search/‘)
def search():
qu = request.args.get(‘search‘)
ques = Question.query.filter(
or_(
Question.question.contains(qu),
Question.questionDetail.contains(qu)
)
).order_by(‘creat_time‘)
return render_template(‘base.html‘,questions = ques)
- 修改base.html 中搜索输入框所在的
- <form action="{{ url_for(‘search‘) }}" method="get">
- <input name="q" type="text" placeholder="请输入关键字">
<form action="{{ url_for(‘search‘) }}" method="get"> <li><input type="text"id="search" class="form-control" name="search"placeholder="请输入搜索内容" ></li> <li><button id="button1"type="submit">搜索</button></li> </form>
- 组合条件查询
from sqlalchemy import or_, and_
(9)密码保护
①更新User对象,设置对内的_password
_password = db.Column(db.String(200), nullable=False) #内部使用
②编写对外的password
from werkzeug.security import generate_password_hash, check_password_hash
③密码验证的方法:
def check_password(self, row_password): #密码验证
result = check_password_hash(self._password,row_password)
return result
@property def password(self):#外部使用,取值 return self._password @password.setter def password(self, row_password): self._password = generate_password_hash(row_password) def check_password(self, row_password):#外部使用,赋值 result = check_password_hash(self._password, row_password) return result
if user.check_password(password):
以上内容为我期末作品的大致制作过程,代码仍存在缺陷,我会继续努力的。