在Python的Tornado框架中实现简单的在线代理的教程


Posted in Python onMay 02, 2015

实现代理的方式很多种,流行的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

Python 相关文章推荐
Tornado Web服务器多进程启动的2个方法
Aug 04 Python
python 使用正则表达式按照多个空格分割字符的实例
Dec 20 Python
使用Python在Windows下获取USB PID&VID的方法
Jul 02 Python
django fernet fields字段加密实践详解
Aug 12 Python
Python对接 xray 和微信实现自动告警
Sep 17 Python
Python 迭代,for...in遍历,迭代原理与应用示例
Oct 12 Python
tensorflow-gpu安装的常见问题及解决方案
Jan 20 Python
Python netmiko模块的使用
Feb 14 Python
PyCharm取消波浪线、下划线和中划线的实现
Mar 03 Python
selenium+python配置chrome浏览器的选项的实现
Mar 18 Python
python实现拼接图片
Mar 23 Python
python 还原梯度下降算法实现一维线性回归
Oct 22 Python
探究Python的Tornado框架对子域名和泛域名的支持
May 02 #Python
Python编程中运用闭包时所需要注意的一些地方
May 02 #Python
按日期打印Python的Tornado框架中的日志的方法
May 02 #Python
详细解读Python的web.py框架下的application.py模块
May 02 #Python
使用Python的web.py框架实现类似Django的ORM查询的教程
May 02 #Python
在ironpython中利用装饰器执行SQL操作的例子
May 02 #Python
用Python编写简单的定时器的方法
May 02 #Python
You might like
PHP数据流应用的一个简单实例
2012/09/14 PHP
Yii遍历行下每列数据的方法
2016/10/17 PHP
PHP redis实现超迷你全文检索
2017/03/04 PHP
php7函数,声明,返回值等新特性介绍
2018/05/25 PHP
PHP删除数组中特定元素的两种方法
2019/02/28 PHP
PHP笛卡尔积实现原理及代码实例
2020/12/09 PHP
9行javascript代码获取QQ群成员具体实现
2013/10/16 Javascript
对Web开发中前端框架与前端类库的一些思考
2015/03/27 Javascript
JavaScript脚本库编写的方法
2015/12/09 Javascript
微信小程序 Storage API实例详解
2016/10/02 Javascript
微信小程序 122100版本更新问题解决方案
2016/12/22 Javascript
Node.js的Mongodb使用实例
2016/12/30 Javascript
jQuery按需加载轮播图(web前端性能优化)
2017/02/17 Javascript
EasyUI为Numberbox添加blur事件的方法
2017/03/05 Javascript
jQuery Ajax前后端使用JSON进行交互示例
2017/03/17 Javascript
JavaScript文件的同步和异步加载的实现代码
2017/08/19 Javascript
js嵌套的数组扁平化:将多维数组变成一维数组以及push()与concat()区别的讲解
2019/01/19 Javascript
详解Vue串联过滤器的使用场景
2020/04/30 Javascript
[40:29]2018DOTA2亚洲邀请赛 4.7总决赛 LGD vs Mineski 第一场
2018/04/10 DOTA
全面理解Python中self的用法
2016/06/04 Python
利用arcgis的python读取要素的X,Y方法
2018/12/22 Python
3行Python代码实现图像照片抠图和换底色的方法
2019/10/10 Python
解决jupyter notebook 出现In[*]的问题
2020/04/13 Python
使用豆瓣源来安装python中的第三方库方法
2021/01/26 Python
HTML5中的新元素介绍
2008/10/17 HTML / CSS
Bluebella法国官网:英国性感内衣品牌
2019/05/03 全球购物
值传递还是引用传递
2015/02/08 面试题
餐饮主管岗位职责
2013/12/10 职场文书
工作会议方案
2014/05/21 职场文书
有关环保的标语
2014/06/13 职场文书
煤矿安全保证书
2015/02/27 职场文书
检讨书范文大全
2015/05/07 职场文书
父亲节感言
2015/08/03 职场文书
教学反思怎么写
2016/02/24 职场文书
Python Matplotlib绘制条形图的全过程
2021/10/24 Python
html中两种获取标签内的值的方法
2022/06/10 HTML / CSS