期末作品检查

个人学期总结

基于这一学期学习的Python+Flask+MysqL的web个人学期总结,Python, 是一种面向对象的解释型计算机程序设计语言,由荷兰人Guido van Rossum于1989年发明,第一个公开发行版发行于1991年。

Python是纯粹的自由软件源代码解释器CPython遵循 GPL(GNU General Public License)协议[2]  。Python语法简洁清晰,特色之一是强制用空白符(white space)作为语句缩进。

Python具有丰富和强大的库。它常被昵称为胶水语言,能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。常见的一种应用情形是,使用Python快速生成程序的原型(有时甚至是程序的最终界面),然后对其中[3]  有特别要求的部分,用更合适的语言改写,比如3D游戏中的图形渲染模块,性能要求特别高,就可以用C/C++重写,而后封装为Python可以调用的扩展类库。需要注意的是在您使用扩展类库时可能需要考虑平台问题,某些可能不提供跨平台的实现。

Flask: Flask是一个使用 Python 编写的轻量级 Web 应用框架。其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2 。Flask使用 BSD 授权。

Flask也被称为 “microframework” ,因为它使用简单的核心,用 extension 增加其他功能。Flask没有默认使用的数据库、窗体验证工具。

   Mysql: MySQL是一个关系型数据库管理系统由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下产品。MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MySQL是最好的 RDBMS (Relational Database Management System,关系数据库管理系统) 应用软件。

MySQL是一种关系数据库管理系统,关系数据库将数据保存在不同的表中,而不是将所有数据放在一个大仓库内,这样就增加了速度并提高了灵活性。

MySQL所使用的 SQL 语言是用于访问数据库的最常用标准化语言。MySQL 软件采用了双授权政策,分为社区版和商业版,由于其体积小、速度快、总体拥有成本低,尤其是开放源码这一特点,一般中小型网站的开发都选择 MySQL 作为网站数据库。

由于其社区版的性能卓越,搭配 PHPApache 可组成良好的开发环境

   我所学习的是基于Python+Flask+MysqL的网页制作。而根据所学习的内容实现的功能包括:网站父模板统一布局:头部导航条、底部图片导航、中间主显示区域布局

注册、登录、注销、发布、列表显示详情页评论、列表显示个人中心,搜索,条件组合搜索。

   经过这一学期的学习,对于Python+Flask+MysqL的web制作,我认为Python+Flask+MysqL是相对于初学网页设计很好的学习工具,能够清晰的梳理网页前端,后台和数据库的联系,相对于其他学习工具而言Python+Flask+Mysql,更加具有学习性,也比较易懂和容易上手。这一学期的网页制作学习个人认为收获很大。

 

总结Python+Flask+MysqL的web建设

 

建设过程包括三部分,前端网页,后台和数据库连接:

用到的工具有:JetBrains PyCharm Community Edition 2017.2.2,Navicat for MySQL

 前端的网页css格式可以借用菜鸟编程的代码

1创建表

在Navicat for MySQL创建或者在mysql后台建

 

在python 连接数据库,新建python项目

 

from datetime import datetime

from werkzeug.security import generate_password_hash,check_password_hash
from exit import db


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) #内部使用
    nickname=db.Column(db.String(50))

    @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




# db.create_all()
class Fankui(db.Model):
    __tablename__ = 'fankui'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)

    biaoti = 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('fankui'))

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'))
    fankui_id= db.Column(db.Integer,db.ForeignKey('fankui.id'))
    creat_time = db.Column(db.DateTime, default=datetime.now)
    detail=db.Column(db.Text,nullable=False)
    fankui = db.relationship('Fankui',backref=db.backref('comment', order_by=creat_time.desc))
    author = db.relationship('User',backref=db.backref('comment'))

 

z

 

1这是网页颜色模式转换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>夜晚模式</title>
    <script>
        function mySwitch() {
            var oBody= document.getElementById("myBody");
            var oOnoff=document.getElementById("myOnOff");
            if(oOnoff.src.match("b9999_")){
                oOnoff.src="https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1509520370&di=f7ae57dab90eab30c78e8f4733607b02&src=http://pic29.photophoto.cn/20131121/0017029581107509_b.jpg";
                oBody.style.background="black";
                oBody.style.color="yellow";
            }else{oOnoff.src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509532539555&di=5c7e5df90fa122e5a6dcae2de5fb45d5&imgtype=0&src=http%3A%2F%2Fwww.jbhdq.com%2Fuploadfile%2F2016%2F0617%2F20160617103213932.jpg";
                oBody.style.background="white";
                oBody.style.color="black";
            }
        }


    </script>

