This repository has been archived on 2021-12-22. You can view files and clone it, but cannot push or open issues or pull requests.
tkGemini/gemini.py

54 lines
1.8 KiB
Python

import socket
import ssl
import urllib.parse
# See https://tildegit.org/solderpunk/gemini-demo-1/src/branch/master/gemini-demo.py
# See also https://gemini.circumlunar.space/docs/specification.html for more details
class Request():
def __init__(self, url):
self.url = url
parsed_url = urllib.parse.urlparse(self.url)
if ":" in parsed_url.netloc:
self.hostname, self.port = parsed_url.netloc.split(":")
else:
self.hostname = parsed_url.netloc
self.port = 1965
def makeRequest(self):
try:
# Create socket
s = socket.create_connection((self.hostname, self.port))
context = ssl.SSLContext()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
s = context.wrap_socket(s, server_hostname = self.hostname)
# Send request
s.sendall((self.url + '\r\n').encode("UTF-8"))
# Receive the answer
fp = s.makefile("rb")
# Read header
self.header = fp.readline().decode("UTF-8").strip()
self.status = self.header[0:2]
self.meta = self.header[3:]
# Handle errors
if self.status[0] == "4" or self.status[0] == "5":
# There is an error and no content so we display error code and error message
self.content = "Error " + self.status + " : " + self.meta
else:
# Read the content
self.content = fp.read().decode("UTF-8")
# Return the status code
return self.status
# Something went wrong during the connecgtion to the server
except Exception as err:
self.meta = err
self.content = str(err)
return "err"