期末作品检查

                                                                 关于python学习

        近年来,python编程语言大火,在2017年,国外的许多知名杂志和机构都对python和其他编程语言进行了比较。2017年7月,IEEE Spectrum 杂志发布了一年一度的编程语言排行榜,python居于首位;9月,Stack Overflow发布的统计数据表明,python是增长量最快的编程语言。在2017年年末,IEEE Spectrum杂志发布了2017年的编程语言排行榜,从数据上显示,python语言仅次于C语言,排名第二。至于国内,有关python的事情也很多,例如浙江信息技术教材将放弃VB,改向Python;山东小学教材加入Python内容;教育部也决定在2018年起,Python列入全国计算机等级考试等等新闻。在人工智能的时代,该学习什么编程语言,python是不二之选。

       这个学期以来,我们学习python,一方面是利用python语言进行爬虫,另一方面就是利用python来开发网页。管理信息系统这门课程,我们主要是学习了python的相关知识和利用python做前端网页设计,以下为这个学期关于python学习的总结和介绍了利用Python+Flask+MySQL的web建设技术过程。

       学期总结:在刚开始学习python的过程中,前期主要利用python3.6软件学习python的基础知识,例如python中的turtle库、利用python进行中文词频统计等;后期,主要利用python来设计网页。python语言比java语言相对简单一些,利用python做web方便快捷。在整个学期的学习过程中,前期所学的python基础知识都没什么问题,但是在后来的学习,利用python设计web的知识就逐渐深入了。刚开始设计简单的web模板还行,到了后来要实现网页的各种功能时,我感觉有点吃力,不理解如何运用、设计功能,在写完代码对项目进行调试时,总是出现一些错误。或许是因为自己不理解,又或者是因为自己的分析错误能力还欠缺,导致整个项目无法正常进行。不过,经过查找资料、查阅书籍和请教同学,最终还是把问题解决了,使项目能够正常运行。我们现在所学的python知识还只是冰山一角,还有很多深奥的知识还有待去深入学习,真正掌握python语言。不积跬步,无以至千里;不积小流,无以成江海,这个学期所学的python知识只是打下一个基础,在今后的学习中需要不断加深理解python知识,从基础学起,做到能够顺手利用python做爬虫、做网页开发。同时,也需要温故而知新,对所学的知识进行复习,真正掌握、理解每一个知识的应用。

      Python+Flask+MySQL的web建设技术过程:

      1.需要安装python3.6、Pycharm、MySQL等相关软件和安装相关的库。

   

    2.需要有python、CSS、javastring、mysql、html等基础知识。

    3.以下为本学期设计的一个简单web项目

       创建html、js、CSS、python文件的时候最好存放规范合理,命名合理

     

  父模板的制作      base.css

nav ul{
            width: 1000px;
            border: 1px solid pink;
            margin: 50px auto 0px auto;
        }
        .nav ul li{
            float: left;
        }
        .nav ul li a{
            width: 80px;
            height: 28px;
            line-height: 28px;
            background-color: pink;
            color: aliceblue;
            margin: 5px 35px;
            font-size: 12px;
            display: block;
            text-align: center;
            text-decoration: none;
        }
        .nav ul li a:hover{
            width: 78px;
            height: 26px;
            line-height: 28px;
            border: 1px solid pink;
            background: #FFF;
        }
        .nav img{
            height: 28px;
            width:28px;
            float: left
        }
        .all{
            width: 88%;
            height:70%;
            overflow: auto;
            margin: auto;
            position: absolute;
            top: 0; left: 0; bottom: 0; right: 0;
        }
        .pic{
            border: 1px solid orange;
            width: 300px;
            float: left;
            margin: 15px;
        }
        .pic img{
            width: 100%;
            height: 180px;
        }
        .wenzi1{
            text-align: center;
            padding: 5px;
            font-family: '';
            background-color: bisque;
        }
        .wenzi1:hover{
            border: 1px solid orangered;
            background-color: salmon;
        }
        .wenzi2{
            text-align: center;
            padding: 5px;
            font-family: '';
            background-color: darkseagreen
        }
        .wenzi2:hover{
            border: 1px solid orangered;
            background: darkgreen;
        }
        .wenzi3{
            text-align: center;
            padding: 5px;
            font-family: '';
            background-color: khaki;
        }
        .wenzi3:hover{
            border: 1px solid orangered;
            background: orange;
        }
        .wenzi4{
            text-align: center;
            padding: 5px;
            font-family: '';
            background-color:salmon;
        }
        .wenzi4:hover{
            border: 1px solid orangered;
            background: red;
        }
        .pic img:hover{
            border: 1px solid orangered;
        }
        .all a{
            text-decoration: none;
            font-family: '华文中宋';
        }

 base.html

