学习 Flask Web Development 2nd Edition
Posted 加载Python技能
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了学习 Flask Web Development 2nd Edition相关的知识,希望对你有一定的参考价值。
学习思想:学习可以看作一个 输入-方法-输出 过程,敲几遍是 Learn by Doing 的实践,是一种有效的方式目标:学习 Flask Web Development 2nd Edition环境:Python 3.6.4, Flask
前言 (Preface) 查看示例代码
$git clone https://github.com/miguelgrinberg/flasky.git
进入 flasky 目录
$cd flasky
进入某一个 commit 历史,比如 1a 这个 tag
$git checkout 1a
如果有什么改动,用 git checkout
进入下一个标签会失败,用 git reset
命令可以还原任何改变。所以如果在使用这个命令前,不想丢失某些改变,应该 git commit
做保存
$git reset --hard
如果想要更新(刷新)本地的仓库,和 github 上的仓库保持一致,可以用这几个命令
$git fetch --all
$git fetch --tags
$git reset --hard origin/master
git diff
命令可以显示出不同版本的不同之处,比如,查看 2a 和 2b 版本的不同可以用这个命令
$git diff 2a 2b
第一章 安装 (Installation)
如果你自己敲代码,不只是看克隆的代码,可以新建一个空文件夹
$mkdir flaksy
$cd flasky
创建一个 Python 3 的虚拟环境,我这里已经安装了 pipenv,就用这个命令
$pipenv shell
用 pipenv 安装 Python Packages,在虚拟环境下安装 Flask 包,用这个命令
pipenv install flask
确认 Flask 已经安装就绪,用 Python 解释器查看
$python
>>>import flask
>>>
第二章 应用的基本结构 (Basic Application Structure)
Flask 应用都要创建应用实例。应用实例是一个 Flask 类的对象,通常这样创建
from flask import Flask
app = Flask(__name__)
路由 (route) 可以关联 URL 和 Python 函数 (function). 最方便的定义路由的方式是用 app.route
装饰器,比如
@app.route('/')
def index():
return '<h1>Hello World!</h1>'
Flask 有一个传统的方式设置路由,用 app.add_url_rule()
方法,有三个基本参数,URL,endpoint 名字,view 函数,下面是一个等价写法
def index():
return '<h1>Hello World!</h1>'
app.add_url_rule('/', 'index', index)
index() 就是一个 view 函数路由可以包含变量部分,使用 app.route
装饰器,包含在 <> 内,比如
@app.route('/user/<name>')
def user(name):
return '<h1>Hello, {}!</h1>'.format(name)
Flask 支持的路由变量部分的类型包括 string, int, float 和 path, path 类型是可以包含 /
的特殊 string. 比如,变量部分是整数,/user/<int:id>
把应用实例、路由和 view 函数放到一起,就成为一个完整的 Flask 应用
# hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<h1>Hello World!</h1>'
用 flask run
可以运行开发的 Flask 应用。
$export FLASK_APP=hello.py
$flask run
用浏览器打开 http://127.0.0.1:5000/ 可以看到这个页面增加一个动态路由
# hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<h1>Hello World!</h1>'
@app.route('/user/<name>')
def user(name):
return '<h1>Hello, {}!</h1>'.format(name)
sever 继续运行,可以到 http://localhost:5000/user/sam
测试动态路由开发阶段,debug 模式很有用,因为 reloader 模块可以在代码修改后自动重启 server,debugger 模块可以让我们在浏览器查看 exception 信息。但是 debug 模式是默认关闭的,可以在调用 flask run
之前设置FLASK_DEBUG=1
$export FLASK_APP=hello.py
$export FLASK_DEBUG=1
$flask run
命令行选项
$flask --help
$flask run --help
$flask run --host 0.0.0.0
request-response 循环
from flask import request
@app.route('/')
def index():
user_agent = request.headers.get('User-Agent')
return '<p>Your browser is {}</p>'.format(user_agent)
Flask 有两种环境 (conntexts): application context 和 request context
Variable name | Context | Description |
---|---|---|
current_app | Application context | The application instance for the active application. |
g | Application context | An object that the application can use for temporary storage during the handling of a request. This variable is reset with each request. |
request | Request context | The request object, which encapsulates the contents of a HTTP request sent by the client. |
session | Request context | The user session, a dictionary that the application can use to store values that are “remembered” between requests. This object will be |
示例一下 applicaiton context 是如何工作的
>>> from hello import app
>>> from flask import current_app
>>> current_app.name
Traceback (most recent call last):
...
RuntimeError: working outside of application context
>>> app_ctx = app.app_context()
>>> app_ctx.push()
>>> current_app.name
'hello'
>>> app_ctx.pop()
request 派遣 (Request Dispatching)
>>> from hello import app
>>> app.url_map
Map([<Rule '/' (HEAD, OPTIONS, GET) -> index>,
<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>,
<Rule '/user/<name>' (HEAD, OPTIONS, GET) -> user>])
最常用的 Flask request 对象 (object)
Attribute or Method | Description |
---|---|
form | A dictionary with all the form fields submitted with the request. |
args | A dictionary with all the arguments passed in the query string of the URL. |
values | A dictionary that combines the values in form and args. |
cookies | A dictionary with all the cookies included in the request. |
headers | A dictionary with all the HTTP headers included in the request. |
files | A dictionary with all the file uploads included with the request. |
get_data() | Return the buffered data from the request body. |
get_json() | A Python dictionary with the parsed JSON included in the body of the request. |
blueprint | The name of the Flask blueprint that is handling the request. |
endpoint | The name of the Flask endpoint that is handling the request. Flask uses the name of the view function as the endpoint name for a route. |
method | The HTTP request method, such as GET or POST. |
scheme | The URL scheme (http or https). |
is_secure() | Return True if the request came through a secure (https) connection. |
host | The host defined in the request, including the port number if given by the client. |
path | The path portion of the URL. |
query_string | The query string portion of the URL, as a raw binary value. |
full_path | The path and query string portions of the URL. |
url | The complete URL requested by the client. |
base_url | Same as url, but without the query string component. |
remote_addr | The IP address of the client. |
environ | The raw WSGI environment dictionary for the request. |
Request 挂钩 (Request Hooks)Request 挂钩以装饰器实现,Flask 支持四种 Request 挂钩:before_first_request
, before_request
, after_request
,teardown_request
响应 (Responses)view 函数返回一个状态 400 代码示例
@app.route('/')
def index():
return '<h1>Bad Request</h1>', 400
响应对象 (response object) 示例
from flask import make_response
@app.route('/')
def index():
response = make_response('<h1>This document carries a cookie!</h1>')
response.set_cookie('answer', '42')
return response
最常用的 Flask Response Object (响应对象)
Attribute or Method | Description |
---|---|
status_code | The numeric HTTP status code. |
headers | A dictionary-like object with all the headers that will be sent with the response. |
set_cookie() | Add a cookie to the response. |
delete_cookie() | Remove a cookie. |
content_length | The length of the response body. |
content_type | The media type of the response body. |
set_data() | Set the response body as a string or bytes value. |
get_data() | Get the response body. |
一种特殊的响应 redirect() 示例
from flask import redirect
@app.route('/')
def index():
return redirect('http://www.example.com')
一种特殊的响应 abort() 示例
from flask import abort
@app.route('/user/<id>')
def get_user(id):
user = load_user(id)
if not user:
abort(404)
return '<h1>Hello, {}</h1>'.format(user.name)
以上是关于学习 Flask Web Development 2nd Edition的主要内容,如果未能解决你的问题,请参考以下文章
Flask Web Development —— 数据库(上)