期末做品檢查

 我的學期總結:javascript

學習python,首先要配置好環境,安裝好軟件,css

 

 

 一開始老師教turtle利用條件、循環、函數定義畫各類圖形如,五角星、同心圓、太陽花、中國國旗等;而後學習了字符串的基本操做,輸出代碼計算後的結果,還有凱撒密碼、GDP格式化輸出、九九乘法表;利用python進行英文詞彙統計,組合數據類型練習等, 我的有一部分心得,html

1.Python對於代碼格式要求至關嚴格,經過對於縮進的距離來判斷代碼是否處於同一個代碼塊。該開始學習的時候常常因爲縮進出錯形成代碼錯誤。java

2.1.python中雙引號和單引號做用同樣,print 'hello World'和print "hello World"是同樣的。python

3.python,使用變量,不須要定義類型,只要賦初值就行,和javascript中定義變量有點相似,只是更簡單了,連var都不須要mysql

4.python中的控制語句,if,while,for.值得注意的是條件都沒有括號,條件後必須加:,while也能夠有else語句jquery

5.python 定義函數的方法web

              def fun_name(parameter1,parameter2...):sql

6.python中的數據結構有列表,元組,字典.其定義以下數據庫

               mylist = ['apple','banana','orange']列表

               zoo = ('aaa','bbb','ccc')元組

               dic = {'zhang':'san',

                         'li':'si','wang':'wu'}

 

 總結Python+Flask+MysqL的web建設技術過程:

導入包:

from flask import Flask
from flask import render_template, request, redirect, url_for, session
from functools import wraps
from datetime import datetime

from werkzeug.security import check_password_hash, generate_password_hash

 

建表
class User(db.Model):
    __tablename__='user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(100), nullable=False)
    _password = db.Column(db.String(500), nullable=False)#內部使用
    nickname = db.Column(db.String(20), nullable=True)

  class Ques(db.Model):
    __tablename__='question'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    author = db.relationship('User', backref=db.backref('question'))
    title = db.Column(db.String(20), nullable=False)
    detail = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now)

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'))
    question = db.relationship('Ques', backref=db.backref('comment'))
    author = db.relationship('User', backref=db.backref('comment'))
    detail = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now)

 

 建表以下:

 

 創建一個父模版:

包含導航條

  <meta charset="UTF-8">
    <title> 靈魂有香氣的女子&nbsp;{% block title %}{% endblock %}</title>

    <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
{% block head %} {% endblock %}
</head>
 <link rel="stylesheet" type="text/css" href="{{url_for('static',filename='css/style.css') }}">
<nav class="navbar navbar-default" role="navigation">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="{{ url_for('index') }}">首頁</a>

            </div>
            <form class="navbar-form navbar-left" action="{{ url_for('search') }}" method="get" role="search">
                <div class="form-group">
                    <input type="text" class="form-control" name="search" placeholder="靈魂有香氣的女子">
                </div>
                <button type="submit" class="btn btn-default">搜索</button>
            </form>
            <div class="navbar-footer">
                <ul class="nav nav-tabs" >
                    {% if username %}
                        <li><a href="{{ url_for('usercenter',user_id=userid,tag='1') }}">{{ username }}</a></li>
                        <li><a href="{{ url_for('loginout') }}">註銷</a></li>
                    {% else %}
                        <li><a href="{{ url_for('login') }}">登陸</a></li>
                        <li><a href="{{ url_for('register') }}">註冊</a></li>
                    {% endif %}
                    <li><a href="{{ url_for('fabu') }}">發佈</a></li>
                </ul>
            </div>

子模版繼承:

{% extends 'base.html' %}
{% block title %}登陸{% endblock %}
{% block head %}{% endblock %}
{% block body %}{% endblock %}

註冊頁面:

<div class="col-md-6 column">
            <form class="form-horizontal" role="form" action="{{ url_for('register')}}"method="post">
                <div class="form-group">
                     <label for="inputEmail3" class="col-sm-2 control-label">賬號:</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="username" name="username" />
                    </div>
                </div>
                <div class="form-group">
                     <label for="inputEmail3" class="col-sm-2 control-label">暱稱:</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="nickname" name="nickname" />
                    </div>
                </div>
                <div class="form-group">
                     <label for="inputPassword3" class="col-sm-2 control-label">密碼:</label>
                    <div class="col-sm-10">
                        <input type="password" class="form-control" id="password" name="password" />
                    </div>
                </div>
                <div class="form-group">
                     <label for="inputPassword3" class="col-sm-2 control-label">確認密碼:</label>
                    <div class="col-sm-10">
                        <input type="password" class="form-control" id="inputPassword3" />
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                         <button type="submit" class="btn btn-default">註冊</button>
                    </div>
                </div>
