YWEIEN

导航

期末作品检查


1期末作品检查:必须完成:

1,网站父模板统一布局:头部导航条、底部图片导航、中间主显示区域布局

开始flask项目

mis_db.py

from flask import Flask,render_template,request,redirect,url_for,session
from flask_sqlalchemy import SQLAlchemy
import config
from functools import wraps
from datetime import datetime
from sqlalchemy import or_


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(50))
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)
    create_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'))
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'))
    create_time = db.Column(db.DateTime, default=datetime.now)
    detail = db.Column(db.Text, nullable=False)
    question = db.relationship('Question', backref=db.backref('comments'))
    author = db.relationship('User', backref=db.backref('comments'))
db.create_all()
# 增加
# user = User(username='mis1114',password = 'mis1114',nickname='mis1114')
# db.session.add(user)
# db.session.commit()
# # 查询
# User.query.filter(User.username == 'mis1114').first()
# #修改
# user =User.query.filter(User.username =='mis1114').first()
# user.password='23456'
# print(user.username,user.password)
# db.session.commit()
# # 删除
# user =User.query.filter(User.username =='mis1114').first()
# db.session.delete(user)
# db.session.commit()

#首页
@app.route('/')
def index():
    context ={
        'question': Question.query.order_by('-create_time').all()
    }
    return render_template('index.html',**context)

# @app.route('/')
# def base():
#     return render_template('base.html')

@app.route('/ll/',methods=['GET','POST'])
def ll():
    if request.method=='GET':
        return render_template('ll.html')
    else:
        username=request.form.get('username')
        password=request.form.get('password')
        user=User.query.filter(User.username==username,User.password==password).first()
        if user:
            session['user']=username
            session['userid'] = user.id
            session.permanent=True
            return redirect(url_for('index'))
        else:
            return u'error username or password'


@app.route('/zc/',methods=['GET','POST'])
def zc():
    if request.method=='GET':
         return render_template('zc.html')
    else:
        username=request.form.get('username')
        password=request.form.get('password')
        user = User.query.filter(User.username==username).first()
        if user:
            return u'username existed'
        else:
            user = User(username=username, password= password)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('ll'))


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






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


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


def loginFirst(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if session.get('user'):
            return func(*args, **kwargs)
        else:
            return redirect(url_for('ll'))
    return wrapper

@app.route('/question/', methods=['GET','POST'])
@loginFirst
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('/comment/',methods=['POST'])
@loginFirst
def comment():
        comment = request.form.get('new_comment')
        ques_id = request.form.get('question_id')
        auth_id = User.query.filter(User.username == session.get('user')).first().id
        comm = Comment( detail=comment, question_id=ques_id,author_id=auth_id)
        db.session.add(comm)
        db.session.commit()
        return redirect(url_for('detail',question_id = ques_id))


# def login_re(func):
#     @wraps(func)
#     def wrapper(*args, **kwargs):
#         if session.get('comment'):
#             return func(*args,**kwargs)
#         else:
#             return redirect(url_for('ll'))
#     return wrapper

@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('/usercenter/<user_id>/<tag>')
@loginFirst
def usercenter(user_id,tag):
    user=User.query.filter(User.id==user_id).first()
    context={
        'user':user,
        'username': user.username,
        'questions': user.question,
        'comments': user.comments,

    }
    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.context_processor
def mycontext():
    username = session.get('userbase')
    if username:
        return {'username': username}
    else:
        return {}

@app.route('/question/', methods=['GET', 'POST'])
@loginFirst
def ask():
    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('userbase')).first().id  # 判断用户是否存在
        question = Question(title=title, detail=detail, author_id=author_id)
        db.session.add(question)  # 保存到数据库
        db.session.commit()  # 提交
        return redirect(url_for('userbase'))  # 跳转


@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('-create_time')
    return render_template('index.html',question = ques)

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

2,注册、登录、注销功能

(1)登录 login.html

