目录结构

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

【python】使用flask制作小型页面的关键点总结的更多相关文章

  1. Flask学习之旅--用 Python + Flask 制作一个简单的验证码系统

    一.写在前面 现在无论大大小小的网站,基本上都会使用验证码,登录的时候要验证,下载的时候要验证,而使用的验证码也从那些简简单单的字符图形验证码“进化”成了需要进行图文识别的验证码.需要拖动滑块的滑动验 ...

  2. 使用python的Flask实现一个RESTful API服务器端[翻译]

    最近这些年,REST已经成为web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了. 本文将会使用python的Flask框架轻松实现一个RESTful的服务 ...

  3. 使用python的Flask实现一个RESTful API服务器端

    使用python的Flask实现一个RESTful API服务器端 最近这些年,REST已经成为web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了. 本文 ...

  4. python的Flask 介绍

    Flask 介绍 知识点 微框架.WSGI.模板引擎概念 使用 Flask 做 web 应用 模板的使用 根据 URL 返回特定网页 实验步骤 1. 什么是 Flask? Flask 是一个 web ...

  5. python之Flask实现登录功能

    网站少不了要和数据库打交道,归根到底都是一些增删改查操作,这里做一个简单的用户登录功能来学习一下Flask如何操作MySQL. 用到的一些知识点:Flask-SQLAlchemy.Flask-Logi ...

  6. 通过flask实现web页面简单的增删改查bootstrap美化版

    通过flask实现web页面简单的增删改查bootstrap美化版 项目目录结构 [root@node1 python]# tree -L 2 . ├── animate.css ├── fileut ...

  7. web基础,用html元素制作web页面

    用div,form制作登录页面,尽可能做得漂亮. 练习使用下拉列表选择框,无序列表,有序列表,定义列表. 观察常用网页的HTML元素,在实际的应用场景中,用已学的标签模仿制作. <!DOCTYP ...

  8. 【Python】Flask系列-URL和视图笔记

    1.学习目标 熟悉Flask相关知识. 熟悉web开发流程. 能独立开发Flask项目. 2.环境配置 Python虚拟环境安装 因为python的框架更新迭代太快了,有时候需要在电脑上存在一个框架的 ...

  9. 转:使用python的Flask实现一个RESTful API服务器端

    提示:可以学习一下flask框架中对于密码进行校验的部分.封装了太多操作. 最近这些年,REST已经成为web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了 ...

随机推荐

  1. OpenJudge-bailian 3454 秦腾与教学评估

    http://bailian.openjudge.cn/practice/3454?lang=en_US 题目 在秦腾进入北京大学学习的第一个学期,就不幸遇到了前所未有的教学评估.在教学评估期间,同学 ...

  2. 指路Reactive Programming

    指路Reactive Programming Mar 02, 2016 in Engineering 我在工作中采用Reactive Programming(RP)已经有一年了,对于这个“新鲜”的辞藻 ...

  3. Python中eval函数的作用

    eval eval函数就是实现list.dict.tuple与str之间的转化str函数把list,dict,tuple转为为字符串# 字符串转换成列表a = "[[1,2], [3,4], ...

  4. ORACLE创建表空间 新建用户 授权

    --建表空间create tablespace <用户> datafile 'D:\oradatadev\<用户>.dbf' size 200mautoextend on ne ...

  5. vue-cli 项目踩坑 npm install 时出错

    1.报错如下: 2.此时你执行npm run dev  / npm run build 会报错如下 npm ERR! code ELIFECYCLEnpm ERR! errno 1npm ERR! v ...

  6. Unity安装(Windows版)

    Unity下载助手 Unity下载助手是一个小型可执行程序(大小约为1 MB),它允许您选择要下载和安装的Unity Editor的那些组件. 如果你不知道要安装,保留默认选择,单击继续 ,然后按照安 ...

  7. 如何设置Maven代理

    1.公司的网络走的是代理,那么如何设置maven下载jar包时也走代理呢. 根据百度出来的两篇文章 设置了一下,但是还是报错. Plugin org.apache.maven.plugins:mave ...

  8. postman接口测试笔记

    1.GET 和POST 的区别: GET 使用URL 或Cookie 传参,而POST将数据放在Body 中. GET的URL 在长度上会有限制,而POST没有. POST比GET相对安全,因为在地址 ...

  9. DirectX11 With Windows SDK--25 法线贴图

    前言 在很早之前的纹理映射中,纹理存放的元素是像素的颜色,通过纹理坐标映射到目标像素以获取其颜色.但是我们的法向量依然只是定义在顶点上,对于三角形面内一点的法向量,也只是通过比较简单的插值法计算出相应 ...

  10. 实现Map接口(hash原理)

    闲来无事,就实现一个简单的map来练练手吧! HashMap的底层实现主要是基于数组和链表来实现的,HashMap中通过key的hashCode来计算hash值的,由这个hash值计算在数组中的位置, ...