!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
        {% block title %}
        {% endblock %}
        Home</title>
    <link rel="stylesheet" href="{{ url_for('static',filename='css/common.css')}}">
{% block head %}
{% endblock %}
</head>
<body id="myBody">
    <div class="banner">
        <div class="p-nav">
            <div class="container">
                <ul class="nav_left">
                    <li><a href="{{ url_for('home') }}">首页</a></li>
                    <li><a href="#">下载</a></li>
                    <li><a href="#">新闻</a></li>
                    <li><a href="{{ url_for('question') }}">发布问答</a></li>
                </ul>
                <form action="{{ url_for('search') }}" method="get">
                    <div style="  height: 50px;padding-top: 13px;">
                        <button type="submit" class="search">搜索</button>
                        <input type="text" style="padding-left: 10px;width: 200px" name="q" PLACEHOLDER="输入要搜索的内容">
                    </div>
                </form>
                <ul class="nav_right">
                    {% if username %}
                        <li><a href="#">{{username}}</a></li>
                        <li><a href="{{ url_for('logout') }}">退出</a></li>
                    {% else %}
                        <li><a href="{{ url_for('sign_in') }}">登录</a></li>
                        <li><a href="{{ url_for('sign_up') }}">注册</a></li>
                    {% endif %}
                </ul>
            </div>
        </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 &copy; 2017. Created by <a href="#" target="_blank">niu</a></p>
    </div>
</body>
</html>


 

              首页的制作

             index.css

.ties-list{
    position: relative;
    margin: 50px auto;
    width: 90%;
}
.tie-item{
    border: 1px solid #ddd;
    background: #fff;
    padding: 10px 20px;
    margin-bottom: -1px;
}
.tie-item:hover {
    border: 1px solid #169fe6;
    position: relative;
    z-index: 10;
}
.tie-title
{
    font-size: 16px;
    line-height: 1.5em;
    float: left;
    clear: right;
}

.tie-title a{
    text-decoration: none;
    font-size: 16px;
    line-height: 1.5em;
}
.tie-content
{
    font-size: 14px;
    color: #333;
    line-height: 200%;
    word-wrap: break-word;
    word-break: break-all;
    overflow: hidden;
    padding: 15px 0;
    clear: both;
}
.tie-desc-link
{
    color: #9ab26b;
    padding-left: 5px;
}
.tie-desc {
    clear: both;
    color: #bcbcbc;
    float: none;
    text-align: left;
    line-height: 200%;
    font-size: 12px;
}

 index.html

