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 #数据库名称 ...
随机推荐
- spring boot 2.x拦截器导致静态资源404终极解决办法
首先添加application文件static路径,我的是yml文件 spring: mvc: static-path-pattern: /static/**然后注册拦截器类如下方法; @Overri ...
- C# 处理json字符串中image数据(byte)Base64
static void Main(string[] args) { string factString = "中华人民共和国"; byte[] myByte; str ...
- HDU 3047 Zjnu Stadium(带权并查集,难想到)
M - Zjnu Stadium Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u Su ...
- docker 导出导入
容器导出 docker export -o myname.tar 容器id 容器导人 docker import myname.tar httpd:v1
- Java中的类与对象
一.类与对象的概念 1.类:类是一组相同属性.方法的对象的集合:对象是类的具体化. 2.对象具有类所有的特征,类拥有的,对象就拥有. 3.类与对象他们的关系是相对的. 类有什么特点 1) 类是对象的类 ...
- 网站jcms流程分析
本实例大致流程:基于jsp页面,通过servlet传递数据调用方法,利用service更改数据库.本文重点分析的是其中的两个小方法add()和delete(),来反映出反射机制的一个具体作用:减少Se ...
- 不可变字符串String与可变字符串StringBuilder、StringBuffer使用详解
String字符串 char类型只能表示一个字符,而String可以表示字符串,也就是一个字符序列.但String不是基本类型,而是一个定义好的类,是一个引用类型.在Java中,可以将字符串直接量赋给 ...
- 关于DP
关于DP 似乎摸到了门槛呢,学着学着Dijkstra突然有了感觉. 我们遍历的时候会遍历整张图的每个点每条边,然后与已知的对比大小,如果比现在方案好,就放入数组 那么,DP岂不是同样的思想? 在背包问 ...
- 谈谈对html5的了解
1.良好的移动性,以移动端设备为主. 2.响应式设计,以适应自动变化的屏幕尺寸. 3.支持离线缓存技术,webStorage本地缓存. 4.新增canvas,video,audio等新.标签元素.新增 ...
- 浅淡 RxJS WebSocket
const open$ = new Subject(); const ws = webSocket({ url: 'wss://echo.websocket.org', openObserver: o ...