一步一步制作自己的留言板
首选组织一下文件布局:
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还没验证邮箱格式,已经输入中文对中文的显示可能有点问题。
源码见附件: