Handle return value

This commit is contained in:
Romain de Laage 2020-12-03 18:18:29 +01:00
parent 345c3d4d6a
commit 03e7a0abfc
Signed by: rdelaage
GPG Key ID: 534845FADDF0C329
2 changed files with 46 additions and 11 deletions

View File

@ -3,6 +3,7 @@ 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):
@ -16,22 +17,33 @@ class Request():
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")
header = fp.readline().decode("UTF-8").strip()
status, mime = header.split()
print("STATUS : " + status)
print("MIME : " + mime)
body = fp.read().decode("UTF-8")
return body
# 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
except Exception as err:
print(err)

27
main.py
View File

@ -1,4 +1,6 @@
import tkinter as tk
import tkinter.messagebox
import tkinter.simpledialog
import gemini
# See https://tildegit.org/solderpunk/gemini-demo-1/src/branch/master/gemini-demo.py
@ -12,10 +14,31 @@ class Application():
self.current_URL = "about:home"
def updateContent(self):
# Get url asked
self.current_URL = self.nav_bar.getURL()
# New request
r = gemini.Request(self.current_URL)
text = r.makeRequest()
self.content.setContent(text)
status = r.makeRequest()
# The server asked for user input
if status[0] == "1":
user_input = tkinter.simpledialog.askstring("User input", "The server asked for " + r.meta + ".")
self.nav_bar.URL_var.set(self.current_URL + "?" + user_input)
self.updateContent()
# If server asked for redirection
elif status[0] == "3":
# Ask to user
confirm = tkinter.messagebox.askyesno("Server redirection", "This server ask for redirection to " + r.meta + ". Follow ?")
# If he accepted
if confirm:
self.nav_bar.URL_var.set(r.meta)
self.updateContent()
# The server asked for client certificate, unsupported
elif status[0] == "6":
tkinter.messagebox.showerror("Client certificate required", "Error " + status + " : " + r.meta)
else:
self.content.setContent(r.content)
class NavBar():
def __init__(self, parent):