execfile
을 사용하지 않는 것이 좋습니다. 대신 내장 된 __import__
함수를 사용하여 요청한 파이썬 파일을 모듈로 동적으로 가져올 수 있습니다. 여기에 그냥 쓴 테스트하는 완벽한 작업 예제 :이 경우에 따라서
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
filename = self.path.lstrip("/")
self.wfile.write("You requested " + filename + "\n\n")
if filename.endswith(".py"):
pyname = filename.replace("/", ".")[:-3]
module = __import__(pyname)
self.wfile.write(module.do_work())
HTTPServer(("",8080), Handler).serve_forever()
, 누군가가 http://localhost:8080/some_page 다음 "당신은 some_page 요청"인쇄됩니다 방문 할 경우.
그러나 http://localhost:8080/some_module.py을 요청하면 some_module.py
파일을 Python 모듈로 가져오고 해당 모듈에 do_work
함수가 호출됩니다. 해당 모듈 코드
def do_work():
return "Hello World!"
을 포함하고 해당 요청을한다면, 그 결과 페이지는
You requested some_module.py
Hello World!
이
는 그런 것들을 처리하기위한 좋은 출발점이 될해야 할 것이다. 제쳐두고,보다 고급 웹 서버를 원할 경우
CherryPy을 적극 권장합니다.