function fozhuce() {
            var oUname = document.getElementById("uname");
            var oError = document.getElementById("error_box");
            var oUpass = document.getElementById("upass");
            var oUpass1 = document.getElementById("upass1");
            var isError = true;
            oError.innerHTML = "<br>";

            if (oUname.value.length < 6 || oUname.value.length > 20) {
                oError.innerHTML = "用戶名要6-20位";
                isError = false;
                return isError;
            }else if(oUname.value.charCodeAt(0)>=48 &&(oUname.value.charCodeAt(0)<=57)){
                oError.innerHTML="首位不能爲數字";
                isError = false;
                return isError;
            }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)<58)&&(oUname.value.charCodeAt(i)>97)){
                oError.innerHTML="只能爲數字和字母";
                isError = false;
                return isError;
               }
            }if (oUpass.value.length < 6 || oUpass.value.length > 20) {
                oError.innerHTML = "密碼要6-20位";
                isError = false;
                return isError;
            }else if(oUpass.value!=oUpass1.value) {
                oError.innerHTML = "設置密碼和驗證密碼不一致";
                isError = false;
                return isError;
            }
            return ture;
            }

登陸頁面:

                            <label for="inputEmail3" class="col-sm-2 control-label">賬號:</label>
                            <div class="col-sm-10">
                                <input type="text" style="width: 300px" class="form-control" id="username"
                                       name="username"/>
                            </div>
                        </div>
                        <div class="form-group">

                            <label for="inputPassword3" class="col-sm-2 control-label">密碼:</label>
                             <div class="col-sm-10">
                                <input type="password" style="width: 300px" class="form-control" id="password"
                                       name="pass"/>
                            </div>
                        </div>
                        <div class="form-group" align="center">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="submit" class="btn btn-default" onclick=" return login()">登陸</button>
                            </div>
                        </div>
                        <div align="center">
                            <div id="error_box"></div>
                            <br>

1.讀取表單數據

2.查詢數據庫

 (1)用戶名密碼對:

        跳轉到首頁

  (2)用戶名密碼不對:

   提示相應錯誤。

 

@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('pass')
        user = User.query.filter(User.username == username).first()
        # 判斷用戶名是否存在
        if user:
            if user.check_password(password):
                session['user'] = username
                session['userid']=user.id
                session.permanent = True
                return redirect(url_for('index'))
            else:
                return u'密碼錯誤'
        else:
            return u'帳號不存在'

