app.py web代碼 store.db 存儲信息的輕量數據庫,用的sqlite3 schema.sql 數據庫的初始化建表語句 settings.cfg 配置信息 static/style.css html中每一個標籤相關的格式信息,好比,字體顏色,字體大小,背景顏色,佔用寬度高度等 templates/layout.html 目錄名必須是templates。顯示的web頁面,使用jinja2渲染引擎,支持一些判斷循環的語句
一個style.css的例子css
body { font-family: sans-serif; background: #eee; } /* 設定body模塊的字體和背景顏色 */ h1, h2 { color: #377BA8; } /* 設定h1, h2的文字顏色 */ h2 { font-size: 2.5em; } /* 設定h2的字體大小爲默認大小的2.5倍 */ .left {float: left; width: 50%} /* 設定class爲left的部分靠左側,佔用50%的寬度 */ .right {float: right; width: 50%} /* 設定class爲right的部分靠右側,佔用50%的寬度 */ .comment {width:95%; overflow:auto; word-break:break-all;} /* 設定class爲comment的部分佔95%的寬度 */
{% xxx %}這樣的語句是jinja2的控制語句html
layout.htmlpython
<!doctype html> <title>Test</title> <link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}"> //加載css格式文件 <h1>Test</h1> {% for message in get_flashed_messages() %} <div class=flash>{{ message }}</div> {% endfor %} {% block body %}{% endblock %}
show.htmlweb
{% extends "layout.html" %} {% block body %} // 新塊開始,此處body對應style.css的body <div class="left"> // 一個新區域,採用style.css中left的格式 <form action="{{ url_for('test') }}" method=post class=test> //提交表單區域 <p>Text:</p> {% for entry in entries %} <textarea class=comment name=text rows=50 cols=120>{{ entry.text }}</textarea> // 實際填寫提交信息的地方 {% else %} <textarea class=comment name=text rows=50 cols=120></textarea> {% endfor %} <input type=submit value=Submit> // 表單提交按鈕 </form> </div> <div class="right"> <p>Detail:</p> {% for entry in entries %} <textarea class=comment rows=50 cols=120>{{ entry.detail_str }}</textarea> {% else %} <textarea class=comment rows=50 cols=120></textarea> {% endfor %} </div> <div class="bottom"> {% for entry in entries %} <h2>{{ entry.result }}</h2> {% endfor %} </div> {% endblock %}
注意數據庫的獲取,全局信息的處理。sql
"""Connects to the specific database.""" import os import sqlite3 import urllib import logging import logging.handlers import json from datetime import datetime from core.analysis import analysis_string_v3 from flask import Flask, request, g, redirect, url_for, render_template app = Flask(__name__) app.config.from_envvar('SETTINGS', silent=True) cur_path = os.path.dirname(os.path.realpath(__file__)) def init_logging(filename, logmod): log_size = 100000000 log_backupcount = 1 handler = logging.handlers.RotatingFileHandler(filename, maxBytes=log_size, backupCount=log_backupcount) formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s", datefmt='[%b %d %H:%M:%S]') handler.setFormatter(formatter) my_logger = logging.getLogger(logmod) my_logger.setLevel(logging.DEBUG) my_logger.addHandler(handler) return my_logger logger = init_logging(os.path.join(cur_path, "api.log"), "test") def connect_db(): """Connects to the specific database.""" logger.debug("[start] connect_db") rv = sqlite3.connect(app.config['DATABASE']) rv.row_factory = sqlite3.Row logger.debug("[end] connect_db") return rv def init_db(): logger.debug("[start] init_db") with app.app_context(): db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() logger.debug("[end] init_db") def get_db(): """Opens a new database connection if there is none yet for the current application context.""" logger.debug("[start] get_db") if not hasattr(g, 'db'): g.db = connect_db() logger.debug("[end] get_db") return g.db # init_db() @app.teardown_appcontext def close_db(error): """Closes the database again at the end of the request.""" logger.debug("[start] close_db") if hasattr(g, 'db'): g.db.close() logger.debug("[end] close_db") @app.route('/') def show(): logger.debug("[start] show") get_db() cur = g.db.execute('select text from queries order by id desc limit 0, 1') queries = [dict(query_time=row[0], text=row[1], result=row[2], detail_str=row[3]) for row in cur.fetchall()] logger.debug("[end] show") return render_template('show.html', entries=queries) @app.route('/test/', methods=['POST']) def test(): logger.debug("[start] test") s = request.form['text'] get_db() g.db.execute('insert into queries (text) values (?)', [request.form['text']]) g.db.commit() logger.debug("[end] test") return redirect(url_for('show'))
注意環境變量寫法數據庫
environment=SETTINGS=/home/test/settings.cfg