{% extends 'base.html' %}
{% block title %}
登录
{% endblock %}
{% block head %}
   <link href="{{ url_for('static',filename='css/ll.css') }}" rel="stylesheet" type="text/css">
    <script src="{{ url_for('static',filename='js/ll.js')}}"></script>
{% endblock %}

{% block main %}

 <div class="box">
     <h2 class="d">登录</h2>
     <form action="{{url_for('ll')}}" method="post">
     <div class="input_box">
            <input style="background-color: deepskyblue;" id="uname" type="text" placeholder="请输入用户名" name="username">
        </div>
        <br>
        <div class="input_box">
            <input style="background-color: deepskyblue;" id="upass" type="password" placeholder="请输入密码" name="password">
        </div>
        <br>
        <div id="error_box"><br></div>
        <div class="input_box">
            <button class="dl" onclick="fnLogin()">enter</button>

        </div>
        <br>

</div>


{% endblock %}

ll.js

 function fnLogin() {
        var oUname=document.getElementById("uname")
        var oUpass=document.getElementById("upass");
        var oError=document.getElementById("error_box")
        var isError=true;
        oError.innerHTML="<br>"
        if(oUname.value.length<6|| oUname.value.length > 20){
            oError.innerHTML="用户名至少6-20位"
            return false;
        }else if((oUname.value.charCodeAt(0)>=48) && (oUname.value.charCodeAt(0)<=57)){
            oError.innerHTML="first.number."
            return false;
        }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 = "only letter or number.";
                return false;
            }
        }
        if(oUpass.value.length<6|| oUpass.value.length > 20){
            oError.innerHTML="密码至少6-20位"
            return false;
        }
        if((oUname.value.length < 6 || oUname.value.length > 20) && (oUpass.value.length < 6 || oUpass.value.length > 20)){
            oError.innerHTML="用户名密码至少6-20位"
              return false;
            }

            return true;
            window.alert("登录成功")
        }

 

(2)首页 base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}MIS07</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/base.css') }}">
<script src="{{ url_for('static',filename='js/wd.js')}}"></script>

    {% block head %}
    {% endblock %}
</head>


<body id="myBody">
<div class="dhl" >
    <ul>
                <img id="on_off" onclick="mySwitch()" src="http://www.runoob.com/images/pic_bulbon.gif" width="25px">

                <img src="http://img15.3lian.com/2015/f1/26/d/114.jpg" width="60" height="60" >
                <a class="dhg" href="">SECRET</a>
                <a class="dha" href="{{ url_for('index') }}">首页</a>
                <a class="dll" href="{{ url_for('question') }}" >发布问答</a>

                <form action="{{url_for('search')}}" method="get" class="navbar-form navbar-left">

                    <input name="q" type="text" cols="40" rows="1" class="soua" placeholder="请输入关键字">

                    <button type="submit" class="soub">查询</button>
                </form>


        {% if username %}

        <a class="dll" href="{{url_for('usercenter',user_id = session.get('userid'),tag=1)}}">{{ session.get('user') }}</a>
        <!--<a class="dll" href="#">{{ username }}</a>-->
        <a class="dll" href="{{ url_for('logout') }}">注销</a>
      {% else %}
        <a class="dll" href="{{ url_for('ll') }}">登录</a> <br>

        <a class="dll" href="{{ url_for('zc') }}">注册</a>
      {% endif %}



 </ul>


</div>

<div>
    <nav>
          <div class="button">
    <a href="">联系我们</a>
    <a href="">加入我们</a>
    <a href="">帮助中心</a>
    <a href="">合作伙伴</a>
</div>

        <p>版权 @ cc</p>

</div>
<body>

{% block main %}{% endblock %}
</body>
    </nav>

 (3)注册  zc.html

{% extends 'base.html' %}
{% block title %}
注册
{% endblock %}
{% block head %}
   <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/zc.css') }}">
    <script src="{{ url_for('static',filename='js/zc.js')}}"></script>
{% endblock %}

