def check_xsrf_cookie(self): if self.is_request_from_web() is False: return token = self.get_xsrf() if not token: self.on_response_fail(self.http_response_code_fail, "'_xsrf' argument missing from POST") return _, token, _ = self._decode_xsrf_token(token) _, expected_token, _ = self._get_raw_xsrf_token() if not _time_independent_equals(utf8(token), utf8(expected_token)): self.on_response_fail(self.http_response_code_fail, "XSRF cookie does not match POST argument")
def write(self, chunk): """Writes the given chunk to the output buffer. Checks for curl in the user-agent and if set, provides indented output if returning JSON. To write the output to the network, use the flush() method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as a different ``Content-Type``, call set_header *after* calling write()). :param mixed chunk: The string or dict to write to the client """ if self._finished: raise RuntimeError("Cannot write() after finish(). May be caused " "by using async operations without the " "@asynchronous decorator.") if isinstance(chunk, dict): options = {'ensure_ascii': False} if 'curl' in self.request.headers.get('user-agent'): options['indent'] = 2 options['sort_keys'] = True chunk = json.dumps(chunk, **options).replace("</", "<\\/") + '\n' self.set_header("Content-Type", "application/json; charset=UTF-8") self._write_buffer.append(web.utf8(chunk))
def model_json(self): output = self.model.as_dict() for key in self.REPLACE_ATTRIBUTES: output[key] = self.REPLACE_ATTRIBUTES[key](output[key]) for key in self.STRIP_ATTRIBUTES: del output[key] return web.utf8(escape.json_encode(output))
def write(self, chunk, status=None): """Writes the given chunk to the output buffer. To write the output to the network, use the flush() method below. If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be ``application/json``. (if you want to send JSON as a different ``Content-Type``, call set_header *after* calling write()). Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx """ if self._finished: raise RuntimeError("Cannot write() after finish(). May be caused " "by using async operations without the " "@asynchronous decorator.") if isinstance(chunk, dict): chunk = jsonutil.json_encode(chunk) elif isinstance(chunk, list): chunk = jsonutil.json_encode({"list": chunk}) else: chunk = jsonutil.json_encode({"result": chunk}) chunk = utf8(chunk) self._write_buffer.append(chunk) self.set_header("Content-Type", "application/json; charset=UTF-8") if status is not None: self.set_status(status)
def finish(self, chunk=None): if self.request.path != "/metrics": self.stop_timer() self._return = chunk if chunk is not None: try: chunk = json_encode(chunk) callback = self.get_argument('callback', None) if callback is None: # call base class finish method super(RESTfulHandler, self).finish(chunk) else: jsonp = "{jsfunc}({json})".format(jsfunc=callback, json=chunk) self.set_header('Content-Type', 'application/javascript') self.write(jsonp) super(RESTfulHandler, self).finish() except: super(RESTfulHandler, self).finish(chunk) else: try: callback = utf8(self.get_argument('callback', None)) self._write_buffer.insert(0, callback + '(') self._write_buffer.append(')') # call base class finish method super(RESTfulHandler, self).finish(chunk) except: super(RESTfulHandler, self).finish(chunk)
def set_cookie(self, name, value, domain=None, expires=None, path='/', expires_days=None, **kwargs): """Sets the given cookie name/value with the given options. Additional keyword arguments are set on the Cookie.Morsel directly. See http://docs.python.org/library/cookie.html#morsel-objects for available attributes. """ if domain is None: domain = '.%s' % tld_name(self.request.host) name = utf8(name) value = utf8(value) if re.search(r"[\x00-\x20]", name + value): # Don't let us accidentally inject bad stuff raise ValueError('Invalid cookie %r: %r' % (name, value)) if not hasattr(self, '_new_cookies'): self._new_cookies = [] new_cookie = Cookie.BaseCookie() self._new_cookies.append(new_cookie) new_cookie[name] = value if domain: new_cookie[name]['domain'] = domain if expires_days is not None and not expires: expires = datetime.datetime.utcnow() + datetime.timedelta( days=expires_days) if expires: if type(expires) is not str: timestamp = calendar.timegm(expires.utctimetuple()) expires = email.utils.formatdate(timestamp, localtime=False, usegmt=True) new_cookie[name]['expires'] = expires else: new_cookie[name]['expires'] = 'Tue, 01 Jan 2030 00:00:00 GMT' if path: new_cookie[name]['path'] = path for k, v in kwargs.iteritems(): new_cookie[name][k] = v
def set_cookie(self, name, value, domain=None, expires=None, path='/', expires_days=None, **kwargs): """Sets the given cookie name/value with the given options. Additional keyword arguments are set on the Cookie.Morsel directly. See http://docs.python.org/library/cookie.html#morsel-objects for available attributes. """ if domain is None: domain = '.%s'%tld_name(self.request.host) name = utf8(name) value = utf8(value) if re.search(r"[\x00-\x20]", name + value): # Don't let us accidentally inject bad stuff raise ValueError('Invalid cookie %r: %r' % (name, value)) if not hasattr(self, '_new_cookies'): self._new_cookies = [] new_cookie = Cookie.BaseCookie() self._new_cookies.append(new_cookie) new_cookie[name] = value if domain: new_cookie[name]['domain'] = domain if expires_days is not None and not expires: expires = datetime.datetime.utcnow() + datetime.timedelta( days=expires_days) if expires: if type(expires) is not str: timestamp = calendar.timegm(expires.utctimetuple()) expires = email.utils.formatdate( timestamp, localtime=False, usegmt=True ) new_cookie[name]['expires'] = expires else: new_cookie[name]['expires'] = 'Tue, 01 Jan 2030 00:00:00 GMT' if path: new_cookie[name]['path'] = path for k, v in kwargs.iteritems(): new_cookie[name][k] = v
def finish(self, chunk=None): """Finishes this response, ending the HTTP request.""" assert not self._finished if chunk: self.write(chunk) # get client callback method callback = utf8(self.get_argument(self.CALLBACK)) # format output with jsonp self._write_buffer.insert(0, callback + '(') self._write_buffer.append(')') # call base class finish method super(CPSHandler, self).finish() # chunk must be None