将参数(引用)传递给SimpleHTTPRequestHandler

时间:2015-08-03 21:54:44

标签: python multithreading python-3.x httpserver

我将以下简单脚本放在一起,该脚本显示文件系统中的图像。显示的图像可以通过GET请求切换到在单独的线程中运行的HTTPServer

一切正常,但是在全局范围内存储对UI对象的引用,然后从SimpleHTTPRequestHandler引用它似乎相当hacky和混乱。有没有办法将UI引用或show_image回调传递给Handler?或者更好的结构方式呢?任何想法将不胜感激..谢谢!

from gi.repository import Gtk, Gdk, GdkPixbuf, GObject
from socketserver import ThreadingMixIn
from http.server import SimpleHTTPRequestHandler, HTTPServer
from threading import Thread
import os
import signal

signal.signal(signal.SIGINT, signal.SIG_DFL)

IMAGE_DIRECTORY = 'images'
PORT = 8000


class ThreadingSimpleServer(ThreadingMixIn, HTTPServer):
    pass


class Handler(SimpleHTTPRequestHandler):
    def do_GET(self):
        response = 200 if ui.show_image(self.path[1:]) else 500
        self.send_response(response)
        self.end_headers()


class UI:
    def __init__(self):
        self.window = Gtk.Window()
        self.window.connect('destroy', self.quit)
        self.window.set_default_size(640, 480)
        self.background = Gtk.Image()
        self.window.add(self.background)
        self.server = ThreadingSimpleServer(('', PORT), Handler)

    def run(self):
        self.window.show_all()
        self.show_image('bird.jpg')
        Thread(target=self.server.serve_forever).start()
        Gtk.main()

    def show_image(self, image_name):
        image_path = os.path.join(IMAGE_DIRECTORY, image_name)
        try:
            pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(
                image_path,
                width=640,
                height=480,
                preserve_aspect_ratio=False)
            self.background.set_from_pixbuf(pixbuf)
            return True
        except:
            return False

    def quit(self, window):
        Gtk.main_quit()

ui = UI()
ui.run()

0 个答案:

没有答案