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'))

静态文件伺候

静态文件指应用使用的JavascriptCSS代码及图片资源文件。

  • 在项目根目录下创建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 路由相关操作的更多相关文章

  1. python三大框架之一flask中cookie和session的相关操作

    状态保持 Cookie cookie 是指某些网站为了 辨别  用户身份,进行会话跟踪而储存在用户本地的数据(通常会经过加密),复数形式是 coolies. cookie是由服务器端生成,发送给客户端 ...

  2. 一、Flask路由介绍

    Flask介绍(轻量级的框架,非常快速的就能把程序搭建起来) Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是So ...

  3. Vue-CLI 项目中相关操作

    0830总结 Vue-CLI 项目中相关操作 一.前台路由的基本工作流程 目录结构 |vue-proj | |src | | |components | | | |Nav.vue | | |views ...

  4. 从零自学Hadoop(20):HBase数据模型相关操作上

    阅读目录 序 介绍 命名空间 表 系列索引 本文版权归mephisto和博客园共有,欢迎转载,但须保留此段声明,并给出原文链接,谢谢合作. 文章是哥(mephisto)写的,SourceLink 序 ...

  5. 从零自学Hadoop(21):HBase数据模型相关操作下

    阅读目录 序 变量 数据模型操作 系列索引 本文版权归mephisto和博客园共有,欢迎转载,但须保留此段声明,并给出原文链接,谢谢合作. 文章是哥(mephisto)写的,SourceLink 序 ...

  6. 理解CSV文件以及ABAP中的相关操作

    在很多ABAP开发中,我们使用CSV文件,有时候,关于CSV文件本身的一些问题使人迷惑.它仅仅是一种被逗号分割的文本文档吗? 让我们先来看看接下来可能要处理的几个相关组件的词汇的语义. Separat ...

  7. Liunx下的有关于tomcat的相关操作 && Liunx 常用指令

    先记录以下liunx下的有关于tomcat的相关操作 查看tomcat进程: ps-ef|grep java (回车) 停止tomcat进程: kill -9 PID (进程号如77447) (回车) ...

  8. pip的相关操作

    >Python中的pip是什么?能够做些什么? pip是Python中的一个进行包管理的东西,能够下载包.安装包.卸载包......一些列操作 >怎么查看pip的相关信息 在控制台输入: ...

  9. python操作mysql数据库的相关操作实例

    python操作mysql数据库的相关操作实例 # -*- coding: utf-8 -*- #python operate mysql database import MySQLdb #数据库名称 ...

随机推荐

  1. programming-languages学习笔记--第5部分

    programming-languages学习笔记–第5部分 */--> pre.src {background-color: #292b2e; color: #b2b2b2;} program ...

  2. SpringMVC转发页面405错误

    需要在该方法前加上:@ResponseBody注解 加上这个注解后可能在转发页面的时候出现问题,则需要在方法的参数中增加HttpServletRequest 和HttpServletResponse参 ...

  3. oracle同义词语句备份

    --创建同义词create synonym T_SYSTEM_USERDEPARTMENT for xtzl.T_SYSTEM_USERDEPARTMENT;--查询同义词SELECT * FROM ...

  4. UML架构设计师必备神器

    UML-架构设计师必备神器 做过Java开发的一定都听过UML,也都能感觉到它的重要性.由其是在网上搜索一些高级技术介绍,写的好的.阅读量高的.让初.中级程序员容易看懂的.思路清晰的文章一定有UML类 ...

  5. eclipse 打开一个新工程的基本设置

    1.代码自动提示 Window -> Preferences -> Java -> Editor -> Content Assist -> Auto Activation ...

  6. 同步工具类-----循环栅栏:CyclicBarrier

    import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; impor ...

  7. Navicat 12 连接 Mysql8.0 使用日志

    目前最新的Mysql8.0 + Navicat12,使用中常有一些棘手问题 解决了的都会贴出来,受益于小伙伴们 我们的目标是发现问题,解决问题,欢迎大家贴出自己使用时遇到的问题,集思广益 好了,上干货 ...

  8. 将select的默认小三角替换成别的图片,且实现点击图片出现下拉框选择option

    最近做项目,要求修改select下拉框的默认三角样式,因为它在不同浏览器的样式不同且有点丑,找找网上也没什么详细修改方法,我就总结一下自己的吧. 目标是做成下图效果: 图一:将默认小三角换成红圈的三角 ...

  9. 第五章 C程序结构

    一.数值类型 1.实数常量的表示:3.5(双精度),3.5f(单精度),3.5L(长双精度) 2.整数常量:char字符常量(‘a’,‘b’,‘0’)当做一个整型常量参加运算 3.数字字符与英文字母字 ...

  10. Redis高可用详解:持久化技术及方案选择 (推荐)--转载自编程迷思博客www.cnblogs.com/kismetv/p/8654978.html

    一.Redis高可用概述 在介绍Redis高可用之前,先说明一下在Redis的语境中高可用的含义. 我们知道,在web服务器中,高可用是指服务器可以正常访问的时间,衡量的标准是在多长时间内可以提供正常 ...