在Python的Tornado框架中实现简单的在线代理的教程
作者:goldensun 发布时间:2021-12-31 08:51:39
实现代理的方式很多种,流行的web服务器也大都有代理的功能,比如http://www.tornadoweb.cn用的就是nginx的代理功能做的tornadoweb官网的镜像。
最近,我在开发一个移动运用(以下简称APP)的后台程序(Server),该运用需要调用到另一平台产品(Platform)的API。对于这个系统来说,可选的一种实现方式方式是APP同时跟Server&Platform两者交互;另一种则在Server端封装掉Platform的API,APP只和Server交互。显然后一种方式的系统架构会清晰些,APP编程时也就相对简单。那么如何在Server端封装Platform的API呢,我首先考虑到的就是用代理的方式来实现。碰巧最近Tornado邮件群组里有人在讨论using Tornado as a proxy,贴主提到的运用场景跟我这碰到的场景非常的相似,我把原帖的代码做了些整理和简化,源代码如下:
# -*- coding: utf-8 -*-
#
# Copyright(c) 2011 Felinx Lee & http://feilong.me/
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient
from tornado.web import HTTPError, asynchronous
from tornado.httpclient import HTTPRequest
from tornado.options import define, options
try:
from tornado.curl_httpclient import CurlAsyncHTTPClient as AsyncHTTPClient
except ImportError:
from tornado.simple_httpclient import SimpleAsyncHTTPClient as AsyncHTTPClient
define("port", default=8888, help="run on the given port", type=int)
define("api_protocol", default="http")
define("api_host", default="feilong.me")
define("api_port", default="80")
define("debug", default=True, type=bool)
class ProxyHandler(tornado.web.RequestHandler):
@asynchronous
def get(self):
# enable API GET request when debugging
if options.debug:
return self.post()
else:
raise HTTPError(405)
@asynchronous
def post(self):
protocol = options.api_protocol
host = options.api_host
port = options.api_port
# port suffix
port = "" if port == "80" else ":%s" % port
uri = self.request.uri
url = "%s://%s%s%s" % (protocol, host, port, uri)
# update host to destination host
headers = dict(self.request.headers)
headers["Host"] = host
try:
AsyncHTTPClient().fetch(
HTTPRequest(url=url,
method="POST",
body=self.request.body,
headers=headers,
follow_redirects=False),
self._on_proxy)
except tornado.httpclient.HTTPError, x:
if hasattr(x, "response") and x.response:
self._on_proxy(x.response)
else:
logging.error("Tornado signalled HTTPError %s", x)
def _on_proxy(self, response):
if response.error and not isinstance(response.error,
tornado.httpclient.HTTPError):
raise HTTPError(500)
else:
self.set_status(response.code)
for header in ("Date", "Cache-Control", "Server", "Content-Type", "Location"):
v = response.headers.get(header)
if v:
self.set_header(header, v)
if response.body:
self.write(response.body)
self.finish()
def main():
tornado.options.parse_command_line()
application = tornado.web.Application([
(r"/.*", ProxyHandler),
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
运行上面的代码后,访问 http://localhost:8888/ 将会完整显示飞龙博客的首页,即代理访问了http://feilong.me/的内容。
我考虑用程序的方式来做代理而不是直接用Nginx来做代理,其中一点是考虑到用程序可以很容易的控制Platform的哪些API是需要代理的,而哪些是要屏蔽掉的,还有哪些可能是要重写的(比如Server的login可能不能直接代理Platform的login,但却要调用到Platform的login API)。
以上这段代码只是做了简单的页面内容代理,并没有对页面进行进一步的解析处理,比如链接替换等,这些就交个有兴趣的朋友去开发了。基于以上这段代码,将其扩展一下,是完全可以实现一个完整的在线代理程序的。
这段代码我已放到了我的实验项目里,见https://bitbucket.org/felinx/labs,我将会放更多类似于这样的实验性质的小项目到这个repository里来,有兴趣的朋友可以关注一下。
转载请注明出处:http://feilong.me/2011/09/tornado-as-a-proxy


猜你喜欢
- 本文实例为大家分享了PHP实现统计代码行数小工具,供大家参考,具体内容如下为了方面统计编程代码行数,做了一个小工具。自动统计指定目录以及目录
- help函数是python的一个内置函数,在python基础知识中介绍过什么是内置函数,它是python自带的函数,任何时候都可以被使。he
- 1.分包背景这里首先介绍下MultiDex的产生背景。当Android系统安装一个应用的时候,有一步是对Dex进行优化,这个过程有一个专门的
- 本文实例为大家分享了python使用itchat实现手机控制电脑的具体代码,供大家参考,具体内容如下1.准备材料首先电脑上需要安装了pyth
- 日常工作生活中,事情一多,就会忘记一些该做未做的事情。即使有时候把事情记录在了小本本上或者手机、电脑端备忘录上,也总会有查看不及时,导致错过
- 物化表首先提出一个不相关的IN子查询SELECT * FROM s1 WHERE key1 IN (SELECT common_field
- PHP版: $o = array('x'=>1, 'y'=>2, 'z'=>
- 背景最近正在学nodejs,想到曾经有台云服务器,但是很久不用了,由于怕麻烦,一股脑的把云主机重装了个Ubuntu系统,于是配置MySQL成
- 前言硬要说这篇文章怎么来的,那得先从那几个吃野味的人开始说起…… 前天睡醒:假期还有几天;昨天睡醒:假期还有十几天;今天睡醒:假期还有一个月
- 一、使用replace+空格ordersdetaildf['商品名称2']=ordersdetaildf['商品名称
- 在工作和学习中如果同时传输多个文件,大的安装包,python提供了一种无线传输的方法,开启一个本地http服务器,同一局域网下可方便访问 经
- Django模板系统压根儿就没想过实现一个全功能的编程语言,所以它不允许我们在模板中执行Python的语句(还是那句话,要了解更多请参看理念
- 最近经常需要出一些临时性的报表,于是就用python 的smtplib 和email 两模块写了个小程序,当数据处理完后通过邮箱把报表文件从
- 最近在学习MySQL优化方面的知识。本文就数据类型和schema方面的优化进行介绍。1. 选择优化的数据类型MySQL支持的数据类型有很多,
- 本文实例讲述了Python实现将一个正整数分解质因数的方法。分享给大家供大家参考,具体如下:遇到一个python编程联系题目:将一个正整数分
- 函数签名对象,表示调用函数的方式,即定义了函数的输入和输出。在Python中,可以使用标准库inspect的一些方法或类,来操作或创建函数签
- 1. 下载RPM安装包, 因为安装MySQL的时候,软件会需要一依赖关系, 所以建议把所有的安装包下载下载, 再依次安装所以的RPM包。 2
- 一、route()路由概述功能:将URL绑定到函数路由函数route()的调用有两种方式:静态路由和动态路由二、静态路由和动态路径方式1:静
- 1.前言在移动商业广告的测试的工作中,经常会需要对广告请求进行捕获和分析,常使用的有两个测试工具:fiddler,Charles,这两个工具
- 一、注意你的Python版本Python官方网站为http://www.python.org/,当前最新稳定版本为3.6.5,在3.0版本时