def test_find_mod_for_url_youtube(self): url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ' server.setup() handler = server.find_mod_for_url(url) self.assertEqual("handlers.youtube", handler.__name__)
def test_find_mod_for_url_youtube_with_other_params(self): url = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=xxxxx' server.setup() handler = server.find_mod_for_url(url) self.assertEqual("handlers.youtube", handler.__name__)
def test_find_mod_for_url_html_default(self): url = 'https://www.google.com' server.setup() handler = server.find_mod_for_url(url) self.assertEqual("handlers.html_default", handler.__name__)
def startServer(): global root root.withdraw() #hide the root Tk instance (the current window) server.setup() #setup the server (import the config and net types declaration) serverWindow = rootTopLevel(root) #create a toplevel to hold the server gui server.initTk(serverWindow) #initialize the server tkinter gui using the Toplevel just created as the parent server.initListner() #initialize the server listner to listner for incomming connections
def get_wsgi_application(): """ The public interface to Server's WSGI support. Return a WSGI callable. Avoids making server.core.handlers.WSGIHandler a public API, in case the internal WSGI implementation changes or moves in the future. """ server.setup(set_prefix=False) return WSGIHandler()
def run(): schedule.every().day.at("%s:00" % (ON_HOUR % 24)).do(wake) schedule.every().day.at("%s:00" % (OFF_HOUR % 24)).do(sleep) setup(set_mode, set_brightness) if is_on_time(): wake() else: sleep() while True: schedule.run_pending() ctrl.tick()
# # start the server # import sys from bottle import run from server import setup if len(sys.argv) > 2: base = sys.argv[1] conf_fn = sys.argv[2] setup(base,conf_fn) run(host='localhost', port=8080) else: print "usage:", sys.argv[0],"[base_dir] [conf file]"
def test_pfioh_constructor(self): parser = ArgumentParser(description=str_desc, formatter_class=RawTextHelpFormatter) parser.add_argument('--ip', action='store', dest='ip', default='localhost', help='IP to expose.') parser.add_argument('--port', action='store', dest='port', default='5055', help='Port to use.') parser.add_argument( '--forever', help= 'if specified, serve forever, otherwise terminate after single service.', dest='b_forever', action='store_true', default=False) parser.add_argument('--storeBase', action='store', dest='storeBase', default='/tmp', help='Base path for internal storage.') parser.add_argument('--swift-storage', action='store_true', dest='b_swiftStorage', default=False, help='If specified, use Swift as object Storage') parser.add_argument('--httpResponse', help='if specified, return HTTP responses', dest='b_httpResponse', action='store_true', default=False) parser.add_argument( '--createDirsAsNeeded', help= 'if specified, allow the service to create base storage directories as needed', dest='b_createDirsAsNeeded', action='store_true', default=False) args = parser.parse_args() args.port = int(args.port) server = pfioh.ThreadedHTTPServer((args.ip, args.port), pfioh.StoreHandler) server.setup(args=vars(args), desc=str_desc) handler = pfioh.StoreHandler(test=True) handler.do_POST( d_msg={ "action": "hello", "meta": { "askAbout": "sysinfo", "echoBack": "Hi there!" } }) self.assertTrue(True)
# Run me with "twistd -ny launcher_s.tac.py -l -" # Run listening from twisted.internet import defer on_startup = defer.Deferred() import config from bitcoin_rpc import BitcoinRPC bitcoin_rpc = BitcoinRPC(config.BITCOIN_TRUSTED_HOST, config.BITCOIN_TRUSTED_PORT, config.BITCOIN_TRUSTED_USER, config.BITCOIN_TRUSTED_PASSWORD) # initialize the current prevhash (updated in BitcoindUpdater) current_prevhash = None # TODO: Start the VC twisted server here import server server.setup(on_startup) ################# # TODO: communication with bitcoind from bitcoind_updater import BitcoindUpdater BitcoindUpdater(bitcoin_rpc, current_prevhash) ################# # TODO: communication with VC database from db_updater import DBUpdater DBUpdater()
# # start the server # import sys from bottle import run from server import setup if len(sys.argv) > 2: base = sys.argv[1] conf_fn = sys.argv[2] setup(base, conf_fn) run(host='192.168.0.92', port=8080) else: print "usage:", sys.argv[0], "[base_dir] [conf file]"
def test_pfioh_constructor(self): parser = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter) parser.add_argument( '--ip', action = 'store', dest = 'ip', default = 'localhost', help = 'IP to expose.' ) parser.add_argument( '--port', action = 'store', dest = 'port', default = '5055', help = 'Port to use.' ) parser.add_argument( '--forever', help = 'if specified, serve forever, otherwise terminate after single service.', dest = 'b_forever', action = 'store_true', default = False ) parser.add_argument( '--storeBase', action = 'store', dest = 'storeBase', default = '/tmp', help = 'Base path for internal storage.' ) parser.add_argument( '--swift-storage', action = 'store_true', dest = 'b_swiftStorage', default = False, help = 'If specified, use Swift as object Storage' ) parser.add_argument( '--httpResponse', help = 'if specified, return HTTP responses', dest = 'b_httpResponse', action = 'store_true', default = False ) parser.add_argument( '--createDirsAsNeeded', help = 'if specified, allow the service to create base storage directories as needed', dest = 'b_createDirsAsNeeded', action = 'store_true', default = False ) args = parser.parse_args() args.port = int(args.port) server = pfioh.ThreadedHTTPServer((args.ip, args.port), pfioh.StoreHandler) server.setup(args = vars(args), desc = str_desc) handler = pfioh.StoreHandler(test = True) handler.do_POST( d_msg = { "action": "hello", "meta": { "askAbout": "sysinfo", "echoBack": "Hi there!" } } ) self.assertTrue(True)
self.log_queue.put(line) def info(self, i): line = u'[%s] [INFO] %s' % (str(self.get_readable_time()), i) self.log_queue.put(line) def process_queue(self): while not self.abort: try: log_line = self.log_queue.get(timeout=1) print log_line self.file.write("%s\n" % log_line) self.file.flush() except Queue.Empty: pass def stop(self): self.abort = True log = PymineLogger() server = server.Server(log) server.setup() try: server.listen() except KeyboardInterrupt: log.info("Gracefully terminating") log.stop() server.close() except Exception, e: log.error(e)
def handle(self, app_or_project, name, target=None, **options): self.app_or_project = app_or_project self.paths_to_remove = [] self.verbosity = options['verbosity'] self.validate_name(name, app_or_project) # if some directory is given, make sure it's nicely expanded if target is None: top_dir = path.join(os.getcwd(), name) try: os.makedirs(top_dir) except FileExistsError: raise CommandError("'%s' already exists" % top_dir) except OSError as e: raise CommandError(e) else: top_dir = os.path.abspath(path.expanduser(target)) if not os.path.exists(top_dir): raise CommandError("Destination directory '%s' does not " "exist, please create it first." % top_dir) extensions = tuple(handle_extensions(options['extensions'])) extra_files = [] for file in options['files']: extra_files.extend(map(lambda x: x.strip(), file.split(','))) if self.verbosity >= 2: self.stdout.write("Rendering %s template files with " "extensions: %s\n" % (app_or_project, ', '.join(extensions))) self.stdout.write("Rendering %s template files with " "filenames: %s\n" % (app_or_project, ', '.join(extra_files))) base_name = '%s_name' % app_or_project base_subdir = '%s_template' % app_or_project base_directory = '%s_directory' % app_or_project camel_case_name = 'camel_case_%s_name' % app_or_project camel_case_value = ''.join(x for x in name.title() if x != '_') context = Context( { **options, base_name: name, base_directory: top_dir, camel_case_name: camel_case_value, 'docs_version': get_docs_version(), 'server_version': server.__version__, }, autoescape=False) # Setup a stub settings environment for template rendering if not settings.configured: settings.configure() server.setup() template_dir = self.handle_template(options['template'], base_subdir) prefix_length = len(template_dir) + 1 for root, dirs, files in os.walk(template_dir): path_rest = root[prefix_length:] relative_dir = path_rest.replace(base_name, name) if relative_dir: target_dir = path.join(top_dir, relative_dir) if not path.exists(target_dir): os.mkdir(target_dir) for dirname in dirs[:]: if dirname.startswith('.') or dirname == '__pycache__': dirs.remove(dirname) for filename in files: if filename.endswith(('.pyo', '.pyc', '.py.class')): # Ignore some files as they cause various breakages. continue old_path = path.join(root, filename) new_path = path.join(top_dir, relative_dir, filename.replace(base_name, name)) for old_suffix, new_suffix in self.rewrite_template_suffixes: if new_path.endswith(old_suffix): new_path = new_path[:-len(old_suffix)] + new_suffix break # Only rewrite once if path.exists(new_path): raise CommandError("%s already exists, overlaying a " "project or app into an existing " "directory won't replace conflicting " "files" % new_path) # Only render the Python files, as we don't want to # accidentally render Server templates files if new_path.endswith(extensions) or filename in extra_files: with open(old_path, 'r', encoding='utf-8') as template_file: content = template_file.read() template = Engine().from_string(content) content = template.render(context) with open(new_path, 'w', encoding='utf-8') as new_file: new_file.write(content) else: shutil.copyfile(old_path, new_path) if self.verbosity >= 2: self.stdout.write("Creating %s\n" % new_path) try: shutil.copymode(old_path, new_path) self.make_writeable(new_path) except OSError: self.stderr.write( "Notice: Couldn't set permission bits on %s. You're " "probably using an uncommon filesystem setup. No " "problem." % new_path, self.style.NOTICE) if self.paths_to_remove: if self.verbosity >= 2: self.stdout.write("Cleaning up temporary files.\n") for path_to_remove in self.paths_to_remove: if path.isfile(path_to_remove): os.remove(path_to_remove) else: shutil.rmtree(path_to_remove)
def execute(self): """ Given the command-line arguments, figure out which subcommand is being run, create a parser appropriate to that command, and run it. """ try: subcommand = self.argv[1] except IndexError: subcommand = 'help' # Display help if no arguments were given. # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands that are available, so they # must be processed early. parser = CommandParser(usage='%(prog)s subcommand [options] [args]', add_help=False, allow_abbrev=False) parser.add_argument('--settings') parser.add_argument('--pythonpath') parser.add_argument('args', nargs='*') # catch-all try: options, args = parser.parse_known_args(self.argv[2:]) handle_default_options(options) except CommandError: pass # Ignore any option errors at this point. try: settings.INSTALLED_APPS except ImproperlyConfigured as exc: self.settings_exception = exc except ImportError as exc: self.settings_exception = exc if settings.configured: # Start the auto-reloading dev server even if the code is broken. # The hardcoded condition is a code smell but we can't rely on a # flag on the command class because we haven't located it yet. if subcommand == 'runserver' and '--noreload' not in self.argv: try: autoreload.check_errors(server.setup)() except Exception: # The exception will be raised later in the child process # started by the autoreloader. Pretend it didn't happen by # loading an empty list of applications. apps.all_models = defaultdict(OrderedDict) apps.app_configs = OrderedDict() apps.apps_ready = apps.models_ready = apps.ready = True # Remove options not compatible with the built-in runserver # (e.g. options for the contrib.staticfiles' runserver). # Changes here require manually testing as described in # #27522. _parser = self.fetch_command('runserver').create_parser( 'server', 'runserver') _options, _args = _parser.parse_known_args(self.argv[2:]) for _arg in _args: self.argv.remove(_arg) # In all other cases, server.setup() is required to succeed. else: server.setup() self.autocomplete() if subcommand == 'help': if '--commands' in args: sys.stdout.write( self.main_help_text(commands_only=True) + '\n') elif not options.args: sys.stdout.write(self.main_help_text() + '\n') else: self.fetch_command(options.args[0]).print_help( self.prog_name, options.args[0]) # Special-cases: We want 'server-admin --version' and # 'server-admin --help' to work, for backwards compatibility. elif subcommand == 'version' or self.argv[1:] == ['--version']: sys.stdout.write(server.get_version() + '\n') elif self.argv[1:] in (['--help'], ['-h']): sys.stdout.write(self.main_help_text() + '\n') else: self.fetch_command(subcommand).run_from_argv(self.argv)
import server json_string = '{ "lambda_name" : "grayscaleLambda", "key" : "video.mp4" }' server.setup("./grayscaleLambda.zip", json_string)
import server #Configuracao do Servidor #Deve ser executado antes de executar o Cliente, caso contrario, a conexao #sera recusada print('Digite 1 para TCP caso contrario, sera UDP') choice = input() #Inicializacao do Servidor server.setup(choice)
def start_server(): server.setup() server.start()
'Meat Temp': topic: test_topic json_template: '{{ meat_temp }}' Meat5: 'Meat Temp': topic: test_topic json_template: '{{ meat_temp }}' """ % server if __name__ == '__main__': settings = yaml.load(test_settings) if os.path.isfile("./Oven.db"): os.remove("./Oven.db") app = Flask(__name__, static_url_path='', static_folder='static') app.secret_key = SECRET_KEY app.config['SESSION_TYPE'] = 'memcache' app.config['ADMIN_USERNAME'] = "******" app.config['ADMIN_PASSWORD'] = "******" socketio = SocketIO(app, async_mode='gevent', logger=True, engineio_logger=True) setup(app, socketio, **settings) socketio.run(app, host="0.0.0.0", port=3000, debug=True, use_reloader=False)
# ------------------------------------------------------------------------------ # ViUR admin tool specific configurations # conf["admin.vi.name"] = "{{app_id}}" #conf["admin.vi.logo"] = "/static/meta/logo.svg" # ------------------------------------------------------------------------------ # Content Security Policy # conf["viur.security.contentSecurityPolicy"] = {} # ------------------------------------------------------------------------------ # Bugsnag: Tell us what is wrong! # #conf["bugsnag.apiKey" ] = "INSERT YOUR BUGSNAG API KEY HERE" # ------------------------------------------------------------------------------ # Server startup # import server, modules #server.setDefaultLanguage("en") #set default language! application = server.setup(modules, server.render) if __name__ == '__main__': server.run()
securityheaders.addCspRule("style-src", "fonts.googleapis.com", "enforce") securityheaders.addCspRule("style-src", "unsafe-inline", "enforce") # securityheaders.addCspRule("style-src","hello.myfonts.net","enforce") #Noop! securityheaders.addCspRule("frame-src", "self", "enforce") securityheaders.addCspRule("frame-src", "www.youtube-nocookie.com", "enforce") securityheaders.addCspRule("frame-src", "www.youtube.com", "enforce") securityheaders.addCspRule("frame-src", "docs.google.com", "enforce") securityheaders.addCspRule("frame-src", "maps.google.de", "enforce") securityheaders.addCspRule("frame-src", "www.google.com", "enforce") securityheaders.addCspRule("frame-src", "drive.google.com", "enforce") securityheaders.addCspRule("frame-src", "accounts.google.com", "enforce") server.setDefaultLanguage("de") application = server.setup(modules) conf["viur.availableLanguages"] = ["de"] conf["viur.defaultLanguage"] = "de" conf["viur.languageMethod"] = "url" conf["viur.forceSSL"] = True conf["viur.db.caching"] = 0 conf["viur.debug.traceQueries"] = True conf["viur.debug.traceExternalCallRouting"] = True conf["viur.debug.traceInternalCallRouting"] = True def main(): server.run()
from robot import Robot import sys import server import os, re def start_flask_app(app): app.run(debug=True, threaded=True, port=8080, host='0.0.0.0') def start_robot_master(q): robot = Robot(q) robot.run() if __name__ == '__main__': env = sys.argv[1] if len(sys.argv) == 2 else 'default' config = import_module('conf.%s' % env).config os.system("rm -f static/*.jpg") q = Queue() flask_app = server.setup(q) p_flask = Process(target=start_flask_app, args=(flask_app, )) p_flask.start() p_robot = Process(target=start_robot_master, args=(q, )) p_robot.start() p_robot.join()
# -*- coding: utf-8 -*- from flask import Flask,session,render_template from lib.RedisSesison import RedisSessionInterface app = Flask(__name__) app.config.from_pyfile("settings.py") app.session_interface = RedisSessionInterface() import server server.setup(app) @app.before_request def make_session_permanent(): session.permanent = True @app.route('/') def test(): return render_template('login.html') @app.route('/name/<name>') def set_name(name): session['name'] = name return 'hi {0}'.format(name) def runserver(host=None,port=None): host = host or app.config['SERVER_HOST'] port = port or app.config['SERVER_PORT'] app.run(host,port)