【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
【python】使用flask制作小型页面的关键点总结的更多相关文章
- Flask学习之旅--用 Python + Flask 制作一个简单的验证码系统
一.写在前面 现在无论大大小小的网站,基本上都会使用验证码,登录的时候要验证,下载的时候要验证,而使用的验证码也从那些简简单单的字符图形验证码“进化”成了需要进行图文识别的验证码.需要拖动滑块的滑动验 ...
- 使用python的Flask实现一个RESTful API服务器端[翻译]
最近这些年,REST已经成为web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了. 本文将会使用python的Flask框架轻松实现一个RESTful的服务 ...
- 使用python的Flask实现一个RESTful API服务器端
使用python的Flask实现一个RESTful API服务器端 最近这些年,REST已经成为web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了. 本文 ...
- python的Flask 介绍
Flask 介绍 知识点 微框架.WSGI.模板引擎概念 使用 Flask 做 web 应用 模板的使用 根据 URL 返回特定网页 实验步骤 1. 什么是 Flask? Flask 是一个 web ...
- python之Flask实现登录功能
网站少不了要和数据库打交道,归根到底都是一些增删改查操作,这里做一个简单的用户登录功能来学习一下Flask如何操作MySQL. 用到的一些知识点:Flask-SQLAlchemy.Flask-Logi ...
- 通过flask实现web页面简单的增删改查bootstrap美化版
通过flask实现web页面简单的增删改查bootstrap美化版 项目目录结构 [root@node1 python]# tree -L 2 . ├── animate.css ├── fileut ...
- web基础,用html元素制作web页面
用div,form制作登录页面,尽可能做得漂亮. 练习使用下拉列表选择框,无序列表,有序列表,定义列表. 观察常用网页的HTML元素,在实际的应用场景中,用已学的标签模仿制作. <!DOCTYP ...
- 【Python】Flask系列-URL和视图笔记
1.学习目标 熟悉Flask相关知识. 熟悉web开发流程. 能独立开发Flask项目. 2.环境配置 Python虚拟环境安装 因为python的框架更新迭代太快了,有时候需要在电脑上存在一个框架的 ...
- 转:使用python的Flask实现一个RESTful API服务器端
提示:可以学习一下flask框架中对于密码进行校验的部分.封装了太多操作. 最近这些年,REST已经成为web services和APIs的标准架构,很多APP的架构基本上是使用RESTful的形式了 ...
随机推荐
- OpenStack 命令行速查表
OpenStack 命令行速查表 updated: 2017-07-18 08:53 Contents 认证 (keystone) 镜像(glance) 计算 (nova) 实例的暂停.挂起.停止 ...
- 【集训队作业2018】取名字太难了 任意模数FFT
题目大意 求多项式 \(\prod_{i=1}^n(x+i)\) 的系数在模 \(p\) 意义下的分布,对 \(998244353\) 取模. \(p\) 为质数. \(n\leq {10}^{18} ...
- did not finish being created even after we waited 189 seconds or 61 attempts. And its status is downloading
did not finish being created even after we waited 189 seconds or 61 attempts. And its status is down ...
- 互相关(cross-correlation)及其在Python中的实现
互相关(cross-correlation)及其在Python中的实现 在这里我想探讨一下“互相关”中的一些概念.正如卷积有线性卷积(linear convolution)和循环卷积(circular ...
- beego学习2 控制器与路由
beego控制器 controller目录新建test.go文件 结构体集成beego.Controller 控制名需大写,否则为私有方法 package controllers import ( & ...
- .NET面试题系列(十八)常用关键字
序言 const和readonly关键字 private protected public internal的区别 out ref out适合用在需要retrun多个返回值的地方,而ref则用在需要 ...
- 非阻塞读和写:str_cli函数
void str_cli(FILE *fp, int sockfd) { int maxfdp1, val, stdineof; ssize_t n, nwritten; fd_set rset, w ...
- C# 01 Primitive Types and Expressions
Class Data or Attributes state of the application Methods or Functions have behavior Namespace is a ...
- 怎样解决canvas 插件 和html 页面中的事件冲突问题 ?
很简单 ,在html 执行事件所在的div中 设置 position:relative;
- Linux基础系统优化及常用命令
# Linux基础系统优化及常用命令 [TOC] ## Linux基础系统优化 Linux的网络功能相当强悍,一时之间我们无法了解所有的网络命令,在配置服务器基础环境时,先了解下网络参数设定命令. - ...