文章目录
轻量级框架,几行代码就可以起一个web服务,组件很少,可根据需求安装不同组件,
安装:pip
install
flask
参考资料http://www.cnblogs.com/GGGG-XXXX/articles/10182786.html
用werkzeug模块起项目
wsgi是个协议,
django:wsgiref模块:封装request和socket
flask: werkzeug模块:封装socket
from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple
@Request.application
def run(request): # 起web服务,request参数,请求进run
return Response('Wendy~~~')
if __name__ == '__main__': # 以下代码只在此脚本运行,别的脚本运行不了
run_simple('localhost', 5000, run)
# 通过run_simple在本地5000端口起一个web服务,监听run函数
flask起项目
from flask import Flask
# 实例化Flask,名字为__name__
app = Flask(__name__)
@app.route('/') # 实例化对象的route方法,通过装饰器建立路由和视图的关系,'/'路径执行index
def index():
return 'Laura~~~'
if __name__ == '__main__':
app.run() # 实例化对象执行run就可以起flask服务,默认端口5000
flask实现登录
from flask import Flask, render_template, request, redirect
app = Flask(__name__, template_folder='templates') # 可以修改默认模版文件夹名
@app.route('/login', methods=['GET', 'POST']) # 默认只允许get请求
def login():
if request.method == 'POST':
username = request.form.get('username')
pwd = request.form.get('pwd')
if username == 'Iris' and pwd == '123':
return redirect('/') # 重定向
return render_template('login.html') # 跳转页面
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run()
配置文件
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
print(app.config) # 查看配置文件信息
return '主页'
if __name__ == '__main__':
app.run()
运行结果
< Config
{
‘ENV’: ‘production’,
‘DEBUG’: False, \ # 是否开启debug模式
‘TESTING’: False, \ # 是否开启测试模式
‘PROPAGATE_EXCEPTIONS’: None,
‘PRESERVE_CONTEXT_ON_EXCEPTION’: None,
‘SECRET_KEY’: None,
‘PERMANENT_SESSION_LIFETIME’: datetime.timedelta(31),
‘USE_X_SENDFILE’: False,
‘SERVER_NAME’: None,
‘APPLICATION_ROOT’: ‘/’,
‘SESSION_COOKIE_NAME’: ‘session’,
‘SESSION_COOKIE_DOMAIN’: None,
‘SESSION_COOKIE_PATH’: None,
‘SESSION_COOKIE_HTTPONLY’: True,
‘SESSION_COOKIE_SECURE’: False,
‘SESSION_COOKIE_SAMESITE’: None,
‘SESSION_REFRESH_EACH_REQUEST’: True,
‘MAX_CONTENT_LENGTH’: None,
‘SEND_FILE_MAX_AGE_DEFAULT’: datetime.timedelta(0, 43200),
‘TRAP_BAD_REQUEST_ERRORS’: None,
‘TRAP_HTTP_EXCEPTIONS’: False,
‘EXPLAIN_TEMPLATE_LOADING’: False,
‘PREFERRED_URL_SCHEME’: ‘http’,
‘JSON_AS_ASCII’: True,
‘JSON_SORT_KEYS’: True,
‘JSONIFY_PRETTYPRINT_REGULAR’: False,
‘JSONIFY_MIMETYPE’: ‘application/json’,
‘TEMPLATES_AUTO_RELOAD’: None, ‘MAX_COOKIE_SIZE’: 4093
} >
更改默认配置
# 以类的形式区分配置信息
class DEVConfig(object):
DEBUG = True
class TestConfig(object): # 测试环境
TESTING = True
# print(dir(DEVConfig))
脚本文件
from flask import Flask
app = Flask(__name__)
app.config.from_object('settings.DEVConfig') # 如果把Debug改为True就加此句
app.config.from_object('settings.TestConfig') # TESTING该为True
@app.route('/')
def index():
print(app.config) # 查看配置文件信息
return '主页'
if __name__ == '__main__':
app.run()
运行结果
< Config
{‘ENV’: ‘production’, ‘DEBUG’: True, ‘TESTING’: True, …
原理
flask配置路由
路由参数
例
@app.route(’/user/’)
@app.route(’/post/int:post_id’)
@app.route(’/post/float:post_id’)
@app.route(’/post/path:path’)
路由默认支持的参数
DEFAULT_CONVERTERS = {
‘default’: UnicodeConverter,
‘string’: UnicodeConverter,
‘any’: AnyConverter,
‘path’: PathConverter,
‘int’: IntegerConverter,
‘float’: FloatConverter,
‘uuid’: UUIDConverter,
}
路由的命名和反向解析
上例中endpoint默认是函数名,也就是book
模版
脚本文件
from flask import Flask, redirect, url_for, render_template
app = Flask(__name__)
book_list = [
{
'id': 1, 'title': '世界简史'},
{
'id': 2, 'title': '人类简史'},
{
'id': 3, 'title': '未来简史'},
]
def my_func():
return '<h1>自定义函数返回的内容</h1>'
name = 'Iris'
@app.route('/book')
def book():
return render_template('book.html', **{
'book_list': book_list, 'name': name, 'my_func': my_func})
@app.route('/')
def index():
return redirect(url_for('book')) # 反向解析
if __name__ == '__main__':
app.run()
book.html文件
< !DOCTYPE
html >
< html
lang = "zh-CN" >
< head >
< meta
charset = "UTF-8" >
< title > Title < / title >
< / head >
< body >
< h1 > 这是图书管理页面 < / h1 >
< table >
< thead >
< tr >
< th > # </th>
< th > 书名 < / th >
< th > 操作 < / th >
< / tr >
< / thead >
< tbody >
{ %
for book in book_list %}
< tr >
< td > {
{book.id}} < / td >
< td > {
{book.title}} < / td >
< td > 删除 | 编辑 < / td >
< / tr >
{ % endfor %}
< / tbody >
< / table >
< hr >
{
{name}}
< hr >
{
{my_func() | safe}}
< / body >
< / html >
效果
请求和响应
每个request都会有个独立内存空间,使用的是协程
from flask import Flask
from flask import request
from flask import render_template
from flask import redirect
from flask import make_response
app = Flask(__name__)
@app.route('/login.html', methods=['GET', "POST"])
def login():
# 请求相关信息
# request.method
# request.args
# request.form
# request.values
# request.cookies
# request.headers
# request.path
# request.full_path
# request.script_root
# request.url
# request.base_url
# request.url_root
# request.host_url
# request.host
# request.files
# obj = request.files['the_file_name']
# obj.save('/var/www/uploads/' + secure_filename(f.filename))
# 响应相关信息
# return "字符串"
# return render_template('html模板路径',**{})
# return redirect('/index.html')
# response = make_response(render_template('index.html'))
# response是flask.wrappers.Response类型
# response.delete_cookie('key')
# response.set_cookie('key', 'value')
# response.headers['X-Something'] = 'A value'
# return response
return "内容"
if __name__ == '__main__':
app.run()
sessions
from flask import Flask, render_template, session, redirect, request
app = Flask(__name__)
app.config.from_object('settings.DEVConfig')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
name = request.form.get('username')
pwd = request.form.get("pwd")
if name == 'Iris' and pwd == '123':
session['userinfo'] = {
'name': name}
return redirect('/')
return render_template('login.html')
@app.route('/')
def index():
print(session.get('userinfo')) # 打印浏览器的session值
return render_template('index.html')
if __name__ == '__main__':
app.run()
settings文件
# 以类的形式区分配置信息
class DEVConfig(object):
DE