在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实现哈希表
Feb 07 Python
python实现在windows下操作word的方法
Apr 28 Python
python3设计模式之简单工厂模式
Oct 17 Python
放弃 Python 转向 Go语言有人给出了 9 大理由
Oct 20 Python
python3使用scrapy生成csv文件代码示例
Dec 28 Python
wxPython实现窗口用图片做背景
Apr 25 Python
python redis 删除key脚本的实例
Feb 19 Python
python opencv将表格图片按照表格框线分割和识别
Oct 30 Python
详解centos7+django+python3+mysql+阿里云部署项目全流程
Nov 15 Python
Python Pillow.Image 图像保存和参数选择方式
Jan 09 Python
pytorch 彩色图像转灰度图像实例
Jan 13 Python
Python编程中Python与GIL互斥锁关系作用分析
Sep 15 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
使用sockets:从新闻组中获取文章(二)
2006/10/09 PHP
一个SQL管理员的web接口
2006/10/09 PHP
解析:使用php mongodb扩展时 需要注意的事项
2013/06/18 PHP
解析thinkphp中的导入文件标签
2013/06/20 PHP
PHP+Ajax检测用户名或邮件注册时是否已经存在实例教程
2014/08/23 PHP
[原创]php使用curl判断网页404(不存在)的方法
2016/06/23 PHP
基于jquery的jqDnR拖拽溢出的修改
2011/02/12 Javascript
基于jQuery的烟花效果(运动相关)点击屏幕出烟花
2012/06/14 Javascript
原生javascript图片自动或手动切换示例附演示源码
2013/09/04 Javascript
jquery列表拖动排列(由项目提取相当好用)
2014/06/17 Javascript
jQuery实现分隔条左右拖动功能
2015/11/21 Javascript
jQuery模拟12306城市选择框功能简单实现方法示例
2018/08/13 jQuery
vue绑定事件后获取绑定事件中的this方法
2018/09/15 Javascript
Python专用方法与迭代机制实例分析
2014/09/15 Python
python smtplib模块自动收发邮件功能(二)
2018/05/22 Python
Python实现聊天机器人的示例代码
2018/07/09 Python
详解Python3除法之真除法、截断除法和下取整对比
2019/05/23 Python
纯python进行矩阵的相乘运算的方法示例
2019/07/17 Python
django云端留言板实例详解
2019/07/22 Python
python 接口实现 供第三方调用的例子
2019/08/13 Python
pandas按行按列遍历Dataframe的几种方式
2019/10/23 Python
Python完全识别验证码自动登录实例详解
2019/11/24 Python
解决python执行较大excel文件openpyxl慢问题
2020/05/15 Python
利用keras使用神经网络预测销量操作
2020/07/07 Python
CSS3美化表单控件全集
2016/06/29 HTML / CSS
如何查看浏览器对html5的支持情况
2020/12/15 HTML / CSS
Sneaker Studio匈牙利:购买运动鞋
2018/03/26 全球购物
俄罗斯一家时尚女装商店:Charuel
2019/12/04 全球购物
Kiehl’s科颜氏西班牙官方网站:源自美国的植物护肤品牌
2020/02/22 全球购物
考博自荐信
2013/10/25 职场文书
学前教育专业求职信
2014/09/02 职场文书
政风行风整改方案
2014/10/25 职场文书
奖学金申请个人主要事迹材料
2015/11/04 职场文书
财务人员廉洁自律心得体会
2016/01/13 职场文书
Python 数据可视化之Matplotlib详解
2021/11/02 Python
CSS中妙用 drop-shadow 实现线条光影效果
2021/11/11 HTML / CSS