{% extends'base.html' %}
{% block title %}
    Home
{% endblock %}
{% block head %}
    <link rel="stylesheet" href="{{ url_for('static',filename='css/index.css')}}">
    <style type="text/css">
    div.all{
        width: 80%;
        margin: auto;
    }
    div.pic{
        width: 50%;
        float: left;
    }
    img{
        width: 100%;
        height: 400px;
    }
    </style>
{% endblock %}
{% block main %}
    <div class="ties-list">
       {% for tie in question %}
            <div class="tie-item">
                <div class="tie-title">
                    <a href="{{ url_for('question_detail',question_id = tie.id) }}" target="_blank">{{tie.title }}</a></div>
                <div class="tie-content">
                    {{ tie.detail | safe }}
                    <a class="tie-desc-link" href="{{ url_for('question_detail',question_id = tie.id) }}" >阅读全文</a>
                </div>
                <div class="tie-desc">{{tie.author.username}}发布于({{tie.creatTime }})
                    <span><a href="#">评论({{ tie.comments|length }})</a></span>
                </div>
            </div>
       {% endfor %}
    </div>
    <div class="all">
        <div class="pic">
            <a href="#"><img src="http://pic1.win4000.com/wallpaper/f/51b9b06f1d0fb.jpg"></a>
            <div class="wenzi1"><a  href="">淡雅清新</a></div>
        </div>
        <div class="pic">
            <a href="#">
                <img src="http://www.zcool.com.cn/community/0379bb5579eead00000012e7e1c65aa.jpg"></a>
            <div class="wenzi2"><a href="">蓓蕾初开</a></div>
        </div>
        <div class="pic">
            <a href="#">
                <img src="http://imgstore.cdn.sogou.com/app/a/100540002/766171.jpg"></a>
            <div class="wenzi3"><a href="">仓央兮措</a></div>
        </div>
        <div class="pic">
            <a href="#">
                <img src="http://pic.5442.com:82/2013/0417/16/02.jpg%21720.jpg"></a>
            <div class="wenzi4"><a href="">骄阳似火</a></div>
        </div>
    </div>
{% endblock %}

注册页面设计  regiser.html

{% extends'base.html' %}
{% block title %}
    Login
{% endblock %}
{% block head %}
        <title>注册页面</title>
        <script type="text/javascript" src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
        <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/register.css')}}">
        <script type="text/javascript">
            $(function () {
                 $("button.submit").click(function () {
                     var userName = $("input[name='user']").val();
                     var passWord = $("input[name='pwd']").val();
                     var RepassWord = $("input[name='repwd']").val();
                     if(userName.length == 0 || userName== " ")
                     {
                         $("#register_notice").html("用户名不允许为空");
                         $("#register_notice").show();
                         $("input[name='user']").val("");
                     }
                     else if(passWord != RepassWord)
                     {
                         $("#register_notice").html("两次输入密码不一致");
                         $("#register_notice").show();
                         $("input[name='pwd']").val("");
                         $("input[name='repwd']").val("");
                     }
                    else
                    {
                        var data = {"username":userName, "password":passWord};
                        $.post("{{ url_for('sign_up') }}",data,function(result)
                        {
                            var err = result["err"];
                            if (err ==0)
                            {
                                alert("注册成功");
                            }
                            else
                            {
                                $("#register_notice").text(result["text"]);
                                $("#register_notice").show();
                                $("input[name='user']").val("");
                                $("input[name='pwd']").val("");
                                $("input[name='repwd']").val("");
                            }
                        });
                    }
                 });
            });
        </script>
{% endblock %}
{% block main %}
    <body>
        <div class="logo">
        </div>
        <div class="register">
            <p>
                <label>用户名<br>
                    <input type="text" name="user" class="input" size="20">
                </label>
            </p>
            <p>
                <label>密码<br>
                    <input type="password" name="pwd" value="" size="20">
                </label>
            </p>
            <p>
                <label>确认密码<br>
                    <input type="password" name="repwd" value="" size="20">
                </label>
            </p>
            <p>
                <a href="{{ url_for('index') }}">← 返回到博客</a>
                <button class="submit">注册</button>
            </p>
            <span id="register_notice">用户名或者密码错误</span>
        </div>
    </body>
{% endblock %}

css

body{
                background:#e7e7e7 ;
            }
            .logo{
                width: 330px;
                height: 58px;
                margin: 100px auto 0;
                background-image: url("../image/logo_daizuo.png");
            }
            .register{
                width: 260px;
                margin: 0 auto;
                height: 340px;
                box-shadow: 10px 10px 5px #888888;
                background: white;
                padding: 10px 60px;
            }
            label{
                color: #72777c;
                font-size: 14px;
            }
            input{
                width: 100%;
                height: 34px;
            }
            p>a{
                float: left;
                font-size: 14px;
                height: 36px;
                line-height: 36px;
                color: #72777c;
                text-decoration: none;
            }
            button{
                float: right;
                width: 80px;
                height: 36px;
                background: #108099;
                color: #fff;
            }
            #register_notice{
                float: left;
                margin-left: 50px;
                color: red;
                font-size: 14px;
                display: none
            }

 

