def check_files(): global reloading_exception if not reloading_exception: modules = [ m for name, m in sys.modules.items() if getattr(m, 'USE_AUTORELOAD', False) and (name.startswith('pony.examples.') or not name.startswith('pony.')) ] try: for m in modules: filename = abspath(m.__file__) if filename.endswith(".pyc") or filename.endswith(".pyo"): filename = filename[:-1] if not exists(filename): continue mtime = get_mtime(filename) if mtimes.setdefault(filename, mtime) != mtime: try: reload(modules, m, filename) except Exception: # Запоминаем traceback так что мы можем отобразить его # на веб-странице позднее, когда поступит какой-либо HTTP запрос reloading_exception = sys.exc_info() else: reloading_exception = None break except: log_exc() sys.exit()
def reload(): global last_check_time now = time() if abs(now - last_check_time) <= options.RELOADING_CHECK_INTERVAL: return with lock: if abs(now - last_check_time) <= options.RELOADING_CHECK_INTERVAL: return last_check_time = now changed = {} for fname, mtime, trans in trans_files: try: new_mtime = get_mtime(fname) except: # file not found? new_mtime = None if new_mtime != mtime: changed[fname] = new_mtime if not changed: return erroneous = set() log(type='RELOAD:begin', prefix='RELOADING: ', text=shortened_filename(fname), severity=ERROR, files=[ fname for fname, mtime, trans in trans_files ], changed=changed) try: translations.clear() for i, (fname, mtime, trans) in enumerate(trans_files): if fname in changed: new_mtime = changed[fname] trans = {} if new_mtime is not None: try: trans = load(fname) except: erroneous.add(fname) log_exc() trans_files[i] = fname, new_mtime, trans update(translations, trans) finally: log(type='RELOAD:end', severity=DEBUG, success=not erroneous, erroneous=erroneous, text='Reloaded with errors' if erroneous else 'Reloaded successfully')
def reload(modules, changed_module, filename): global reloading reloading = True success = True log(type='RELOAD:begin', prefix='RELOADING: ', text=shortened_filename(filename), severity=ERROR, module=changed_module.__name__, modules=dict((m.__name__, m.__file__) for m in modules)) try: for clear_func in clear_funcs: clear_func() mtimes.clear() linecache.checkcache() for m in modules: sys.modules.pop(m.__name__, None) load_main() except Exception: success = False log_exc() raise finally: log(type='RELOAD:end', severity=DEBUG, success=success, text='Reloaded successfully' if success else 'Reloaded with errors') reloading = False
def load(environ, cookies=None): local.clear() local.environ = environ if cookies is None: cookies = Cookie.SimpleCookie() if 'HTTP_COOKIE' in environ: cookies.load(environ['HTTP_COOKIE']) morsel = cookies.get(options.COOKIE_NAME) local.ip = ip = environ.get('REMOTE_ADDR') local.user_agent = user_agent = environ.get('HTTP_USER_AGENT') local.cookie_value = cookie_value = morsel.value if morsel else None if not cookie_value: return now = int(time()) // 60 try: ctime_str, mtime_str, data_str, hash_str, longlife_key = cookie_value.split(':') ctime = local.ctime = int(ctime_str, 16) mtime = local.mtime = int(mtime_str, 16) ctime_diff = now - ctime mtime_diff = now - mtime if ctime_diff < -1 or mtime_diff < -1: return if ctime_diff > options.MAX_SESSION_CTIME or mtime_diff > options.MAX_SESSION_MTIME: resurrect_longlife_session(longlife_key); return data = b64decode(data_str) hash = b64decode(hash_str) hashobject = get_hashobject(mtime) hashobject.update(ctime_str) hashobject.update(data) hashobject.update(user_agent or '') if hash != hashobject.digest(): hashobject.update(ip or '') if hash != hashobject.digest(): return local.remember_ip = True else: local.remember_ip = False if data.startswith('C'): # "C" stands for "C"ookies-only session_id = None data = data[1:] elif data.startswith('S'): # "S" stands for "S"torage session_id = data[1:] data = storage.get(session_id, ctime, mtime) if data is None: return else: return info = loads(data) local.user, session_dict = info local.session = Session(session_dict) local.session_id = session_id local.longlife_key = longlife_key or None local.longlife_session = bool(longlife_key) except: log_exc() return
def app(environ): request = local.request = HttpRequest(environ) log_request(request) response = local.response = HttpResponse() local.no_cookies = False auth.load(environ, request.cookies) auth.verify_ticket(request.fields.getfirst('_t')) postprocessing = True no_exception = False if autoreload.reloading_exception and not request.url.startswith('/pony/static/'): status, headers = INTERNAL_SERVER_ERROR result = format_exc(autoreload.reloading_exception) elif request.method not in ('HEAD', 'GET', 'POST', 'PUT', 'DELETE'): status = '501 Not Implemented' headers = {'Content-Type' : 'text/plain'} result = 'Unknown HTTP method: %s' % request.method else: try: try: if auth.local.ticket_payload is not None: form = cPickle.loads(auth.local.ticket_payload) form._handle_request_() form = None result = invoke(request.url) finally: if auth.local.ticket and not request.form_processed and request.form_processed is not None: auth.unexpire_ticket() except HttpException as e: status, headers, result = e.status, e.headers, e.content result, headers = normalize_result(result, headers) except BdbQuit: raise except: log_exc() status, headers = INTERNAL_SERVER_ERROR result, headers = normalize_result(format_exc(), headers) else: no_exception = True status = response.status headers = response.headers postprocessing = response.postprocessing content_type = headers.get('Content-Type', 'text/plain') media_type, type_params = cgi.parse_header(content_type) charset = type_params.get('charset', 'iso-8859-1') if isinstance(result, basestring): if media_type == 'text/html' and postprocessing: if no_exception: result = postprocess(result, response.base_stylesheets, response.component_stylesheets, response.scripts) else: result = postprocess(result, [], [], []) if isinstance(result, unicode): if media_type == 'text/html' or 'xml' in media_type : result = result.encode(charset, 'xmlcharrefreplace') else: result = result.encode(charset, 'replace') headers['Content-Length'] = str(len(result)) headers = headers.items() for header, value in headers: assert isinstance(header, str) assert isinstance(value, str) if not local.no_cookies and not status.startswith('5'): auth.save(response.cookies) headers += httputils.serialize_cookies(environ, response.cookies) log(type='HTTP:response', prefix='Response: ', text=status, severity=DEBUG, headers=headers) if request.method == 'HEAD' and 'Content-Length' in headers: result = '' return status, headers, result
def app(environ): request = local.request = HttpRequest(environ) log_request(request) response = local.response = HttpResponse() local.no_cookies = False auth.load(environ, request.cookies) auth.verify_ticket(request.fields.getfirst('_t')) postprocessing = True no_exception = False if autoreload.reloading_exception and not request.url.startswith( '/pony/static/'): status, headers = INTERNAL_SERVER_ERROR result = format_exc(autoreload.reloading_exception) elif request.method not in ('HEAD', 'GET', 'POST', 'PUT', 'DELETE'): status = '501 Not Implemented' headers = {'Content-Type': 'text/plain'} result = 'Unknown HTTP method: %s' % request.method else: try: try: if auth.local.ticket_payload is not None: form = cPickle.loads(auth.local.ticket_payload) form._handle_request_() form = None result = invoke(request.url) finally: if auth.local.ticket and not request.form_processed and request.form_processed is not None: auth.unexpire_ticket() except HttpException as e: status, headers, result = e.status, e.headers, e.content result, headers = normalize_result(result, headers) except BdbQuit: raise except: log_exc() status, headers = INTERNAL_SERVER_ERROR result, headers = normalize_result(format_exc(), headers) else: no_exception = True status = response.status headers = response.headers postprocessing = response.postprocessing content_type = headers.get('Content-Type', 'text/plain') media_type, type_params = cgi.parse_header(content_type) charset = type_params.get('charset', 'iso-8859-1') if isinstance(result, basestring): if media_type == 'text/html' and postprocessing: if no_exception: result = postprocess(result, response.base_stylesheets, response.component_stylesheets, response.scripts) else: result = postprocess(result, [], [], []) if isinstance(result, unicode): if media_type == 'text/html' or 'xml' in media_type: result = result.encode(charset, 'xmlcharrefreplace') else: result = result.encode(charset, 'replace') headers['Content-Length'] = str(len(result)) headers = headers.items() for header, value in headers: assert isinstance(header, str) assert isinstance(value, str) if not local.no_cookies and not status.startswith('5'): auth.save(response.cookies) headers += httputils.serialize_cookies(environ, response.cookies) log(type='HTTP:response', prefix='Response: ', text=status, severity=DEBUG, headers=headers) if request.method == 'HEAD' and 'Content-Length' in headers: result = '' return status, headers, result