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. 【转】Linux下RabbitMQ服务器搭建(单实例)

    阅读目录 系统环境 安装步骤 注意事项 参考资料 回到顶部 系统环境 操作系统:CentOS6.9 erlang:OTP 19.3 rabbitmq:rabbitmq-server 3.6.12 回到 ...

  2. [LuoguP1363]幻想迷宫

    [LuoguP1363]幻想迷宫(Link) 现在有一个迷宫,从迷宫边界的任意一点可以走到对面,即:若都是路面,则可以从\((1, i)\)走到\((N, i)\).其余情况依旧.问是否可以从指定的起 ...

  3. JNI由浅入深_3_Hello World

    1.需要准备的工具,eclipse,cdt(c++)插件,cygwin(unix)和 android ndk. 在cygwin的etc目录下将ndk的路径引入到profile文件中,可以在cygwin ...

  4. 允许跨域资源共享(CORS)携带 Cookie (转载)

    如何让CORS携带Cookie CORS 是一个 W3C 标准,全称是“跨域资源共享”(Cross-origin resource sharing).默认浏览器为了安全,遵循“同源策略”,不允许 Aj ...

  5. Asp.net MVC使用FormsAuthentication,MVC和WEB API可以共享身份认证 (转载)

    在实际的项目应用中,很多时候都需要保证数据的安全和可靠,如何来保证数据的安全呢?做法有很多,最常见的就是进行身份验证.验证通过,根据验证过的身份给与对应访问权限.同在Web Api中如何实现身份认证呢 ...

  6. 用HTML编写漫威页面

    <!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8" ...

  7. java核心技术-多线程之线程内存模型

    对于每一种编程语言,理解它的内存模型是理所当然的重要.下面我们从jvm的内存模型来体会下java(不限java语言,严格来讲是JVM内存模型,所有JVM体系的变成语言均适用)的内存模型. 堆: 就是我 ...

  8. Python编程Message: CGI script is not executable ('/cgi-bin/xxxxx.py')

    Message: CGI script is not executable ('/cgi-bin/xxxxx.py'). 今天在练习python服务器端编程时遇到了这个错误,查阅一番最终解决 系统为l ...

  9. 移动端H5页面解决软件键盘把页面顶起

    在input失去焦点的时候加上强制页面归位 window.scroll(0,0); 上代码 <input data-component="SearchInput" type= ...

  10. react脚手架环境搭建流程

    1.安装与配置node.js:1.1软件下载地址:https://nodejs.org/en/,推荐下载.msi文件,其中npm已经集成在了node.js中.1.2 双击下载的.msi文件进行安装,安 ...