Flask 路由相关操作
URL Route
- URL 后接
/作为目录级访问 - URL 后不接
/作为文件级访问
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/about')
def about():
return 'The about page'
| type:XXX | 说明 |
|---|---|
| string | (default) accepts any text without a slash |
| int | accepts positive integers |
| float | accepts positive floating point values |
| path | like string but also accepts slashes |
| uuid | accepts UUID strings |
from flask import Flask
app = Flask(__name__)
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
# show the subpath after /path/
return 'Subpath %s' % subpath
- 可以使用
methods来指定该路由使用的HTTP方法。
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return do_the_login()
else:
return show_the_login_form()
参考
URL Binding
使用
url_for()方法可以调用参数中的route方法,以便满足某种调用目的,如单元测试。
from flask import Flask
from flask import Flask, url_for
app = Flask(__name__)
with app.test_request_context():
print(url_for('index'))
print(url_for('login'))
print(url_for('login', next='/'))
print(url_for('profile', username='John Doe'))
静态文件伺候
静态文件指应用使用的
Javascript、CSS代码及图片资源文件。
- 在项目根目录下创建
static目录
url_for('static', filename='style.css')
模板文件伺候
Flask会自动寻找
templates目录,所以原则上请不要自定义这个目录的名字,且应该将其放在项目(或模块)的根路径下。
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
<body>
Hello, World!
from templates
</body>
参考
请求处理
Request
@app.route('/test', methods=['POST', 'GET'])
def test():
error = None
if request.method == 'POST':
t1 = request.form['1']
t2 = request.form['2']
elif request.method == 'GET':
# for URL `?key=value`
t3 = request.args.get('key', '')
else:
error = 'Method is not POST or GET!'
return render_template('test.html', error=error)
参考
文件上传
- 保存时重新指定文件名
from flask import request
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('/var/www/uploads/uploaded_file.txt')
...
- 保存时,使用上传的文件名
from flask import request
from werkzeug.utils import secure_filename
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('/var/www/uploads/' + secure_filename(f.filename))
...
参考
Cookies
- 读取
cookie
from flask import request
@app.route('/')
def index():
username = request.cookies.get('username')
# use cookies.get(key) instead of cookies[key] to not get a
# KeyError if the cookie is missing.
- 写入
cookie
from flask import make_response
@app.route('/')
def index():
resp = make_response(render_template(...))
resp.set_cookie('username', 'the username')
return resp
重定向
- 使用
url_for来找到URL地址 - 使用
redirect来重定向
from flask import abort, redirect, url_for
@app.route('/')
def index():
return redirect(url_for('login'))
- 使用
abort来返回错误码
@app.route('/login')
def login():
abort(401)
this_is_never_executed()
- 使用
@app.errorhandler()来处理错误码对应的请求
from flask import render_template
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
参考
Flask 路由相关操作的更多相关文章
- python三大框架之一flask中cookie和session的相关操作
状态保持 Cookie cookie 是指某些网站为了 辨别 用户身份,进行会话跟踪而储存在用户本地的数据(通常会经过加密),复数形式是 coolies. cookie是由服务器端生成,发送给客户端 ...
- 一、Flask路由介绍
Flask介绍(轻量级的框架,非常快速的就能把程序搭建起来) Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是So ...
- Vue-CLI 项目中相关操作
0830总结 Vue-CLI 项目中相关操作 一.前台路由的基本工作流程 目录结构 |vue-proj | |src | | |components | | | |Nav.vue | | |views ...
- 从零自学Hadoop(20):HBase数据模型相关操作上
阅读目录 序 介绍 命名空间 表 系列索引 本文版权归mephisto和博客园共有,欢迎转载,但须保留此段声明,并给出原文链接,谢谢合作. 文章是哥(mephisto)写的,SourceLink 序 ...
- 从零自学Hadoop(21):HBase数据模型相关操作下
阅读目录 序 变量 数据模型操作 系列索引 本文版权归mephisto和博客园共有,欢迎转载,但须保留此段声明,并给出原文链接,谢谢合作. 文章是哥(mephisto)写的,SourceLink 序 ...
- 理解CSV文件以及ABAP中的相关操作
在很多ABAP开发中,我们使用CSV文件,有时候,关于CSV文件本身的一些问题使人迷惑.它仅仅是一种被逗号分割的文本文档吗? 让我们先来看看接下来可能要处理的几个相关组件的词汇的语义. Separat ...
- Liunx下的有关于tomcat的相关操作 && Liunx 常用指令
先记录以下liunx下的有关于tomcat的相关操作 查看tomcat进程: ps-ef|grep java (回车) 停止tomcat进程: kill -9 PID (进程号如77447) (回车) ...
- pip的相关操作
>Python中的pip是什么?能够做些什么? pip是Python中的一个进行包管理的东西,能够下载包.安装包.卸载包......一些列操作 >怎么查看pip的相关信息 在控制台输入: ...
- python操作mysql数据库的相关操作实例
python操作mysql数据库的相关操作实例 # -*- coding: utf-8 -*- #python operate mysql database import MySQLdb #数据库名称 ...
随机推荐
- 2、Android-UI(自定义控件&ListView)
2.4.系统控件不够用创建自定义控件 控件的和布局的集成结构: 所有的控件都是间接或者直接集成View的 所有的布局都是直接或者间接继承自ViewGroup的 View是Android种最基本的一种U ...
- 20165302实验二java面向对象程序设计
20165302实验二java面向对象程序设计 实验结果 提交点1 1.实验要求: 参考 (http://www.cnblogs.com/rocedu/p/6371315.html#SECUNITTE ...
- 【luogu P3258 [JLOI2014]松鼠的新家】 题解
题目链接:https://www.luogu.org/problemnew/show/P3258 谁说树剖过不去会RE呢? 我今天就是要强行树剖了 树剖强艹 #include <cstdio&g ...
- DataFrame 加减乘除
headlist = ['a', 'b'] datalist = [[1, 2], [0,3], [3,2]] df = pd.DataFrame(data=datalist,columns=head ...
- 图形剖析,当给 ul 设置padding=0, margin=0后 li前面的小黑点消失的现象原理!
- 多线程系列之 java多线程的个人理解(二)
前言:上一篇多线程系列之 java多线程的个人理解(一) 讲到了线程.进程.多线程的基本概念,以及多线程在java中的基本实现方式,本篇主要接着上一篇继续讲述多线程在实际项目中的应用以及遇到的诸多问题 ...
- Linux 下让终端走代理的方法
转载: https://blog.fazero.me/2015/09/15/%E8%AE%A9%E7%BB%88%E7%AB%AF%E8%B5%B0%E4%BB%A3%E7%90%86%E7%9A%8 ...
- 使用DBNEWID Utility 修改oracle数据库的 db name 和 dbid
使用DBNEWID Utility 工具可以同时修改数据库名.DBID,也可以只修改其中一项 官方参考: https://docs.oracle.com/cd/E11882_01/server.112 ...
- activemq的高级特性:集群实战
高级特性实战需求 当消费端是多个集群,集群A又包含多个服务. 当每个集群都要接受相同的一批消息,而集群内的每个服务都去分摊消息. 解决办法一:级联 增加一个中转者.但是不是特别的优化,而且性能也不是特 ...
- 完美解决 Cydia 不能上网
国行手机比美版.港版.韩版手机新增了网络授权的功能,iOS 10 及以上系统版本,任何应用首次打开,如果有请求网络的行为,都会提示网络请求授权的对话框. 首次打开 Cydia 并没有提示网络请求授权的 ...