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. Hadoop学习之路(二十五)MapReduce的API使用(二)

    学生成绩---增强版 数据信息 computer,huangxiaoming,85,86,41,75,93,42,85 computer,xuzheng,54,52,86,91,42 computer ...

  2. C/C++——new/delete和malloc/free的区别

    new/delete和malloc/free的区别 扩容操作: 对于malloc是有一个realloc函数对应用于扩容的: 对于new,只能再new一个,for循环赋值过去,把原来的delete掉: ...

  3. robotframwork的WEB功能测试(一)—切换window窗口

    selenium2library提供的切换到新窗口的关键字,只有select window,而且也只能根据title.name.url去定位.如下图所示,明显在实际使用中是不够的. 所以这里总结了一下 ...

  4. php7.0编译安装

    1.解压安装  tar zxvf php-7.0.2.tar.gz  cd php-7.0.2 2.安装依赖库: yum -y install libjpeg libjpeg-devel libpng ...

  5. python中matplotlib总结

    该总结只是为了记录自己学习过程中容易遗忘的问题,权当一个记事本使用. 1:散点图 plt.scatter()函数的原型 scatter(x, y, s=s, c=c, marker=marker, c ...

  6. PAT——1035. 插入与归并

    根据维基百科的定义: 插入排序是迭代算法,逐一获得输入数据,逐步产生有序的输出序列.每步迭代中,算法从输入序列中取出一元素,将之插入有序序列中正确的位置.如此迭代直到全部元素有序. 归并排序进行如下迭 ...

  7. HDU 3047 Zjnu Stadium(带权并查集,难想到)

    M - Zjnu Stadium Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Su ...

  8. cocos2d-x开发: 如何从项目中分离出接口范例

    cocos2d-x开发,包括核心模块接口开发和脚本部分的业务逻辑实现.从上层应用需求开始说,脚本在做业务逻辑实现的时候, 很多时候都需要依赖底层的接口功能,但是不是所有的人都可以游刃有余的去明白该怎么 ...

  9. node.js环境下写的vue项目

    github地址:https://github.com/anxizhihai/JournalismProject.git

  10. 实际SQL案例解决方法整理_LEAD函数相关

    表结构及数据如下: 需求: 将记录按照时间顺序排列,每三条记录为一组,若第二条记录与第一条记录相差5分钟,则删除该记录,若第三条与第二条记录相差5分钟,则删除该记录, 第二组同理,遍历全表,按要求删除 ...