登录功能设计

{% extends'base.html' %}
{% block title %}
    Login
{% endblock %}
{% block head %}
    <script type="text/javascript" src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/login.css')}}">
    <script type="text/javascript">
            $(function () {
                 $("button.submit").click(function () {
                     var userName = $("input[name='user']").val();
                     var passWord = $("input[name='pwd']").val();
                     var data = {"username":userName,"password":passWord};
                     $.post("{{ url_for('sign_in') }}",data,function(result)
                     {
                        var err = result["err"];
                        if (err ==0)
                        {
                            window.location.href = "/";
                        }
                        else
                        {
                            $("#login_notice").html(result["text"]);
                            $("#login_notice").show();
                            $("input[name='user']").val("");
                            $("input[name='pwd']").val("");
                        }
                     });
                 });
            });
    </script>
{% endblock %}
{% block main %}
<body>
    <div class="logo">
    </div>
    <div class="login">
        <p>
            <label for="user_login">用户名<br>
                <input type="text" name="user" class="input" size="20">
            </label>
        </p>
        <p>
            <label for="user_pass">密码<br>
                <input type="password" name="pwd" value="" size="20">
            </label>
        </p>
        <p>
            <a href="{{ url_for('index') }} ">← 返回到博客</a>
            <button class="submit">登录</button>
        </p>
        <span id="login_notice" style="">用户名或者密码错误</span>
    </div>
</body>
{% endblock %}

 

发布问答功能

{% extends'base.html' %}
{% block title %}
    Question
{% endblock %}
{% block head %}
    <link rel="stylesheet" href="{{ url_for('static',filename='css/question.css')}}">
    <style>
        div.question{
            width: 80%;
            margin: auto;
        }
    textarea.form-control{
        width: 80%;
        margin: auto;
    }
    </style>
{% endblock %}
{% block main %}
    <div class="question">
        {% if username %}
            <p class="name">欢迎你,{{ username }}</p>
            <h1>发布问答</h1>
            <form class="biao" action="{{ url_for('question') }}" method="post">
                <div class="form-group">
                    <label for="ask">Question</label><br>
                    <textarea name='title' class="form-control" rows="1" id="ask"></textarea>
                </div>
                <br>
                <div class="form-group">
                    <label for="questionDetail">Detail</label><br>
                    <textarea name='detail' class="form-control" rows="8" id="questionDetail"></textarea>
                </div>
                <button type="submit" class="btn-default">发布</button>
            </form>
        {% else %}
            <p class="name">欢迎你,请先<a href="{{ url_for('sign_in') }}" >登录</a>或者<a href="{{ url_for('sign_up') }}">注册</a></p>
        {% endif %}
    </div>
{% endblock %}

评论功能设计

{% extends'base.html' %}
{% block title %}
    Question
{% endblock %}

{% block head %}
    <link rel="stylesheet" href="{{ url_for('static',filename='css/question_detail.css')}}">
    <style>
    </style>
{% endblock %}
{% block main %}
    <section>
        <div class="container">
            <div class="artical_content">
                <div class="content_head">
                    <h3 class="article_title">{{question.title}}</h3>
                    <p class="time">发布时间:{{question.create_time}}&nbsp;</p>
                </div>
                <article>
                    {{question.detail|safe}}
                </article>
                {% if username %}
                    <form action="{{ url_for('comment') }}" method="post">
                        <textarea name='detail' class="form-control" rows="3" id="questionDetail"></textarea><br>
                        <button class="btn-default">发布</button>
                        <input name="question_id" value="{{ question.id }}" type="hidden"  />
                     </form>
                {% else %}
                    <p class="name">欢迎你,请先<a href="{{ url_for('sign_in') }}" >登录</a>或者<a href="{{ url_for('sign_up') }}">注册</a></p>
                {% endif %}
                <p>评论:({{ question.comments|length }})</p>
                <ul >
                    {% for foo in question.comments %}
                        <li><p>{{ foo.author.username }} ({{ foo.creatTime }})</p><p class="neirong">{{ foo.detail }}</p></li>
                    {% endfor %}
                </ul>
            </div>
        </div>
    </section>
{% endblock %}

 数据库功能设计

