GTK+ POST Sender
Nathan Osman — 11 years, 7 months ago


#!/usr/bin/env python
# Simple script to send POST data to a specified URL.
# Copyright (c) 2012 - Nathan Osman
from gi.repository import Gtk
from urllib2 import HTTPError, urlopen
class MainWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title='POST Sender')
self.set_border_width(10)
# Create the VBox that will contain the controls.
vbox = Gtk.Box(spacing=8, orientation=Gtk.Orientation.VERTICAL)
self.add(vbox)
# Create the URL entry.
label = Gtk.Label(label='URL:')
self.url = Gtk.Entry(text='http://')
url_box = Gtk.Box(spacing=8)
url_box.pack_start(label, False, False, 0)
url_box.pack_start(self.url, True, True, 0)
vbox.pack_start(url_box, False, False, 0)
# Create the content-type field.
label = Gtk.Label(label='Content-type:')
self.ct = Gtk.Entry(text='text/plain')
ct_box = Gtk.Box(spacing=8)
ct_box.pack_start(label, False, False, 0)
ct_box.pack_start(self.ct, True, True, 0)
vbox.pack_start(ct_box, False, False, 0)
# Create the label and text entry for the POST body.
label = Gtk.Label(label='POST data:', halign=Gtk.Align.START)
self.data = Gtk.TextView()
scrollwin = Gtk.ScrolledWindow(shadow_type=1)
scrollwin.set_size_request(0, 100)
scrollwin.add(self.data)
vbox.pack_start(label, False, False, 0)
vbox.pack_start(scrollwin, True, True, 0)
# ...and the same for the response.
label = Gtk.Label(label='Response:', halign=Gtk.Align.START)
self.response = Gtk.TextView()
scrollwin = Gtk.ScrolledWindow(shadow_type=1)
scrollwin.set_size_request(0, 100)
scrollwin.add(self.response)
vbox.pack_start(label, False, False, 0)
vbox.pack_start(scrollwin, True, True, 0)
# Create the spinner and send button.
send = Gtk.Button(label='Send')
send.connect("clicked", self.on_send_clicked)
self.spinner = Gtk.Spinner()
self.spinner.start()
send_box = Gtk.Box(spacing=8)
send_box.pack_start(send, False, False, 0)
send_box.pack_start(self.spinner, False, False, 0)
vbox.pack_start(send_box, False, False, 0)
# Show everything - and then hide the spinner.
self.show_all()
self.spinner.hide()
def on_send_clicked(self, widget):
# Display the spinner.
self.spinner.show()
# Make the request.
try:
b = self.data.get_buffer()
data = urlopen(self.url.get_text(),
data=b.get_text(b.get_start_iter(),
b.get_end_iter(), False)).read()
except HTTPError, e:
data = e.read()
self.response.get_buffer().set_text(data)
# Hide the spinner.
self.spinner.hide()
win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
Gtk.main()