py文件:css
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 app = Flask(__name__) # 建立Flask對象 app.config.from_object(config) # 關聯config.py文件進來 db = SQLAlchemy(app) # 創建和數據庫的關係映射 class User(db.Model): # 建立類User __tablename__ = 'user' # 類對應的表名user id = db.Column(db.Integer, primary_key=True, autoincrement=True) # autoincrement自增加 username = db.Column(db.String(20), nullable=False) # nullable是否爲空 password = db.Column(db.String(20), nullable=False) nickname = db.Column(db.String(20), nullable=True) class Fabu(db.Model): __tablename__ = 'fabu' 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')) # 數據類型是db.Integer,db.ForeignKey參數指定外鍵是哪一個表中哪一個id author = db.relationship('User', backref=db.backref('fabu')) # 創建關聯,其author屬性將返回與問答相關聯的用戶實例,至關於數據庫中的錶鏈接 # 第一個參數代表這個關係的另外一端是哪一個類,第二個參數backref,將向User類中添加一個fabu屬性,從而定義反向關係,這一屬性可訪問Fabu類,獲取的是模型對象 db.create_all() # 測試是否鏈接成功 ''' # 插入功能 user = User(username='15',password='12') db.session.add(user) db.session.commit() # 查詢功能 user=User.query.filter(User.username=="15").first() print(user.username,user.password) # 修改功能 user=User.query.filter(User.username=="15").first() user.password='888' db.session.commit() # 刪除功能 user=User.query.filter(User.username=="15").first() db.session.delete(user) db.session.commit() ''' # session會話鏈接 # filter()過濾器 # route制定路徑和函數之間的關係 # def定義一個變量 @app.route('/') # 跳轉首頁。 def daohang(): context = { 'fabus': Fabu.query.order_by('-creat_time').all() # order_by('-creat_time')按時間降序排列,Fabu.query.all()查出了Fabu類的全部元組 } return render_template('daohang.html', **context) # **context將該封裝傳遞到daohang.html中調用,而上下文處理器是能夠在任何html中調用。 @app.route('/lin/') # 跳轉測試。 def lin(): return 'lin' # 跳轉登錄。 @app.route('/denglu/', methods=['GET', 'POST']) # methods定義它有兩種請求方式 def denglu(): if request.method == 'GET': return render_template('denglu.html') else: username = request.form.get('user') # post請求模式,安排對象接收數據 password = request.form.get('pass') user = User.query.filter(User.username == username).first() # 做查詢,並判斷 if user: # 判斷用戶名 if user.password == password: # 判斷密碼 session['user'] = username # 利用session添加傳回來的值username session.permanent = True # 設置session過時的時間 return redirect(url_for('daohang')) else: return u'用戶密碼錯誤' else: return u'用戶不存在,請先註冊' @app.context_processor # 上下文處理器,定義變量而後在全部模板中均可以調用,相似idea中的model def mycontext(): user = session.get('user') if user: return {'username': user} # 包裝到username,在全部html模板中可調用 else: return {} # 返回空字典,由於返回結果必須是dict # 跳轉註銷。 @app.route('/logout') def logout(): session.clear() # 註銷時刪除全部session return redirect(url_for('daohang')) # 跳轉註冊。 @app.route('/zhuce/', methods=['GET', 'POST']) # methods定義它有兩種請求方式,由於它在表單的請求是post,相似咱們在idea中的sava請求模式 def zhuce(): if request.method == 'GET': return render_template('zhuce.html') else: username = request.form.get('user') # post請求模式,安排對象接收數據 password = request.form.get('pass') nickname = request.form.get('nickname') user = User.query.filter(User.username == username).first() # 做查詢,並判斷 if user: return u'該用戶已存在' else: user = User(username=username, password=password, nickname=nickname) # 將對象接收的數據賦到User類中,即存到數據庫 db.session.add(user) # 執行操做 db.session.commit() return redirect(url_for('denglu')) # redirect重定向 # 定義decorator能夠加強函數功能,裝飾器自己是函數,入參是函數,返回值也是函數 def loginFirst(fabu): @wraps(fabu) # 加上wraps,它能夠保留原有函數的__name__,docstring def wrapper(*args, **kwargs): # 定義wrapper函數將其返回,用*args, **kwargs把原函數的參數進行傳遞 if session.get('user'): # 只有通過登錄,session才能記住並get到值 return fabu(*args, **kwargs) else: return redirect(url_for('denglu')) return wrapper # 跳轉圖片。 @app.route('/tupian/') def tupian(): return render_template('tupian.html') # 跳轉發布。 @app.route('/fabu/', methods=['GET', 'POST']) # methods定義它有兩種請求方式 @loginFirst # 將decorator定義的加強函數放在待加強函數定義的上面 def fabu(): if request.method == 'GET': return render_template('fabu.html') else: title = request.form.get('title') # post請求模式,安排對象接收數據 detail = request.form.get('detail') author_id = User.query.filter(User.username == session.get('user')).first().id # 將session get到的user進行查詢並取出id放到外鍵author_id中 fabu = Fabu(title=title, detail=detail, author_id=author_id) # 將對象接收的數據賦到Fabu類中,即存到數據庫 db.session.add(fabu) # 執行操做 db.session.commit() # 提交到數據庫 return redirect(url_for('daohang')) # redirect重定向 # 跳轉發布詳情 @app.route('/fabuview/<fabu_id>') # 和idea的update同樣,將id帶到控制器 def fabuview(fabu_id): fa = Fabu.query.filter(Fabu.id == fabu_id).first() # 根據id查詢出整條元組記錄,丟進fa return render_template('fabuview.html', fa=fa) # 把值fa丟進鍵fa,在fabuview.html頁面調用 # 方法二: # fabu={ # 'fa':Fabu.query.filter(Fabu.id == fabu_id).first() # } # return render_template('fabuview.html',**fabu) if __name__ == '__main__': app.run(debug=True)
daohang.html:html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> 首頁 {% block denglutitle %}{% endblock %} {% block zhucetitle %}{% endblock %} {% block tupiantitle %}{% endblock %} {% block fabutitle %}{% endblock %} {% block fabu_viewtitle %}{% endblock %} </title> <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="{{ url_for('static',filename='css/daohang.css') }}"> <link rel="stylesheet" href="{{ url_for('static',filename='css/wenben.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> <script src="{{ url_for('static',filename='js/daohang.js') }}"></script> {% block dengluhead %}{% endblock %} {% block zhucehead %}{% endblock %} {% block tupianhead %}{% endblock %} {% block fabuhead %}{% endblock %} {% block fabu_viewhead %}{% endblock %} </head> <body id="mybody"> <nav class="navbar navbar-inverse" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="{{ url_for('daohang') }}">首頁</a> </div> <div> <ul class="nav navbar-nav navbar-right"> {% if username %} <li><a href="#" onclick="">{{ username }}</a></li> <li><a href="{{ url_for('logout') }}" onclick=""><span class="glyphicon glyphicon-log-out"></span> 註銷</a></li> {% else %} <li><a href="{{ url_for('denglu') }}" onclick=""><span class="glyphicon glyphicon-log-in"></span> 登錄</a> </li> <li><a href="{{ url_for('zhuce') }}" onclick=""><span class="glyphicon glyphicon-user"></span> 註冊</a></li> {% endif %} </ul> </div> <div style="float: right"> <img id="myonoff" onclick="mySwitch()" src="http://www.runoob.com/images/pic_bulbon.gif" style="width:40px"> </div> <div> <ul class="nav navbar-nav"> <li><a href="{{ url_for('tupian') }}" onclick="">圖片區</a></li> </ul> <ul class="nav navbar-nav"> <li><a href="{{ url_for('fabu') }}" onclick="">發佈</a></li> </ul> <ul class="nav navbar-nav"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> 設置 <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a href="#">收藏</a></li> <li><a href="#">分享</a></li> <li><a href="#">搜索</a></li> <li class="divider"></li> <li><a href="#">點贊</a></li> </ul> </li> <li><a href="#">||</a></li> </ul> </div> <div> <input type="text" name="sousuo" id="sousuo" placeholder="請輸入內容"> <input type="button" value="搜索" class="btn btn-success" onclick=""> </div> </div> </nav> <nav class="navbar navbar-inverse navbar-fixed-bottom" role="navigation"> <ul class="nav navbar-nav"> <li><img src="http://www.gzcc.cn/2016/images/footer1-logo.png"></li> <li style="color: bisque;">版權全部@lin</li> </ul> </nav> <div id="navtop"></div> <p class="text-center"> <script>document.write(Date())</script> </p> {% block daohangbody %} <div class="container"> <div class="row clearfix"> <div class="col-md-2 column s1"> <h3> 標題3(如下是無序標籤) </h3> <ul> <li> Lorem ipsum dolor sit amet </li> <li> Consectetur adipiscing elit </li> <li> Integer molestie lorem at massa </li> <li> Facilisis in pretium nisl aliquet </li> <li> Nulla volutpat aliquam velit </li> <li> Faucibus porta lacus fringilla vel </li> <li> Aenean sit amet erat nunc </li> <li> Eget porttitor lorem </li> </ul> </div> <div class="col-md-6 column s1"> <h3 class="text-center">發佈</h3> <ul class="list-unstyled"> {% for foo in fabus %} <li class="list-group-item-success"> <a href="#">{{ foo.author.username }}</a> <h4 class="text-center"><a href="{{ url_for('fabuview',fabu_id=foo.id) }}">{{ foo.title }}</a></h4> <span class="badge pull-right">{{ foo.creat_time }}</span> <br> <p>{{ foo.detail }}</p> </li> {% endfor %} </ul> </div> <div class="col-md-4 column"> <ul class="nav nav-pills"> <li class="active"> <a href="#"> <span class="badge pull-right">42</span> Home</a> </li> <li> <a href="#"> <span class="badge pull-right">16</span> More</a> </li> </ul> </div> </div> </div> {% endblock %} </body> </html>
fabuview.html:前端
{% extends 'daohang.html' %} {% block fabu_viewtitle %}發佈內容{% endblock %} {% block fabu_viewhead %} <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> {% endblock %} {% block daohangbody %} <div class="col-md-2 column "></div> <div class="col-md-8 column "> <ul class="list-unstyled"> <li> <h2 href="#" class="text-center">{{ fa.title }}</h2> <br> <p class="text-center"> <a href="#"> <small>{{ fa.author.username }}</small> </a>    <span class="pull-center"><small>{{ fa.creat_time }}</small></span> </p> <p>{{ fa.detail }}</p> <form> <div class="form-group"> <textarea name="comment" class="form-control" rows="5" id="comment" placeholder="請輸入評論"></textarea> </div> <button type="submit" class="btn btn-default">發送</button> </form> </li> </ul> </div> <div class="col-md-2 column "></div> {% endblock %}