登陸後更新導航:

 用上下文處理器app_context_processor定義函數

  1. 獲取session中保存的值
  2. 返回字典
    @app.context_processor
    def context():
        username=session.get('user')
        userid=session.get('userid')
        if username:
            return {'username': username,'userid':userid}
        else:
            return {}

    註銷功能

  3.    1.清除session

        2.跳轉

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

    問答平臺及詳情頁:

    {% extends 'base.html' %}
    {% block title %}發佈詳情{% endblock %}
    {% block head %}{% endblock %}
    {% block body %}
        <div class="container">
            <div class="row clearfix">
                <div class="col-md-3 column">
                </div>
                <div class="col-md-6 column">
                    <h3 align="center">{{ quest.title }}</h3>
                    <div align="center" style="font-weight: 900 ">
                        {#                    <span style="color: red">做者:{{ quest.author.username }}&nbsp;時間:{{ quest.creat_time }}</span>#}
                        <span class="badge">做者:{{ quest.author.nickname }}&nbsp;&nbsp;發佈時間:{{ quest.create_time }}</span>
                    </div>
                    <div class="panel panel-default">
                        <div class="panel-body" style="font-size:large">
                            &nbsp;&nbsp; &nbsp;{{ quest.detail }}
                        </div>
                    </div>
                    <hr>
                    <h4>評論區</h4>
                    {% for foo in comments %}
                        <div class="list-group">
                            <a href="" class="list-group-item">{{ foo.author.nickname }}&nbsp;<span
                                    class="badge">發佈時間:{{ foo.create_time }}</span></a>
                            <div class="list-group-item">
                                <p class="list-group-item-text">
                                    &nbsp;&nbsp;{{ foo.detail }}
                                </p>
                            </div>
    
                        </div>
                    {% endfor %}
                    <h3>
                        發佈評論({{ comments|length }})
                    </h3>
                    <form action="{{ url_for('comment') }}" method="post">
                        <div class="form-group">
                            <textarea type="text" class="form-control"
                                      id="detail" name="detail"
                                      cols="50" rows="5"/></textarea>
                        </div>
    
    
                        <button type="submit" class="btn btn-default">發佈</button>
                    </form>
                </div>
            </div>
            <div class="col-md-3 column">
            </div>
        </div>
        </div>
    
    
    {% endblock %}
    {% extends 'user.html' %}
    {% block user %}
     <hr>
                    <h3 align="center">
                        <small>所有問答</small>
                    </h3>
                    <ul class="list-unstyled">
                        {% for foo in questions %}
                            <li class="list-group-item">
                                <span class="glyphicon glyphicon-user"></span><a>{{ foo.author.username }}</a>
                                <p><a href="{{ url_for('detail',question_id=foo.id)}}">標題:{{ foo.title }}</a></p>
                                <span class="badge pull-right">{{ foo.create_time }}</span>
                                <p>問答內容:{{ foo.detail }}</p>
                                <br>
                            </li>
                        {% endfor %}
                    </ul>
    
    {% endblock %}
  4. 我的中心:我的中心父模板 + 所有評論 + 所有問答 + 我的信息

    {% extends 'user.html' %}
    {% block user %}
    
                    <hr>
                    <h3 align="center">
                        <small>我的信息</small>
                    </h3>
                    <ul class="list-group">
                        <li class="list-group-item" style="background-color: antiquewhite"><span class="glyphicon glyphicon-user"></span>用戶:{{ username }}</li>
                        <li class="list-group-item" style="background-color: wheat">暱稱:{{ nickname }}</li>
                        <li class="list-group-item" style="background-color: aquamarine">文章篇數:{{ questions|length }}</li>
                    </ul>
    
    {% endblock %}
    {% extends 'base.html' %}
    {% block title %}我的中心{% endblock %}
    {% block head %}{% endblock %}
    {% block body %}
    <div class="container">
        <div class="row clearfix">
            <div class="col-md-1 column">
            </div>
            <div class="col-md-10 column">
                <div class="tabbable" id="tabs-795847">
                    <ul class="nav nav-tabs">
                        <li  role="presentation">
                             <a href="{{ url_for('usercenter',user_id = username_id,tag='2') }}">所有問答</a>
                        </li>
                        <li  role="presentation">
                             <a href="{{ url_for('usercenter',user_id = username_id,tag='3') }}">所有評論</a>
                        </li>
                        <li role="presentation">
                             <a href="{{ url_for('usercenter',user_id = username_id,tag='1')}}" >我的中心</a>
                        </li>
                    </ul>
                {% block user %}{% endblock %}
                </div>
            </div>
            <div class="col-md-1 column">
            </div>
        </div>
    </div>
    
    
    {% endblock %}

     

  5. 密碼保護:更新User對象,設置對內的_password,  編寫對外的password

    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)   #內部使用
    @property
        def password(selfs): #外部使用,取值
            return self._password
    
        @password.setter
        def password(self,row_password): #外部使用,賦值
            self._password=generate_password_hash(row_password)

     

  6. 登錄驗證
    @app.route('/denglu/', methods=['GET', 'POST'])
    def denglu():
        if request.method == 'GET':
            return render_template('dl.html')
        else:
            username = request.form.get('username')
            password = request.form.get('password')
            user = User.query.filter(User.username == username).first()
            # 判斷用戶名是否存在
            if user:
                if user.check_password(password):
                    session['user'] = username
                    session['id'] = user.id
                    session.permanent = True
                    return redirect(url_for('shouye'))
                else:
                    return '密碼錯誤'
            else:
                return '此用戶不存在'

    密碼驗證

     def check_password(self,row_password):
            result=check_password_hash(self._password,row_password)
            return result

     

  7. 發佈評論
    @app.route('/comment/', methods=['POST'])
    @log
    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(author_id=auth_id,question_id=ques_id,detail=comment)
        db.session.add(comm)
        db.session.commit()
        return redirect(url_for('detail',question_id=ques_id))

     

  8. 我的中心
    @app.route('/usercenter/<user_id>/<tag>',methods=['GET','POST'])
    @loginFirst
    def usercenter(user_id,tag):
        user = User.query.filter(User.id == user_id).first()
        context = {
            'username_id': user.id,
            'username': user.username,
            'questions': user.question,
            'comments': user.comment,
            'nickname':user.nickname
        }
        if tag == '1':
            return render_template('usercenter.html', **context)
        elif tag == '2':
            return render_template('all_question.html', **context)
        else:
            return render_template('all_comment.html', **context)

     

  9. 搜索
    1. 獲取搜索關鍵字
      q = request.args.get('q’)
    2. 條件查詢
      qu = Question.query.filter(Question.title.contains(q)).order_by('-creat_time’)
    3. 加載查詢結果:
      return render_template('index.html', question=qu)
  10. @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('')
    
        return render_template('hh.html',questions=ques)

     

  11. Flask應用程序及數據庫鏈接 

    from flask import Flask
    app = Flask(__name__)  #構造函數的name參數,__name__變量是須要傳遞的值

    數據庫配置連接

    import os
    DEBUG = True
    SECRET_KEY = os.urandom(24)
    
    SQLALCHEMY_DATABASE_URI='mysql+pymysql://root:@localhost:3306/wlin?charset=utf8' 
    SQLALCHEMY_TRACK_MODIFICATTONS = False

     

  12. 運行中可能遇到的錯誤

    程序沒有指定Python運行

      解決方式:進入設置——項目——project interpreter 選擇運行環境

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息