</head>
<body id="myBody">
<img id="myOnOff" onclick="mySwitch()" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509532539555&di=5c7e5df90fa122e5a6dcae2de5fb45d5&imgtype=0&src=http%3A%2F%2Fwww.jbhdq.com%2Fuploadfile%2F2016%2F0617%2F20160617103213932.jpg"
     width="40px">
<script>
    document.write(Date())
</script>



</body>
</html>

网站首页

   <!DOCTYPE html>
        <html lang="en">
        <head>
        {% block head %}{% endblock %}
            <meta charset="UTF-8">
            <title>{% block title %}{% endblock %}首页</title>
  

<nav class="navbar navbar-default" role="navigation">
    <img class="navbar-brand" src="http://cdn2.jianshu.io/assets/web/logo-58fd04f6f0de908401aa561cda6a0688.png" width="40px">
            <link rel="stylesheet" href="{{url_for('static',filename='css/loginMy.css')}}">
                <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
            <script type="text/javascript" src="../static/js/switch.js"></script>
     <img class="navbar-brand"  src="{{url_for('static',filename='image/yezi.jpg')}}" alt="wo" width="50px">
    <div class="container-fluid">
    <div class="navbar-header">

        {% if usernamedd %}


        <a class="navbar-brand" href="{{url_for('usercenter',user_id = session.get('id'),tag = 1)}}">{{usernamedd}}</a>

                 <a class="navbar-brand" href="{{url_for('logout')}}">注销</a>
                <a class="navbar-brand" href="{{url_for('edit',user_id=session.get('id'))}}">修改密码</a>

                {% else %}
                 <a class="navbar-brand" href="{{url_for('login')}}">登陆</a>
                 <a class="navbar-brand" href="{{url_for('register')}}">注册</a>

                {% endif %}




        <a class="navbar-brand" href="{{url_for('danghangye')}}">首页</a>
        <a class="navbar-brand" href="{{url_for('fankui')}}">发布</a>

    </div>
    <form class="navbar-form navbar-left" role="search" action="{{url_for('search')}}" method="get" >
        <div class="form-group">
            <input name="q" type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default" name="q">提交</button>
    </form>
           <img class="navbar-brand" id="myOnOff" onclick="mySwitch()" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509532539555&di=5c7e5df90fa122e5a6dcae2de5fb45d5&imgtype=0&src=http%3A%2F%2Fwww.jbhdq.com%2Fuploadfile%2F2016%2F0617%2F20160617103213932.jpg"
             width="40px">
        <p>欢迎来到跑酷社区</p>
    </div>
