def restart_with_reloader(self): """Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. """ while 1: _log('info', ' * Restarting with %s' % self.name) args = _get_args_for_reloading() # a weird bug on windows. sometimes unicode strings end up in the # environment and subprocess.call does not like this, encode them # to latin1 and continue. if os.name == 'nt' and PY2: new_environ = {} for key, value in iteritems(os.environ): if isinstance(key, text_type): key = key.encode('iso-8859-1') if isinstance(value, text_type): value = value.encode('iso-8859-1') new_environ[key] = value else: new_environ = os.environ.copy() new_environ['WERKZEUG_RUN_MAIN'] = 'true' exit_code = subprocess.call(args, env=new_environ, close_fds=False) if exit_code != 3: return exit_code
def werk_log(self, type, message, *args): try: msg = '%s - - [%s] %s' % ( self.address_string(), self.log_date_time_string(), message % args, ) http_code = str(args[1]) except: return _orig_log(type, message, *args) # Utilize terminal colors, if available if http_code[0] == '2': # Put 2XX first, since it should be the common case msg = _style.HTTP_SUCCESS(msg) elif http_code[0] == '1': msg = _style.HTTP_INFO(msg) elif http_code == '304': msg = _style.HTTP_NOT_MODIFIED(msg) elif http_code[0] == '3': msg = _style.HTTP_REDIRECT(msg) elif http_code == '404': msg = _style.HTTP_NOT_FOUND(msg) elif http_code[0] == '4': msg = _style.HTTP_BAD_REQUEST(msg) else: # Any 5XX, or any other response msg = _style.HTTP_SERVER_ERROR(msg) _log(type, msg)
def run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, passthrough_errors=False, processes=None, threaded=False, ssl_context=None): if use_debugger: from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, use_evalex) processes = max(processes, 1) def serve_forever(): make_server(hostname, port, application, processes=processes, threaded=threaded, passthrough_errors=passthrough_errors, ssl_context=ssl_context).serve_forever() if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': display_hostname = hostname != '*' and hostname or 'localhost' if ':' in display_hostname: display_hostname = '[%s]' % display_hostname _log('info', ' * Running on %s://%s:%d/', ssl_context is None and 'http' or 'https', display_hostname, port) if use_reloader: open_test_socket(hostname, port) run_with_reloader(serve_forever, extra_files, reloader_interval) else: serve_forever()
def restart_with_reloader(): """Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. """ while 1: _log('info', ' * Restarting with reloader') requires_shell = False if sys.executable: args = [sys.executable] + sys.argv else: args, requires_shell = detect_executable() new_environ = os.environ.copy() new_environ['WERKZEUG_RUN_MAIN'] = 'true' # a weird bug on windows. sometimes unicode strings end up in the # environment and subprocess.call does not like this, encode them # to latin1 and continue. if os.name == 'nt' and PY2: for key, value in iteritems(new_environ): if isinstance(value, text_type): new_environ[key] = value.encode('iso-8859-1') exit_code = subprocess.call(args, env=new_environ, shell=requires_shell) if exit_code != 3: return exit_code
def run(self): watches = {} observer = self.observer_class() observer.start() to_delete = set(watches) paths = _find_observable_paths(self.extra_files) for path in paths: if path not in watches: try: watches[path] = observer.schedule(self.event_handler, path, recursive=True) except OSError as e: message = str(e) if message != "Path is not a directory": # Log the exception _log('error', message) # Clear this path from list of watches We don't want # the same error message showing again in the next # iteration. watches[path] = None to_delete.discard(path) for path in to_delete: watch = watches.pop(path, None) if watch is not None: observer.unschedule(watch) self.observable_paths = paths yield from self.should_reload.wait() sys.exit(3)
def werk_log(self, type, message, *args): time_str = datetime.datetime.now().strftime("%H:%M:%S:%f") try: msg = '[{}] {}'.format(time_str, message % args) http_code = str(args[1]) except Exception: return _orig_log(type, message, *args) # Utilize terminal colors, if available if http_code[0] == '2': # Put 2XX first, since it should be the common case msg = _style.HTTP_SUCCESS(msg) elif http_code[0] == '1': msg = _style.HTTP_INFO(msg) elif http_code == '304': msg = _style.HTTP_NOT_MODIFIED(msg) elif http_code[0] == '3': msg = _style.HTTP_REDIRECT(msg) elif http_code == '404': msg = _style.HTTP_NOT_FOUND(msg) elif http_code[0] == '4': msg = _style.HTTP_BAD_REQUEST(msg) else: # Any 5XX, or any other response msg = _style.HTTP_SERVER_ERROR(msg) _log(type, msg)
def restart_with_reloader(): """Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. """ while 1: _log('info', ' * Restarting with reloader') #fix lastest python version entry_point script file incompatible bug if sys.argv[0].endswith('.pyw') or sys.argv[0].endswith('.py'): args = [sys.executable] + sys.argv else: args = sys.argv new_environ = os.environ.copy() new_environ['WERKZEUG_RUN_MAIN'] = 'true' # a weird bug on windows. sometimes unicode strings end up in the # environment and subprocess.call does not like this, encode them # to latin1 and continue. if os.name == 'nt' and PY2: for key, value in iteritems(new_environ): if isinstance(value, text_type): new_environ[key] = value.encode('iso-8859-1') exit_code = subprocess.call(args, env=new_environ) if exit_code != 3: return exit_code
def reloader_loop(extra_files = None, interval = 1): def iter_module_files(): for module in sys.modules.values(): filename = getattr(module, '__file__', None) if filename: old = None while not os.path.isfile(filename): old = filename filename = os.path.dirname(filename) if filename == old: break else: if filename[-4:] in ('.pyc', '.pyo'): filename = filename[:-1] yield filename mtimes = {} while 1: for filename in chain(iter_module_files(), extra_files or ()): try: mtime = os.stat(filename).st_mtime except OSError: continue old_time = mtimes.get(filename) if old_time is None: mtimes[filename] = mtime continue elif mtime > old_time: _log('info', ' * Detected change in %r, reloading' % filename) sys.exit(3) time.sleep(interval)
def log_pin_request(self): """Log the pin if needed.""" if self.pin_logging and self.pin is not None: _log('info', ' * To enable the debugger you need to ' 'enter the security pin:') _log('info', ' * Debugger pin code: %s' % self.pin) return Response('')
def restart_with_reloader(): """Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. """ while 1: _log('info', ' * Restarting with reloader') #args = [sys.executable] + sys.argv args = ['moin.py','server','standalone'] new_environ = os.environ.copy() new_environ['WERKZEUG_RUN_MAIN'] = 'true' # a weird bug on windows. sometimes unicode strings end up in the # environment and subprocess.call does not like this, encode them # to latin1 and continue. if os.name == 'nt': for key, value in new_environ.iteritems(): if isinstance(value, unicode): new_environ[key] = value.encode('iso-8859-1') shell = True else: shell = False exit_code = subprocess.call(args, env=new_environ, shell=shell) if exit_code != 3: return exit_code
def log_request(self, code='-', size='-'): _log('info', '%s -- [%s] %s %s', self.address_string(), self.requestline, code, size )
def _reloader_stat_loop(extra_files=None, interval=1): """When this function is run from the main thread, it will force other threads to exit when any modules currently loaded change. Copyright notice. This function is based on the autoreload.py from the CherryPy trac which originated from WSGIKit which is now dead. :param extra_files: a list of additional files it should watch. """ from itertools import chain mtimes = {} while 1: for filename in chain(_iter_module_files(), extra_files or ()): try: mtime = os.stat(filename).st_mtime except OSError: continue old_time = mtimes.get(filename) if old_time is None: mtimes[filename] = mtime continue elif mtime > old_time: _log("info", " * Detected change in %r, reloading" % filename) sys.exit(3) time.sleep(interval)
def run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, passthrough_errors=False, ssl_context=None): if use_debugger: from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, use_evalex) def serve_forever(): make_server(hostname, port, application, passthrough_errors=passthrough_errors, ssl_context=ssl_context).serve_forever() if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': display_hostname = hostname != '*' and hostname or 'localhost' if ':' in display_hostname: display_hostname = '[%s]' % display_hostname _log('info', ' * Running on %s://%s:%d/', ssl_context is None and 'http' or 'https', display_hostname, port) if use_reloader: open_test_socket(hostname, port) run_with_reloader(serve_forever, extra_files, reloader_interval) else: serve_forever()
def thumbs(): # not good (type of values) but something like this infile = request.args.get('file', None) width = request.args.get('width', 120) height = request.args.get('height', 90) quality = request.args.get('quality', 100) crop = request.args.get('crop', False) origfile = os.path.join(basedir, app.static_folder + infile) if not os.path.isfile(origfile): infile = '/img/nopic.jpg' origfile = os.path.join(basedir, app.static_folder + infile) filehash = sha1(infile.encode('utf-8')).hexdigest() #cached_file = os.path.basename(infile).rsplit('.',1)[0] + \ # '_' + width + 'x' + height + '.' + \ # os.path.basename(infile).rsplit('.',1)[1] cached_file = filehash + \ '_' + width + 'x' + height + '.' + \ os.path.basename(infile).rsplit('.', 1)[1] newpath = os.path.join(basedir, app.static_folder + '/img/cache/' + cached_file) if os.path.isfile(newpath): _log('info', newpath) return send_file(newpath) resize(Image.open(origfile), (int(width), int(height)), crop, newpath, quality) return send_file(newpath, add_etags=False)
def run(self): watches = {} observer = self.observer_class() observer.start() to_delete = set(watches) paths = _find_observable_paths(self.extra_files) for path in paths: if path not in watches: try: watches[path] = observer.schedule( self.event_handler, path, recursive=True) except OSError as e: message = str(e) if message != "Path is not a directory": # Log the exception _log('error', message) # Clear this path from list of watches We don't want # the same error message showing again in the next # iteration. watches[path] = None to_delete.discard(path) for path in to_delete: watch = watches.pop(path, None) if watch is not None: observer.unschedule(watch) self.observable_paths = paths yield from self.should_reload.wait() sys.exit(3)
def _reloader_stat_loop(extra_files=None, interval=1): """When this function is run from the main thread, it will force other threads to exit when any modules currently loaded change. Copyright notice. This function is based on the autoreload.py from the CherryPy trac which originated from WSGIKit which is now dead. :param extra_files: a list of additional files it should watch. """ from itertools import chain mtimes = {} while 1: for filename in chain(_iter_module_files(), extra_files or ()): try: mtime = os.stat(filename).st_mtime except OSError: continue old_time = mtimes.get(filename) if old_time is None: mtimes[filename] = mtime continue elif mtime > old_time: _log('info', ' * Detected change in %r, reloading' % filename) sys.exit(3) time.sleep(interval)
def run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, passthrough_errors=False, processes=None, threaded=False, ssl_context=None): if use_debugger: from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, use_evalex) processes = max(processes, 1) def serve_forever(): make_server(hostname, port, application, processes=processes, threaded=threaded, passthrough_errors=passthrough_errors, ssl_context=ssl_context).serve_forever() def serve_error_app(tb_str, monitored_files): from clastic import flaw err_app = flaw.create_app(tb_str, monitored_files) err_server = make_server(hostname, port, err_app) thread.start_new_thread(err_server.serve_forever, ()) return err_server if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': display_hostname = hostname != '*' and hostname or 'localhost' if ':' in display_hostname: display_hostname = '[%s]' % display_hostname _log('info', ' * Running on %s://%s:%d/', ssl_context is None and 'http' or 'https', display_hostname, port) if use_reloader: open_test_socket(hostname, port) run_with_reloader(serve_forever, extra_files, reloader_interval, error_func=serve_error_app) else: serve_forever()
def pauseSession(): u = User.query.get(session['userID']) _log("info", u.__str__()) s = u.getRunningSession() s.startPause() return "gepauzeerd"
def run_simple( hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, reloader_type="auto", threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, ssl_context=None, ): if use_debugger: from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, use_evalex) if static_files: from werkzeug.wsgi import SharedDataMiddleware application = SharedDataMiddleware(application, static_files) def inner(): # Override here make_server( hostname, port, application, threaded, processes, request_handler, passthrough_errors, ssl_context ).serve_forever() if os.environ.get("WERKZEUG_RUN_MAIN") != "true": display_hostname = hostname != "*" and hostname or "localhost" if ":" in display_hostname: display_hostname = "[%s]" % display_hostname quit_msg = "(Press CTRL+C to quit)" _log( "info", " * Running on %s://%s:%d/ %s", ssl_context is None and "http" or "https", display_hostname, port, quit_msg, ) if use_reloader: # Create and destroy a socket so that any exceptions are raised before # we spawn a separate Python interpreter and lose this ability. address_family = select_ip_version(hostname, port) test_socket = socket.socket(address_family, socket.SOCK_STREAM) test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) test_socket.bind((hostname, port)) test_socket.close() from werkzeug._reloader import run_with_reloader run_with_reloader(inner, extra_files, reloader_interval, reloader_type) else: inner()
def stop(): _log('info', 'Issuing kill command') subprocess.call(["sudo pkill -9 -f user_script.py"], shell = True) #commands.getstatusoutput('python /home/pi/blockytalky/code/kill.py') toSend = Message("name", None, "HwCmd", Message.createImage(motor1=0, motor2=0, motor3=0, motor4=0, pin13=0)) toSend = Message.encode(toSend) channel.basic_publish(exchange="", routing_key="HwCmd", body=toSend) return 'OK'
def send_data(content, to_user, from_user, nonce): timeInt = str(int(time.time())) template = u"""<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>""" _log("info", (template % (to_user, from_user, timeInt, content)).encode("UTF-8")) return wxcpt.EncryptMsg( (template % (to_user, from_user, timeInt, content)).encode("UTF-8"), nonce)
def log_startup(sock): display_hostname = hostname not in ('', '*') and hostname or 'localhost' if ':' in display_hostname: display_hostname = '[%s]' % display_hostname quit_msg = '(Press CTRL+C to quit)' port = sock.getsockname()[1] _log('info', ' * Running on %s://%s:%d/ %s', ssl_context is None and 'http' or 'https', display_hostname, port, quit_msg)
def bind_socket(options, ssl_context=None): server_address, server_port = options.bind_address, options.bind_port server_socket = create_socket(server_address, server_port) display_hostname = server_address != '*' and server_address or 'localhost' if ':' in display_hostname: display_hostname = '[%s]' % display_hostname _log('info', ' * Running on %s://%s:%d/', ssl_context is None and 'http' or 'https', display_hostname, server_port) return server_socket
def log_pin_request(self): """Log the pin if needed.""" if self.pin_logging and self.pin is not None: _log( "info", " * To enable the debugger you need to " "enter the security pin:", ) _log("info", " * Debugger pin code: %s" % self.pin) return Response("")
def reloader_loop(files, reloader=None, interval=1): """Monitor files, copies files to invenio install when they change and eventually restart our worker process""" mtimes = {} while 1: has_changes = False has_conf_changes = False for filename in set(files): try: stats = os.stat(filename) except AttributeError: continue except OSError: continue mtime = stats.st_mtime old_time = mtimes.get(filename) if old_time is None: mtimes[filename] = mtime continue elif mtime > old_time: mtimes[filename] = mtime # Sleep for a while to wait for the texteditor to # finish writing the file time.sleep(0.1) if os.path.basename(filename) == config.LOCAL_CONFIG_FILENAME: dest = None else: dest = select_destination_path(filename) if dest: _log( 'info', ' * Detected change in %r, ' 'copying to %s' % (filename, dest)) shutil.copyfile(filename, dest) else: _log('info', ' * Detected change in %r' % filename) if os.path.basename(filename) in ( config.CONFIG_FILENAME, config.LOCAL_CONFIG_FILENAME): has_conf_changes = True has_changes = True if has_conf_changes: update_conf() if has_changes and reloader: reloader() if not reloader.worker_pid: return time.sleep(1) time.sleep(interval)
def restart_with_reloader(): to_mon = [] while 1: _log('info', ' * Clastic restarting with reloader') args = [sys.executable] + sys.argv new_environ = os.environ.copy() new_environ['WERKZEUG_RUN_MAIN'] = 'true' if os.name == 'nt': for key, value in new_environ.iteritems(): if isinstance(value, unicode): new_environ[key] = value.encode('iso-8859-1') stderr_buff = [] child_proc = subprocess.Popen(args, env=new_environ, stderr=subprocess.PIPE) rf = child_proc.stderr exit_code, lines = None, [] while exit_code is None or lines: if child_proc.poll() is None: lines.append(rf.readline()) elif exit_code is None: lines.extend(rf.readlines()) exit_code = child_proc.returncode if not lines: break cur_line = lines.pop(0) if cur_line.startswith(_MON_PREFIX): to_mon = literal_eval(cur_line[len(_MON_PREFIX):]) else: sys.stderr.write(cur_line) stderr_buff.append(cur_line) if len(stderr_buff) > _STDERR_BUFF_SIZE: stderr_buff.pop(0) if exit_code == 3: continue elif exit_code == 1 and stderr_buff: enable_tty_echo() from clastic import flaw tb_str = ''.join(stderr_buff) err_app = flaw.create_app(tb_str, to_mon) # TODO: these values should be passed through err_server = make_server('localhost', 5000, err_app) thread.start_new_thread(err_server.serve_forever, ()) try: reloader_loop(to_mon, 1) except KeyboardInterrupt: return 0 except SystemExit as se: if se.code == 3: continue return se.code finally: err_server.shutdown() err_server.server_close() return 0 else: return exit_code
def commitSession(): sessionID = session['sessionID'] userSession = UserSession.query.get(sessionID) _log("info", "mr usersessio: " + userSession.__str__()) userSession.commitSession() sessionID = session.pop('sessionID',None) session.pop('isPauzed',None) #return redirect("app/" + session["userID"].__str__() + "/dashboard") return "Yolo"
def log_startup(sock): display_hostname = hostname if hostname not in ('', '*') else 'localhost' quit_msg = '(Press CTRL+C to quit)' if sock.family == af_unix: _log('info', ' * Running on %s %s', display_hostname, quit_msg) else: if ':' in display_hostname: display_hostname = '[%s]' % display_hostname port = sock.getsockname()[1] _log('info', ' * Running on %s://%s:%d/ %s', 'http' if ssl_context is None else 'https', display_hostname, port, quit_msg)
def upload(): startTime = None endTime = None if request.method == "POST": data = request.form data1 = data.copy() data2 = data1.get('<xml xmlns') _log('info', 'Blockly code received') toWrite = "<xml xmlns = " + data2 upload_code(toWrite) return 'OK'
def restart_with_reloader(): """Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. """ while 1: _log('info', ' * Restarting with reloader...') args = [sys.executable] + sys.argv new_environ = os.environ.copy() new_environ['WERKZEUG_RUN_MAIN'] = 'true' exit_code = subprocess.call(args, env=new_environ) if exit_code != 3: return exit_code
def optimize_after(wrapped, instance, args, kwargs): # we are overriding : # def process_image(ctx, source_image, dst_filename, width, height=None, crop=False): # so args[2] is dst_filename dst = args[2] final=wrapped(*args, **kwargs) try: result=pyimagediet.diet(dst, DIET_CONFIG) if result: _log('info', "(optimized)") except pyimagediet.CompressFileDietException, e: raise Exception(e.msg)
def detect_executable(): '''When sys.executable is None, try to detect how Python was started. Currently only supports Jython. ''' #Standalone Jython won't refresh properly #https://gist.github.com/paolodina/b98c3f3a159024584e13 import platform is_jython = False is_windows = False #Check if platform is jython if platform.python_implementation().lower() == 'jython': import java #When running Jython with -jar, rt.jar doesn't get imported try: import java.lang.management as mgmt except ImportError: _log( 'error', "ERROR: java.lang.management namespace is broken. Please make sure your CLASSPATH includes rt.jar." ) raise ImportError is_jython = True #Get the args passed to the java exe and the classpath bean = mgmt.ManagementFactory.getRuntimeMXBean() input_args = bean.getInputArguments() cp_string = bean.getClassPath() classpath = [] if cp_string: classpath += ['-cp', cp_string] #Check if we're on Windows os_bean = mgmt.ManagementFactory.getOperatingSystemMXBean() os_name = os_bean.getName().lower() is_windows = os_name.startswith('windows') #Get the Java exe name java_exe = os.path.join(java.lang.System.getProperty('java.home'), 'bin', 'java') args = [java_exe] + classpath + input_args + [ 'org.python.util.jython' ] + sys.argv #Return args and whether shell is required return args, (is_windows and is_jython)
def run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, threaded=False, processes=1, request_handler=None): """Start an application using wsgiref and with an optional reloader. This wraps `wsgiref` to fix the wrong default reporting of the multithreaded WSGI variable and adds optional multithreading and fork support. :param hostname: The host for the application. eg: ``'localhost'`` :param port: The port for the server. eg: ``8080`` :param application: the WSGI application to execute :param use_reloader: should the server automatically restart the python process if modules were changed? :param use_debugger: should the werkzeug debugging system be used? :param use_evalex: should the exception evaluation feature be enabled? :param extra_files: a list of files the reloader should listen for additionally to the modules. For example configuration files. :param reloader_interval: the interval for the reloader in seconds. :param threaded: should the process handle each request in a separate thread? :param processes: number of processes to spawn. :param request_handler: optional parameter that can be used to replace the default wsgiref request handler. Have a look at the `werkzeug.serving` sourcecode for more details. """ if use_debugger: from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, use_evalex) def inner(): srv = make_server(hostname, port, application, threaded, processes, request_handler) try: srv.serve_forever() except KeyboardInterrupt: pass if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': display_hostname = hostname or '127.0.0.1' _log('info', ' * Running on http://%s:%d/', display_hostname, port) if use_reloader: # Create and destroy a socket so that any exceptions are raised before # we spawn a separate Python interpreter and loose this ability. test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) test_socket.bind((hostname, port)) test_socket.close() run_with_reloader(inner, extra_files, reloader_interval) else: inner()
def getAllSessions(): userID = request.args["userID"] user = User.query.get(userID); _log("info", user.sessions.all().__str__()) #Move to UserSesssion returnList = [] for nextSession in user.sessions.all(): returnList.append({"sessionID":nextSession.id, "sessionData":nextSession.outputSession()}) return json.dumps(returnList)
def spawn_server(options, server_socket): """Create a new worker""" _log('info', ' * Spawning worker') pid = os.fork() if pid == 0: try: start_server(options, server_socket) except: print traceback.format_exc()[:-1] _log('info', ' * Worker crashed') # We do not want to free this pid because it will be killed while True: time.sleep(6000) return pid
def log_startup(sock): display_hostname = hostname not in ("", "*") and hostname or "localhost" if ":" in display_hostname: display_hostname = "[%s]" % display_hostname quit_msg = "(Press CTRL+C to quit)" port = sock.getsockname()[1] _log( "info", " * Running on %s://%s:%d/ %s", ssl_context is None and "http" or "https", display_hostname, port, quit_msg, )
def restart_with_reloader(): while 1: _log('info', ' * Restarting with reloader...') args = [sys.executable] + sys.argv new_environ = os.environ.copy() new_environ['WERKZEUG_RUN_MAIN'] = 'true' if os.name == 'nt': for key, value in new_environ.iteritems(): if isinstance(value, unicode): new_environ[key] = value.encode('iso-8859-1') exit_code = subprocess.call(args, env=new_environ) if exit_code != 3: return exit_code
def restart_with_reloader(): """Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. """ while 1: _log('info', ' * Restarting with reloader...') args = [sys.executable] + sys.argv if sys.platform == 'win32': args = ['"%s"' % arg for arg in args] new_environ = os.environ.copy() new_environ['WERKZEUG_RUN_MAIN'] = 'true' exit_code = os.spawnve(os.P_WAIT, sys.executable, args, new_environ) if exit_code != 3: return exit_code
def is_valid(request): _log("info", "==========开始认证===============") _log("info", "==========URL参数===============") signature, timestamp, nonce = WxApp.get_query_param(request) verifyEchoStr = request.values["echostr"] param_list = [token, timestamp, nonce] param_list.sort() sha1 = hashlib.sha1() sha1.update("".join(param_list).encode("utf-8")) hashcode = sha1.hexdigest() if hashcode == signature: return verifyEchoStr else: return ""
def restart_with_reloader(error_func=None): to_mon = [] while 1: _log('info', ' * Clastic restarting with reloader') args = [sys.executable] + sys.argv new_environ = os.environ.copy() new_environ['WERKZEUG_RUN_MAIN'] = 'true' if os.name == 'nt': for key, value in new_environ.iteritems(): if isinstance(value, unicode): new_environ[key] = value.encode('iso-8859-1') child_proc = subprocess.Popen(args, env=new_environ, stderr=subprocess.PIPE) stderr_buff = deque(maxlen=_STDERR_BUFF_SIZE) def consume_lines(): for line in iter(child_proc.stderr.readline, ''): if line.startswith(_MON_PREFIX): to_mon[:] = literal_eval(line[len(_MON_PREFIX):]) else: sys.stderr.write(line) stderr_buff.append(line) while child_proc.poll() is None: consume_lines() consume_lines() exit_code = child_proc.returncode if exit_code == 3: continue elif error_func and exit_code == 1 and stderr_buff: enable_tty_echo() tb_str = ''.join(stderr_buff) err_server = error_func(tb_str, to_mon) try: reloader_loop(to_mon, 1) except KeyboardInterrupt: return 0 except SystemExit as se: if se.code == 3: continue return se.code finally: err_server.shutdown() err_server.server_close() return 0 else: return exit_code
def run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, reloader_type='auto', threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, ssl_context=None): if use_debugger: from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, use_evalex) if static_files: from werkzeug.wsgi import SharedDataMiddleware application = SharedDataMiddleware(application, static_files) def inner(): # Override here make_server(hostname, port, application, threaded, processes, request_handler, passthrough_errors, ssl_context).serve_forever() if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': display_hostname = hostname != '*' and hostname or 'localhost' if ':' in display_hostname: display_hostname = '[%s]' % display_hostname quit_msg = '(Press CTRL+C to quit)' _log('info', ' * Running on %s://%s:%d/ %s', ssl_context is None and 'http' or 'https', display_hostname, port, quit_msg) if use_reloader: # Create and destroy a socket so that any exceptions are raised before # we spawn a separate Python interpreter and lose this ability. address_family = select_ip_version(hostname, port) test_socket = socket.socket(address_family, socket.SOCK_STREAM) test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) test_socket.bind((hostname, port)) test_socket.close() from werkzeug._reloader import run_with_reloader run_with_reloader(inner, extra_files, reloader_interval, reloader_type) else: inner()
def serve_forever(self): self.shutdown_signal = False try: if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': display_hostname = self.host != '*' and self.host or 'localhost' if ':' in display_hostname: display_hostname = '[%s]' % display_hostname quit_msg = '(Press CTRL+C to quit)' _log('info', ' * Running on %s://%s:%d/ %s', self.ssl_context is None and 'http' or 'https', display_hostname, self.port, quit_msg) HTTPServer.serve_forever(self) except KeyboardInterrupt: pass finally: self.server_close()
def loadOdm(): """Form a complex number. Keyword arguments: real -- the real part (default 0.0) imag -- the imaginary part (default 0.0) """ ctx = None db = getattr(g, '_odm', None) if db is None: _log( 'info', " * MongoDB Connection created DB Object %s in Context %s " % (hex(id(db)), hex(id(ctx)))) db = g._odm = MongoEngine(current_app) return db
def _reloader_stat_loop(fnames, interval=1): mtimes = {} while 1: for filename in fnames: try: mtime = os.stat(filename).st_mtime except OSError: continue old_time = mtimes.get(filename) if old_time is None: mtimes[filename] = mtime continue elif mtime > old_time: _log('info', ' * Detected change in %r, reloading' % filename) sys.exit(3) time.sleep(interval)
def restart_with_reloader(): """Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. """ while 1: _log('info', ' * Restarting with reloader...') args = [sys.executable] + sys.argv new_environ = os.environ.copy() new_environ['WERKZEUG_RUN_MAIN'] = 'true' if os.name == 'nt': for key, value in new_environ.iteritems(): if isinstance(value, unicode): new_environ[key] = value.encode('iso-8859-1') exit_code = subprocess.call(args, env=new_environ) if exit_code != 3: return exit_code
def restart_with_reloader(self): """Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. """ _log('info', ' * Restarting with %s' % self.name) args = [sys.executable] + sys.argv new_environ = os.environ.copy() new_environ['WERKZEUG_RUN_MAIN'] = 'true' exit_code = 3 while exit_code == 3: self.process = yield from asyncio.create_subprocess_shell( ' '.join(args), env=new_environ, cwd=os.getcwd(), stdout=sys.stdout) exit_code = yield from self.process.wait() return exit_code
def reloader_loop(extra_files=None, interval=1): """When this function is run from the main thread, it will force other threads to exit when any modules currently loaded change. Copyright notice. This function is based on the autoreload.py from the CherryPy trac which originated from WSGIKit which is now dead. :param extra_files: a list of additional files it should watch. """ def iter_module_files(): for module in sys.modules.values(): filename = getattr(module, '__file__', None) if filename: old = None while not os.path.isfile(filename): old = filename filename = os.path.dirname(filename) if filename == old: break else: if filename[-4:] in ('.pyc', '.pyo'): filename = filename[:-1] yield filename mtimes = {} while 1: for filename in chain(iter_module_files(), extra_files or ()): try: mtime = os.stat(filename).st_mtime except OSError: continue old_time = mtimes.get(filename) if old_time is None: mtimes[filename] = mtime continue elif mtime > old_time: _log('info', ' * Detected change in %r, reloading' % filename) sys.exit(3) time.sleep(interval)