{% block main %}

 <div class="box">
     <h2 class="d">注册</h2>
     <form action="{{ url_for('zc') }}"method="post">
     <div class="input_box">
            <input style="background-color: deepskyblue;" id="uname" type="text" placeholder="请输入你的昵称" name="username">
     </div>
        <br>
     <div class="input_box">
            <input style="background-color: deepskyblue;" id="upass" type="password" placeholder="请输入你的密码" name="password">
     </div>
        <br>
        <div class="input_box">
            <input style="background-color: deepskyblue;" id="upass" type="password" placeholder="请再输入密码" name="password1">
        </div>
        <br>
         <div id="error_box"><br></div>
     <div class="input_box">
            <button class="dl" onclick="fnLogin()">注册</button>
     </div>
        <br>
 </div>



{% endblock %}

zc.js

function tnlogin() {
    var oUname = document.getElementById("uname")
    var oError = document.getElementById("error_box")
    var oUpass = document.getElementById("upass")
    var oUpass1 = document.getElementById("upass1")

    oError.innerHTML = "<br>"
    if (oUname.value.length < 6 || oUname.value.length > 20) {
        oError.innerHTML = "用户名必须在6-20之间";
        return;
    } else if ((oUname.value.charCodeAt(0) >= 48) && (oUname.value.charCodeAt(0) <= 57)) {
        oError.innerHTML = "首字母不能为数字";
        return;
    } 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 = "只能填写数字或字母";
            return;
        }
    }
  if (oUpass.value.length > 20 || oUpass.value.length < 6) {
        oError.innerHTML = "密码必须在6-20之间";
        return;
    } else if (oUpass!= oUpass1) {
        document.getElementById("error_box").innerHTML = "两次密码不一致"
        return false;
    }
    return true;
    window.alert("注册成功!")
}

 

(4)发布问答 question.html

