【python】使用flask制作小型页面的关键点总结
目录结构
app.py web代码
store.db 存储信息的轻量数据库,用的sqlite3
schema.sql 数据库的初始化建表语句
settings.cfg 配置信息
static/style.css html中每个标签相关的格式信息,比如,字体颜色,字体大小,背景颜色,占用宽度高度等
templates/layout.html 目录名必须是templates。显示的web页面,使用jinja2渲染引擎,支持一些判断循环的语句
css
一个style.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%的宽度 */
templates
{% xxx %}这样的语句是jinja2的控制语句
layout.html
<!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.html
{% 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 %}
app.py
注意数据库的获取,全局信息的处理。
"""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'))
启动控制supervisor
注意环境变量写法
environment=SETTINGS=/home/test/settings.cfg