Lui*_*lli 16 python python-requests
通常,使用请求框架执行发布请求是通过以下方式完成的:
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
Run Code Online (Sandbox Code Playgroud)
但是:如何连接到unix套接字而不是进行TCP连接?
在相关的说明中,如何在URL中编码域路径?
ldapi,其中套接字名称在主机字段中是%编码的httpiehttp+unix在主机字段中使用scheme和%-encoded path这些是一些例子,但是有RFC还是已建立的最佳实践?
Dim*_*nek 18
没有必要重新发明轮子:
https://github.com/msabramo/requests-unixsocket
URL方案是http+unix和套接字路径百分比编码到主机字段:
import requests_unixsocket
session = requests_unixsocket.Session()
# Access /path/to/page from /tmp/profilesvc.sock
r = session.get('http+unix://%2Ftmp%2Fprofilesvc.sock/path/to/page')
assert r.status_code == 200
Run Code Online (Sandbox Code Playgroud)
If you are looking for a minimalistic and clean approach to this in Python 3, here's a working example that will talk to Ubuntu's snapd on a unix domain socket.
import requests
import socket
import pprint
from urllib3.connection import HTTPConnection
from urllib3.connectionpool import HTTPConnectionPool
from requests.adapters import HTTPAdapter
class SnapdConnection(HTTPConnection):
def __init__(self):
super().__init__("localhost")
def connect(self):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect("/run/snapd.socket")
class SnapdConnectionPool(HTTPConnectionPool):
def __init__(self):
super().__init__("localhost")
def _new_conn(self):
return SnapdConnection()
class SnapdAdapter(HTTPAdapter):
def get_connection(self, url, proxies=None):
return SnapdConnectionPool()
session = requests.Session()
session.mount("http://snapd/", SnapdAdapter())
response = session.get("http://snapd/v2/system-info")
pprint.pprint(response.json())
Run Code Online (Sandbox Code Playgroud)
您可以使用socat创建 TCP 到 UNIX 套接字代理,例如:
socat TCP-LISTEN:80,reuseaddr,fork UNIX-CLIENT:/tmp/foo.sock
Run Code Online (Sandbox Code Playgroud)
然后将您的 http 请求发送到该代理。侦听 UNIX 套接字的服务器/tmp/foo.sock仍然必须理解 HTTP,因为socat它不进行任何消息转换。
| 归档时间: |
|
| 查看次数: |
11122 次 |
| 最近记录: |