Javascript 如何在金字塔框架中创建代理机制?
我有以下问题: 有一个服务器和金字塔应用程序,他是可见的,可以从互联网。 有一个带有地图的服务器,它在internet上不可见(两个服务器都在一个本地网络中)。 应用服务器从地图服务器请求一些数据,但这些请求是用javascript编写的,javascript在客户端的机器上运行,请求由ip发出,ip当然是本地的(比如192.168.1.28),从我们的本地网络用户可以看到地图,但从internet看不到。 如何制作一个工具(可能是额外的视图或类似的东西)将请求重定向到映射,以便金字塔服务器在客户端请求映射时像代理一样工作 像这样:Javascript 如何在金字塔框架中创建代理机制?,javascript,python,proxy,pyramid,Javascript,Python,Proxy,Pyramid,我有以下问题: 有一个服务器和金字塔应用程序,他是可见的,可以从互联网。 有一个带有地图的服务器,它在internet上不可见(两个服务器都在一个本地网络中)。 应用服务器从地图服务器请求一些数据,但这些请求是用javascript编写的,javascript在客户端的机器上运行,请求由ip发出,ip当然是本地的(比如192.168.1.28),从我们的本地网络用户可以看到地图,但从internet看不到。 如何制作一个工具(可能是额外的视图或类似的东西)将请求重定向到映射,以便金字塔服务器在客
来自internet Pyramid Map server的客户端我假设您希望使用Pyramid应用程序构建HTTP代理,尽管还不完全清楚您为什么要使用Pyramid进行此操作,或者它是这里的最佳解决方案 Pyramid和大多数现代Python web应用程序使用WSGI标准来解码和处理HTTP请求。下面我将介绍一个解决方案,该解决方案应适用于所有WSGI服务器。这是一个稍微修改过的。示例的完整源代码和实现是可用的。此实现只允许代理不同的
localhost
端口,但可以将其更新为允许任意内部网源IP
您可以编写一个金字塔视图,用于捕获到特定路径的所有请求,例如,/map to internal server
:
def proxy_it(request, port):
"""Proxy HTTP request to upstream server."""
proxy_app = WSGIProxyApplication(port)
return request.get_response(proxy_app)
然后,您可以使用WSGIProxyApplication,它执行连接上游服务器并将响应流式传输到客户端的逻辑:
# Courtesy of https://bitbucket.org/dahlia/wsgi-proxy/raw/02ab0dfa8e0078add268e91426e1cc1a52664cf5/wsgi_proxy/__init__.py
import http.client
import logging
from urllib.parse import urlparse, urlunsplit, urlunparse, unquote_plus
#: (:class:`frozenset`) The set of hop-by-hop headers. All header names
#: all normalized to lowercase.
HOPPISH_HEADERS = frozenset([
'keep-alive', 'proxy-authenticate',
'proxy-authorization', 'te', 'trailers', 'transfer-encoding',
'proxy-connection'
# "upgrade", "connection"
])
def is_hop_by_hop(header):
"""Returns :const:`True` if the given ``header`` is hop by hop.
:param header: the header name
:type header: :class:`basestring`
:returns: whether the given ``header`` is hop by hop or not
:rtype: :class:`bool`
"""
return header.lower() in HOPPISH_HEADERS
def reconstruct_url(environ, port):
"""Reconstruct the remote url from the given WSGI ``environ`` dictionary.
:param environ: the WSGI environment
:type environ: :class:`collections.MutableMapping`
:returns: the remote url to proxy
:rtype: :class:`basestring`
"""
# From WSGI spec, PEP 333
url = environ.get('PATH_INFO', '')
if not url.startswith(('http://', 'https://')):
url = '%s://%s%s' % (
environ['wsgi.url_scheme'],
environ['HTTP_HOST'],
url
)
# Fix ;arg=value in url
if '%3B' in url:
url, arg = url.split('%3B', 1)
url = ';'.join([url, arg.replace('%3D', '=')])
# Stick query string back in
try:
query_string = environ['QUERY_STRING']
except KeyError:
pass
else:
url += '?' + query_string
parsed = urlparse(url)
replaced = parsed._replace(netloc="localhost:{}".format(port))
url = urlunparse(replaced)
environ['reconstructed_url'] = url
return url
class WSGIProxyApplication:
"""WSGI application to handle requests that need to be proxied.
You have to instantiate the class before using it as WSGI app::
from wsgiref.simple_server import make_server
app = WSGIProxyApplication()
make_server('', 8080, app).serve_forever()
"""
#: (:class:`types.ClassType`) The connection class of :mod:`httplib` module.
#: It should be a subtype of :class:`httplib.HTTPConnection`.
#: Default is :class:`httplib.HTTPConnection`.
connection_class = http.client.HTTPConnection
def __init__(self, port):
# Target port where we proxy IPython Notebook
self.port = port
def handler(self, environ, start_response):
"""Proxy for requests to the actual http server"""
logger = logging.getLogger(__name__ + '.WSGIProxyApplication.handler')
url = urlparse(reconstruct_url(environ, self.port))
# Create connection object
try:
connection = self.connection_class(url.netloc)
# Build path
path = url.geturl().replace('%s://%s' % (url.scheme, url.netloc),
'')
except Exception:
start_response('501 Gateway Error', [('Content-Type', 'text/html')])
logger.exception('Could not Connect')
yield '<H1>Could not connect</H1>'
return
# Read in request body if it exists
body = length = None
try:
length = int(environ['CONTENT_LENGTH'])
except (KeyError, ValueError):
# This is a situation where client HTTP POST is missing content-length.
# This is also situation where (WebOb?) may screw up encoding and isert extranous = in the body.
# https://github.com/ipython/ipython/issues/8416
if environ["REQUEST_METHOD"] == "POST":
if environ.get("CONTENT_TYPE") == 'application/x-www-form-urlencoded; charset=UTF-8':
body = environ['wsgi.input'].read()
try:
body = unquote_plus(body.decode("utf-8"))
# Fix extra = at end of JSON payload
if body.startswith("{") and body.endswith("}="):
body = body[0:len(body)-1]
except Exception as e:
logger.exception(e)
logger.error("Could not decode body: %s", body)
length = len(body)
else:
body = environ['wsgi.input'].read(length)
# Build headers
logger.debug('environ = %r', environ)
headers = dict(
(key, value)
for key, value in (
# This is a hacky way of getting the header names right
(key[5:].lower().replace('_', '-'), value)
for key, value in environ.items()
# Keys that start with HTTP_ are all headers
if key.startswith('HTTP_')
)
if not is_hop_by_hop(key)
)
# Handler headers that aren't HTTP_ in environ
try:
headers['content-type'] = environ['CONTENT_TYPE']
except KeyError:
pass
# Add our host if one isn't defined
if 'host' not in headers:
headers['host'] = environ['SERVER_NAME']
# Make the remote request
try:
logger.debug('%s %s %r',
environ['REQUEST_METHOD'], path, headers)
connection.request(environ['REQUEST_METHOD'], path,
body=body, headers=headers)
except Exception as e:
# We need extra exception handling in the case the server fails
# in mid connection, it's an edge case but I've seen it
logger.exception(e)
start_response('501 Gateway Error', [('Content-Type', 'text/html')])
yield '<H1>Could not proxy IPython Notebook running localhost:{}</H1>'.format(self.port).encode("utf-8")
return
response = connection.getresponse()
hopped_headers = response.getheaders()
headers = [(key, value)
for key, value in hopped_headers
if not is_hop_by_hop(key)]
start_response('{0.status} {0.reason}'.format(response), headers)
while True:
chunk = response.read(4096)
if chunk:
yield chunk
else:
break
def __call__(self, environ, start_response):
return self.handler(environ, start_response)
#由https://bitbucket.org/dahlia/wsgi-proxy/raw/02ab0dfa8e0078add268e91426e1cc1a52664cf5/wsgi_proxy/__init__.py
导入http.client
导入日志记录
从urllib.parse导入urlparse、urunsplit、urunparse、unquote_plus
#:(:class:`frozenset`)逐跳标头的集合。所有标题名称
#:全部规范化为小写。
HOPPISH_HEADERS=冻结集([
“保持活动状态”、“代理身份验证”,
‘代理授权’、‘te’、‘拖车’、‘传输编码’,
“代理连接”
#“升级”、“连接”
])
def是逐跳的(标题):
“”“如果给定的``header``是逐跳的,则返回:const:`True`。
:param header:标题名称
:type header::class:`basestring`
:返回:给定的“`header``是否是逐跳的
:rtype::class:`bool`
"""
返回HOPPISH_标题中的header.lower()
def地址(环境、端口):
“”“从给定的WSGI``environ``字典重建远程url。
:param environ:WSGI环境
:type environ::class:`collections.MutableMapping`
:返回:代理服务器的远程url
:rtype::class:`basestring`
"""
#来自WSGI规范,PEP 333
url=environ.get('PATH\u INFO','')
如果不是url.startswith(('http://','https://'):
url='%s://%s%s'%(
环境['wsgi.url_scheme'],
环境['HTTP_HOST'],
网址
)
#固定;arg=url中的值
如果url中有“%3B”:
url,arg=url.split(“%3B”,1)
url=“;”。加入([url,arg.replace('%3D','='))
#将查询字符串重新插入
尝试:
query\u string=environ['query\u string']
除KeyError外:
通过
其他:
url+=“?”+查询字符串
已解析=url解析(url)
已替换=已解析。_replace(netloc=“localhost:{}”。格式(端口))
url=urlunparse(已替换)
环境['url']=url
返回url
WSGIPROXY类应用程序:
“”“WSGI应用程序处理需要代理的请求。
在将该类用作WSGI应用程序之前,必须先实例化该类:
从wsgiref.simple_服务器导入make_服务器
app=WSGIProxyApplication()
制作服务器(“”,8080,应用程序)。永远为你服务()
"""
#:(:class:`types.ClassType`)mod:`httplib`模块的连接类。
#:它应该是:class:`httplib.HTTPConnection`的子类型。
#:默认值为:class:`httplib.HTTPConnection`。
connection\u class=http.client.HTTPConnection
def _u初始(自身,端口):
#我们代理IPython笔记本的目标端口
self.port=端口
def处理程序(自身、环境、启动响应):
“”“对实际http服务器的请求的代理”“”
logger=logging.getLogger(_uname_u+'.WSGIProxyApplication.handler'))
url=urlparse(重构url(environ,self.port))
#创建连接对象
尝试:
connection=self.connection\u类(url.netloc)
#构建路径
path=url.geturl().replace(“%s://%s%”(url.scheme,url.netloc),
'')
除例外情况外:
启动响应('501网关错误',[('Content-Type','text/html'))
logger.exception('无法连接')
“无法连接”
返回
#在请求正文中读取(如果存在)
正文=长度=无
尝试:
长度=整数(环境['CONTENT\u length'])
除了(KeyError、ValueError):
#这是一种客户端HTTP POST缺少内容长度的情况。
#在这种情况下,(WebOb?)可能会破坏编码,并在体内产生isert extranous=。
# https://github.com/ipython/ipython/issues/8416
如果环境[“请求方法”]=“发布”:
if environ.get(“CONTENT_TYPE”)=“application/x-www-form-urlencoded;字符集=UTF-8':
body=environ['wsgi.input'].read()
尝试:
body=unquote_plus(body.decode(“utf-8”))
#在JSON有效负载的末尾修复extra=
如果body.startswith(“{”)和body.endswith(“}=”):
主体=主体[0:len(主体)-1]
例外情况除外,如e:
记录器.异常(e)
记录器。错误(“无法解码正文:%s”,正文)
长度=