2012-10-18 2 views
13

파이썬의 SimpleHTTPServer를 사용하여 Ajax 호출 등을 통해 리소스를로드해야하는 모든 종류의 웹 애플리케이션을 로컬 개발하고 싶습니다.SimpleHTPServer가 쿼리 문자열을 요청할 때 왜 쿼리 문자열로 리디렉션되는 이유는 무엇입니까?

URL에 쿼리 문자열을 사용할 때 서버는 항상 슬래시가있는 동일한 URL로 리디렉션됩니다. 추가됨.

예를 들어 /folder/?id=1은 HTTP 301 응답을 사용하여 /folder/?id=1/으로 리디렉션됩니다.

간단히 python -m SimpleHTTPServer을 사용하여 서버를 시작하십시오.

리디렉션 동작을 어떻게 없앨 수 있습니까? 이것은 Python 2.7.2입니다.

+0

SimpleHTTPServer는 파일 만 제공합니다. 요청에서 매개 변수를 처리하기 위해 다른 것을 사용하십시오. –

답변

3
에 대해 일치라고

오케이. Morten의 도움으로 필자는이 모든 것이 필요한 것 같습니다 : 단순히 쿼리 문자열을 무시하고 정적 파일을 제공하면됩니다.

import SimpleHTTPServer 
import SocketServer 

PORT = 8000 


class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): 

    def __init__(self, req, client_addr, server): 
     SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, req, client_addr, server) 

    def do_GET(self): 
     # cut off a query string 
     if '?' in self.path: 
      self.path = self.path.split('?')[0] 
     SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) 


class MyTCPServer(SocketServer.ThreadingTCPServer): 
    allow_reuse_address = True 

if __name__ == '__main__': 
    httpd = MyTCPServer(('localhost', PORT), CustomHandler) 
    httpd.allow_reuse_address = True 
    print "Serving at port", PORT 
    httpd.serve_forever() 
+0

이것은 url 매개 변수를 존중하지 않는 것 같습니다. 그것은 여전히 ​​'/'를 쿼리 매개 변수 다음에 추가합니다. –

2

리디렉션이 어떻게 생성되는지 잘 모르겠습니다 ... 아주 기본적인 SimpleHTTPServer를 구현하려했는데 쿼리 문자열 매개 변수를 사용할 때 리디렉션이 발생하지 않습니다.

self.path.split("/")과 같은 작업을 수행하고 요청을 처리하기 전에 경로를 처리 하시겠습니까?는

좋아 당신은을 사용하지 않은, 그래서 만약 : - :

import SocketServer 
import SimpleHTTPServer 
import os 


class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): 
    def folder(self): 
     fid = self.uri[-1].split("?id=")[-1].rstrip() 
     return "FOLDER ID: %s" % fid 

    def get_static_content(self): 
     # set default root to cwd 
     root = os.getcwd() 
     # look up routes and set root directory accordingly 
     for pattern, rootdir in ROUTES: 
      if path.startswith(pattern): 
       # found match! 
       path = path[len(pattern):] # consume path up to pattern len 
       root = rootdir 
       break 
     # normalize path and prepend root directory 
     path = path.split('?',1)[0] 
     path = path.split('#',1)[0] 
     path = posixpath.normpath(urllib.unquote(path)) 
     words = path.split('/') 
     words = filter(None, words) 
     path = root 
     for word in words: 
      drive, word = os.path.splitdrive(word) 
      head, word = os.path.split(word) 
      if word in (os.curdir, os.pardir): 
       continue 
      path = os.path.join(path, word) 
      return path 

    def do_GET(self): 
     path = self.path 
     self.uri = path.split("/")[1:] 

     actions = { 
      "folder": self.folder, 
     } 
     resource = self.uri[0] 
     if not resource: 
      return self.get_static_content() 
     action = actions.get(resource) 
     if action: 
      print "action from looking up '%s' is:" % resource, action 
      return self.wfile.write(action()) 
     SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) 


class MyTCPServer(SocketServer.ThreadingTCPServer): 
    allow_reuse_address = True 

httpd = MyTCPServer(('localhost', 8080), CustomHandler) 
httpd.allow_reuse_address = True 
print "serving at port", 8080 
httpd.serve_forever() 

그것을 밖으로 시도 :>"FOLDER ID: 500x"

편집

HTTP GET /folder/?id=500x 이 코드는 내가 생각하는 원하는 것을 SimpleHTTPServer-stuff 전에 기본적으로 기본 요청 처리기를 구현하고 do_GET(), do_PUT(), do_POST() 등을 구현합니다.

내가 보통하는 일은 요청 문자열 (re를 사용하여), 패턴 일치를 구문 분석하고 요청 처리기를 찾을 수 있는지 확인한 다음 가능한 경우 정적 요청에 대한 요청으로 처리합니다.

당신은 당신이 요청이 파일 저장소를 일치하는 경우, 당신은 주변에 일치하는이 패턴을 플립해야 가능하다면 정적 콘텐츠를 제공하고, FIRST보고 싶어하지 않을 경우, 다음 핸들러 :

+0

먼저 감사합니다! 그것은 리디렉션을 방지 할 수 있음을 보여줍니다.그러나 마치이 핸들러가 정적 파일을 제공하지 않는 것처럼 보입니다. 기본적으로 원하는 것은 정적 파일로 사용할 수있는 모든 경로를 제공하여 쿼리 문자열 부분을 완전히 무시하는 것입니다. – Marian

+0

do_GET() 메소드에 로직을 추가하기 만하면, –

+0

을 사용하여 web.py를 사용하는 것으로 간주되는 업데이트를 만들었습니까? 정말 가볍고 위 코드의 일부일 것입니다. –

3

쿼리 매개 변수들이 정상적으로 유지하려면이 작업을 수행 할 수있는 올바른 방법은 직접 대신 SimpleHTTPServer을시키기의 파일 이름에 대한 요청을 들어 당신의 index.html

로 리디렉션 있는지 확인하는 것입니다 예 : http://localhost:8000/?param1=1은 리디렉션 (301)을 수행하고 URL을 http://localhost:8000/?param=1/으로 변경하여 쿼리 매개 변수가 엉망입니다.

그러나 http://localhost:8000/index.html?param1=1 (색인 파일을 명시 적으로 만들기) 올바르게로드됩니다.

따라서 URL 리디렉션을 수행하면 SimpleHTTPServer이 문제를 해결하지 못합니다.