text
stringlengths
81
112k
Get the new certificate. Returns the signed bytes. def sign_certificate(): """ Get the new certificate. Returns the signed bytes. """ LOGGER.info("Signing certificate...") cmd = [ 'openssl', 'req', '-in', os.path.join(gettempdir(), 'domain.csr'), '-outform', 'DER' ...
Encode cert bytes to PEM encoded cert file. def encode_certificate(result): """ Encode cert bytes to PEM encoded cert file. """ cert_body = """-----BEGIN CERTIFICATE-----\n{0}\n-----END CERTIFICATE-----\n""".format( "\n".join(textwrap.wrap(base64.b64encode(result).decode('utf8'), 64))) sign...
Helper function to make signed requests to Boulder def _send_signed_request(url, payload): """ Helper function to make signed requests to Boulder """ payload64 = _b64(json.dumps(payload).encode('utf8')) out = parse_account_key() header = get_boulder_header(out) protected = copy.deepcopy(h...
Shamelessly promote our little community. def shamelessly_promote(): """ Shamelessly promote our little community. """ click.echo("Need " + click.style("help", fg='green', bold=True) + "? Found a " + click.style("bug", fg='green', bold=True) + "? Let us " + click.style("k...
Main program execution handler. def handle(): # pragma: no cover """ Main program execution handler. """ try: cli = ZappaCLI() sys.exit(cli.handle()) except SystemExit as e: # pragma: no cover cli.on_exit() sys.exit(e.code) except KeyboardInterrupt: # pragma: n...
A shortcut property for settings of a stage. def stage_config(self): """ A shortcut property for settings of a stage. """ def get_stage_setting(stage, extended_stages=None): if extended_stages is None: extended_stages = [] if stage in extended_s...
Forcefully override a setting set by zappa_settings (for the current stage only) :param key: settings key :param val: value def override_stage_config_setting(self, key, val): """ Forcefully override a setting set by zappa_settings (for the current stage only) :param key: setting...
Main function. Parses command, load settings and dispatches accordingly. def handle(self, argv=None): """ Main function. Parses command, load settings and dispatches accordingly. """ desc = ('Zappa - Deploy Python applications to AWS Lambda' ' and API...
Given a command to execute and stage, execute that command. def dispatch_command(self, command, stage): """ Given a command to execute and stage, execute that command. """ self.api_stage = stage if command not in ['status', 'manage']: if not self.va...
Only build the package def package(self, output=None): """ Only build the package """ # Make sure we're in a venv. self.check_venv() # force not to delete the local zip self.override_stage_config_setting('delete_local_zip', False) # Execute the prebuild ...
Only build the template file. def template(self, lambda_arn, role_arn, output=None, json=False): """ Only build the template file. """ if not lambda_arn: raise ClickException("Lambda ARN is required to template.") if not role_arn: raise ClickException("...
Package your project, upload it to S3, register the Lambda function and create the API Gateway routes. def deploy(self, source_zip=None): """ Package your project, upload it to S3, register the Lambda function and create the API Gateway routes. """ if not source_zip: ...
Repackage and update the function code. def update(self, source_zip=None, no_upload=False): """ Repackage and update the function code. """ if not source_zip: # Make sure we're in a venv. self.check_venv() # Execute the prebuild script i...
Rollsback the currently deploy lambda code to a previous revision. def rollback(self, revision): """ Rollsback the currently deploy lambda code to a previous revision. """ print("Rolling back..") self.zappa.rollback_lambda_function_version( self.lambda_name, versio...
Tail this function's logs. if keep_open, do so repeatedly, printing any new logs def tail(self, since, filter_pattern, limit=10000, keep_open=True, colorize=True, http=False, non_http=False, force_colorize=False): """ Tail this function's logs. if keep_open, do so repeatedly, printing...
Tear down an existing deployment. def undeploy(self, no_confirm=False, remove_logs=False): """ Tear down an existing deployment. """ if not no_confirm: # pragma: no cover confirm = input("Are you sure you want to undeploy? [y/n] ") if confirm != 'y': ...
Update any cognito triggers def update_cognito_triggers(self): """ Update any cognito triggers """ if self.cognito: user_pool = self.cognito.get('user_pool') triggers = self.cognito.get('triggers', []) lambda_configs = set() for trigger in...
Given a a list of functions and a schedule to execute them, setup up regular execution. def schedule(self): """ Given a a list of functions and a schedule to execute them, setup up regular execution. """ events = self.stage_config.get('events', []) if events: ...
Given a a list of scheduled functions, tear down their regular execution. def unschedule(self): """ Given a a list of scheduled functions, tear down their regular execution. """ # Run even if events are not defined to remove previously existing ones (thus default to []...
Invoke a remote function. def invoke(self, function_name, raw_python=False, command=None, no_color=False): """ Invoke a remote function. """ # There are three likely scenarios for 'command' here: # command, which is a modular function path # raw_command, which is a ...
Formats correctly the string output from the invoke() method, replacing line breaks and tabs when necessary. def format_invoke_command(self, string): """ Formats correctly the string output from the invoke() method, replacing line breaks and tabs when necessary. """ str...
Apply various heuristics to return a colorized version the invoke command string. If these fail, simply return the string in plaintext. Inspired by colorize_log_entry(). def colorize_invoke_command(self, string): """ Apply various heuristics to return a colorized version the invoke ...
Describe the status of the current deployment. def status(self, return_json=False): """ Describe the status of the current deployment. """ def tabular_print(title, value): """ Convenience function for priting formatted table items. """ cl...
Make sure the environment contains only strings (since putenv needs a string) def check_environment(self, environment): """ Make sure the environment contains only strings (since putenv needs a string) """ non_strings = [] for (k,v) in environment.items(): ...
Initialize a new Zappa project by creating a new zappa_settings.json in a guided process. This should probably be broken up into few separate componants once it's stable. Testing these inputs requires monkeypatching with mock, which isn't pretty. def init(self, settings_file="zappa_settings.json"): ...
Register or update a domain certificate for this env. def certify(self, no_confirm=True, manual=False): """ Register or update a domain certificate for this env. """ if not self.domain: raise ClickException("Can't certify a domain without " + click.style("domain", fg="red",...
Spawn a debug shell. def shell(self): """ Spawn a debug shell. """ click.echo(click.style("NOTICE!", fg="yellow", bold=True) + " This is a " + click.style("local", fg="green", bold=True) + " shell, inside a " + click.style("Zappa", bold=True) + " object!") self.zappa.shell() ...
Allows the execution of custom code between creation of the zip file and deployment to AWS. :return: None def callback(self, position): """ Allows the execution of custom code between creation of the zip file and deployment to AWS. :return: None """ callbacks = self.s...
Print a warning if there's a new Zappa version available. def check_for_update(self): """ Print a warning if there's a new Zappa version available. """ try: version = pkg_resources.require("zappa")[0].version updateable = check_new_version_available(version) ...
Load the local zappa_settings file. An existing boto session can be supplied, though this is likely for testing purposes. Returns the loaded Zappa object. def load_settings(self, settings_file=None, session=None): """ Load the local zappa_settings file. An existing boto sessi...
Return zappa_settings path as JSON or YAML (or TOML), as appropriate. def get_json_or_yaml_settings(self, settings_name="zappa_settings"): """ Return zappa_settings path as JSON or YAML (or TOML), as appropriate. """ zs_json = settings_name + ".json" zs_yml = settings_name + ".y...
Load our settings file. def load_settings_file(self, settings_file=None): """ Load our settings file. """ if not settings_file: settings_file = self.get_json_or_yaml_settings() if not os.path.isfile(settings_file): raise ClickException("Please configure ...
Ensure that the package can be properly configured, and then create it. def create_package(self, output=None): """ Ensure that the package can be properly configured, and then create it. """ # Create the Lambda zip package (includes project and virtualenvironment) ...
Remove our local zip file. def remove_local_zip(self): """ Remove our local zip file. """ if self.stage_config.get('delete_local_zip', True): try: if os.path.isfile(self.zip_path): os.remove(self.zip_path) if self.handler_...
Remove the local and S3 zip file after uploading and updating. def remove_uploaded_zip(self): """ Remove the local and S3 zip file after uploading and updating. """ # Remove the uploaded zip from S3, because it is now registered.. if self.stage_config.get('delete_s3_zip', True)...
Cleanup after the command finishes. Always called: SystemExit, KeyboardInterrupt and any other Exception that occurs. def on_exit(self): """ Cleanup after the command finishes. Always called: SystemExit, KeyboardInterrupt and any other Exception that occurs. """ if self....
Parse, filter and print logs to the console. def print_logs(self, logs, colorize=True, http=False, non_http=False, force_colorize=None): """ Parse, filter and print logs to the console. """ for log in logs: timestamp = log['timestamp'] message = log['message'] ...
Determines if a log entry is an HTTP-formatted log string or not. def is_http_log_entry(self, string): """ Determines if a log entry is an HTTP-formatted log string or not. """ # Debug event filter if 'Zappa Event' in string: return False # IP address filter...
Apply various heuristics to return a colorized version of a string. If these fail, simply return the string in plaintext. def colorize_log_entry(self, string): """ Apply various heuristics to return a colorized version of a string. If these fail, simply return the string in plaintext. ...
Parse and execute the prebuild_script from the zappa_settings. def execute_prebuild_script(self): """ Parse and execute the prebuild_script from the zappa_settings. """ (pb_mod_path, pb_func) = self.prebuild_script.rsplit('.', 1) try: # Prefer prebuild script in working dire...
Given a string, print a warning if this could collide with a Zappa core package module. Use for app functions and events. def collision_warning(self, item): """ Given a string, print a warning if this could collide with a Zappa core package module. Use for app function...
Ensure we're inside a virtualenv. def check_venv(self): """ Ensure we're inside a virtualenv. """ if self.zappa: venv = self.zappa.get_current_venv() else: # Just for `init`, when we don't have settings yet. venv = Zappa.get_current_venv() if not venv...
Route all stdout to null. def silence(self): """ Route all stdout to null. """ sys.stdout = open(os.devnull, 'w') sys.stderr = open(os.devnull, 'w')
Test the deployed endpoint with a GET request. def touch_endpoint(self, endpoint_url): """ Test the deployed endpoint with a GET request. """ # Private APIGW endpoints most likely can't be reached by a deployer # unless they're connected to the VPC by VPN. Instead of trying ...
Permute all casings of a given string. A pretty algorithm, via @Amber http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python def all_casings(input_string): """ Permute all casings of a given string. A pretty algorithm, via @Amber http://stackoverflow.com/q...
return a dict def status_count(self, project): ''' return a dict ''' result = dict() if project not in self.projects: self._list_project() if project not in self.projects: return result tablename = self._tablename(project) for stat...
Get encoding from request headers or page head. def get_encoding(headers, content): """Get encoding from request headers or page head.""" encoding = None content_type = headers.get('content-type') if content_type: _, params = cgi.parse_header(content_type) if 'charset' in params: ...
encoding of Response.content. if Response.encoding is None, encoding will be guessed by header or content or chardet if available. def encoding(self): """ encoding of Response.content. if Response.encoding is None, encoding will be guessed by header or content or chard...
Content of the response, in unicode. if Response.encoding is None and chardet module is available, encoding will be guessed. def text(self): """ Content of the response, in unicode. if Response.encoding is None and chardet module is available, encoding will be guessed....
Returns the json-encoded content of the response, if any. def json(self): """Returns the json-encoded content of the response, if any.""" if hasattr(self, '_json'): return self._json try: self._json = json.loads(self.text or self.content) except ValueError: ...
Returns a PyQuery object of the response's content def doc(self): """Returns a PyQuery object of the response's content""" if hasattr(self, '_doc'): return self._doc elements = self.etree doc = self._doc = PyQuery(elements) doc.make_links_absolute(utils.text(self.url...
Returns a lxml object of the response's content that can be selected by xpath def etree(self): """Returns a lxml object of the response's content that can be selected by xpath""" if not hasattr(self, '_elements'): try: parser = lxml.html.HTMLParser(encoding=self.encoding) ...
Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred. def raise_for_status(self, allow_redirects=True): """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred.""" if self.status_code == 304: return elif self.error: if self.traceback:...
Do not send process status package back to scheduler. It's used by callbacks like on_message, on_result etc... def not_send_status(func): """ Do not send process status package back to scheduler. It's used by callbacks like on_message, on_result etc... """ @functools.wraps(func) def wrapp...
A decorator for setting the default kwargs of `BaseHandler.crawl`. Any self.crawl with this callback will use this config. def config(_config=None, **kwargs): """ A decorator for setting the default kwargs of `BaseHandler.crawl`. Any self.crawl with this callback will use this config. """ if _c...
method will been called every minutes or seconds def every(minutes=NOTSET, seconds=NOTSET): """ method will been called every minutes or seconds """ def wrapper(func): # mark the function with variable 'is_cronjob=True', the function would be # collected into the list Handler._cron_jobs...
Catch errors of rabbitmq then reconnect def catch_error(func): """Catch errors of rabbitmq then reconnect""" import amqp try: import pika.exceptions connect_exceptions = ( pika.exceptions.ConnectionClosed, pika.exceptions.AMQPConnectionError, ) except Imp...
Reconnect to rabbitmq server def reconnect(self): """Reconnect to rabbitmq server""" import pika import pika.exceptions self.connection = pika.BlockingConnection(pika.URLParameters(self.amqp_url)) self.channel = self.connection.channel() try: self.channel.qu...
Reconnect to rabbitmq server def reconnect(self): """Reconnect to rabbitmq server""" parsed = urlparse.urlparse(self.amqp_url) port = parsed.port or 5672 self.connection = amqp.Connection(host="%s:%s" % (parsed.hostname, port), userid=parsed.use...
Put a task into task queue when use heap sort, if we put tasks(with the same priority and exetime=0) into queue, the queue is not a strict FIFO queue, but more like a FILO stack. It is very possible that when there are continuous big flow, the speed of select is slower than req...
Get a task from queue when bucket available def get(self): '''Get a task from queue when bucket available''' if self.bucket.get() < 1: return None now = time.time() self.mutex.acquire() try: task = self.priority_queue.get_nowait() self.bucket....
Mark task done def done(self, taskid): '''Mark task done''' if taskid in self.processing: self.mutex.acquire() if taskid in self.processing: del self.processing[taskid] self.mutex.release() return True return False
return True if taskid is in processing def is_processing(self, taskid): ''' return True if taskid is in processing ''' return taskid in self.processing and self.processing[taskid].taskid
handler the log records to formatted string def logstr(self): """handler the log records to formatted string""" result = [] formater = LogFormatter(color=False) for record in self.logs: if isinstance(record, six.string_types): result.append(pretty_unicode(re...
Deal one task def on_task(self, task, response): '''Deal one task''' start_time = time.time() response = rebuild_response(response) try: assert 'taskid' in task, 'need taskid in task' project = task['project'] updatetime = task.get('project_updatetim...
Run loop def run(self): '''Run loop''' logger.info("processor starting...") while not self._quit: try: task, response = self.inqueue.get(timeout=1) self.on_task(task, response) self._exceptions = 0 except Queue.Empty as e:...
create connection to message queue name: name of message queue rabbitmq: amqp://username:password@host:5672/%2F see https://www.rabbitmq.com/uri-spec.html beanstalk: beanstalk://host:11300/ redis: redis://host:6379/db redis://host1:port1,host2:port2,...,...
Hide stack traceback of given stack def hide_me(tb, g=globals()): """Hide stack traceback of given stack""" base_tb = tb try: while tb and tb.tb_frame.f_globals is not g: tb = tb.tb_next while tb and tb.tb_frame.f_globals is g: tb = tb.tb_next except Exception as...
Run function in subprocess, return a Process object def run_in_subprocess(func, *args, **kwargs): """Run function in subprocess, return a Process object""" from multiprocessing import Process thread = Process(target=func, args=args, kwargs=kwargs) thread.daemon = True thread.start() return thre...
Formats the given date (which should be GMT). By default, we return a relative time (e.g., "2 minutes ago"). You can return an absolute date string with ``relative=False``. You can force a full format date ("July 10, 1980") with ``full_format=True``. This method is primarily intended for dates in...
Make sure string is utf8 encoded bytes. If parameter is a object, object.__str__ will been called before encode as bytes def utf8(string): """ Make sure string is utf8 encoded bytes. If parameter is a object, object.__str__ will been called before encode as bytes """ if isinstance(string, six...
Make sure string is unicode type, decode with given encoding if it's not. If parameter is a object, object.__str__ will been called def text(string, encoding='utf8'): """ Make sure string is unicode type, decode with given encoding if it's not. If parameter is a object, object.__str__ will been calle...
Make sure string is unicode, try to decode with utf8, or unicode escaped string if failed. def pretty_unicode(string): """ Make sure string is unicode, try to decode with utf8, or unicode escaped string if failed. """ if isinstance(string, six.text_type): return string try: return s...
Make sure string is unicode, try to default with utf8, or base64 if failed. can been decode by `decode_unicode_string` def unicode_string(string): """ Make sure string is unicode, try to default with utf8, or base64 if failed. can been decode by `decode_unicode_string` """ if isinstance(strin...
Make sure keys and values of dict is unicode. def unicode_dict(_dict): """ Make sure keys and values of dict is unicode. """ r = {} for k, v in iteritems(_dict): r[unicode_obj(k)] = unicode_obj(v) return r
Make sure keys and values of dict/list/tuple is unicode. bytes will encode in base64. Can been decode by `decode_unicode_obj` def unicode_obj(obj): """ Make sure keys and values of dict/list/tuple is unicode. bytes will encode in base64. Can been decode by `decode_unicode_obj` """ if isinstan...
Decode string encoded by `unicode_string` def decode_unicode_string(string): """ Decode string encoded by `unicode_string` """ if string.startswith('[BASE64-DATA]') and string.endswith('[/BASE64-DATA]'): return base64.b64decode(string[len('[BASE64-DATA]'):-len('[/BASE64-DATA]')]) return str...
Decode unicoded dict/list/tuple encoded by `unicode_obj` def decode_unicode_obj(obj): """ Decode unicoded dict/list/tuple encoded by `unicode_obj` """ if isinstance(obj, dict): r = {} for k, v in iteritems(obj): r[decode_unicode_string(k)] = decode_unicode_obj(v) ret...
Load object from module def load_object(name): """Load object from module""" if "." not in name: raise Exception('load object need module.object') module_name, object_name = name.rsplit('.', 1) if six.PY2: module = __import__(module_name, globals(), locals(), [utf8(object_name)], -1) ...
Return a interactive python console instance with caller's stack def get_python_console(namespace=None): """ Return a interactive python console instance with caller's stack """ if namespace is None: import inspect frame = inspect.currentframe() caller = frame.f_back if...
Start a interactive python console with caller's stack def python_console(namespace=None): """Start a interactive python console with caller's stack""" if namespace is None: import inspect frame = inspect.currentframe() caller = frame.f_back if not caller: logging.e...
XMLRPC service for windmill browser core to communicate with def handler(self, environ, start_response): """XMLRPC service for windmill browser core to communicate with""" if environ['REQUEST_METHOD'] == 'POST': return self.handle_POST(environ, start_response) else: sta...
Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. def handle_POST(self, environ, start_r...
create database object by url mysql: mysql+type://user:passwd@host:port/database sqlite: # relative path sqlite+type:///path/to/database.db # absolute path sqlite+type:////path/to/database.db # memory database sqlite+type:// mongodb: mongodb+t...
Check project update def _update_projects(self): '''Check project update''' now = time.time() if ( not self._force_update_project and self._last_update_project + self.UPDATE_PROJECT_INTERVAL > now ): return for project in self.projectd...
update one project def _update_project(self, project): '''update one project''' if project['name'] not in self.projects: self.projects[project['name']] = Project(self, project) else: self.projects[project['name']].update(project) project = self.projects[project[...
load tasks from database def _load_tasks(self, project): '''load tasks from database''' task_queue = project.task_queue for task in self.taskdb.load_tasks( self.taskdb.ACTIVE, project.name, self.scheduler_task_fields ): taskid = task['taskid'] _s...
return False if any of 'taskid', 'project', 'url' is not in task dict or project in not in task_queue def task_verify(self, task): ''' return False if any of 'taskid', 'project', 'url' is not in task dict or project in not in task_queue ''' ...
put task to task queue def put_task(self, task): '''put task to task queue''' _schedule = task.get('schedule', self.default_schedule) self.projects[task['project']].task_queue.put( task['taskid'], priority=_schedule.get('priority', self.default_schedule['priority']), ...
dispatch task to fetcher out queue may have size limit to prevent block, a send_buffer is used def send_task(self, task, force=True): ''' dispatch task to fetcher out queue may have size limit to prevent block, a send_buffer is used ''' try: self.out_queue....
Check status queue def _check_task_done(self): '''Check status queue''' cnt = 0 try: while True: task = self.status_queue.get_nowait() # check _on_get_info result here if task.get('taskid') == '_on_get_info' and 'project' in task and '...
Check new task queue def _check_request(self): '''Check new task queue''' # check _postpone_request first todo = [] for task in self._postpone_request: if task['project'] not in self.projects: continue if self.projects[task['project']].task_queue....
Check projects cronjob tick, return True when a new tick is sended def _check_cronjob(self): """Check projects cronjob tick, return True when a new tick is sended""" now = time.time() self._last_tick = int(self._last_tick) if now - self._last_tick < 1: return False s...
Select task to fetch & process def _check_select(self): '''Select task to fetch & process''' while self._send_buffer: _task = self._send_buffer.pop() try: # use force=False here to prevent automatic send_buffer append and get exception self.send_t...
Dump counters to file def _dump_cnt(self): '''Dump counters to file''' self._cnt['1h'].dump(os.path.join(self.data_path, 'scheduler.1h')) self._cnt['1d'].dump(os.path.join(self.data_path, 'scheduler.1d')) self._cnt['all'].dump(os.path.join(self.data_path, 'scheduler.all'))
Dump counters every 60 seconds def _try_dump_cnt(self): '''Dump counters every 60 seconds''' now = time.time() if now - self._last_dump_cnt > 60: self._last_dump_cnt = now self._dump_cnt() self._print_counter_log()
Check project delete def _check_delete(self): '''Check project delete''' now = time.time() for project in list(itervalues(self.projects)): if project.db_status != 'STOP': continue if now - project.updatetime < self.DELETE_TIME: continue ...
Set quit signal def quit(self): '''Set quit signal''' self._quit = True # stop xmlrpc server if hasattr(self, 'xmlrpc_server'): self.xmlrpc_ioloop.add_callback(self.xmlrpc_server.stop) self.xmlrpc_ioloop.add_callback(self.xmlrpc_ioloop.stop)
comsume queues and feed tasks to fetcher, once def run_once(self): '''comsume queues and feed tasks to fetcher, once''' self._update_projects() self._check_task_done() self._check_request() while self._check_cronjob(): pass self._check_select() self....
Start scheduler loop def run(self): '''Start scheduler loop''' logger.info("scheduler starting...") while not self._quit: try: time.sleep(self.LOOP_INTERVAL) self.run_once() self._exceptions = 0 except KeyboardInterrupt: ...