安全的 Cookie
WebDev Cookie 安全 Tornado 2019-01-13本文讲的是 Tornado 框架中的 “secure cookie” 实现。
Web 开发(前后端与站点建设)
本文讲的是 Tornado 框架中的 “secure cookie” 实现。
Apache,Nginx 都有缓存功能,再加上 Redis 做动态数据的缓存,再加上 CDN,所以我还没有用过专门的缓存服务。
但是这些服务真是大名鼎鼎,即便不用,我也可以先列出来做个简单的了解。
这套方案名气比较大,了解看看。
一般都是参考着 官网示例 写,修修改改就好了,挺方便。
from werkzeug.wrappers import Request, Response
from werkzeug.routing import Map, Rule
class Application:
def __init__(self):
self.url_map = Map([
Rule('/', endpoint='hello')
])
def hello(self, request):
text = 'Hello, World!'
response = Response(text, content_type='text/plain')
return response
@Request.application
def __call__(self, request):
adapter = self.url_map.bind_to_environ(request.environ)
endpoint, values = adapter.match()
handler = getattr(self, endpoint)
return handler(request, **values)
if __name__ == '__main__':
from werkzeug.serving import run_simple
app = Application()
run_simple('localhost', 5000, app)
async/await)Werkzeug 1.x 开始已经提供了对协程的支持。
PS:WSGI 规范是基于同步的设计,没有较好的适配异步编程,所以后面一些更年轻的框架选择了 ASGI(Async Server Gateway Interface)。
PS:2014/03/01, WSGI
PS:2021/11/06, 体验 ASGI
import asyncio
from werkzeug.wrappers import Request, Response
from werkzeug.routing import Map, Rule
class Application:
def __init__(self):
self.url_map = Map([
Rule('/', endpoint='hello')
])
async def hello(self, request):
text = 'Hello, World!'
response = Response(text, content_type='text/plain')
return response
@Request.application
async def __call__(self, request):
adapter = self.url_map.bind_to_environ(request.environ)
endpoint, values = adapter.match()
handler = getattr(self, endpoint)
response = await handler(request, **values)
return response
if __name__ == '__main__':
from werkzeug.serving import run_simple
app = Application()
run_simple('localhost', 5000, app)
| 版本 | 时间 |
|---|---|
| 2.3.4 | May 9, 2023 |
| 2.3.3 | May 1, 2023 |
| 2.3.2 | Apr 29, 2023 |
| 2.3.1 | Apr 27, 2023 |
| 2.3.0 | Apr 26, 2023 |
| 2.2.3 | Feb 15, 2023 |
| 2.2.2 | Aug 9, 2022 |
| 2.2.1 | Jul 28, 2022 |
| 2.2.0 | Jul 24, 2022 |
| 2.1.2 | Apr 29, 2022 |
| 2.1.1 | Apr 2, 2022 |
| 2.1.0 | Mar 29, 2022 |
| 2.0.3 | Feb 8, 2022 |
| 2.0.2 | Oct 6, 2021 |
| 2.0.1 | May 18, 2021 |
| 2.0.0 | May 12, 2021 |
| 1.0.1 | Apr 1, 2020 |
| 1.0.0 | Feb 7, 2020 |
| 0.16.1 | Jan 27, 2020 |
| 0.16.0 | Sep 19, 2019 |
| 0.15.6 | Sep 5, 2019 |
| 0.15.5 | Jul 17, 2019 |
| 0.15.4 | May 15, 2019 |
| 0.15.3 | May 15, 2019 |
| 0.15.2 | Apr 3, 2019 |
| 0.15.1 | Mar 22, 2019 |
| 0.15.0 | Mar 20, 2019 |
| 0.14.1 | Jan 1, 2018 |
| 0.14 | Dec 31, 2017 |
| 0.13 | Dec 8, 2017 |
| 0.12.2 | May 16, 2017 |
| 0.12.1 | Mar 16, 2017 |
| 0.12 | Mar 10, 2017 |
| 0.11.15 | Dec 31, 2016 |
| 0.11.14 | Dec 31, 2016 |
| 0.11.13 | Dec 27, 2016 |
| 0.11.12 | Dec 26, 2016 |
| 0.11.11 | Aug 31, 2016 |
| 0.11.10 | May 24, 2016 |
| 0.11.9 | Apr 25, 2016 |
| 0.11.8 | Apr 15, 2016 |
| 0.11.7 | Apr 15, 2016 |
| 0.11.6 | Apr 14, 2016 |
| 0.11.5 | Mar 23, 2016 |
| 0.11.4 | Feb 15, 2016 |
| 0.11.3 | Dec 20, 2015 |
| 0.11.2 | Nov 12, 2015 |
| 0.11.1 | Nov 10, 2015 |
| 0.11 | Nov 8, 2015 |
| 0.10.4 | Mar 26, 2015 |
| 0.10.3 | Mar 26, 2015 |
| 0.10.2 | Mar 26, 2015 |
| 0.10.1 | Feb 4, 2015 |
| 0.10 | Jan 30, 2015 |
| 0.9.6 | Jun 7, 2014 |
| 0.9.5 | Jun 7, 2014 |
| 0.9.4 | Aug 26, 2013 |
| 0.9.3 | Jul 25, 2013 |
| 0.9.2 | Jul 18, 2013 |
| 0.9.1 | Jun 14, 2013 |
| 0.9 | Jun 13, 2013 |
| 0.8.3 | Feb 5, 2012 |
| 0.8.2 | Dec 16, 2011 |
| 0.8.1 | Sep 30, 2011 |
| 0.8 | Sep 30, 2011 |
| 0.7.2 | Sep 30, 2011 |
| 0.7.1 | Jul 26, 2011 |
| 0.7 | Jul 24, 2011 |
| 0.6.2 | Apr 24, 2010 |
| 0.6.1 | Apr 13, 2010 |
| 0.6 | Feb 19, 2010 |
| 0.5.1 | Jul 10, 2009 |
| 0.5 | Apr 25, 2009 |
| 0.4.1 | Jan 11, 2009 |
| 0.4 | Nov 23, 2008 |
| 0.3.1 | Jun 24, 2008 |
| 0.3 | Jun 15, 2008 |
| 0.2 | Feb 14, 2008 |
| 0.1 | Dec 10, 2007 |
这个组织下的每个项目单拿出来都是响当当的存在:
- Click — Beautiful, composable command line interface creation kit.
- Flask — a flexible and popular web development framework
- ItsDangerous — Safely pass trusted data to untrusted environments and back.
- Jinja — a full featured template engine for Python
- MarkupSafe — Safely add untrusted strings to HTML/XML markup.
- Quart — an async reimplementation of flask
- Werkzeug — The comprehensive WSGI web application library.
Nginx 商用版 1.5.7 (2013 年) 开始支持 sticky 指令。
文档: https://nginx.org/en/docs/http/ngx_http_upstream_module.html#sticky
Syntax: sticky cookie name [expires=time] [domain=domain] [httponly] [samesite=strict|lax|none] [secure] [path=path];
sticky route $variable ...;
sticky learn create=$variable lookup=$variable zone=name:size [timeout=time] [header] [sync];
Default: —
Context: upstream
开源版有 nginx-sticky-module。
C 语言写的,BSD 协议。
代码看起来并不复杂,如果需要用到的时候,可以进行一个粗略的 Review。
# 下载 nginx 源码 (2016-04-26)
wget http://nginx.org/download/nginx-1.10.0.tar.gz http://nginx.org/download/nginx-1.10.0.tar.gz.asc
gpg --verify nginx-1.10.0.tar.gz.asc
# 下载 nginx-sticky-module (2015-08-06)
wget https://bitbucket.org/nginx-goodies/nginx-sticky-module-ng/get/1.2.6.zip
unzip 1.2.6.zip
cd nginx-goodies-nginx-sticky-module-ng-c78b7dd79d0d/
unzip nginx-1.10.0.zip
cd nginx-1.10.0/
# 其他参数按需添加
./configure --add-module=../nginx-goodies-nginx-sticky-module-ng-c78b7dd79d0d/
make && make install
# Configuration summary
# + using system PCRE library
# + OpenSSL library is not used
# + md5: using system crypto library
# + sha1: using system crypto library
# + using system zlib library
# nginx path prefix: "/usr/local/nginx"
# nginx binary file: "/usr/local/nginx/sbin/nginx"
# nginx modules path: "/usr/local/nginx/modules"
# nginx configuration prefix: "/usr/local/nginx/conf"
# nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
# nginx pid file: "/usr/local/nginx/logs/nginx.pid"
# nginx error log file: "/usr/local/nginx/logs/error.log"
# nginx http access log file: "/usr/local/nginx/logs/access.log"
# nginx http client request body temporary files: "client_body_temp"
# nginx http proxy temporary files: "proxy_temp"
# nginx http fastcgi temporary files: "fastcgi_temp"
# nginx http uwsgi temporary files: "uwsgi_temp"
# nginx http scgi temporary files: "scgi_temp"
upstream {
sticky;
server 127.0.0.1:9000;
server 127.0.0.1:9001;
server 127.0.0.1:9002;
}
sticky [name=route] [domain=.foo.bar] [path=/] [expires=1h]
[hash=index|md5|sha1] [no_fallback] [secure] [httponly];
CentOS 下的安装:
sudo yum install -y httpd-utils
Debian/Ubuntu 下的安装:
sudo apt install -y apache2-utils
ab -n 请求数 -c 并发书 URL
常用参数:
-n 请求数-c 并发数-t 持续测试时间-k 启用 HTTP KeepAlive-H 设置请求头-m 请求方式-T 设置 Content-Type-p 设置 POST 数据文件如果 POST 请求:
echo 'key1=value1&key2=value2' > /tmp/postdata
-T 'application/x-www-form-urlencoded' -p postdata
echo '{"key1":"value1","key2":"value2"}' > /tmp/postdata
-T 'application/json' -p postdata
执行 ab -n100 -c10 https://www.baidu.com/ 可以得到以下结果:

需要重要关注的数据做了标记,分别是:
测试持续时间 / 请求数并发数 / 吞吐量Update @ 2021-12-29
url="https://www.baidu.com/"
rm -rf /tmp/httpbench-*.log
for c in {1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100,150,200,250,300,350,400,450,500,600,700,800,900,1000};
do echo "==== Concurrency Level: $c ===="; let n=$((c * 100)); ab -n $n -c $c $url > /tmp/httpbench-$c.log; sleep 10; done;
然后用 Python 脚本解析 ab 输出生成报告。
Python 代码就不贴了, 如果感兴趣可以打开看看: abReport.py
如果觉得我的方案不妥当,非常欢迎提出意见或建议。
Update @ 2021-12-30:
又对 abReport.py 做了调整 (abReport2.py),现在可以输出一个 ECharts 图表了(尽整些花里胡哨的东西)。

2.2 版本下的权限控制语句在 2.4 下已经不再适用,需要做一些调整。
Order deny,allow
Deny from all
应该改成:Require all denied
Order deny,allow
Deny from all
Allow from example.com
应该改成:Require host example.com
Order allow,deny
Allow from all
应该改成:Require all granted
嗯,挺好,新语法更加简单。
https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods
GET R 查POST C 增PUT U 改DELETE D 删PATCH U 改HEAD 和 GET 相同,不过只返回请求头,不返回请求体OPTIONS 返回这个请求支持的 HTTP 方法TRACE 返回服务器收到的请求,调试用CONNECT 为代理服务器准备的 HTTP 隧道方法PATCH 和 PUT 的区别:PUT 是使用新版本来替换旧版本,PATCH 则是在旧版本的基础上修改。
> OPTIONS / HTTP/1.1
> Host: www.markjour.com
> User-Agent: curl/7.74.0
> Accept: */*
< HTTP/1.1 200 OK
< Date: Sat, 11 Jan 2014 06:59:50 GMT
< Server: Apache
< Allow: OPTIONS,GET,HEAD,POST
< Vary: Accept-Encoding,User-Agent
< Content-Length: 0
< Content-Type: text/html
> GET / HTTP/1.1
> Host: www.baidu.com
> User-Agent: curl/7.74.0
> Accept: */*
< HTTP/1.1 200 OK
< Accept-Ranges: bytes
< Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
< Connection: keep-alive
< Content-Length: 2443
< Content-Type: text/html
< Date: Sat, 11 Jan 2014 06:52:33 GMT
< Etag: "588603fd-98b"
< Last-Modified: Mon, 23 Jan 2017 13:24:13 GMT
< Pragma: no-cache
< Server: bfe/1.0.8.18
< Set-Cookie: BDORZ=27315; max-age=86400; domain=.baidu.com; path=/
RFC 7231 中的 Safe Methods,Idempotent Methods,Cacheable Methods。
幂等:重复请求也不会对资源产生影响:
上面四个安全方法自不用说
为什么 XXX 不幂等?
CONNECT 隧道而已,里面的请求具体是什么都不知道
可缓存(该小节在 RFC 2616 没有):
GET
PUT,DELETE 可以导致之前的相关缓存失效。
为什么 POST/PATCH 方法 cacheable?
RFC 2616:
Some HTTP methods MUST cause a cache to invalidate an entity. This is either the entity referred to by the Request-URI, or by the Location
or Content-Location headers (if present). These methods are:
- PUT
- DELETE
- POST
RFC 7231:
this specification defines GET, HEAD, and POST as cacheable, although the overwhelming majority of cache implementations only support GET and HEAD.
Mozilla Developer Network:
Only if freshness information is included
根据相关 RFC,如果响应头中有 Expires, Cache-Control 头,可以缓存 POST/PATCH。
我想,这个可能是为了避免资源重复创建而设计?
不过现实是,没有浏览器或服务器支持缓存 POST/PATCH 请求。
备注:最终可缓存状态还取决于 HTTP 状态码, 必须是 200、203、204、206、300、301 才可以缓存。
当然,只需要客户端和服务器端都能支持,请求方法可以自定义,如:
Update @ 2020-04-01:
WebDAV 协议就可以看作是一个 HTTP 拓展, 增加了以下方法的支持:
The Web Server Gateway Interface (WSGI, pronounced whiskey or WIZ-ghee) is a simple calling convention for web servers to forward requests to web applications or frameworks written in the Python programming language.
The current version of WSGI, version 1.0.1, is specified in Python Enhancement Proposal (PEP) 3333.
Web 服务器网关接口(WSGI,发音为威士忌或 WIZ-ghee)是一种简单的调用约定,用于将请求转发到用 Python 编写的 Web 应用程序或框架的 Web 服务器。
当前版本的 WSGI,即 1.0.1 版本,由 Python 增强提案(PEP)3333 指定。
WSGI was originally specified as PEP-333 in 2003.
PEP-3333, published in 2010, updates the specification for Python 3.
WSGI 最初是在 2003 年的 PEP-333 中指定的。
2010 年发布的 PEP-3333 更新了 Python 3 的规范。
In 2003, Python web frameworks were typically written against only CGI, FastCGI, mod_python, or some other custom API of a specific web server. To quote PEP 333:
2003 年,Python Web 框架通常只针对 CGI、FastCGI、mod_python 或某些特定 Web 服务器的其他自定义 API 编写。引用 PEP 333 的话:
Python currently boasts a wide variety of web application frameworks, such as Zope, Quixote, Webware, SkunkWeb, PSO, and Twisted Web -- to name just a few. This wide variety of choices can be a problem for new Python users, because generally speaking, their choice of web framework will limit their choice of usable web servers, and vice versa... By contrast, although Java has just as many web application frameworks available, Java's "servlet" API makes it possible for applications written with any Java web application framework to run in any web server that supports the servlet API.
Python 目前拥有众多 Web 应用程序框架,例如 Zope、Quixote、Webware、SkunkWeb、PSO 和 Twisted Web 等等。这种广泛的选择可能会成为新 Python 用户的问题,因为一般来说,他们选择的 Web 框架将限制他们可用的 Web 服务器的选择,反之亦然……相比之下,尽管 Java 也拥有同样多的 Web 应用程序框架,但 Java 的“servlet”API 使得使用任何 Java Web 应用程序框架编写的应用程序都能在支持 servlet API 的任何 Web 服务器中运行。
WSGI was thus created as an implementation-neutral interface between web servers and web applications or frameworks to promote common ground for portable web application development.
因此,WSGI 被创建为实现中立的 Web 服务器和 Web 应用程序或框架之间的接口,以促进可移植 Web 应用程序的开发和共同基础。
The WSGI has two sides:
WSGI 有两个方面:
Between the server and the application, there may be one or more WSGI middleware components, which implement both sides of the API, typically in Python code.
在服务器和应用程序之间,可能会有一个或多个WSGI 中间件组件,它们在 Python 代码中实现了 API 的两个方面。
WSGI does not specify how the Python interpreter should be started, nor how the application object should be loaded or configured, and different frameworks and webservers achieve this in different ways.
WSGI 不指定 Python 解释器应如何启动,也不指定应用程序对象如何加载或配置,不同的框架和 Web 服务器以不同的方式实现这些功能。
A WSGI middleware component is a Python callable that is itself a WSGI application, but may handle requests by delegating to other WSGI applications. These applications can themselves be WSGI middleware components.
一个 WSGI 中间件组件是一个 Python 可调用对象,它本身是一个 WSGI 应用程序,但可以通过委托给其他 WSGI 应用程序来处理请求。这些应用程序本身可以是 WSGI 中间件组件。
A middleware component can perform such functions as:
中间件组件可以执行以下功能:
A WSGI-compatible "Hello, World!" application written in Python:
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
yield b'Hello, World!\n'
Where:
application, which takes two parameters, environ and start_response. environ is a dictionary containing CGI environment variables as well as other request parameters and metadata under well-defined keys. start_response is a callable itself, taking two positional parameters, status and response_headers.start_response, specifying "200 OK" as the HTTP status and a "Content-Type" response header.A full example of a WSGI network server is outside the scope of this article. Below is a sketch of how one would call a WSGI application and retrieve its HTTP status line, response headers, and response body, as Python objects. Details of how to construct the environ dict have been omitted.
完整的 WSGI 网络服务器示例不再本文范围之内。以下只是一个 Demo,说明如何调用 WSGI 应用程序并检索其 HTTP 状态行、响应头和响应正文,作为 Python 对象。如何构造 environ 字典的详细信息已被省略。
from io import BytesIO
def call_application(app, environ):
status = None
headers = None
body = BytesIO()
def start_response(rstatus, rheaders):
nonlocal status, headers
status, headers = rstatus, rheaders
app_iter = app(environ, start_response)
try:
for data in app_iter:
assert status is not None and headers is not None, \
"start_response() was not called"
body.write(data)
finally:
if hasattr(app_iter, 'close'):
app_iter.close()
return status, headers, body.getvalue()
environ = {...} # "environ" dict
status, headers, body = call_application(app, environ)
PEP 3333 引入了一些新特性和更严格的规范,以提高 Python Web 应用程序的可移植性和互操作性。其中一些变化包括:
此外,PEP 3333 还引入了一些新的建议,包括使用可选的服务器和客户端请求信息,提供更好的错误处理和日志记录,以及更好地处理请求和响应的二进制数据。
Content-Type: text/html; charset=ISO-8859-4 HTTP 头部<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta charset="utf-8"><?xml version="1.0" encoding="ISO-8859-1"?> XHTML 可以才用 XML 声明来定义编码