def write(self, chunk): if isinstance(chunk, dict) and self.settings.get('debug'): RequestHandler.write(self, json.dumps(chunk, indent=4)) else: RequestHandler.write(self, chunk) if isinstance(chunk, dict): self.set_header('Content-Type', self._ct('json'))
def write_error(self, status_code, **kwargs): try: error_env = Environment(loader = FileSystemLoader(self.__project_path + '/public')) temp = error_env.get_template(str(status_code) + '.html') self.write(temp.render()) except TemplateNotFound: RequestHandler.write_error(self, status_code, **kwargs)
def write_error(self, *args, **kwargs): ''' Must override base write error to stop uncaught HTTP errors from clearing CORS headers ''' self.write_cors_headers() RequestHandler.write_error(self, *args, **kwargs)
def _execute(self, transforms, *args, **kwargs): ''' select base handler for self ''' with LogicContext(): if isinstance(self, WebSocketHandler): WebSocketHandler._execute(self, transforms, *args, **kwargs) elif isinstance(self, RequestHandler): RequestHandler._execute(self, transforms, *args, **kwargs)
def write(self, payload, passthru=False): if passthru: return RequestHandler.write(self, payload) self.set_header('Content-Type', 'application/json; charset=UTF-8') RequestHandler.write(self, json.dumps(payload, indent=options.debug and 2 or None, default=_ToJSONMixin.json_default))
def _handle_request_exception(self, exc): options = { "user": {"id": self.request.remote_ip}, "context": self._get_context(), "request": { "url": self.request.full_url(), "method": self.request.method, "arguments": self.request.arguments, }, "severity_reason": { "type": "unhandledExceptionMiddleware", "attributes": { "framework": "Tornado" } } } # Notify bugsnag, unless it's an HTTPError that we specifically want # to ignore should_notify_bugsnag = True if type(exc) == HTTPError: ignore_status_codes = self.bugsnag_ignore_status_codes() if ignore_status_codes and exc.status_code in ignore_status_codes: should_notify_bugsnag = False if should_notify_bugsnag: bugsnag.auto_notify(exc, **options) # Call the parent handler RequestHandler._handle_request_exception(self, exc)
def write_error(self, status_code, **kwargs): if status_code == 404: self.render('404.html') elif status_code >= 500 and status_code < 600: self.render('500.html') else: RequestHandler.write_error(self, status_code, **kwargs)
def __init__(self, application, request): RequestHandler.__init__(self, application, request) self._current_user = None self.middleware_manager = MiddlewareManager(self) self._is_threaded = False self._is_whirlwind_finished = False self.view = {}
def test_on_request(self): app = Application() request = HTTPRequest('POST', '/collector?hello=world', body=b"foo=bar&bar=foo", headers={'Content-Type': 'application/x-www-form-urlencoded'}, connection=get_dummy_connection()) handler = RequestHandler(app, request) handler.run = Run() self.collector.on_request(handler, handler.run) self.assertEquals({ 'body_arguments': {}, 'cookies': '', 'headers': {'Content-Type': 'application/x-www-form-urlencoded'}, 'host': '127.0.0.1', 'method': 'POST', 'path': '/collector', 'protocol': 'http', 'query': 'hello=world', 'body': 'foo=bar&bar=foo', 'query_arguments': {'hello': ['world']}, 'remote_ip': '127.0.0.1', 'uri': '/collector?hello=world', 'version': 'HTTP/1.0', 'controller': {'class': False, 'file': False, 'line': False, 'method': False}, 'route': False, 'status_code': False, }, handler.run.get_metric('request'))
def prepare(self): """ Prepare the request """ RequestHandler.prepare(self) self.model.session.expunge_all() # Always start a request fresh. self._call_preprocessor()
def check_xsrf_cookie(self): if self.application.testing_key \ and self.request.headers.get('X-Testing-Key') \ == self.application.testing_key: return RequestHandler.check_xsrf_cookie(self)
def initialize(self, html_template=None, js_template=None, cors_origins=None): RequestHandler.initialize(self) self.set_cors_methods("OPTIONS,GET,POST") if cors_origins: self.set_cors_whitelist(cors_origins) self._html_template = html_template self._js_template = js_template
def finish(self, chunk=None): ''' 重写服务的finish, 并存储返回值 ''' RequestHandler.finish(self, chunk=chunk) self.return_value = chunk
def render(self, template_name, **kwargs): params = dict() for key, val in self.request.arguments.items(): params[key] = ','.join(val) if isinstance(val, list) else val kwargs["params"] = params kwargs["json_dict"] = json_to_dict RequestHandler.render(self, template_name, **kwargs)
def set_user_cookie(app, request, username): from tornado.web import RequestHandler r = RequestHandler(app, request) r.set_secure_cookie('user', username) authcookie = r._new_cookies[0] cookiestring = authcookie.items()[0][1] request.cookies.update({'user': cookiestring}) return request
def write_error(self, status_code, **kwargs): if 'exc_info' in kwargs: typ, value, tb = kwargs['exc_info'] if isinstance(value, PermissionError): self.set_status(403) self.write('PermissionError') return RequestHandler.write_error(self, status_code, **kwargs)
def write_error(self, code, **kwargs): exc_type, exc_value, _exc_tb = kwargs.get('exc_info', [None] * 3) if exc_type is not None and issubclass(exc_type, HTTPError): self.set_header('Content-Type', 'text/plain') if exc_value.log_message: self.write(exc_value.log_message + '\n') else: RequestHandler.write_error(self, code, **kwargs)
def __init__(self, application, request): RequestHandler.__init__(self, application, request) self._current_user = None self.middleware_manager = MiddlewareManager(self) self._is_threaded = False self._is_whirlwind_finished = False self.view = dotdict() self.db = Mongo.db.ui #@UndefinedVariable
def __init__(self, application, request, **kwargs): RequestHandler.__init__(self, application, request, **kwargs) _headers = self.request.headers self.mn_server = _headers.get(MN_INSTANCE_SERVER,'') self.mn_port = _headers.get(MN_INSTANCE_PORT,'') self.ProductID = _headers.get(MN_PRODUCT_ID,'') self._instance = application._instance self._search_count = 2 self._not_found_callback = self._response_no_agent
def get(self, filename): index = RequestHandler.get_argument(self, name='index', default='papers') # allow query to be passed to body: body = RequestHandler.get_argument(self, name='body', default={'query': {'match_all': {}}}) response = es.search(index=index, body=body) hits = response['hits']['hits'] self.write(json.dumps(hits))
def render(self, template_name, **kwargs): kwargs.update(session=self.session) kwargs.update(config=self.configuration) kwargs.update(current_page=self.current_page) kwargs.update(has_nav=self.has_nav) kwargs.update(html5=self.html5) kwargs.update(rendered_time=self.rendered_time) kwargs.update(prefix_url=self.prefix_url) RequestHandler.render(self, template_name, **kwargs)
def write(self, value): # note that serving a json list is a security risk # This is meant to be serving public-read only data only. if isinstance(value, (dict, list, tuple)): value_str = json.dumps(value) RequestHandler.write(self, value_str) self.set_header('Content-type', 'application/json; charset=utf-8') else: RequestHandler.write(self, value)
def render(self, *args, **kwargs): # każde wywołanie render przekazuje dodatkowo następujące obiekty mykwargs = { "get_flash": self.get_flash, "is_flash": self.is_flash, "session": self.session, } # wywołaj render od ojca RequestHandler.render(self, *args, **dict(kwargs.items() + mykwargs.items()))
def finish(self, chunk=None): if not self.request.connection.stream.closed(): RequestHandler.finish(self, chunk) access_logger.info('', extra={'version': 'V' + twork.version, 'status': self.get_status(), 'method': self.request.method, 'remoteip': self.request.remote_ip, 'uri': self.request.uri, 'rt': '%.6f' % self.request.request_time()})
def initialize(self): 'Hook for subclass initialization' commit_db() self.uuid = self.gen_uuid() self.request.uuid = self.uuid self.request.o_method = self.request.method method = self.get_argument('_method', None) if method is not None: self.request.method = str(method.upper()) RequestHandler.initialize(self)
def write_error(self, status_code, **kwargs): if status_code == 403: script = str(self.request.uri).strip() token = script.strip('/') self.finish("<html><title>%(code)d: %(message)s</title>" "<body>%(code)d: %(message)s</body></html>" % { "code": status_code, "message": "PeerPlot failed to create a session, please try again later" }) return RequestHandler.write_error(self, status_code, **kwargs)
def __init__(self, application, request, **kwargs): BaseRequestHandler.__init__(self, application, request, **kwargs) self.db = application.database if not self.template_env: self.template_env = Environment(loader=FileSystemLoader(convention.template_path)) self.session = None session_id = self.get_cookie(self.SESSIONID) if session_id: self.session = Session.get_session(session_id)
def __init__(self, application, request): RequestHandler.__init__(self, application, request) self._current_user = None # self._username = None # self._keep_logged_in=False self.middleware_manager = MiddlewareManager(self) self._is_threaded = False self._is_toolstar_finished = False self._is_threaded = False self.view = dotdict() self.db = Mongo.ui
def render(self, template_name, **kwargs): error = self.get_secure_cookie("errmsg") status = self.get_secure_cookie("statmsg") self.clear_cookie("errmsg") self.clear_cookie("statmsg") #session.clear() RequestHandler.render(self, template_name, is_admin=self.user_is_admin(), errmsg=error, statmsg=status, **kwargs)
def initialize(self, html_template=None, js_template=None, http_origins=None, ws_url=None): RequestHandler.initialize(self) self.set_cors_methods("OPTIONS,GET,POST") if http_origins: self.set_cors_whitelist(http_origins) self._html_template = html_template self._js_template = js_template self._ws_url = ws_url if ws_url else ''
def get(self, *args, **kwargs): messages = [] url = RequestHandler.reverse_url(self, "register") return self.render("index/register.html", url=url, messages=messages)
def __init__(self, application, request, **kwargs): RequestHandler.__init__(self, application, request, **kwargs) # TODO: REMOVE? self.access_control_allow()
def __init__(self, *args, **kwargs): RequestHandler.__init__(self, *args, **kwargs) self.cfg = Config()
def __init__(self, application, request, wrapper, fuzzer): RequestHandler.__init__(self, application, request) self.wrapper = wrapper self.fuzzer = fuzzer
def write(self, chunk, status=None): if status: self.set_status(status) RequestHandler.write(self, chunk)
def prepare(self): BaseHandler.prepare(self) JsonRequestResponseMixin.prepare(self) RequestHandler.prepare(self)
def finish(self, chunk=None): # add before-response hooks self._chunk = chunk self.tmiddleware.before_response_hooks(self._chunk) RequestHandler.finish(self, self._chunk)
def get_secure_cookie(self, name, if_none=""): cook = RequestHandler.get_secure_cookie(self, name) if cook == None: return if_none return cook
def track_page_view(handler): """ // Track a page view, updates all the cookies and campaign tracker, // makes a server side request to Google Analytics and writes the transparent // gif byte data to the response. """ time_tup = time.localtime(time.time() + COOKIE_USER_PERSISTENCE) # set some useful items in environ: x_utmac = handler.request.arguments.get('x_utmac', '') domain = handler.request.headers.get('Host', '') # Get the referrer from the utmr parameter, this is the referrer to the # page that contains the tracking pixel, not the referrer for tracking # pixel. document_referer = handler.request.arguments.get('utmr', []) if not document_referer or document_referer == "0": document_referer = "-" else: document_referer = document_referer[0] document_referer = unquote(document_referer) document_path = handler.request.arguments.get('utmp', '') if document_path: document_path = document_path[0] document_path = unquote(document_path) account = handler.request.arguments.get('utmac', '') if account: account = account[0] user_agent = handler.request.headers.get('User-Agent', '') # // Try and get visitor cookie from the request. cookie = RequestHandler.get_cookie(handler, COOKIE_NAME) guidheader = handler.request.headers.get("X-DCMGUID", '') if not guidheader: guidheader = handler.request.headers.get("X-UP-SUBNO", '') if not guidheader: guidheader = handler.request.headers.get("X-JPHONE-UID", '') if not guidheader: guidheader = handler.request.headers.get("X-EM-UID", '') visitor_id = get_visitor_id(guidheader, account, user_agent, cookie) # // Always try and add the cookie to the response. # cookie = SimpleCookie() # cookie[COOKIE_NAME] = visitor_id # morsel = cookie[COOKIE_NAME] # morsel['expires'] = time.strftime('%a, %d-%b-%Y %H:%M:%S %Z', time_tup) # morsel['path'] = COOKIE_PATH expires = datetime(*time_tup[0:6]) RequestHandler.set_cookie(handler, COOKIE_NAME, visitor_id, expires=expires) utm_gif_location = "http://www.google-analytics.com/__utm.gif" i = handler.request.headers.get( "X-Forwarded-For", handler.request.headers.get("X-Real-Ip", None)) if not i: i = handler.request.remote_ip i = i.split(",")[0] for utmac in [account, x_utmac]: if not utmac: continue # // Construct the gif hit url. utm_url = ( utm_gif_location + "?" + "utmwv=" + VERSION + "&utmn=" + get_random_number() + "&utmhn=" + quote(domain) + "&utmsr=" + handler.request.arguments.get('utmsr', [''])[0] + "&utme=" + handler.request.arguments.get('utme', [''])[0] + "&utmr=" + quote(document_referer) + "&utmp=" + quote(document_path) + "&utmac=" + utmac + "&utmcc=__utma%3D999.999.999.999.999.1%3B" + "&utmvid=" + visitor_id + "&utmip=" + get_ip(i) + "&utmul=" + handler.request.headers.get("Accept-Language", '-') + "&utmcs=" + handler.request.headers.get("Accept-Charset", '-')) # dbgMsg("utm_url: " + utm_url) send_request_to_google_analytics(utm_url, handler) # // If the debug parameter is on, add a header to the response that contains # // the url that was used to contact Google Analytics. # headers = [('Set-Cookie', str(cookie).split(': ')[1])] headers = [] if handler.request.arguments.get('utmdebug', False): headers.append(('X-GA-MOBILE-URL', utm_url)) # Finally write the gif data to the response response = write_gif_data() response_headers = response['response_headers'] response_headers.extend(headers) return response
def __init__(self, application, request, **kwargs): RequestHandler.__init__(self, application, request, **kwargs) # init tmiddleware self.tmiddleware = TMiddleware(self)
def __init__(self, application, request, status_code): RequestHandler.__init__(self, application, request) self.set_status(status_code)
def __init__(self, application, request, **kwargs): RequestHandler.__init__(self, application, request) self._payload = kwargs
async def send_file(h_request: RequestHandler, fp: GridOut, cache_time: int = 0): # If-Modified-Since header is only good to the second. modified = fp.upload_date.replace(microsecond=0) h_request.set_header("Last-Modified", modified) # MD5 is calculated on the MongoDB server when GridFS file is created h_request.set_header("Etag", f'"{fp.md5}"') mime_type = fp.content_type if not mime_type: mime_type = fp.metadata.get('contentType') # Starting from here, largely a copy of StaticFileHandler if mime_type: h_request.set_header("Content-Type", mime_type) if cache_time > 0: h_request.set_header( "Expires", datetime.utcnow() + timedelta(seconds=cache_time)) h_request.set_header("Cache-Control", f"max-age={cache_time}") else: h_request.set_header("Cache-Control", "public") # Check the If-Modified-Since, and don't send the result if the # content has not been modified ims_value = h_request.request.headers.get("If-Modified-Since") if ims_value is not None: date_tuple = email.utils.parsedate(ims_value) # If our MotorClient is tz-aware, assume the naive ims_value is in # its time zone. if_since = datetime.fromtimestamp( time.mktime(date_tuple)).replace(tzinfo=modified.tzinfo) if if_since >= modified: h_request.set_status(304) return # Same for Etag etag = h_request.request.headers.get("If-None-Match") if etag is not None and etag.strip('"') == fp.md5: h_request.set_status(304) return h_request.set_header("Content-Length", fp.length) await fp.stream_to_handler(h_request) h_request.finish()
def __init__(self, rpc_handler, *args, **kwargs): if not issubclass(rpc_handler, RpcHandler): raise Exception("Argument rpc_handler must be a subclass of " + "RpcHandler") self.rpc_handler = rpc_handler() RequestHandler.__init__(self, *args, **kwargs)
def _handle_request_exception(self, e): RequestHandler._handle_request_exception(self,e) if self.settings.get('debug_pdb') and not isinstance(e, socket.error): import pdb pdb.post_mortem()
def get_template_namespace(self, *args, **kwargs): res = RequestHandler.get_template_namespace(self, *args, **kwargs) res.update(self.template_var) res['settings'] = self.settings return res
def __call__(self, request_handler: RequestHandler) -> None: status, reason = self.status.split(" ", 1) request_handler.set_status(int(status), reason) for header, value in self.headers: request_handler.add_header(header, value) if isinstance(self.body, str): request_handler.write(self.body.encode()) elif isinstance(self.body, bytes): request_handler.write(self.body) # chunked else: for item in self.body: if not isinstance(item, bytes): item = item.encode("utf8") request_handler.write(item) request_handler.flush()
def finish(self, chunk=None): if not self.request.connection.stream.closed(): RequestHandler.finish(self, chunk)
def log_exception(self, typ, value, tb): if isinstance(value, PermissionError): app_log.warning('custom logging for PermissionError: %s', value.args[0]) else: RequestHandler.log_exception(self, typ, value, tb)
def __init__(self, master_ip): RequestHandler.__init__(self) self.master = master_ip
def __init__(self, application, request, **kwargs): RequestHandler.__init__(self, application, request, **kwargs) self.db = self.application.db
def __init__(self, application, request, **kwargs): self.path = None RequestHandler.__init__(self, application, request, **kwargs)
def __init__(self, application, request): RHandler.__init__(self, application, request) self.commentDao = CommentDao()
def initialize(self): self.template = getTName(self) self.data = {'error': '0'} RequestHandler.initialize(self)
def post(self, *args, **kwargs): """ 处理用户注册 :param args: :param kwargs: :return: 失败返回失败信息并返回注册页面,成功跳转聊天室 """ messages = [] url = RequestHandler.reverse_url(self, "register") account = self.get_body_argument("account", default=None, strip=True) get_user = self.db_checker.find_one({"account": account}) # 检查账户是否存在并是否合法 if get_user or not Support.check_account(account): messages.append("账户已存在或帐号不合法") return self.render("index/register.html", url=url, messages=messages) password = self.get_body_argument("password", default=None, strip=True) confirm = self.get_body_argument("confirm", default=None, strip=True) # 检查两次输入密码是否相同 if not password or not confirm: messages.append("请输入密码和重复密码") return self.render("index/register.html", url=url, messages=messages) if password != confirm: messages.append("两次输入的密码不一致") return self.render("index/register.html", url=url, messages=messages) email = self.get_body_argument("email", default=None, strip=True) # email检查 if len(email) < 4: messages.append("请输入正确格式的邮箱") return self.render("index/register.html", url=url, messages=messages) get_email = self.db_checker.find_one({"email": email}) if get_email: messages.append("注册邮箱已存在") return self.render("index/register.html", url=url, messages=messages) username = self.get_body_argument("username", default=None, strip=True) # 用户名检查 if len(username) <= 2: messages.append("用户名过短") return self.render("index/register.html", url=url, messages=messages) # 通过注册检测 # 生产md5密码 md5_password = Support.get_password(password) # 包装插入MongoDB数据 user_data = [ { 'account': account, 'password': md5_password, 'username': username, 'email': email, }, ] # 插入数据 self.db_checker.insert(user_data) # 获取聊天室url地址 chat_room_url = RequestHandler.reverse_url(self, "chat") # 获取单点登陆的token user_token_value = Support.single_login_token(account) # 设置单点登陆的cookie self.set_secure_cookie("user_token", user_token_value) # 设置用户账户的cookie self.set_secure_cookie("chat_room_user", account) # 设置用户名的cookie self.set_secure_cookie("chat_room_username", username) # Redis记录单点登陆token self.redis.hset("user_token", account, user_token_value) # 跳转聊天室 return self.redirect(chat_room_url)
def __init__(self, application, request, **kwargs): RequestHandler.__init__(self, application, request, **kwargs) self.set_header('Content-Type', 'text/json')
def static_url(path): logger.info(path) return RequestHandler.make_static_url(tornado_settings, path)
def __init__(self, _application, request, **kwargs): RequestHandler.__init__(self, _application, request) self.accounts = kwargs['accounts']
def dataset_not_found(handler: RequestHandler, name: str): handler.clear() handler.set_status(404) handler.write({ 'message': f'Cannot find dataset {repr(name)}!' })
def __init__(self, application, request, **kwargs): RequestHandler.__init__(self, application, request, **kwargs) self._sign = signature() self._deskew = imageDeskew()