在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 相关文章推荐
Python中的exec、eval使用实例
Sep 23 Python
django 常用orm操作详解
Sep 13 Python
解决python中使用plot画图,图不显示的问题
Jul 04 Python
Python中文编码知识点
Feb 18 Python
python使用MQTT给硬件传输图片的实现方法
May 05 Python
Python3.8中使用f-strings调试
May 22 Python
python射线法判断检测点是否位于区域外接矩形内
Jun 28 Python
解决python中用matplotlib画多幅图时出现图形部分重叠的问题
Jul 07 Python
python绘图模块matplotlib示例详解
Jul 26 Python
python+opencv边缘提取与各函数参数解析
Mar 09 Python
python中的垃圾回收(GC)机制
Sep 21 Python
Python调用Redis的示例代码
Nov 24 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中4个加速、缓存扩展的区别和选用建议
2014/03/12 PHP
PHP不用递归遍历目录下所有文件的代码
2014/07/04 PHP
PHP根据两点间的经纬度计算距离
2014/10/31 PHP
php实现递归的三种基本方式
2020/07/04 PHP
yii2局部关闭(开启)csrf的验证的实例代码
2017/07/10 PHP
php微信开发之关键词回复功能
2018/06/13 PHP
使用js操作cookie的一点小收获分享
2013/09/03 Javascript
表单元素与非表单元素刷新区别详细解析
2013/11/06 Javascript
js实现固定显示区域内自动缩放图片的方法
2015/07/18 Javascript
JS表格组件神器bootstrap table使用指南详解
2017/04/12 Javascript
使用jQuery 操作table 完成单元格合并的实例
2017/12/27 jQuery
linux 后台运行node服务指令方法
2018/05/23 Javascript
新手简单了解vue
2019/05/29 Javascript
返回上一个url并刷新界面的js代码
2020/09/12 Javascript
[55:25]VGJ.T vs Optic Supermajor小组赛D组 BO3 第三场 6.3
2018/06/04 DOTA
[51:26]VP vs VG 2018国际邀请赛小组赛BO2 第二场 8.19
2018/08/21 DOTA
[48:00]完美世界DOTA2联赛循环赛 Forest vs Inki BO2第二场 11.04
2020/11/04 DOTA
python函数参数*args**kwargs用法实例
2013/12/04 Python
Swift 3.0在集合类数据结构上的一些新变化总结
2016/07/11 Python
shelve  用来持久化任意的Python对象实例代码
2016/10/12 Python
Python多线程threading和multiprocessing模块实例解析
2018/01/29 Python
Tensorflow 训练自己的数据集将数据直接导入到内存
2018/06/19 Python
使用python将请求的requests headers参数格式化方法
2019/01/02 Python
python输出电脑上所有的串口名的方法
2019/07/02 Python
Python 正则表达式 re.match/re.search/re.sub的使用解析
2019/07/22 Python
Python文件读写w+和r+区别解析
2020/03/26 Python
通过Python pyecharts输出保存图片代码实例
2020/11/25 Python
CSS实现鼠标滑过鼠标点击代码写法
2016/12/26 HTML / CSS
土耳其时尚购物网站:Morhipo
2017/09/04 全球购物
Office DEPOT法国官网:欧迪办公用品采购
2018/01/03 全球购物
幼儿园优秀教师事迹
2014/02/13 职场文书
竞选班干部演讲稿500字
2014/08/20 职场文书
转让协议书
2015/01/27 职场文书
纪检干部学习心得体会
2016/01/23 职场文书
CSS3中Animation实现简单的手指点击动画的示例
2021/07/15 HTML / CSS
MySQL中rank() over、dense_rank() over、row_number() over用法介绍
2022/03/23 MySQL