【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的形式了 ...
随机推荐
- Python 目录指引
1.0 Python 基础整合 1.1 变量 1.2 数据类型 1.3 基础语法 1.4 文件操作 1.5 函数 1.6 生成器 1.7 迭代器 1.8 装饰器 1.9 字符集 2.0 Python ...
- 第四十五篇--将文件写入SD卡
RAM: 运行内存 ROM: 外部存储,手机内部存储 SD卡:外部存储,SD卡存储. 在存储文件时千万不要忘记向清单文件中添加相应权限,并且android6.0以后还要添加运行时权限 还有一个权限有所 ...
- (二叉树 递归) leetcode 889. Construct Binary Tree from Preorder and Postorder Traversal
Return any binary tree that matches the given preorder and postorder traversals. Values in the trave ...
- I/O模型系列之五:IO多路复用 select、poll、epoll
IO多路复用之select.poll.epoll IO多路复用:通过一种机制,一个进程可以监视多个描述符,一旦某个描述符就绪(一般是读就绪或者写就绪),能够通知程序进行相应的读写操作. 应用:适用于针 ...
- python之路(7)装饰器
前言 装饰器:为函数添加附属功能,本质为函数 原则:不修改被修饰函数的源代码 不修改被修饰函数的调用方式 装饰器=高阶函数+函数嵌套+闭包 使用场景演示 定义下面函数 def cal(l): res ...
- day22 栈 , 队列 , 约束和反射
#!/usr/bin/env python# -*- coding:utf-8 -*- # 1.请使用面向对象实现栈(后进先出)"""class Account: def ...
- JGUI源码:响应式布局简单实现(13)
首先自我检讨下,一直没有认真研究过响应式布局,有个大致概念响应式就是屏幕缩小了就自动换行或者隐藏显示,就先按自己的理解来闭门造车思考实现过程吧. 1.首先把显示区域分成12等分,bootstrap是这 ...
- PHP安装文件的审计
初始化安装 一般php程序都有一个初始安装的问题,如果使用了一些cms安装后且没有删除安装文件的话,就会导致二次安装等问题. 具体但不限于以下几种情况: 无验证功能,任意重装覆盖 $_GET['ste ...
- Thinkphp生成的验证码不显示——解决方法
在调用验证码之前加上 ob_clean(); 不显示验证码的代码: public function verify(){ $verify = new \Think\Verify(); $verify-& ...
- 环境判断:区别h5打开还是weixin打开?
var source_platform = '' , pf_source = 2; //系统平台 //区别是否是 微信浏览器 , source_platform 系统平台 2018.12.6新增 va ...