期末作品检查
个人学期总结
这个学期接触到了一门新的课程,叫管理信息系统,虽然叫做管理信息系统,但是我们学的是利用Python、flask和mysql进行网页开发与设计,也是一门蛮有意思的课程。
一开始,我以为我们会做一个系统什么的,用于管理信息,当然只是从课程名字的字面意思去理解这门课程,但第一节课就让我对这门课程有了一个初步的印象,就是写网页。虽然刚刚开始,把一些小的功能都演示一遍并且自己实操一遍,但是我能预料到,最后一定是把自己学过的所有东西汇总在一起,成为一个完整的作品。果不其然,期末的大作业正是如此。
由于之前有学过Java,所以对这些代码有一定的接触,不会产生太大的陌生感,尽管代码有些不同,但是也是八九不离十,有些代码是比较晦涩难懂,在老师和同学的帮助下也能顺利的解决问题,其实嘛,代码也不难,有些是固定的标签什么的,有些功能类的代码老师都会讲解的比较清楚,所以学习起来并不是那么的艰难。再加上我们有另一门课程叫做jsp,也是写网页的,和这一门课有一些异曲同工之妙,两者相辅相成,相得益彰,在某种程度上也是可以融会贯通的。
通过一学期的学习,我发现我们是一个制作网页的过程,虽然有些简单,但是自己制作出来的网页还是蛮有成就感的。
总结Python+Flask+MysqL的web建设技术过程,标准如下:
- 即是对自己所学知识的梳理
- 也可作为初学入门者的简单教程
- 也可作为自己以后复习的向导
- 也是一种向外展示能力的途径
1、网站父模板统一布局:头部导航条、底部图片导航、中间主显示区域布局
主py文件:
from flask import Flask,render_template,request,redirect,url_for,session from flask_sqlalchemy import SQLAlchemy import config from sqlalchemy import or_, and_ from functools import wraps from datetime import datetime app = Flask(__name__) app.config.from_object(config) db=SQLAlchemy(app) class User(db.Model): __table__name = 'user' id = db.Column(db.Integer,primary_key=True,autoincrement=True) username = db.Column(db.String(20),nullable=False) password = db.Column(db.String(20),nullable=False) nickname = db.Column(db.String(50)) class Question(db.Model): __tablename__ = 'question' id = db.Column(db.Integer,primary_key=True,autoincrement=True) title=db.Column(db.String(100),nullable=False) detail=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')) 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() @app.route('/') def index(): context = { 'question': Question.query.all() } # question : Question.query.all() return render_template('index.html', **context) @app.route('/regist/',methods=['GET','POST']) def regist(): if request.method=='GET': return render_template('regist.html') else: username=request.form.get('username') password=request.form.get('password') nickname=request.form.get('nickname') user=User.query.filter(User.username==username).first() if user: return u'username existed' else: user=User (username=username,password=password,nickname=nickname) db.session.add(user) db.session.commit() return redirect(url_for('login')) @app.route('/login/',methods=['GET','POST']) def login(): if request.method=='GET': return render_template('login.html') else: username=request.form.get('username') password=request.form.get('password') user = User.query.filter(User.username == username).first() if user: if user.password==password: session['user']=username session['userid'] = user.id return redirect(url_for('index')) else: return u'password error' else: return u'username is not existed' @app.context_processor def mycontext(): usern=session.get('user') if usern: return{'username':usern} else: return{} @app.route('/logout/') def logout(): session.clear() return redirect(url_for('index')) def loginFirst(func): @wraps(func) def wrapper(*args,**kwargs): if session.get('user'): return func(*args,**kwargs) else: return redirect(url_for('login')) return wrapper @app.route('/lable/',methods=['GET','POST']) @loginFirst def lable(): if request.method == 'GET': return render_template('lable.html') else: title = request.form.get('title') detail = request.form.get('detail') author_id = User.query.filter(User.username == session.get('user')).first().id question = Question(title=title, detail=detail, author_id=author_id) db.session.add(question) db.session.commit() return redirect(url_for('index')) @app.route('/detail/<question_id>') def detail(question_id): # context={ # 'comments':Comment.query.all() # } quest = Question.query.filter(Question.id == question_id).first() return render_template('detail.html',ques=quest) @app.route('/comment/', methods=['GET','POST']) @loginFirst def comment(): comment= request.form.get('commentdetail') ques_id=request.form.get('question_id') auth_id=User.query.filter(User.username==session.get('user')).first().id comm=Comment(author_id=auth_id,question_id=ques_id,detail=comment) # question.author=User db.session.add(comm) # 数据库,添加操作 db.session.commit() #提交 return redirect(url_for('detail', question_id=ques_id)) @app.route('/usercenter/<user_id>/<tag>') @loginFirst def usercenter(user_id,tag): user=User.query.filter(User.id==user_id).first() context={ # 'username':user.username, # 'questions':user.question, # 'comments':user.comments, 'user': user } # return render_template('user.html',ques=user) if tag == '1': return render_template('user1.html',**context) elif tag == '2': return render_template('user2.html',**context) else: return render_template('user3.html',**context) @app.route('/search/') def search(): qu=request.args.get('q') ques=Question.query.filter( or_( Question.title.contains(qu), Question.detail.contains(qu) ) ).order_by('-creat_time') return render_template('index.html',question=ques) if __name__ == '__main__': app.run(debug=True)
import os SECRET_KEY = os.urandom(24) SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root@localhost:3306/mis_db?charset=utf8' SQLALCHEMY_TRACK_MODIFICATIONS = False
父模板导航base. html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{% block title%}car{% endblock %}</title> <link href="{{ url_for('static',filename='css/base.css') }}" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="{{ url_for('static',filename='js/base.js') }}"></script> {% block head %} {% endblock %} <style> nav navbar-nav li { list_style: none; float: left; margin: 10px; } .nav1 li{ list-style: none; float: left; margin: 10px; } </style> </head> <body id="mybody"> <div class="daohang_box"><form action="{{ url_for('search')}}" method="get" > <nav class="navbar" role="navigation" style=""> <div class="container-fluid" id="container"> <div class="navbar-header"> <a class="navbar-brand" href="{{ url_for('index') }}">首页</a> </div> <div> <ul class="nav navbar-nav"> {% if username %} <li><a href={{ url_for('usercenter',user_id=session.get('userid'),tag=1) }}>{{ username }}</a></li> <li><a href="{{ url_for('logout') }}">注销 </a></li> {% else %} <li><a href="{{ url_for('login') }}" onclick="">登录</a></li> <li><a href="{{ url_for('regist') }}" onclick="">注册</a></li> {% endif %} <li><a href="{{ url_for('lable') }}" onclick="">发布问答</a></li> </ul> </div> <div style="float: right"> <img style="width: 50px; height: 50px" id="myonoff" onclick="mySwitch()" src="https://ps.ssl.qhimg.com/sdmt/119_135_100/t01ebad6510c93738fc.gif" style="width:50px" > </div> <div><input id="search_box" name='q'type="text" placeholder="请输入关键词查找"> <button id="search" type="submit">搜索</button> </div> {# <body background="http://p5.so.qhimgs1.com/bdr/_240_/t01fb87f1928a69d5eb.jpg" style="width: 100%; height: 100%"></body>#} </div> </nav> </form> {% block main %}{% endblock %} </body > </html> </body>
base.js
function mySwitch() { var oBody = document.getElementById("mybody"); var oOnoff = document.getElementById("myonoff"); if (oOnoff.src.match("t01ebad6510c93738fc")) { oOnoff.src = "https://ps.ssl.qhimg.com/sdmt/119_135_100/t01ebad6510c93738fc.gif"; oBody.style.background = "black"; oBody.style.color = "yellow" } else { oOnoff.src = "https://ps.ssl.qhimg.com/sdmt/119_135_100/t01ebad6510c93738fc.gif"; oBody.style.background = "white"; oBody.style.color = "black" } }
base.css
img { width: 200px; } #container { background: cyan; } div.sa { border-style: solid; border-width: 5px; border-color: gold; width: 400px; float: left; margin: 5px; } div.sa img { width: 80%; heigh: aute; } div.st { text-align: center; padding: 2px; } div.sa:hover { border-style: solid; border-width: 5px; border-color: green; }
2、注册、登录、注销
regist.html
{% extends 'base.html' %} {% block title %}注册{% endblock %} {% block head %} <link href="{{ url_for('static',filename='css/regist.css') }}" rel="stylesheet" type="text/css"> <script src="{{ url_for('static',filename='js/regist.js') }}"></script> {% endblock %} {% block main %} <div class="a" > <div class="regist" ><h2>注册</h2></div> <form action="{{ url_for('regist') }}"method="post" onsubmit="return myLogin()"> <div class="a1" > Username:<input id="name" type="text"placeholder="请输入用户名" name="username"><br> Nickname:<input id="nickname" type="text"placeholder="请输入昵称" name="nickname"><br> Password:<input id="password" type="password"placeholder="请输入密码" name="password"><br> Password:<input id="password1" type="password"placeholder="请再次输入密码" name="password1"><br> </div> <div id="error_box"><br></div> <div class="a2" > <button >注册</button> <button type="button" onclick=window.alert("是否取消登录!")>取消</button> </div> </div> <div class="a3" >Created.by.xuejing</div> </div> </form> {% endblock %}
regist.js
function myLogin(){ var uName=document.getElementById("name"); var uError=document.getElementById("error_box"); var nickname = document.getElementById("nickname"); var upass = document.getElementById("password"); var upass1 = document.getElementById("password1"); uError.innerHTML = "<br>" //uname if(uName.value.length>12 || uName.value.length<6){ uError.innerHTML="Username 6-12 bits"; return false; }else if((uName.value.charCodeAt(0)>=48)&& uName.value.charCodeAt(0)<=57){ uError.innerHTML="The first letter cannot be numeric"; return false; }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 = "only letter or number."; return false; } } if(upass.value.length>12 || upass.value.length<6){ uError.innerHTML="password 6-12 bits"; return false; } if(upass.value != upass1.value){ uError.innerHTML="The password input is inconsistent"; return false; } isError =true; window.alert("注册成功 !") }
regist.css
div{ margin:0 auto; text-align:center; backgroup-color:blue } .a{ width:380px; height:230px; background-color: cornflowerblue; margin-top:200px; } .regist{ font-size: 30px; color: black; font-family:宋体; } .a1{ font-size:20px; font-weight:bold; color: black; font-family:宋体; } .a2{ width:150px; height:60px; boder-style:hidden; } .a3{ background-color:cyan; width:380px; clear:both; text-align:center; } .design{ font-size:10px; color:yellowgreen; } #error_box{ color:red; }
login.html
{% extends 'base.html' %} {% block title %}登录{% endblock %} {% block head %} <link href="{{ url_for('static',filename='css/login.css') }}" rel="stylesheet" type="text/css"> <script src="{{ url_for('static',filename='js/login.js') }}"></script> {% endblock %} {% block main %} <div class="a" > <div class="login" ><h2>登录</h2></div> <form action="{{ url_for('login') }}"method="post"> <div class="a1" > Username:<input id="name" type="text"placeholder="请输入用户名" name="username"><br> Password:<input id="password" type="password"placeholder="请输入密码" name="password"><br> </div> <div id="error_box"><br></div> <div class="a2" > <button onclick="myLogin()">登录</button> <button type="button" onclick=window.alert("是否取消登录!")>取消</button> </div> </div> <div class="a3" >Created.by.xuejing</div> </form> {% endblock %}
login.js
function myLogin(){ var uName=document.getElementById("name"); var uError=document.getElementById("error_box"); var upass = document.getElementById("password"); var isError=true; uError.innerHTML = "<br>" //uname if(uName.value.length>12 || uName.value.length<6){ uError.innerHTML="Username 6-12 bits"; isError=false; return isError; }else if((uName.value.charCodeAt(0)>=48)&& uName.value.charCodeAt(0)<=57){ uError.innerHTML="The first letter cannot be numeric"; 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 = "only letter or number."; isNotError=false; return isError; } } if(upass.value.length>12 || upass.value.length<6){ uError.innerHTML="password 6-12 bits"; isError=false; return isError; } return isError; }
login.css
div{ margin:0 auto; text-align:center; backgroup-color:blue } .a{ width:380px; height:230px; background-color: cornflowerblue; margin-top:200px; } .login{ font-size: 30px; color: black; font-family:宋体; } .a1{ font-size:20px; font-weight:bold; color: black; font-family:宋体; } .a2{ width:150px; height:60px; boder-style:hidden; } .a3{ background-color:cyan; width:380px; clear:both; text-align:center; } .design{ font-size:10px; color:yellowgreen; } #error_box{ color:red; }
3、发布、列表显示
lable.html
{% extends 'base.html' %} {% block title %} 发布问答 {% endblock %} {% block head %} {% endblock %} {% block main %} <form class="all" action="{{ url_for('lable') }}" method="POST"> <div style="margin-left:30%;margin-top: 10%" > <h3 >发布问答</h3> <div class="form_group"></div> <div class="form_group"> <!--<label for="questionDetial">标题</label>--> <!--<textarea class="form-control" rows="1" id="questionDetial"></textarea>--> <label for="biaoti">标题</label> <input id="biaoti" type="text" placeholder="请输入标题!" name="title"> </div> <div class="form_group" > <label for="questionDetial">详情</label> <textarea class="form-control" rows="5" id="questionDetial" style="width:60rem " name="detail"></textarea> </div> </div> <div class="checkbox" style="margin-left:30%;margin-top: 1%"> <button type="submit" class="btn bun-default">发布</button> </div> </form> {% endblock %}
4、详情页
{% extends 'base.html' %} {% block title %}detail{% endblock %} {% block head %} {# <script src="{{ url_for('static',filename='js/base.js') }}" type="text/javascript"></script>#} <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/detail.css') }}"> {% endblock %} {% block main %} <div align="center"> <div class="a1"> <h3>{{ ques.title }}<br><small>{{ ques.author.Username }} <span class="badge">{{ ques.creat_time }}</span></small></h3></div> <p class="lead">{{ ques.detail }}</p> <h3> <form action="{{ url_for('comment') }}" method="post"> {# <h4>评论:({{ ques.comments }})</h4>#} {# <h2>Beyond乐队</h2>#} {# <p>Beyond</p>#} {# <p>1983年成立</p>#} {# <p>detail</p>#} <br></div> <div class="a2" style="margin-left: 25%"> <div class="pinglun"><label for="comment">评论</label><br></div> <textarea id="comment" rows="5" name="commentdetail" style="width: 90ch"></textarea></div> <input name="question_id" type="hidden" value="{{ ques.id }}"/> <button type="submit" class="fasong" style="margin-left: 25%">发送评论</button> <h4 style="margin-left: 25%">comment:({{ ques.comments|length }})</h4> </div> </form> <ul class="list-group" style="margin-left:20%;margin-top: 5%;margin-right:20%"> {% for foo in ques.comments %} <li class="list-group-item" > <a href={{ url_for('usercenter',user_id=foo.author_id,tag=1 )}}>{{ foo.author.username }} </a><br> <a href={{ url_for('detail',question_id=foo.id)}}>{{ foo.title }}</a> <span class="badge">{{ foo.creat_time }}</span> <p class="abstract">{{ foo.detail }}</p> </li> {% endfor %} </ul> </div> {% endblock %}
5、个人中心
{% extends 'base.html' %} {% block title %}个人中心{% endblock %} {% block head %} <style> .nav1 >li{ list-style: none; float: left; margin: 10px; } </style> {% endblock %} {% block main %} <div class="nav1"> <ul> <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> </ul> </div> {% block user %}{% endblock %} {% endblock %}
{% extends 'userbase.html' %} {% block user %} {% block head %} <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/userbase.css') }}"> <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/user.css') }}"> {% endblock %} <div class="a1"> <h3>{{ username }}</h3><br> {# <small>全部问答</small>#} </div> <ul> {% for foo in user.question %} <li class="list-group-item" > <a href={{ url_for('index')}}>{{ foo.author.username }} </a><br> <a href={{ url_for('detail',question_id=foo.id)}}>{{ foo.title }}</a> <span class="badge">{{ foo.creat_time }}</span> <p class="abstract">{{ foo.detail }}</p> </li> {% endfor %} </ul> </div> {% endblock %}
{% extends 'userbase.html' %} {% block user %} {% block head %} <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/userbase.css') }}"> <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/user.css') }}"> {% endblock %} <div class="a1"> <h3>{{ username }}</h3><br> {# <small>全部评论</small>#} </div> <ul> {% for foo in user.comments %} <li class="list-group-item" > <a href={{ url_for('index')}}>{{ foo.author.username }} </a><br> <a href={{ url_for('detail',question_id=foo_id)}}>{{ foo.title }}</a> <span class="badge">{{ foo.creat_time }}</span> <p class="abstract">{{ foo.detail }}</p> </li> {% endfor %} </ul> </div> {% endblock %}
{% extends 'userbase.html' %} {% block user %} {% block head %} <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/userbase.css') }}"> <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/user.css') }}"> {% endblock %} <div class="a1"> <h3>{{ username}} {# <small>个人信息</small>#} </h3><br> <ul> {# <li>用户:{{ username}}</li>#} {# <li>编号:{{ user.id}}</li>#} {# <li>昵称:{{ user.nickname}}</li>#} {# <li>文章篇数:{{ user.question|length }}</li>#} <div class="alert alert-danger" role="alert"> 用户:{{ username}} </div> <div class="alert alert-info" role="alert"> 编号:{{ user.id}} </div> <div class="alert alert-success" role="alert"> 昵称:{{ user.nickname}} </div> <div class="alert alert-danger" role="alert"> 文章篇数:{{ user.question|length }} </div> <div class="alert alert-warning" role="alert"> 评论数:{{ user.comments|length }} </div> </ul> </div> {% endblock %}
@app.route('/search/') def search(): qu=request.args.get('q') ques=Question.query.filter( or_( Question.title.contains(qu), Question.detail.contains(qu) ) ).order_by('-creat_time') return render_template('index.html',question=ques)