{% extends 'base.html' %}
{% block title %}
问答
{% endblock %}
{% block head %}
    <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/question.css') }}">
{#     <script src="{{ url_for('static',filename='js/question.js')}}"></script>#}
{% endblock %}

{% block main %}
<form action="{{ url_for('question') }}" method="post">
<div class="label">
    <h1 >发布问答</h1>
        <div class="form-group">
            <label for="question">标题</label>
            <textarea id="question" cols="40" rows="1" placeholder="请输入标题" name='title'></textarea>
        </div>
        <div class="form-group" style="color:#333">
            <label for="questionDetail">内容</label>
            <textarea class="form-control" id="questionDetail" cols="50" rows="5" placeholder="请输入内容" name='detail'></textarea>
        </div>
       <br>
        <div class="input-area">
            <button onclick="fnQuestion">发布问答</button>
        </div>
    </div>


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

question.js

function fnQuestion() {
    var title =document.getElementById("title")
    var detail = document.getElementById("detail")
    var creat_time=document.getElementById("creat_time")
    var author_id =document.getElementById("author_id")
    var author=document.getElementById("author")
    var isError = true;
     if (title.value.length > 100 || oUpass.value.length < 0) {
        oError.innerHTML = "问题请输入100位以内字符"
        isError = false;
    }
        return isError;
    return isError;
}

  

 

详情页 detil.html

{% extends'base.html' %}
{% block title %}
    detail
{% endblock %}
{#{% block head %}#}
{#    <link rel="stylesheet" href="{{ url_for('static',filename='css/detail.css')}}" type="text/css">#}
{#{% endblock %}#}
{% block main %}
<body>
<div class="post">

<h3 class="title ">{{ques.title}}<br><small>{{ ques.author.username }}<span>{{ ques.create_time }} </span>  </small></h3>
</div>
    <p style="color: #333;">{{ ques.detail }}</p>
    <hr>
    <form action="{{ url_for('comment') }}"method="post">
    <div class="new-comment">
        <textarea name="new_comment" id="new-comment" cols="85" rows="5" placeholder="write your comment"></textarea>
        <input name="question_id" type="hidden" value="{{ ques.id }}" />
    </div>
    <button class="btn-send" type="submit">发送</button>
    </form>

<h4>评论:({{ ques.comment | length }})</h4>
 <ul class="list">
       {% for foo in ques.comments %}
       <li class="post_item">
           <a href="{{ url_for('usercenter',user_id = foo.author.id,tag = 1) }}" class="light">{{foo.author.username }}</a>
           <br>
           <p class="post_item">{{ foo.detail }}</p>
           <span class="foot">发布于  {{ foo.create_time }}</span>
       </li>
       <hr>
{% endfor %}
   </ul>
</body>
{% endblock %}

个人中心 usrbase.html

{% extends "base.html" %}
{% block title %}个人中心{% endblock %}
{% block head %}

    <style>
        .nav_ul li{
            list-style: none;
            float: left;
            margin: 20px;
            border-bottom:outset;
        }
    </style>
{% endblock %}

{% block main %}
<h3><span class="glyphicon glyphicon-user" aria-hidden="true"></span>{{ user.username }}</h3>
<ul class="nav_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>

{% block user %}{% endblock %}

{% endblock %}

usercenter,html

{% extends 'userbase.html' %}
{% block title %}个人中心
{% endblock %}
{% block head %}
    <link rel="stylesheet" href="{{ url_for('static',filename='css/detail.css')}}" type="text/css">
{% endblock %}
{% block main %}
     <div class="page-header">
         <h3><span class="glyphicon glyphicon-user" aria-hidden="true"></span>{{ user.username }}<br><small>全部问答<span class="badge"></span> </small></h3>
          <ul class="list-group" style="color:#333">
              {% for foo in user.question %}
                <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.create_time}}</span>
                  <p style="">{{foo.detail}}</p>
                </li>
              {% endfor %}
          </ul>
     </div>


     <div class="page-header">
          <h3><span class="glyphicon glyphicon-user" aria-hidden="true"></span>{{ user.username }}<br><small>全部评论 <span class="badge"></span> </small></h3>
          <ul class="list-group" style="color:#333">
              {% for foo in user.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.create_time}}</span>
                  <p style="">{{foo.detail}}</p>
                </li>
              {% endfor %}
          </ul>
     </div>


     <div class="page-header">
         <h3><span class="glyphicon glyphicon-user" aria-hidden="true"></span>{{user.username}}<br><small>个人信息 <span class="badge"></span> </small></h3>
          <ul class="list-group" style="">
              <li class="list-group-item">用户:{{ user.username }}</li>
              <li class="list-group-item">编号:{{ user.id }}</li>
              <li class="list-group-item">昵称:xxx</li>
              <li class="list-group-item">头像:</li>
              <li class="list-group-item">问答条数:{{ questions|length }}</li>
              <li class="list-group-item">评论条数:{{ comments|length }}</li>
          </ul>

     </div>

{% endblock %}

usercenter1,html

{% extends 'userbase.html'%}

{%block user%}
<div class="page-header">
    <h3> <span class="glyphicon glyphicon-user" aria-hidden="true"></span>{{username}}<br><small>全部问答<span class="bagde"></span></small>
    </h3>
    <ul class="list-group" >
        {%for foo in question%}
        <li class="list-group-item">
            <span class="glyphicon glyphicon-heart-empty" aria-hidden="true"></span>
            <a href="{{url_for('usercenter',user_id=foo.author_id,tag=1)}}">{{foo.author.username}}</a>
            <span class="badge">{{foo.create_time}}</span>
            <p>文章标题:{{ foo.title }}</p>
            <p>文章内容:{{foo.detail}}</p>
        </li>
        {% endfor %}
    </ul>
</div>
{% endblock%}

usercenter2,html

{% extends 'userbase.html'%}

{%block user%}
<div class="page-header" >
    <h3> <span class="glyphicon glyphicon-user" aria-hidden="true"></span>{{username}}<br><small>全部评论<span class="bagde"></span></small>
    </h3>
    <ul class="list-group" >
        {%for foo in comments%}
        <li class="list-group-item">
            <span class="glyphicon glyphicon-heart-empty" aria-hidden="true"></span>
            <a href="{{url_for('usercenter',user_id=foo.author_id,tag=1)}}">{{foo.author.username}}</a>
            <span class="badge">{{foo.create_time}}</span>
            <p>文章标题:{{ foo.title }}</p>
            <p>评论内容:{{foo.detail}}</p>
        </li>
        {% endfor %}
    </ul>
</div>
{% endblock%}

usercenter3,html

{% extends 'userbase.html'%}

{%block user%}
<div class="page-header" >
    <h3> <span class="glyphicon glyphicon-user" aria-hidden="true"></span>{{username}}<br><small>个人信息<span class="bagde"></span></small>
    </h3>
    <ul class="list-group">
        <li class="list-group-item">用户:{{ username }}</li>
        <li class="list-group-item">编号:{{userid}}</li>
        <li class="list-group-item">昵称:xxx</li>
        <li class="list-group-item">头像:</li>
        <li class="list-group-item">问答条数:{{ questions|length }}</li>
        <li class="list-group-item">评论条数:{{ comments|length }}</li>

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

夜间模式

function mySwitch()
{
    var myele=document.getElementById("on_off");
    if (myele.src.match("bulbon"))
    {
        myele.src="http://www.runoob.com/images/pic_bulboff.gif";
        document.getElementById("myBody").style.background="black";
        document.getElementById("demo").style.color="white"
    }
    else
    {
        myele.src="http://www.runoob.com/images/pic_bulbon.gif";
        document.getElementById("myBody").style.background="white";
        document.getElementById("demo").style.color="black"
    }
}

 

 

 

 

 

个人学期总结

    Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。自从20世纪90年代初Python语言诞生至今,它逐渐被广泛应用于处理系统管理任务和WEB编程。Python已经成为最受欢迎的程序设计语言之一。Python拥有一个强大的标准库。Python语言的核心只包含数字、字符串、列表、字典、文件等常见类型和函数,而由Python标准库提供了系统管理、网络通信、文本处理、数据库接口、图形系统、XML处理等额外的功能。Python标准库命名接口清晰、文档良好,很容易学习和使用。     

        本学期我们进行了对Python的学习我在本次进行课程设计时,将课堂上所学的知识尽可能地发挥到了实践中。在整个Python+Flask+MysqL的web建设技术建设中涉及到的问题还不完善,我会在以后的时间里来使我对的认知和使用更加熟练。通过此次利用python来进行网页设计使我了解好多不理解的问题,在此的过程中有许多问题需要通过查阅,也使我更加熟悉的利用py实现各种实用的库的调用方法,了解python的基本使用方法包括输入输出,基本数据类型,运算,turtle库,循环,条件,函数定义,字符串操作,词频统计等等。

     虽然在这些过程中我们遇到了许多难题,但是,我们通过上网查阅相关资料,问学霸同学、查看类似的操作方法等方式,把我们在进行网页设计中遇到发现的问题一一解决。在这次期末大作业的过程中,虽然遇到不少的挫折,至使很多处代码运行起来不协调,常常遇到问题。但是,正因为这样,我才有克服困难的机会,问题各个击破。从而锻炼了自己对待事情的认真和负责能力,从而也提高了独立思考的能力。

    通过这次设计,我受益非浅,亲身体验了简单的网页设计的过程,在实践中了解了此过程的设计的步骤、流程以及思路,增长了在Python方面的见识和使用熟练度,我深刻认识到以前所学的基础课程的重要性,也使我们掌握了很多新知识,特别是一些课本之外的知识,体会到了理论知识和实践相结合的重要性。这对我来说是非常宝贵的经验之一,设计这个系统的过程不仅是对上学期所学知识的一次回顾,更是在对我们处理问题、解决实际问题能力的培养和锻炼。

 

posted on 2018-01-07 00:26  YWEIEN  阅读(175)  评论(0编辑  收藏  举报