def cookies_partial(self, match): cookies = http.cookies.SimpleCookie() cookies['c1'] = 'other_cookie1' resp = self._start_response(200) for cookie in cookies.output(header='').split('\n'): resp.add_header('Set-Cookie', cookie.strip()) self._response(resp)
def cookies_partial(self, match): cookies = http.cookies.SimpleCookie() cookies["c1"] = "other_cookie1" resp = self._start_response(200) for cookie in cookies.output(header="").split("\n"): resp.add_header("Set-Cookie", cookie.strip()) self._response(resp)
def cookies(self, match): cookies = http.cookies.SimpleCookie() cookies['c1'] = 'cookie1' cookies['c2'] = 'cookie2' resp = self._start_response(200) for cookie in cookies.output(header='').split('\n'): resp.add_header('Set-Cookie', cookie.strip()) resp.add_header( 'Set-Cookie', 'ISAWPLB{A7F52349-3531-4DA9-8776-F74BC6F4F1BB}=' '{925EC0B8-CB17-4BEB-8A35-1033813B0523}; HttpOnly; Path=/') self._response(resp)
def cookies(self, match): cookies = http.cookies.SimpleCookie() cookies["c1"] = "cookie1" cookies["c2"] = "cookie2" resp = self._start_response(200) for cookie in cookies.output(header="").split("\n"): resp.add_header("Set-Cookie", cookie.strip()) resp.add_header( "Set-Cookie", "ISAWPLB{A7F52349-3531-4DA9-8776-F74BC6F4F1BB}=" "{925EC0B8-CB17-4BEB-8A35-1033813B0523}; HttpOnly; Path=/", ) self._response(resp)
def send_standard_headers(self, header_list=[], cachectrl='private', mimetype='text/html', x_dns_prefetch='off'): """ Send common HTTP headers plus a list of custom headers: - Cache-Control - Content-Type - X-DNS-Prefetch-Control This function does not send the HTTP/1.1 header, so ensure self.send_http_response() was called before Keyword arguments: header_list -- A list of custom headers to send, containing key-value tuples cachectrl -- The value of the 'Cache-Control' header field mimetype -- The MIME type to send as 'Content-Type' value """ if mimetype.startswith('text/') and ';' not in mimetype: mimetype += ('; charset = utf-8') self.send_header('Cache-Control', cachectrl) self.send_header('Content-Security-Policy', security.http_content_security_policy(self.server)) self.send_header('Content-Type', mimetype) self.send_header('X-DNS-Prefetch-Control', x_dns_prefetch) self.send_header('X-UA-Compatible', 'IE=Edge') # For old Windowses for header in header_list: self.send_header(header[0], header[1]) session_id = self.session.ui.html_variables.get('http_session') if session_id: cookies = http.cookies.SimpleCookie() cookies[self.server.session_cookie] = session_id cookies[self.server.session_cookie]['path'] = '/' cookies[self.server.session_cookie]['max-age'] = 24 * 3600 self.send_header(*cookies.output().split(': ', 1)) if mailpile.util.QUITTING: self.send_header('Connection', 'close') self.end_headers()
def do_POST(self): """ method: POST """ print("\ndebut POST sessions", self.sessions) input_data = self.rfile.read(int( self.headers['Content-Length'])).decode() input_data = json.loads(input_data) print(input_data) path = urllib.parse.urlparse(self.path).path # get the cookies cookieHeader = self.headers.get('Cookie') cookies = http.cookies.SimpleCookie(cookieHeader) user_data = self._get_user_data(cookieHeader, cookies) if path == "/action_servlet": try: user_data, result = self.actionServlet.fetch( user_data, input_data) if user_data != None: if "session-id" not in cookies: self._create_session(user_data, cookies) self.sessions[int(cookies["session-id"].value)] = user_data self.send_response(HTTPStatus.OK) self.send_header('Content-type', "application/javascript") self.send_header("Access-Control-Allow-Origin", "*") if cookies != None: self.send_header('Set-Cookie', cookies.output(header='')) self.end_headers() self.wfile.write(result.encode("utf8")) except Exception as ex: self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR, "Internal Server Error") raise ex
# coding = utf-8 import http.cookies cookies = http.cookies.SimpleCookie('name=louis') cookies['pass'] = '******' cookies.load('work=swim') print(cookies.output()) out = cookies.output() print(type(out)) print(out.encode('utf-8'))
def _send_headers(self): """ define the common headers for HEAD & GET requests """ mimetypes = { '.html': "text/html", '.css': "text/css", '.png': "image/png", '.gif': "image/gif", '.jpg': "image/jpeg", '.jpeg': "image/jpeg", '.ico': "image/x-icon", '.svg': "image/svg+xml", '.js': "application/javascript", '.json': "application/json" } path = urllib.parse.urlparse(self.path).path # get the cookies cookieHeader = self.headers.get('Cookie') cookies = http.cookies.SimpleCookie(cookieHeader) ADMIN_PAGES = { "/admin.html", "/create_event.html", "/event_details.html" } AUTHENTICATION_PAGE = "login.html" MAIN_ADMIN_PAGE = "admin.html" INDEX_PAGE = "index.html" user_data = self._get_user_data(cookieHeader, cookies) if path == "/": path = INDEX_PAGE # Check file extension and set the right mime type sendReply = False mimetype = "text/html" for extension, type in mimetypes.items(): if path.endswith(extension): mimetype = type sendReply = True break if not sendReply: # Forbidden path = "error403.html" if path in ADMIN_PAGES: if user_data == None: self.send_response(HTTPStatus.FOUND) self.send_header("Location", AUTHENTICATION_PAGE) self.end_headers() return None try: f = open(os.curdir + os.sep + path, mode='rb') except IOError: self.send_error(HTTPStatus.NotFound, 'File Not Found: %s' % self.path) return None # From https://github.com/python/cpython/blob/master/Lib/http/server.py try: fs = os.fstat(f.fileno()) # Use browser cache if possible if ("If-Modified-Since" in self.headers and "If-None-Match" not in self.headers): # compare If-Modified-Since and time of last file modification try: ims = email.utils.parsedate_to_datetime( self.headers["If-Modified-Since"]) except (TypeError, IndexError, OverflowError, ValueError): # ignore ill-formed values pass else: if ims.tzinfo is None: # obsolete format with no timezone, cf. # https://tools.ietf.org/html/rfc7231#section-7.1.1.1 ims = ims.replace(tzinfo=datetime.timezone.utc) if ims.tzinfo is datetime.timezone.utc: # compare to UTC datetime of last modification last_modif = datetime.datetime.fromtimestamp( fs.st_mtime, datetime.timezone.utc) # remove microseconds, like in If-Modified-Since last_modif = last_modif.replace(microsecond=0) if last_modif <= ims: self.send_response(HTTPStatus.NOT_MODIFIED) if cookies != None: self.send_header('Set-Cookie', cookies.output(header='')) self.end_headers() f.close() return None self.send_response(HTTPStatus.OK) self.send_header("Content-type", mimetype) self.send_header("Content-Length", str(fs[6])) self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) if cookies != None: self.send_header('Set-Cookie', cookies.output(header='')) self.end_headers() return f except: f.close() raise