Python and socket - connet to specific path

Viewed 203

I need to connect/send msg to http://localhost:8001/path/to/my/service, but I am not able to find how to do that. I know how to send if I only have localhost and 8001, but I need this specific path /path/to/my/service. There is where my service is running.

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(<full-url-to-my-service>)
s.sendall(bytes('Message', 'utf-8'))

Update

My service is running on localhost:8001/api/v1/namespaces/my_namespace/services/my_service:http/proxy. How can I connect to it with python?

2 Answers

As @furas told in the comments

socket is primitive object and it doesn't have specialized method for this - and you have to on your own create message with correct data. You have to learn HTTP protocol and use it to send

This is a sample snippet to send a GET request in python using requests library

import requests
URL = 'http://localhost:8001/path/to/my/service'
response_text = requests.get(URL).text
print(response_text)

This assumes the Content-Type that GET URL produces is text. If it is json, then a minor change is required

import requests
URL = 'http://localhost:8001/path/to/my/service'
response_json = requests.get(URL).json()
print(response_json)

There are other ways to achieve the same using other good frameworks like urllib, and so on. Here is the documentation of requests library for reference

sendall() requires bytes, so String must be encoded.

s.sendall("foobar".encode())
Related