</nav>



      
            <style>
                body{
                    background:url(http://static01.lvye.com/forum/201405/08/1507433trhpech7irgp8i5.jpg) top left;
                    background-size:100%;
                    overflow:hidden;
                }
            </style>

        </head>

        <body id="myBody">
        {% block main %}

    
{% for foo in fankui %}
<div class="container">
    <div class="row clearfix">
        <div class="col-md-8 column">
            <div class="alert alert-success alert-dismissable">
                 <a href="{{url_for('usercenter',user_id = foo.author_id,tag = 1)}}"></a>
                 <a href="{{url_for('usercenter',user_id = foo.author_id,tag = 1)}}">{{foo.author.username}}</a>
                 <strong>{{foo.creat_time}}</strong><br> <a href="{{url_for('详情页',fankui_id = foo.id )}}">{{foo.biaoti}}</a><br>{{foo.questionDetail}}
            </div>
        </div>
        <div class="col-md-4 column">
        </div>
    </div>
</div>
{% endfor %}





         {% endblock %}
        </body>
        </html>

对应后台

@app.route('/')
def danghangye():
    context = {
        'fankui':Fankui.query.order_by('creat_time').all()
    }
    return render_template('danghangye.html',**context)

 

 

登陆页面

{% extends'danghangye.html' %}
{% block title %}欢迎来到登录界面,请登录{% endblock %}
{% block head %}
     <script type="text/javascript" src="../static/js/cao.js"></script>
    <link rel="stylesheet" href="../static/css/font-awesome.min.css"/>
    <link rel="stylesheet" href="../static/css/loginMy.css"/>
<script type="text/javascript" src="../static/js/switch.js"></script>
    <style>
html,body{width:100%;}
</style>

{% endblock %}

{% block main %}
  <div id="container" style="width: 300px;margin-left: auto;margin-right: auto">


    <div id="header"><h2 align="center">登陆界面</h2></div>

    <div id="content">
           <form action="{{url_for('login')}}" method="post">

            <p align="center"><input id="uname"  name="username"  placeholder="请输入账号">

            </p>
            <p align="center"><input id="upass" type="password"  name="password" placeholder="请输入密码"></p>

            <br>

            <div id="error_box"><br>
            </div>

            <br>

            <input type="checkbox" value="true" width="30px">记住密码 <br>

         <p align="center"><button onclick="return fnLogin()">登录</button></p>



         </form>
    </div>
  </div>
 {% endblock %}

 后台

@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.check_password(passw):
            # if user.password == passw:
                session['user'] = usern
                session['id'] = user.id
                session.permanent = True
                return redirect(url_for('danghangye'))
            else:
                return '密码错误'
        else:
            return '用户不存在'

 对应的js

function fnLogin() {
    var oUname = document.getElementById("uname")
    var oUpass = document.getElementById("upass")
     var oUpass2=document.getElementById("upass2");
    var oError = document.getElementById("error_box")
    var isErrer = true;

    oError.innerHTML="<br>"
    if (oUname.value.length > 20 || oUname.value.length < 6) {
        oError.innerHTML = "请输入用户名6-20位字符"
        isErrer = false
        return isErrer;
    }else if ((oUname.value.charCodeAt(0)>=48)&&(oUname.value.charCodeAt(0)<=57)){
        oError.innerHTML="用户名首字母必须是字母"
        isErrer = false
        return isErrer;
    }else for(var i=0; i<oUname.value.length;i++){
        if((oUname.value.charCodeAt(i)<48)||(oUname.value.charCodeAt(i)>57)&&(oUname.value.charCodeAt(i)<97)||(oUname.value.charCodeAt(i)>122)){
            oError.innerHTML="用户名必须为字母或数字";
            isErrer = false
            return isErrer;
        }

    }

 

 4注册页面

{% extends'danghangye.html' %}
{% block title %} 欢迎来到注册界面{% endblock %}

{% block head %}  <script type="text/javascript" src="../static/js/cao.js"></script>{% endblock %}


{% block main %}
<body>

<div id="container" style="width: 300px;margin-left: auto;margin-right: auto">

    <div id="header"><h2 align="center">注册</h2></div>

    <div id="content">
        <form action="{{url_for('register')}}" method="post">

            <p align="center">用户名:<input id="uname" type="text" placeholder="请输入账号" name="username">

            </p>
            <p align="center"> 密码&nbsp:<input id="upass" type="password"  placeholder="请输入密码" name="password"></p>
             <p align="center">密码&nbsp:<input id="upass2" type="password" name="psw2" placeholder="请再次输入密码"></p>
            <br>
            <div id="error_box"><br>
            </div>

            <br>

            <input type="checkbox" value="true">记住密码 <br>

         <p align="center"><button onclick="return fnLogin()">注册</button></p>
            &nbsp&nbsp&nbsp
        </form>


    </div>
  </form>

    <p id="meto">中国标准时间</p>
<script>document.getElementById("meto").innerHTML = Date()</script>
</div>

</body>
    </html>
{% endblock %}

 5修改密码页面

{% extends'danghangye.html' %}
{% block title %}欢迎来到登录界面,请登录{% endblock %}
{% block head %}
     <script type="text/javascript" src="../static/js/cao.js"></script>
    <link rel="stylesheet" href="../static/css/font-awesome.min.css"/>
    <link rel="stylesheet" href="../static/css/loginMy.css"/>
<script type="text/javascript" src="../static/js/switch.js"></script>
    <style>
html,body{width:100%;}
</style>

{% endblock %}

{% block main %}
  <div id="container" style="width: 300px;margin-left: auto;margin-right: auto">

    <div id="header" style="background-color: darkorange"><h2 align="center" style="color: azure">登陆界面</h2></div>

    <div id="content">
           <form action="{{url_for('edit',user_id=user.id)}}" method="post">

            <!--<p align="center"><input id="username"  name="username"  placeholder="请输入账号">-->
              <a href="#">{{username}}</a>
            </p>
            <p align="center"><input id="password" type=""  name="password" placeholder="请输入密码"></p>


            <br>

            <div id="error_box"><br>
            </div>

            <br>

            <input type="checkbox" value="true" width="30px">记住密码 <br>

         <p align="center"><button onclick="return fnLogin()">保存</button></p>
        <a href="http://localhost:63342/untitled/templates/register.html?_ijt=l785tte8f1v8n30nbrmi0bkp7"><p align="center" style="background-color: darkgrey"><button>注册</button></p></a>
            &nbsp&nbsp&nbsp


         </form>
    </div>
  </div>




 {% endblock %}

 

{% extends'danghangye.html' %}
{% block title %}反馈页面{% endblock %}
{% block head %}
<script src="{{url_for('static',filename='js/wenti.js')}}"></script>

{% endblock %}
{% block main %}
 <form action="{{url_for('fankui')}}" method="post">
<div id="container" align="center">

        <div class="form-group">

            <div><label for="biaoti">标题</label></div>
            <textarea class="form-control" id="biaoti" cols="30" rows="1" name="biaoti"></textarea>
        </div>
        <div class="form-group">
            <div><label for="questionDetail">详情</label></div>
            <textarea class="form-control" id="questionDetail" cols="30" rows="5" name="questionDetail"></textarea>
        </div>
        <div class="input-area">
            <button onclick="return fnLogin()">fabu</button>

        </div>

</div>
 </form>
{% endblock %}

 

8个人页面

{% extends'danghangye.html' %}
{% block title %}个人中心{% endblock %}
{% block head %}
<style>
        .nav_ul li {
            list-style:none;
            float:left;
            margin:10px;
            border-bottom:outset;

        }
    </style>

{% endblock %}



{% block main %}

    <ul class="nav_ul">
        <li role="presentation" ><a href="{{url_for('usercenter',user_id = usern,tag = 1)}}">fankui</a></li>
        <li role="presentation"><a href="{{url_for('usercenter',user_id = usern,tag = 2)}}">comment</a></li>
        <li role="presentation"><a href="{{url_for('usercenter',user_id = usern,tag = 3)}}">person</a></li>


    </ul>

{% block usercenter %}{% endblock %}


{% endblock %}

 

 

 

对应个人页面的主页面

{% extends'usercenter.html' %}




{% block usercenter %}
<div>
    <div>
        <P align="center" style="background-color:rgba(255,255,0,0.25)"></P>
          <ur class="sss" style="background-color:rgba(255,255,0,0.25)">
              <p>{{username}}</p>
              <p>发布({{fankui|length}})</p>
              {% for foo in fankui %}
                 <li class="list">
                 <span class="glyphicon" aria-hidden="true"></span>
                 <!--<a href="#">{{foo.author.username}}</a>-->
                 <br>
                 <a href="{{url_for('详情页',fankui_id = foo.id )}}">{{foo.biaoti}}</a>
                 <span class="badge">{{foo.creat_time}} </span>
                 <p>{{foo.questionDetail}}</p>

                </li>
              {% endfor %}

          </ur>
    </div>




</div>

 详情页

 

{% extends'danghangye.html' %}
{% block title %}详情页{% endblock %}
{% block head %}

{% endblock %}
{% block main %}
 <div class="container" align="center">

    <div>
        <div class="col-md-4 column">
        </div>
        <div class="col-md-4 column">
            <div class="page-header">
                <h1>
                    {{ ques.biaoti }} <small>{{ ques.author.username }}</small>
                </h1>
            </div>
            <p>
                detail {{ ques.creat_time }}
            </p>
            <!--<form action="{{url_for('fankui')}}" method="post">-->

            <!--</form>-->
            <p>
                 <a class="btn" href="#">{{ ques.questionDetail }}</a>
            </p>
            <form action="{{url_for('comment')}}" method="post">
            <div class="form-group">


            <textarea class="form-control" id="new_comment" cols="30" rows="5" name="new_comment"></textarea>
                <input type="hidden" name="fankui_id" value="{{ques.id}}">

            </div>

        <div class="input-area">
            <button type="submit" class="btn btn-dafault">fabu</button>

        </div>
         </form>
        </div>
        <div class="col-md-4 column">
        </div>
        <h3 class="badge pull-right">评论:({{ques.comment|length}})</h3>

        <ul class="sss" style="padding-left: 0px;">
            {% for fo in comment %}
                <li class="list-group-item">
                    <a href="{{url_for('usercenter',user_id = fo.author.id,tag = 1)}}">{{ fo.author.username }}</a>
                    <span class="badge pull-right">{{ fo.creat_time }}</span>
                    <p>{{ fo.detail }}</p>
                    <br>
                </li>
            {% endfor %}
        </ul>
    </div>





</div>

{% endblock %}

 

对应的后台

from flask import Flask, render_template,request,redirect,url_for,session
# from flask_sqlalchemy import SQLAlchemy
import config
from functools import wraps
from sqlalchemy import or_,and_
from modle import User,Fankui,Comment
from exit import db
# from datetime import datetime
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
# from werkzeug.security import generate_password_hash,check_password_hash



# user=User(username='mis01',password='77',nickname='55')
# db.session.add(user)
# db.session.commit()


# user=User.query.filter(User.username=='a1234567').first()
# user.password='5201314'
# db.session.commit()
#
# user=User.query.filter(User.username=='mis14').first()
# db.session.delete(user)
# db.session.commit()


# user=User.query.filter(User.username=='mis00').first()
# user.password='5201314'
# # print(user.username)


# fankui=Fankui.query.filter(Fankui.author_id=='3').first()
# # user.password='5201314'
# print(fankui.biaoti)


@app.route('/')
def danghangye():
    context = {
        'fankui':Fankui.query.order_by('creat_time').all()
    }
    return render_template('danghangye.html',**context)

@app.route('/详情页/<fankui_id>',methods=['GET','POST'])
def 详情页(fankui_id):
    quest=Fankui.query.filter(Fankui.id == fankui_id).first()
    comment = Comment.query.filter(Comment.fankui_id == fankui_id).all()


    return  render_template('详情页.html',ques = quest,comment=comment)







@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.check_password(passw):
            # if user.password == passw:
                session['user'] = usern
                session['id'] = user.id
                session.permanent = True
                return redirect(url_for('danghangye'))
            else:
                return '密码错误'
        else:
            return '用户不存在'

@app.context_processor
def mycontext():
    usern = session.get('user')
    if usern:
        return {'usernamedd' : usern}
    else:
        return {}





# @app.route('/{{foo.biaoti}}/')
# def {{foo.biaoti}}():
#     return render_template('详情页.html')





@app.route('/register/',methods=['GET','POST'])
def register():
    if request.method == 'GET':
         return render_template('register.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'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('/edit/<user_id>',methods=['GET','POST'])
def edit(user_id):
    user = User.query.filter(User.id == user_id).first()
    if request.method =='GET':
        return render_template('edit.html',user=user)
    else:

        _password = user._password = request.form.get('password')
        db.update(_password)
        db.session.commit()
        return redirect(url_for('danghangye'))




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('/fankui/',methods=['GET','POST'])
@loginFirst
def fankui():
    if request.method == 'GET':
        return render_template('fankui.html')
    else:
        biaoti = request.form.get('biaoti')
        questionDetail = request.form.get('questionDetail')
        author_id = User.query.filter(User.username == session.get('user')).first().id
        fankui = Fankui(biaoti=biaoti, questionDetail=questionDetail, author_id=author_id)
        db.session.add(fankui)
        db.session.commit()
        return redirect(url_for('danghangye'))


@app.route('/comment/',methods=['POST'])
@loginFirst
def comment():
    coment = request.form.get('new_comment')
    autho_id = User.query.filter(User.username == session.get('user')).first().id
    fanku_id = request.form.get('fankui_id')
    comm = Comment(detail=coment, fankui_id=fanku_id,author_id=autho_id)
    db.session.add(comm)
    db.session.commit()
    return redirect(url_for('详情页',fankui_id=fanku_id))






@app.route('/logout/')
def logout():
    session.clear()
    return redirect(url_for('danghangye'))




@app.route('/danghangye/')
def danghangy():
    return render_template('danghangye.html')





@app.route('/usercenter/<user_id>/<tag>')
def usercenter(user_id,tag):
    user = User.query.filter(User.id == user_id).first()
    context = {
        'usern': user.id,
        'username': user.username,
        'fankui':user.fankui,
        'comment':user.comment
    }
    if tag =='1':
      return render_template('usercenter1.html',**context)
    elif tag == '2':
       return render_template('usercenter2.html', **context)
    else:
        return render_template('usercenter3.html', **context)










@app.route('/search/')
def search():
    qu = request.args.get('q')
    quet = Fankui.query.filter(or_(Fankui.biaoti.contains(qu),Fankui.questionDetail.contains(qu)))
    return render_template('danghangye.html',fankui=quet)





if __name__ == '__main__':
    app.run()

 

posted on 2017-12-28 21:48  201506050009曹艺健  阅读(197)  评论(0编辑  收藏  举报