本文带你快速了解 Flask,只需 5 分钟即可完成一个基础页面的开发。废话不多说,现在开始!
安装
pip install Flask
你的第一个应用
# 此文件存储为 hello.pyfrom flask import Flaskapp = Flask(__name__)@app.route('/')def hello_world(): return '欢迎来到Flask的世界!'@app.route('/hello')def hello(): return '你好,这是经典的Hello World!'
运行和访问
# Linux 系统:export FLASK_APP=hello.pypython -m flask run * Running on http://127.0.0.1:5000/# Windows 系统:set FLASK_APP=hello.pypython -m flask run --host=0.0.0.0* Running on http://127.0.0.1:5000/
添加 URL 参数
将参数添加到 URL 中,如下代码所示,经常使用的参数类型如下:
- string 接受不带斜杠的任何文本(默认)
- int 接受整数
- float 接受浮点数
- any 匹配提供的项目之一
- uuid 接受 uuid 字符串
@app.route('/user/')def show_user(username): return '用户 %s' % username@app.route('/post/')def show_post(post_id): return '文章 %d' % post_id
HTTP 方法
Flask 可以处理很多 HTTP 方法,默认为 GET,示例如下:
还支持的方法有:POST、HEAD、PUT、DELETE、OPTION。
from flask import request@app.route('/login', methods=['GET', 'POST'])def login(): if request.method == 'POST': return '你访问的是POST方法' else: return '你访问的是非POST方法'
渲染模板
Flask 使用 Jinja2 模板引擎来处理 HTML 页面,使用 render_template 方法来渲染,示例如下:
from flask import render_template@app.route('/hello/')def hello(name): return render_template('hello.html', name=name)
这是一个示例模板:
Hello from Flask{% if name %}
Hello {{ name }}!
{% else %}
Hello, World!
{% endif %}
Flask 将在模板文件夹中查找模板。因此,如果您的应用程序是一个模块,则该文件夹位于该模块旁边,如果它是一个包,则它实际上位于您的包中:
模块示例:/application.py/templates /hello.html包示例:/application /__init__.py /templates /hello.html
POST请求参数
可使用 request.form['username'] 来获取请求参数,示例如下:
from flask import request@app.route('/login', methods=['POST', 'GET'])def login(): error = None if request.method == 'POST': if login(request.form['username'], request.form['password']): return "登录成功" else: error = '用户名或密码错误!'
文件上传
在 HTML 表单上设置 enctype = "multipart / form-data" 属性,Flask 代码如下:
from flask import request@app.route('/upload', methods=['GET', 'POST'])def upload_file(): if request.method == 'POST': f = request.files['file_name'] f.save('你的路径/file_name.xxx')
操作 Cookie
from flask import request@app.route('/')def index():# 读取 Cookie username = request.cookies.get('username')# 写入 Cookieresp = make_response(render_template(...)) resp.set_cookie('username', '张三') return resp
重定向
使用 redirect 函数即可重定向,示例如下:
from flask import abort, redirect, url_for@app.route('/')def index(): return redirect(url_for('login'))
本文是 Flask 的超简洁代码入门文章,如果你还有什么不清楚的地方,欢迎和我交流!