使用 Flask 代理到另一个 Web 服务 [英] Proxying to another web service with Flask

查看:59
本文介绍了使用 Flask 代理到另一个 Web 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将向我的 Flask 应用程序发出的请求代理到机器上本地运行的另一个 Web 服务.我更愿意为此使用 Flask,而不是我们的更高级别的 nginx 实例,以便我们可以重用内置于应用程序中的现有身份验证系统.我们越能保持这种单点登录"越好.

I want to proxy requests made to my Flask app to another web service running locally on the machine. I'd rather use Flask for this than our higher-level nginx instance so that we can reuse our existing authentication system built into our app. The more we can keep this "single sign on" the better.

是否有现有的模块或其他代码可以执行此操作?事实证明,尝试将 Flask 应用连接到诸如 httplib 或 urllib 之类的东西是一件很痛苦的事情.

Is there an existing module or other code to do this? Trying to bridge the Flask app through to something like httplib or urllib is proving to be a pain.

推荐答案

我在基于 Werkzeug 的应用程序中使用 httplib 实现了一个代理(就像你的情况一样,我需要使用 web 应用程序的身份验证和授权).

I have an implementation of a proxy using httplib in a Werkzeug-based app (as in your case, I needed to use the webapp's authentication and authorization).

虽然 Flask 文档没有说明如何访问 HTTP 标头,但您可以使用 request.headers(参见 Werkzeug 文档).如果您不需要修改响应,并且被代理应用使用的标头是可预测的,那么代理是直接的.

Although the Flask docs don't state how to access the HTTP headers, you can use request.headers (see Werkzeug documentation). If you don't need to modify the response, and the headers used by the proxied app are predictable, proxying is staightforward.

注意,如果不需要修改响应,应该使用werkzeug.wsgi.wrap_file来包装httplib的响应流.这允许将打开的操作系统级文件描述符传递给 HTTP 服务器以获得最佳性能.

Note that if you don't need to modify the response, you should use the werkzeug.wsgi.wrap_file to wrap httplib's response stream. That allows passing of the open OS-level file descriptor to the HTTP server for optimal performance.

这篇关于使用 Flask 代理到另一个 Web 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