import os
SECRET_KEY = os.urandom(24)
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@localhost:3306/mis_db?charset=utf8'
SQLALCHEMY_TRACK_MODIFICATIONS = False

 

主py文件

from flask import Flask,render_template,request,redirect, url_for,session,Response
from sqlalchemy import or_, and_
from flask_sqlalchemy import SQLAlchemy
import json
import datetime
import config

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)
    creatTime=db.Column(db.DateTime, default=datetime.datetime.now)
    authorID=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'))
    detail=db.Column(db.Text,nullable=False)
    creatTime=db.Column(db.DateTime,default=datetime.datetime.now)
    question=db.relationship('Question',backref=db.backref('comments',order_by=creatTime.desc))
    author=db.relationship('User',backref=db.backref('comments'))
db.create_all()

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

@app.route('/question_detail/<question_id>')
def question_detail(question_id):
    question = Question.query.filter(Question.id == question_id).first()
    return render_template('question_detail.html', question=question)

@app.route('/home')
def home():
    context={
        'question': Question.query.all()
    }
    return render_template('index.html',  **context)

@app.route('/sign_in',methods=['GET','POST'])
def sign_in():
    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.permanent = True
                return Response(json.dumps({"err": 0,"text":"login success"}), mimetype='application/json')
            else:
                return Response(json.dumps({"err": -1,"text":" user or password error"}), mimetype='application/json')

        else:
            return Response(json.dumps({"err": -1,"text":" username is not existed"}), mimetype='application/json')


@app.route('/sign_up',methods=['GET','POST'])
def sign_up():
    if request.method == 'GET':
        return render_template('register.html')
    else:
        username = request.values.get('username')
        password = request.values.get('password')
        user = User.query.filter(User.username == username).first()
        if user:
            return Response(json.dumps({"err": 0,"text":"username existed."}), mimetype='application/json')
        else:
            user1 = User(username=username, password=password)
            db.session.add(user1)
            db.session.commit()
            return Response(json.dumps({"err": 0}), mimetype='application/json')

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


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

@app.route('/question/',methods=['GET','POST'])
def question():
    if request.method == 'GET':
        return render_template('question.html')
    else:
        title = request.form.get('title')
        detail = request.form.get('detail')
        authorID =User.query.filter(User.username == session.get('user')).first().id
        user = User.query.filter(User.username == session.get('user')).first()
        question = Question.query.filter(Question.title == title).first()
        if question:
            return 'question existed'
        else:
            questions = Question(title=title, detail=detail, authorID=authorID)
            questions.author = user
            db.session.add(questions)
            db.session.commit()
            return redirect(url_for(('home')))


@app.route('/comment/',methods=['GET','POST'])
def comment():
    if request.method == 'GET':
        return render_template('question_detail.html')
    else:
        detail = request.form.get('detail')
        author_id =User.query.filter(User.username == session.get('user')).first().id
        question_id=Question.query.filter(Question.authorID ==author_id).first().id
        comments = Comment(detail=detail,author_id=author_id,question_id=question_id)
        #comments.question=question
        #comments.author = user
        db.session.add(comments)
        db.session.commit()
        return redirect(url_for('question_detail', question_id=question_id))

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

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

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


以上为用python在这个学期中web建设的一些代码,整个设计出来的网页还是很不完整的,部分功能无法实现,在之后的学习中,应该继续完善、改进这个网页。掌握更多的html、python、css、sql知识,熟练这些技术,设计一个更加完整的网页。

 

posted @ 2018-01-07 20:04  064曾志彬  阅读(169)  评论(0编辑  收藏  举报