1.个人学期总结
本人在这学期中学习了管理信息系统这门科目,这门科目主要讲解了基于Python的Flask框架web建设项目。Python,是一种面向对象的解释型计算机程序语言,由荷兰人于1989年发明,第一个公开发行版发行于1991年。Python语言具有很多优点,首先,Python在设计上坚持了清晰划一的风格,这使得Python成为一门易读、易维护,并且被大量用户所欢迎的、用途广泛的语言。再者,Python的作者有意的设计限制性很强的语法,使得不好的编程习惯(例如if语句的下一行不向右缩进)都不能通过编译,其中很重要的一项就是Python的缩进规则。
在前期Python的基础课程中学习到了turtle库的基础练习、字符串的基本操作、凯撒密码 、GDP格式化输出、99乘法表、中英文词频统计、和datetime处理日期和时间等等基础学习。
中期,开始学习用html元素制作web网页,观察常用网页的HTML元素,在实际的应用场景中,用已学的标签模仿制作。制作自己的导航条,认识css的盒子模型,用div等元素布局形成html文件。完成了登录与注册页面的html+css+js, 夜间模式的开启和关闭,制作网站网页共有元素的父模板html,包括顶部导航,中间区块划分,底部导航,底部说明等。汇总相关的样式形成独立的css文件,使用 js代码形成独立的js文件,形成完整的base.html+css+js。
后期,进行flask项目,理解flask项目主程序,使用装饰器,设置路径与函数之间的关系。加载静态文件,父模板的继承和扩展。连接mysql数据库,创建用户模型,通过用户模型,对数据库进行增删改查,完成登录、注册、发布评论等功能,继续对我们的项目进行完善。
完成以上步骤之后,一个网页就差不多完成了。但完成的网页是一个很简单的,所以希望在以后能制作出一个更完美的网页。
2.总结Python+Flask+MysqL的web建设技术过程,标准如下:
- 即是对自己所学知识的梳理
- 也可作为初学入门者的简单教程
- 也可作为自己以后复习的向导
- 也是一种向外展示能力的途径
Python+Flask+MysqL的web建设技术过程:
(1)注册页面的实现:
代码:
{% 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="aa"style="opacity:0.8" > <div class="login" ><h2>注册</h2></div> <form action="{{ url_for(‘regist‘) }}"method="post"> <div class="aa1" > 用户名:<input id="name" type="text"placeholder="请输入用户名"name="username"><br> 昵称:<input id="nickname" type="text"placeholder="昵称"name="nickname"><br> 密码:<input id="password" type="password"placeholder="请输入密码"name="password"><br> 再输密码:<input id="password1" type="password"placeholder="请再次输入密码"><br> </div> <div id="error_box"><br></div> <div class="aa2" > <button onclick="return myLogin()">注册</button> <body background="http://p2.so.qhimgs1.com/bdr/_240_/t015907a1aac845650e.jpg"style="background-repeat:no-repeat;background-size: 100% 100%; background-attachment: fixed;"> </body> </div> </form> </div> {% endblock %}
(2)登陆页面:
代码:
{% 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 %} <body background="http://p0.so.qhmsg.com/bdr/_240_/t017089b71faaa7ce85.jpg"></body> {% block main %} <div class="aa" style="opacity:0.8"> <div class="login" ><h2>登录</h2></div> <form action="{{ url_for(‘login‘) }}"method="post"> <div class="aa1" > 用户名:<input id="name" type="text"name=‘username‘placeholder="请输入用户名"><br> 密码:<input id="password" type="password"name=‘password‘placeholder="请输入密码"><br> </div> <div id="error_box"><br></div> <div class="aa2" > <button onclick="myLogin()">登录</button> <button type="button" onclick=window.alert("是否取消登录!")>取消</button> <body background="http://p0.so.qhimgs1.com/bdr/_240_/t01ebfe75930e0eb7a0.jpg"style="background-repeat:no-repeat;background-size: 100% 100%; background-attachment: fixed;"></body> </div> </form> </div> {% endblock %}
(3)首页页面:
代码:
{% extends ‘base.html‘ %} {% block title %} 首页 {% endblock %} {% block head %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> <link rel="stylesheet" type="text/css"href="../static/css/index.css"> {% endblock %} {% block main %} <div class="card-body"> <div class="card" style="width:50rem; margin:0 auto;opacity:0.9"> {# <li class="list-group-item"style="height:10rem">detail{{ question }}</li>#} <ul class="list-group list-group-flush"> {% for foo in questions %} <li class="list-group-item"> <span class="icon" aria-hidden="true"></span> <br> <h3><a href="{{ url_for(‘detail‘,question_id=foo.id) }}">{{ foo.title }}</a></h3> <p>{{ foo.detail }}</p> <span class="badge"style="float:right">{{ foo.creat_time}}</span> <a href="{{ url_for(‘usercenter‘,user_id=foo.author.id,tag=1) }}">{{ foo.author.username}}</a> <br> 评论:{{ foo.comments|length }} </li> {% endfor %} </ul> </div> <br> <div> <p><span style="font-size: 40px;color: blue;font-family: ‘Consolas‘, ‘Deja Vu Sans Mono‘, ‘Bitstream Vera Sans Mono‘, monospace";>浩瀚星空</span></p> </div> <div> <div class="img"> <a href="https://www.baidu.com/"> <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509806558937&di=e9f6b3da7e4525b5048761d321e7a334&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimage%2Fc0%253Dshijue1%252C0%252C0%252C294%252C40%2Fsign%3D9d0e654a05b30f242197e440a0fcbb36%2F43a7d933c895d1434bcc2a0879f082025aaf0767.jpg"></a> <div class="desc"><a href="https://www.baidu.com/">地球</a></div> </div> <div class="img"> <a href="https://www.baidu.com/"> <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509806558936&di=f4549e6b6f694583b5e01832ae57ff79&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimage%2Fc0%253Dshijue1%252C0%252C0%252C294%252C40%2Fsign%3D7e5fc0351bdfa9ece9235e540ab99d76%2F8b13632762d0f7031d0337f502fa513d2697c562.jpg"></a> <div class="desc"><a href="https://www.baidu.com/">星云</a></div> </div> <div class="img"> <a href="https://www.baidu.com/"> <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509806558935&di=01d805549265c8b439c92ed817f2664d&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimage%2Fc0%253Dshijue1%252C0%252C0%252C294%252C40%2Fsign%3D1fd11f0e9716fdfacc61ceaddce6e621%2Fae51f3deb48f8c542cd0210a30292df5e0fe7f90.jpg"></a> <div class="desc"><a href="https://www.baidu.com/">璀璨星空</a></div> </div> <div class="img"> <a href="https://www.baidu.com/"> <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509806558935&di=b77b1b7fb70e8474b8a317fd70ea71ce&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimage%2Fc0%253Dshijue1%252C0%252C0%252C294%252C40%2Fsign%3D2820c0958dd6277ffd1f3a7b40517545%2F9f2f070828381f304605d987a3014c086e06f084.jpg"></a> <div class="desc"><a href="https://www.baidu.com/">星轨</a></div> </div> </div> <br> <div class="clearfloat" style="text-align: center"> <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509806558937&di=e9f6b3da7e4525b5048761d321e7a334&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimage%2Fc0%253Dshijue1%252C0%252C0%252C294%252C40%2Fsign%3D9d0e654a05b30f242197e440a0fcbb36%2F43a7d933c895d1434bcc2a0879f082025aaf0767.jpg"> <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509806558936&di=f4549e6b6f694583b5e01832ae57ff79&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimage%2Fc0%253Dshijue1%252C0%252C0%252C294%252C40%2Fsign%3D7e5fc0351bdfa9ece9235e540ab99d76%2F8b13632762d0f7031d0337f502fa513d2697c562.jpg"> <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509806558935&di=01d805549265c8b439c92ed817f2664d&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimage%2Fc0%253Dshijue1%252C0%252C0%252C294%252C40%2Fsign%3D1fd11f0e9716fdfacc61ceaddce6e621%2Fae51f3deb48f8c542cd0210a30292df5e0fe7f90.jpg"> <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509806558935&di=b77b1b7fb70e8474b8a317fd70ea71ce&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimage%2Fc0%253Dshijue1%252C0%252C0%252C294%252C40%2Fsign%3D2820c0958dd6277ffd1f3a7b40517545%2F9f2f070828381f304605d987a3014c086e06f084.jpg"> </div> </div> {% endblock %}
(4)发布问答
代码:
{% extends ‘base.html‘ %} {% block title %}问答{% endblock %} {% block head %} <link href="{{ url_for(‘static‘,filename=‘‘) }}" rel="stylesheet" type="text/css"> {% endblock %} {% block main %} <br> <section class="container"> <div class="login" style="text-align: center;"> <label for="ask">Question</label> <form action="{{ url_for(‘question‘) }}" method="post"> <textarea style="width:330px" type="password" rows="3" id="ask" name="title"></textarea> <br> <div> <label for="questionDetail">Detail</label> <br> <textarea rows="5" style="width:330px"id="questionDetail" type="password" name="detail"></textarea> </div> <br> <input type="checkbox">check me <input type="submit" name="commit" value="发布"> </form> </div> </section> {% endblock %}
(5)个人详情页面:
代码:
{% extends ‘userbase.html‘ %} {% block title %} 个人信息页 {% endblock %} {% block head %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> {% endblock%} {% block user %} <div class="card" style="width:50rem; margin:0 auto"> <ul class="list-group list-group-flush" > <h3>全部问答</h3> {% for foo in user.questions %} <li class="list-group-item"> <span class="icon" aria-hidden="true"></span> <br> <h3><img src="../static/image/yezi.jpg" width="20" height="20"> <a href="{{ url_for(‘detail‘,question_id=foo.id) }}">{{ foo.title }}</a></h3> <p>{{ foo.detail }}</p> <span class="badge"style="float:right">{{ foo.creat_time}}</span> <img src="../static/image/touxiang.jpg" width="20" height="20"> <a href="{{ url_for(‘usercenter‘,user_id=foo.author.id) }}">{{ foo.author.username}}</a> </li> {% endfor %} </ul> </div> <br> <br> <div class="card" style="width:50rem; margin:0 auto"> <ul class="list-group list-group-flush"> <h3>全部评论</h3> {% for foo in user.comments %} <li class="list-group-item"> <span class="icon" aria-hidden="true"></span> <br> <h3><img src="../static/image/yezi.jpg" width="20" height="20"> <a href="{{ url_for(‘detail‘,question_id=foo.id) }}">{{ foo.title }}</a></h3> <p>{{ foo.detail }}</p> <span class="badge"style="float:right">{{ foo.creat_time}}</span> <img src="../static/image/touxiang.jpg" width="20" height="20"> <a href="">{{ foo.author.username}}</a> </li> {% endfor %} </ul> </div> <br> <br> <div class="card" style="width:50rem; margin:0 auto"> <h3>{{ username }}个人信息</h3> <ul class="list-group list-group-flush"> <li class="list-group-item"> <span class="icon" aria-hidden="true"> 用户:{{ user.username }}<br> 编号:{{ user.id }}<br> 昵称:{{ user.nickname }}<br> 文章篇数:{{ user.questions|length }} </span> </li> </ul> </div> {% endblock %}
(6)个人用户父类模板代码:
{% extends ‘base.html‘ %} {% block title %} 个人中心 {% endblock %} {% block head %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> {# <style>#} {# .nav_ul li#} {# list-style:none;#} {# float: left;#} {# margin: 10px;#} {# #} {# </style>#} {% endblock %} {% block main %} <div style="width:50rem; margin:0 auto"> <ul class="list-group list-group-flush"> <h2>{{ user.username }}</h2> </ul> <li role="presentation"class="btn btn-light"><a href="{{ url_for(‘usercenter‘,user_id=user.id,tag=‘1‘) }}">全部问答</a> </li> <li role="presentation"class="btn btn-light"><a href="{{ url_for(‘usercenter‘,user_id=user.id,tag=‘2‘) }}">全部评论</a> </li> <li role="presentation"class="btn btn-light"><a href="{{ url_for(‘usercenter‘,user_id=user.id,tag=‘3‘) }}">个人信息</a> </li> </ul> </div> {% block user %} {% endblock %} {% endblock %}
(7)父类模板代码:
<!DOCTYPE HTML> <html> <head lang="en"> <meta charset="UTF-8"> <title>{% block title %}首页{% endblock %}</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> <script src="{{ url_for(‘static‘,filename=‘js/base.js‘) }}"></script> {% block head %}{% endblock %} <body id="mybody"> {#<nav class="navbar navbar-expand-lg navbar navbar-light"style="background-color:#e3f2fd">#} <nav class="navbar navbar-expand-lg navbar navbar-dark bg-blue"style="opacity:0.8"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"><a class="navbar-brand" href="{{ url_for(‘index‘) }}">首页 </a></li> <li class="nav-item active"><a class="navbar-brand" href="{{ url_for(‘question‘) }}">发布问答 </a></li> <li class="nav-item active"><a class="navbar-brand" href="http://www.astron.ac.cn/index.htm">中国天文网</a></li> <li class="nav-item active"><a class="navbar-brand" href="http://www.dili360.com/cng/tag/list/6489.htm">国家地理网</a></li> <li class="nav-item active"><a class="navbar-brand" href="http://www.astronomy.com.cn/bbs/forum.php">天文论坛</a></li> <form action="{{url_for(‘search‘)}}" method="get" class="form-inline" > <input name="q" class="form-control mr-sm-2" type="search" placeholder="请输入关键字" > <button class="btn btn-outline-success my-2 my-sm-0" type="submit">搜索</button> </form> </ul> <nav class="navbar navbar-expand-lg navbar navbar-dark bg-blue"> {% if username %} <a class="navbar-brand" href="{{ url_for(‘usercenter‘,user_id=session.get(‘userid‘),tag=1) }}">{{ session.get(‘user‘) }} </a> <a class="navbar-brand" href="{{ url_for(‘logout‘) }}">注销 </a> {% else %} <a class="navbar-brand" href="{{ url_for(‘login‘) }}">登陆 </a> <a class="navbar-brand" href="{{ url_for(‘regist‘) }}">注册 </a> {% endif %} </nav> </div> </nav> <body background="http://p0.so.qhimgs1.com/bdr/_240_/t01ebfe75930e0eb7a0.jpg"style="background-repeat:no-repeat;background-size: 100% 100%; background-attachment: fixed;"> {% block main %} {% endblock %} <div id="footer"> <div class="copyRight" style="text-align: center"> Copyright ?xulishuai版权所有 </div> </div> </body> </body> </html>
(8)config.py代码:
import os SECRET_KEY = os.urandom(24) SQLALCHEMY_DATABASE_URI = ‘mysql+pymysql://root:123456@127.0.0.1:3306/misdb?charset=utf8‘ SQLALCHEMY_TRACK_MODIFICATIONS = False
(9)tianwen.py代码:
from flask import Flask from flask_sqlalchemy import SQLAlchemy import config from flask import Flask, render_template, request, redirect, url_for,session from functools import wraps from datetime import datetime from sqlalchemy import or_, and_ 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(20), nullable=False) nickname = db.Column(db.String(20)) db.create_all() #问题页的数据库 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(‘questions‘)) db.create_all() 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() # user=User(username=‘mis1‘,password=‘11111‘) # db.session.add(user) # db.session.commit() @app.route(‘/‘) def base(): return render_template(‘base.html‘) # 调用数据库把用户评论放在首页 @app.route(‘/index/‘) def index(): context = { ‘questions‘:Question.query.order_by(‘-creat_time‘).all() } return render_template(‘index.html‘,**context) @app.route(‘/login/‘,methods=[‘GET‘,‘POST‘]) def login(): if request.method == ‘GET‘: return render_template(‘login.html‘) else: usern = request.form.get(‘username‘) passw = request.form.get(‘password‘) user = User.query.filter(User.username == usern).first() if user: if user.password==passw: session[‘user‘] = usern session[‘userid‘] = user.id session.permanent = True return redirect(url_for(‘base‘)) else: return u‘password error‘ else: return u‘password is not existed‘ @app.route(‘/regist/‘,methods=[‘GET‘,‘POST‘]) def regist(): if request.method==‘GET‘: return render_template(‘regist.html‘) else: usern=request.form.get(‘username‘) passw=request.form.get(‘password‘) nickn=request.form.get(‘nickname‘) user=User.query.filter(User.username==usern).first() if user: return u‘username existed‘ else: user=User (username=usern,password=passw,nickname=nickn) db.session.add(user) db.session.commit() return redirect(url_for(‘login‘)) 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(‘/question/‘,methods=[‘GET‘,‘POST‘]) @loginFirst#发布前登录,python装饰器 def question(): if request.method==‘GET‘: return render_template(‘question.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): quest = Question.query.filter(Question.id == question_id).first() return render_template(‘detail.html‘, ques=quest) #评论功能 @app.route(‘/comment/‘,methods=[‘POST‘]) @loginFirst#发布前登录,python装饰器 def comment(): detail = request.form.get(‘fabu‘) author_id = User.query.filter(User.username == session.get(‘user‘)).first().id quest_id =request.form.get(‘question_id‘) pinglun = Comment(question_id=quest_id,detail=detail, author_id=author_id) db.session.add(pinglun) db.session.commit() return redirect(url_for(‘detail‘,question_id=quest_id)) #个人信息页 @app.route(‘/usercenter/<user_id>/<tag>‘) @loginFirst#发布前登录,python装饰器 def usercenter(user_id,tag): user=User.query.filter(User.id== user_id).first() context={ ‘user‘: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.context_processor def mycontext(): usern=session.get(‘user‘) if usern: return{‘username‘:usern} else: return{} @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‘, questions=ques) @app.route(‘/logout/‘) def logout(): session.clear() return redirect(url_for(‘index‘)) if __name__ == ‘__main__‘: app.run(debug=True)
以上就是Python+Flask+MysqL的web建设技术过程,读者可以根据自己的需求修改。