一步一步製作自己的留言板
首選組織一下文件佈局:
application
app.py
models.py
static
css
img
js
templates
index.html
layout.html
show.html
manage.py
requirements.txt
一: 安裝開發所需要的組建
[root@localhost studyflask]# cat requirements.txt flask flask-Script flask-SQLAlchemy MySQL-python 進入virtualenv環境安裝所需組件 [root@localhost studyflask]# . bin/activate (studyflask)[root@localhost studyflask]# pip install -r requirements.txt
關於python flask環境安裝這個部分可以參考我的博文Flask實例教程一
二:編寫manage.py控制代碼的運行
# encoding=utf-8 from flask.ext.script import Manager from application.app import app manager = Manager(app) app.config['DEBUG'] = True if __name__ == '__main__': manager.run()
可以使用這個腳本來管理Flask程序的運行,關於這方面的內容可以參考我的Flask實例教程二
三:編寫models.py
#encoding=utf-8 from app import db from datetime import datetime class Message(db.Model): __tablename__ ="message" id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(200)) time = db.Column(db.DateTime,default=datetime.now()) content = db.Column(db.String(255)) email = db.Column(db.String(100)) title = db.Column(db.String(255)) def __init__(self,name,content,email,title): self.name = name self.content = content self.email = email self.title = title def __repr__(self): return "<User:%s>" %self.name if __name__=="__main__": db.create_all()
藉助SQLAlchemy來實現數據庫的ORM,這裏創建一個表。關於SQLAlchemy可以參考我的Flask實例教程六
四:編寫app.py
#encoding=utf-8 from flask import Flask from flask import render_template from flask import url_for from flask import redirect from flask import request,flash from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI']="mysql://root:@localhost:3306/message" db = SQLAlchemy(app) SECERT_KEY="a secret key" app.config.from_object(__name__) app.secret_key=app.config['SECERT_KEY'] from models import Message @app.route('/',methods=['POST','GET']) def index(): if request.method == 'POST': name = request.form['name'] email = request.form['email'] content = request.form['content'] title = request.form['title'] mess = Message(name=name,email=email,content=content,title=title) db.session.add(mess) db.session.commit() flash("Add Message Sucess!!") #return name+email+content+title return redirect(url_for("index")) else: mess = Message.query.all() return render_template("index.html",message=mess) @app.route('/show/<int:id>') def show(id): mess = Message.query.filter_by(id=id).first() if mess !=None: return render_template("show.html",message=mess) else: return redirect(url_for("index"))
index()主要是實現留言板內容的顯示和添加的,如果請求的方法是get方法則調用模板文件顯示留言內容,如果是POST方式則需要獲取表單內容添加至數據庫。這裏面的所有內容基本上都可以在我之前的博客中看到。
五:編寫模板文件
模板文件這個部分我使用了bootstrap技術來實現頁面的佈局和樣式
layout.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>留言板</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href={{ url_for('static',filename="css/bootstrap.min.css") }} rel="stylesheet" media="screen"> <script src={{ url_for('static',filename="js/jquery.js") }}></script> <script src={{ url_for('static',filename="js/bootstrap.min.js") }}></script> </head> <body> {% block body %} {% endblock %} </body> <html>
index.html
{% extends "layout.html" %} {% block body %} <div class="row"> <div class="span6 offset6"> {% for mess in get_flashed_messages() %} <div class="alert alert-info"> {{ mess }} </div> {% endfor %} </div> </div> <script language="javascript"> function checkinput() { var oName=document.getElementById('name'); if(oName.value == ""){ alert("姓名不能爲空"); return false; } var ocontent=document.getElementById('content'); if(ocontent.value == ""){ alert("內容不能爲空"); return false; } var otitle=document.getElementById('title'); if(otitle.value == ""){ alert("標題不能爲空"); return false; } var oemail=document.getElementById('email'); if(oemail.value == ""){ alert("郵箱不能爲空"); return false; } return true; } </script> <div class="container"> <div class="span8 offset2"> <h2>留言板</h2> <table class="table table-hover"> <tr> <th>姓名</th> <th>留言主題</th> <th>留言時間</th> <th>留言郵箱</th> <tr> {% for i in message %} <tr> <td>{{ i.name }}</td> <td><a href="/show/{{ i.id }}">{{ i.title}}</a></td> <td>{{ i.time }}</td> <td>{{ i.email }}</td> </tr> {% endfor %} </table> </div> </div> <div class="container"> <div class="span12"> <hr> </div> </div> <div class="container"> <div class="span6 offset3"> <form class="form-horizontal" role="form" action="{{ url_for("index") }}" method=post onsubmit="return checkinput();"> <div class="form-group"> <label class="col-sm-4 control-label">姓名</label> <div class="col-sm-8"> <input type=text name="name" id="name" /> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">留言主題</label> <div class="col-sm-8"> <input type=text name="title" id="title" /> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">留言內容</label> <div class="col-sm-8"> <input type=text name="content" id="content" /> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label">留言信箱</label> <div class="col-sm-8"> <input type=text name="email" id="email" /> </div> </div> <div class="span6 offset3"> <input type=submit value="提交" name="sub"/> </div> </div> </form> </div> </div> {% endblock %}
show.html
{% extends "layout.html" %} {% block body %} <h3>{{ message.title }}<h3> <p class="less">{{ message.content }}</p> {% endblock %}
六:留言板展示
七:問題和總結
本博文中涉及的技術在我前面的博文中基本全都有涉及,這裏只不過是組合起來做了一個小例子。如果感興趣可以下載源碼回去慢慢研究學習,代碼寫的不夠規範,而且js還沒驗證郵箱格式,已經輸入中文對中文的顯示可能有點問題。
源碼見附件: