def do_POST(self): # 홈페이지 if self.path != '/': CGIHTTPRequestHandler.do_POST(self) return # 응답 전송 self.send_response(200) self.end_headers() try: # 전송받은 데이터 파싱 data = self.rfile.read() data = data.decode('utf-8') data = urllib.parse.parse_qs(data) # 저장할 데이터 준비 unix_time = int(time.time()) device_id = data['device_id'][0] log_set = data['log_set'][0] # 데이터베이스 커밋 self.cursor.execute(''' INSERT OR IGNORE INTO scan (unix_time, device_id, log_set) VALUES (''' + str(unix_time) + ', ' + '"' + device_id + '", ' + '"' + log_set + '")') self.connector.commit() # 성공 응답 전송 self.send_response(202) self.end_headers() except Exception as err: logging.error(err) # 실패 응답 전송 self.send_response(400) self.end_headers()
def do_GET(self): ''' Present frontpage with user authentication. ''' if self.headers.get('Authorization') is None: self.do_authhead() self.wfile.write(b'no auth header received') elif self.headers.get('Authorization') == 'Basic ' + self.KEY: #SimpleHTTPRequestHandler.do_GET(self) CGIHTTPRequestHandler.do_GET(self) else: self.do_authhead() self.wfile.write(self.headers.get('Authorization')) self.wfile.write('not authenticated')
def do_POST(self): # set up "fake" chrooted CGI directory. self.cgi_directories = ["/"] cdir = os.path.abspath(os.curdir) os.chdir('cmp/') # fake the path to the compiler. self.path = self.path.split("/", 2)[2] # try to run the CGI program. CGIHTTPRequestHandler.do_POST(self) # restore. os.chdir(cdir) self.cgi_directories = ["/cmp/"]
def is_cgi(self): # Having a CGI suffix is really a big hint of being a CGI script. if urlparse(self.path).path.endswith('.cgi'): self.cgi_info = _url_collapse_path_split(self.path) return True else: return CGIHTTPRequestHandler.is_cgi(self)
def parse_request(self): ret = CGIHTTPRequestHandler.parse_request(self) print(self.requestline) print('client id %s ' % (self.client_address)) # print(self.headers.get('REMOTE_ADDR'), self.headers.get( # 'HTTP_VIA'), self.headers.get('HTTP_X_FORWARDED_FOR'), self.address_string(), self.client_address) return ret
def translate_path(self, path): """For paths starting with /cgi-bin/, serve from cgi_dir""" paths = path.split("/") if len(paths) > 1 and paths[0] == "" and paths[1] not in [ 'server', 'client', 'cgi-bin' ]: return os.path.join('', 'index.html') return CGIHTTPRequestHandler.translate_path(self, path)
def do_GET(self): """Answer to a GET request.""" path = urllib.parse.unquote(self.path, encoding='utf-8') print("do_GET for [%s]" % path) # HTML return if path == "/": # could be set to path="/index.html" self.mime_type = 'text/html' self.do_HEAD() content = """<html> <body><h1>Hello World</h1> <ul> <li>Path requested : %s</li> <li>Path modified : %s</li> </ul> </body> </html>""" % (self.path, path) self.wfile.write(content.encode('utf-8')) elif path == "/list": self.mime_type = 'text/html' self.do_HEAD() self.wfile.write("<html><body><ul>".encode('utf-8')) c = os.listdir(HTTPHandler.WWW) for f in c: r = "<li>%s</li>" % (f,) self.wfile.write(r.encode('utf-8')) self.wfile.write("</ul></body></html>".encode('utf-8')) else: self.mime_type = self.get_mime_type(path) if self.mime_type is None: self.error() elif self.mime_type == 'cgi_python': #import subprocess #result = subprocess.run(['python', HTTPHandler.WWW + os.sep + path], stdout=subprocess.PIPE) #self.wfile.write(result.stdout) CGIHTTPRequestHandler.cgi_directories = ['/', 'Code'] # ne marche pas CGIHTTPRequestHandler.do_POST(self) else: try: f = open(HTTPHandler.WWW + os.sep + path, 'rb') # os.curdir = '.' can be used (ou getcwd()) self.do_HEAD() self.wfile.write(f.read()) f.close() return except IOError: self.error()
def do_GET(self): current_dir = os.getcwd() target = os.path.join(current_dir, self.path[1:]) # Debug print('Path:', self.path) print('Could be:', target) # File requested? if os.path.isfile(target): # CGI script requested? if os.path.splitext(target)[1] == '.py': CGIHTTPRequestHandler.do_GET(self) return # no CGI else: self.serve_file(target) # no file else: self.serve_default()
def do_GET(self): if self.path == '/table/': # Обрабатываем, действия, происходящие при переходе по пути /table/ template = ''' <tr> <td>{}</td> <td>{}</td> <td>{}</td> <td>{}</td> <td>{}</td> <td>{}</td> <td>{}</td> </tr> ''' # Шаблон строки таблицы tbody = '' # Здесь будут все строки таблицы peoples cursor = db.cursor() # Создаем курсор перед выполением запроса cursor.execute(''' SELECT p.surname, p.name, p.patronymic, r.region, c.city, p.telephone, p.email FROM peoples p JOIN regions r ON p.regionId = r.id JOIN cities c ON (p.cityId=c.id AND p.regionId = c.regionId) ''') # Выполняем запрос SQL peoples = cursor.fetchall() # Забираем все найденные данные for person in peoples: tbody += template.format( *person ) # Постепенно заполняем tbody, подставляя в шаблон строки полученные с запроса данные table = open('peoples.html', encoding='utf-8').readlines( ) # Считываем html файл, который сдержит в себе саму таблицу с шапкой, но пока без тела table = ('%s' * len(table) % tuple(table)).format( tbody ) # подставляем полученное тело таблицы tbody в таблицу, считанную из html файла self.send_response(200) # ответ get запроса (ОК) self.send_header("Content-type", "text/html") # Тип получаемых данных - html self.end_headers() # конец заголовка ответа get запроса self.wfile.write( table.encode('cp1251') ) # Записываем тело ответа get запроса (это весь сформированный выше html файл с таблицей) else: CGIHTTPRequestHandler.do_GET( self ) # Если пользователь перешел не по /table/, то изменений нет
def guess_type(self, path): ## if path[-4:] == ".svg": ## print("image/xml+svg") ## return "image/xml+svg" ## elif path[-5:] == ".svgz": ## print("image/xml+svg") ## return "image/xml+svg" ## else: mimetype = CGIHTTPRequestHandler.guess_type(self, path) print(mimetype) return mimetype
def translate_path(self, path): if path in self.subst: return self.subst[path] else: return CGIHTTPRequestHandler.translate_path(self, path)
def do_GET(self): CGIHTTPRequestHandler.do_GET(self)
def do_POST(self): CGIHTTPRequestHandler.do_POST(self)
def translate_path(self, path): if path.find("/../") >= 0: path = "/" path = CGIHTTPRequestHandler.translate_path(self, path) return path
def translate_path(self, path): """For paths starting with /cgi-bin/, serve from cgi_dir""" elts = path.split('/') if len(elts)>1 and elts[0]=='' and elts[1]=='cgi-bin': return os.path.join(cgi_dir,*elts[2:]) return CGIHTTPRequestHandler.translate_path(self, path)
def run_cgi(self): onescan_signature = self.headers.get("x-onescan-signature") if onescan_signature: os.environ['X-ONESCAN-SIGNATURE'] = onescan_signature CGIHTTPRequestHandler.run_cgi(self)
def do_GET(self): CGIHTTPRequestHandler.do_GET(self) if self.path == '/quit.html': quit()
def _maybe_redirect(handler: CGIHTTPRequestHandler) -> None: if _path(handler) == _CGI_BIN: handler.path = str(POSIX_ROOT)
def translate_path(self, path): return CGIHTTPRequestHandler.translate_path(self, path)
def __init__(self, request, client_address, server): CGIHTTPRequestHandler.__init__(self, request, client_address, server)
def do_POST(self): CGIHTTPRequestHandler.do_POST(self) print("do_POST, path: %s %s" % (self.path, self.client_address[0])) pass
def translate_path(self, path): if self.respondedWithFile: if os.path.isfile(self.respondedWithFile): return self.respondedWithFile return CGIHTTPRequestHandler.translate_path(self, path)
from http.server import CGIHTTPRequestHandler CGIHTTPRequestHandler.test()