INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Extracts video ID from URL.
def get_vid_from_url(url): """Extracts video ID from URL. """ return match1(url, r'youtu\.be/([^?/]+)') or \ match1(url, r'youtube\.com/embed/([^/?]+)') or \ match1(url, r'youtube\.com/v/([^/?]+)') or \ match1(url, r'youtube\.com/watch/([^/?]+)') or \ pars...
str - > list Convert XML to URL List. From Biligrab.
def sina_xml_to_url_list(xml_data): """str->list Convert XML to URL List. From Biligrab. """ rawurl = [] dom = parseString(xml_data) for node in dom.getElementsByTagName('durl'): url = node.getElementsByTagName('url')[0] rawurl.append(url.childNodes[0].data) return rawurl
From http:// cdn37. atwikiimg. com/ sitescript/ pub/ dksitescript/ FC2. site. js Also com. hps. util. fc2. FC2EncrptUtil. makeMimiLocal L110
def makeMimi(upid): """From http://cdn37.atwikiimg.com/sitescript/pub/dksitescript/FC2.site.js Also com.hps.util.fc2.FC2EncrptUtil.makeMimiLocal L110""" strSeed = "gGddgPfeaf_gzyr" prehash = upid + "_" + strSeed return md5(prehash.encode('utf-8')).hexdigest()
wrapper
def fc2video_download(url, output_dir = '.', merge = True, info_only = False, **kwargs): """wrapper""" #'http://video.fc2.com/en/content/20151021bTVKnbEw' #'http://xiaojiadianvideo.asia/content/20151021bTVKnbEw' #'http://video.fc2.com/ja/content/20151021bTVKnbEw' #'http://video.fc2.com/tw/content/20...
Downloads Dailymotion videos by URL.
def dailymotion_download(url, output_dir='.', merge=True, info_only=False, **kwargs): """Downloads Dailymotion videos by URL. """ html = get_content(rebuilt_url(url)) info = json.loads(match1(html, r'qualities":({.+?}),"')) title = match1(html, r'"video_title"\s*:\s*"([^"]+)"') or \ mat...
http:// stackoverflow. com/ a/ 30923963/ 2946714
def dictify(r,root=True): """http://stackoverflow.com/a/30923963/2946714""" if root: return {r.tag : dictify(r, False)} d=copy(r.attrib) if r.text: d["_text"]=r.text for x in r.findall("./*"): if x.tag not in d: d[x.tag]=[] d[x.tag].append(dictify(x,False)...
video page
def ucas_download_single(url, output_dir = '.', merge = False, info_only = False, **kwargs): '''video page''' html = get_content(url) # resourceID is UUID resourceID = re.findall( r'resourceID":"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})', html)[0] assert resourceID != '', 'Canno...
course page
def ucas_download_playlist(url, output_dir = '.', merge = False, info_only = False, **kwargs): '''course page''' html = get_content(url) parts = re.findall( r'(getplaytitle.do\?.+)"', html) assert parts, 'No part found!' for part_path in parts: ucas_download('http://v.ucas.ac.cn/course/' +...
Downloads a Sina video by its unique vid. http:// video. sina. com. cn/
def sina_download_by_vid(vid, title=None, output_dir='.', merge=True, info_only=False): """Downloads a Sina video by its unique vid. http://video.sina.com.cn/ """ xml = api_req(vid) urls, name, size = video_info(xml) if urls is None: log.wtf(name) title = name print_info(site_inf...
Downloads a Sina video by its unique vkey. http:// video. sina. com/
def sina_download_by_vkey(vkey, title=None, output_dir='.', merge=True, info_only=False): """Downloads a Sina video by its unique vkey. http://video.sina.com/ """ url = 'http://video.sina.com/v/flvideo/%s_0.flv' % vkey type, ext, size = url_info(url) print_info(site_info, title, 'flv', size) ...
Downloads Sina videos by URL.
def sina_download(url, output_dir='.', merge=True, info_only=False, **kwargs): """Downloads Sina videos by URL. """ if 'news.sina.com.cn/zxt' in url: sina_zxt(url, output_dir=output_dir, merge=merge, info_only=info_only, **kwargs) return vid = match1(url, r'vid=(\d+)') if vid is Non...
wrapper
def yixia_download(url, output_dir = '.', merge = True, info_only = False, **kwargs): """wrapper""" hostname = urlparse(url).hostname if 'n.miaopai.com' == hostname: smid = match1(url, r'n\.miaopai\.com/media/([^.]+)') miaopai_download_by_smid(smid, output_dir, merge, info_only) re...
Get item_id
def veoh_download(url, output_dir = '.', merge = False, info_only = False, **kwargs): '''Get item_id''' if re.match(r'http://www.veoh.com/watch/\w+', url): item_id = match1(url, r'http://www.veoh.com/watch/(\w+)') elif re.match(r'http://www.veoh.com/m/watch.php\?v=\.*', url): item_id = match...
Source: Android mobile
def veoh_download_by_id(item_id, output_dir = '.', merge = False, info_only = False, **kwargs): """Source: Android mobile""" webpage_url = 'http://www.veoh.com/m/watch.php?v={item_id}&quality=1'.format(item_id = item_id) #grab download URL a = get_content(webpage_url, decoded=True) url = match1(a, ...
self str - > None Keyword arguments: self: self vid: The video ID for BokeCC cloud something like FE3BB999594978049C33DC5901307461 Calls the prepare () to download the video. If no title is provided this method shall try to find a proper title with the information providin within the returned content of the API.
def download_by_id(self, vid = '', title = None, output_dir='.', merge=True, info_only=False,**kwargs): """self, str->None Keyword arguments: self: self vid: The video ID for BokeCC cloud, something like FE3BB999594978049C33DC5901307461 Calls the prepare...
Extracts video ID from live. qq. com.
def get_vid_from_url(self, url): """Extracts video ID from live.qq.com. """ hit = re.search(r'live.qq.com/(\d+)', url) if hit is not None: return hit.group(1) hit = re.search(r'live.qq.com/directory/match/(\d+)', url) if hit is not None: return sel...
Format text with color or other effects into ANSI escaped string.
def sprint(text, *colors): """Format text with color or other effects into ANSI escaped string.""" return "\33[{}m{content}\33[{}m".format(";".join([str(color) for color in colors]), RESET, content=text) if IS_ANSI_TERMINAL and colors else text
Print a log message to standard error.
def print_log(text, *colors): """Print a log message to standard error.""" sys.stderr.write(sprint("{}: {}".format(script_name, text), *colors) + "\n")
Print an error log message.
def e(message, exit_code=None): """Print an error log message.""" print_log(message, YELLOW, BOLD) if exit_code is not None: sys.exit(exit_code)
What a Terrible Failure!
def wtf(message, exit_code=1): """What a Terrible Failure!""" print_log(message, RED, BOLD) if exit_code is not None: sys.exit(exit_code)
Detect operating system.
def detect_os(): """Detect operating system. """ # Inspired by: # https://github.com/scivision/pybashutils/blob/78b7f2b339cb03b1c37df94015098bbe462f8526/pybashutils/windows_linux_detect.py syst = system().lower() os = 'unknown' if 'cygwin' in syst: os = 'cygwin' elif 'darwin' ...
Source: Android mobile
def miaopai_download_by_fid(fid, output_dir = '.', merge = False, info_only = False, **kwargs): '''Source: Android mobile''' page_url = 'http://video.weibo.com/show?fid=' + fid + '&type=mp4' mobile_page = get_content(page_url, headers=fake_headers_mobile) url = match1(mobile_page, r'<video id=.*?src=[\...
str - > None
def vimeo_download_by_channel(url, output_dir='.', merge=False, info_only=False, **kwargs): """str->None""" # https://vimeo.com/channels/464686 channel_id = match1(url, r'http://vimeo.com/channels/(\w+)') vimeo_download_by_channel_id(channel_id, output_dir, merge, info_only, **kwargs)
str/ int - > None
def vimeo_download_by_channel_id(channel_id, output_dir='.', merge=False, info_only=False, **kwargs): """str/int->None""" html = get_content('https://api.vimeo.com/channels/{channel_id}/videos?access_token={access_token}'.format(channel_id=channel_id, access_token=access_token)) data = loads(html) id_li...
try: # normal Vimeo video html = get_content ( https:// vimeo. com/ + id ) cfg_patt = r clip_page_config \ s * = \ s * ( \ {. + ? \ } ) ; cfg = json. loads ( match1 ( html cfg_patt )) video_page = get_content ( cfg [ player ] [ config_url ] headers = fake_headers ) title = cfg [ clip ] [ title ] info = loads ( video_pa...
def vimeo_download_by_id(id, title=None, output_dir='.', merge=True, info_only=False, **kwargs): ''' try: # normal Vimeo video html = get_content('https://vimeo.com/' + id) cfg_patt = r'clip_page_config\s*=\s*(\{.+?\});' cfg = json.loads(match1(html, cfg_patt)) video_page...
str - > dict Information for CKPlayer API content.
def ckplayer_get_info_by_xml(ckinfo): """str->dict Information for CKPlayer API content.""" e = ET.XML(ckinfo) video_dict = {'title': '', #'duration': 0, 'links': [], 'size': 0, 'flashvars': '',} dictified = dictify(e)['ckplayer...
Splicing URLs according to video ID to get video details
def get_video_url_from_video_id(video_id): """Splicing URLs according to video ID to get video details""" # from js data = [""] * 256 for index, _ in enumerate(data): t = index for i in range(8): t = -306674912 ^ unsigned_right_shitf(t, 1) if 1 & t else unsigned_right_shitf(t...
Extracts video ID from URL.
def get_vid_from_url(url): """Extracts video ID from URL. """ vid = match1(url, 'https?://www.mgtv.com/(?:b|l)/\d+/(\d+).html') if not vid: vid = match1(url, 'https?://www.mgtv.com/hz/bdpz/\d+/(\d+).html') return vid
str - > list of str Give you the real URLs.
def get_mgtv_real_url(url): """str->list of str Give you the real URLs.""" content = loads(get_content(url)) m3u_url = content['info'] split = urlsplit(m3u_url) base_url = "{scheme}://{netloc}{path}/".format(scheme = split[0], ...
Get ( branch commit ) from HEAD of a git repo.
def get_head(repo_path): """Get (branch, commit) from HEAD of a git repo.""" try: ref = open(os.path.join(repo_path, '.git', 'HEAD'), 'r').read().strip()[5:].split('/') branch = ref[-1] commit = open(os.path.join(repo_path, '.git', *ref), 'r').read().strip()[:7] return branch, co...
Converts a string to a valid filename.
def legitimize(text, os=detect_os()): """Converts a string to a valid filename. """ # POSIX systems text = text.translate({ 0: None, ord('/'): '-', ord('|'): '-', }) # FIXME: do some filesystem detection if os == 'windows' or os == 'cygwin' or os == 'wsl': #...
Get ( width height ) of the current terminal.
def get_terminal_size(): """Get (width, height) of the current terminal.""" try: import fcntl, termios, struct # fcntl module only available on Unix return struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '1234')) except: return (40, 80)
Downloads CBS videos by URL.
def cbs_download(url, output_dir='.', merge=True, info_only=False, **kwargs): """Downloads CBS videos by URL. """ html = get_content(url) pid = match1(html, r'video\.settings\.pid\s*=\s*\'([^\']+)\'') title = match1(html, r'video\.settings\.title\s*=\s*\"([^\"]+)\"') theplatform_download_by_pi...
Override the original one Ugly ugly dirty hack
def download(self, **kwargs): """Override the original one Ugly ugly dirty hack""" if 'json_output' in kwargs and kwargs['json_output']: json_output.output(self) elif 'info_only' in kwargs and kwargs['info_only']: if 'stream_id' in kwargs and kwargs['stream_id']: ...
str str str bool bool - > None
def acfun_download_by_vid(vid, title, output_dir='.', merge=True, info_only=False, **kwargs): """str, str, str, bool, bool ->None Download Acfun video by vid. Call Acfun API, decide which site to use, and pass the job to its extractor. """ #first call the main parasing API info = json.loa...
Main entry point. you - get - dev
def main_dev(**kwargs): """Main entry point. you-get-dev """ # Get (branch, commit) if running from a git repo. head = git.get_head(kwargs['repo_path']) # Get options and arguments. try: opts, args = getopt.getopt(sys.argv[1:], _short_options, _options) except getopt.GetoptErro...
str str - > True WARNING: NOT THE SAME PARMS AS OTHER FUNCTIONS!!!!!! You can basicly download anything with this function but better leave it alone with
def ffmpeg_download_stream(files, title, ext, params={}, output_dir='.', stream=True): """str, str->True WARNING: NOT THE SAME PARMS AS OTHER FUNCTIONS!!!!!! You can basicly download anything with this function but better leave it alone with """ output = title + '.' + ext if not (output_dir...
Scans through a string for substrings matched some patterns ( first - subgroups only ).
def match1(text, *patterns): """Scans through a string for substrings matched some patterns (first-subgroups only). Args: text: A string to be scanned. patterns: Arbitrary number of regex patterns. Returns: When only one pattern is given, returns a string (None if no match found). ...
Scans through a string for substrings matched some patterns.
def matchall(text, patterns): """Scans through a string for substrings matched some patterns. Args: text: A string to be scanned. patterns: a list of regex pattern. Returns: a list if matched. empty if not. """ ret = [] for pattern in patterns: match = re.finda...
Parses the query string of a URL and returns the value of a parameter.
def parse_query_param(url, param): """Parses the query string of a URL and returns the value of a parameter. Args: url: A URL. param: A string representing the name of the parameter. Returns: The value of the parameter. """ try: return parse.parse_qs(parse.urlparse...
Decompresses data for Content - Encoding: gzip.
def ungzip(data): """Decompresses data for Content-Encoding: gzip. """ from io import BytesIO import gzip buffer = BytesIO(data) f = gzip.GzipFile(fileobj=buffer) return f.read()
Decompresses data for Content - Encoding: deflate. ( the zlib compression is used. )
def undeflate(data): """Decompresses data for Content-Encoding: deflate. (the zlib compression is used.) """ import zlib decompressobj = zlib.decompressobj(-zlib.MAX_WBITS) return decompressobj.decompress(data)+decompressobj.flush()
Gets the content of a URL via sending a HTTP GET request.
def get_content(url, headers={}, decoded=True): """Gets the content of a URL via sending a HTTP GET request. Args: url: A URL. headers: Request headers used by the client. decoded: Whether decode the response body using UTF-8 or the charset specified in Content-Type. Returns: ...
Post the content of a URL via sending a HTTP POST request.
def post_content(url, headers={}, post_data={}, decoded=True, **kwargs): """Post the content of a URL via sending a HTTP POST request. Args: url: A URL. headers: Request headers used by the client. decoded: Whether decode the response body using UTF-8 or the charset specified in Content...
Parses host name and port number from a string.
def parse_host(host): """Parses host name and port number from a string. """ if re.match(r'^(\d+)$', host) is not None: return ("0.0.0.0", int(host)) if re.match(r'^(\w+)://', host) is None: host = "//" + host o = parse.urlparse(host) hostname = o.hostname or "0.0.0.0" port =...
Overload default print function as py ( <3. 3 ) does not support flush keyword. Although the function name can be same as print to get itself overloaded automatically I d rather leave it with a different name and only overload it when importing to make less confusion.
def print_more_compatible(*args, **kwargs): import builtins as __builtin__ """Overload default print function as py (<3.3) does not support 'flush' keyword. Although the function name can be same as print to get itself overloaded automatically, I'd rather leave it with a different name and only overload...
str - > str
def showroom_get_roomid_by_room_url_key(room_url_key): """str->str""" fake_headers_mobile = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'UTF-8,*;q=0.5', 'Accept-Encoding': 'gzip,deflate,sdch', 'Accept-Language': 'en-US,en;q=0.8...
Source: Android mobile
def showroom_download_by_room_id(room_id, output_dir = '.', merge = False, info_only = False, **kwargs): '''Source: Android mobile''' while True: timestamp = str(int(time() * 1000)) api_endpoint = 'https://www.showroom-live.com/api/live/streaming_url?room_id={room_id}&_={timestamp}'.format(room_...
JSON int int int - > str Get a proper title with courseid + topicID + partID.
def _wanmen_get_title_by_json_topic_part(json_content, tIndex, pIndex): """JSON, int, int, int->str Get a proper title with courseid+topicID+partID.""" return '_'.join([json_content[0]['name'], json_content[0]['Topics'][tIndex]['name'], json_content[0]['Topics']...
int - > None Download a WHOLE course. Reuse the API call to save time.
def wanmen_download_by_course(json_api_content, output_dir='.', merge=True, info_only=False, **kwargs): """int->None Download a WHOLE course. Reuse the API call to save time.""" for tIndex in range(len(json_api_content[0]['Topics'])): for pIndex in range(len(json_api_content[0]['Topics'][t...
int int int - > None Download ONE PART of the course.
def wanmen_download_by_course_topic_part(json_api_content, tIndex, pIndex, output_dir='.', merge=True, info_only=False, **kwargs): """int, int, int->None Download ONE PART of the course.""" html = json_api_content title = _wanmen_get_title_by_json_topic_part(html, ...
int int - > list Get the height of the videos. Since brightcove is using 3 kinds of links: rtmp http and https we will be using the HTTPS one to make it secure. If somehow akamaihd. net is blocked by the Great Fucking Wall change the startswith https to http.
def get_streams_by_id(account_number, video_id): """ int, int->list Get the height of the videos. Since brightcove is using 3 kinds of links: rtmp, http and https, we will be using the HTTPS one to make it secure. If somehow akamaihd.net is bloc...
Checks if a task is either queued or running in this executor
def has_task(self, task_instance): """ Checks if a task is either queued or running in this executor :param task_instance: TaskInstance :return: True if the task is known to this executor """ if task_instance.key in self.queued_tasks or task_instance.key in self.running:...
Returns and flush the event buffer. In case dag_ids is specified it will only return and flush events for the given dag_ids. Otherwise it returns and flushes all
def get_event_buffer(self, dag_ids=None): """ Returns and flush the event buffer. In case dag_ids is specified it will only return and flush events for the given dag_ids. Otherwise it returns and flushes all :param dag_ids: to dag_ids to return events for, if None returns all ...
one method to fetch connection params as a dict used in get_uri () and get_connection ()
def _get_conn_params(self): """ one method to fetch connection params as a dict used in get_uri() and get_connection() """ conn = self.get_connection(self.snowflake_conn_id) account = conn.extra_dejson.get('account', None) warehouse = conn.extra_dejson.get('wareho...
override DbApiHook get_uri method for get_sqlalchemy_engine ()
def get_uri(self): """ override DbApiHook get_uri method for get_sqlalchemy_engine() """ conn_config = self._get_conn_params() uri = 'snowflake://{user}:{password}@{account}/{database}/' uri += '{schema}?warehouse={warehouse}&role={role}' return uri.format(**conn_...
Returns a snowflake. connection object
def get_conn(self): """ Returns a snowflake.connection object """ conn_config = self._get_conn_params() conn = snowflake.connector.connect(**conn_config) return conn
returns aws_access_key_id aws_secret_access_key from extra
def _get_aws_credentials(self): """ returns aws_access_key_id, aws_secret_access_key from extra intended to be used by external import and export statements """ if self.snowflake_conn_id: connection_object = self.get_connection(self.snowflake_conn_id) ...
Fetches a field from extras and returns it. This is some Airflow magic. The grpc hook type adds custom UI elements to the hook page which allow admins to specify scopes credential pem files etc. They get formatted as shown below.
def _get_field(self, field_name, default=None): """ Fetches a field from extras, and returns it. This is some Airflow magic. The grpc hook type adds custom UI elements to the hook page, which allow admins to specify scopes, credential pem files, etc. They get formatted as shown b...
Executes SQL using psycopg2 copy_expert method. Necessary to execute COPY command without access to a superuser.
def copy_expert(self, sql, filename, open=open): """ Executes SQL using psycopg2 copy_expert method. Necessary to execute COPY command without access to a superuser. Note: if this method is called with a "COPY FROM" statement and the specified input file does not exist, it creat...
Loads a tab - delimited file into a database table
def bulk_load(self, table, tmp_file): """ Loads a tab-delimited file into a database table """ self.copy_expert("COPY {table} FROM STDIN".format(table=table), tmp_file)
Dumps a database table into a tab - delimited file
def bulk_dump(self, table, tmp_file): """ Dumps a database table into a tab-delimited file """ self.copy_expert("COPY {table} TO STDOUT".format(table=table), tmp_file)
Uploads the file to Google cloud storage
def execute(self, context): """ Uploads the file to Google cloud storage """ hook = GoogleCloudStorageHook( google_cloud_storage_conn_id=self.google_cloud_storage_conn_id, delegate_to=self.delegate_to) hook.upload( bucket_name=self.bucket, ...
Gets the max partition for a table.
def max_partition( table, schema="default", field=None, filter_map=None, metastore_conn_id='metastore_default'): """ Gets the max partition for a table. :param schema: The hive schema the table lives in :type schema: str :param table: The hive table you are interested in, supports t...
This function finds the date in a list closest to the target date. An optional parameter can be given to get the closest before or after.
def _closest_date(target_dt, date_list, before_target=None): """ This function finds the date in a list closest to the target date. An optional parameter can be given to get the closest before or after. :param target_dt: The target date :type target_dt: datetime.date :param date_list: The list ...
This function finds the date in a list closest to the target date. An optional parameter can be given to get the closest before or after.
def closest_ds_partition( table, ds, before=True, schema="default", metastore_conn_id='metastore_default'): """ This function finds the date in a list closest to the target date. An optional parameter can be given to get the closest before or after. :param table: A hive table name :...
Returns a mysql connection object
def get_conn(self): """ Returns a mysql connection object """ conn = self.get_connection(self.mysql_conn_id) conn_config = { "user": conn.login, "passwd": conn.password or '', "host": conn.host or 'localhost', "db": self.schema or c...
Loads a tab - delimited file into a database table
def bulk_load(self, table, tmp_file): """ Loads a tab-delimited file into a database table """ conn = self.get_conn() cur = conn.cursor() cur.execute(""" LOAD DATA LOCAL INFILE '{tmp_file}' INTO TABLE {table} """.format(tmp_file=tmp_fil...
Checks whether new objects have been uploaded and the inactivity_period has passed and updates the state of the sensor accordingly.
def is_bucket_updated(self, current_num_objects): """ Checks whether new objects have been uploaded and the inactivity_period has passed and updates the state of the sensor accordingly. :param current_num_objects: number of objects in bucket during last poke. :type current_num_o...
Helps debug deadlocks by printing stacktraces when this gets a SIGQUIT e. g. kill - s QUIT <PID > or CTRL + \
def sigquit_handler(sig, frame): """Helps debug deadlocks by printing stacktraces when this gets a SIGQUIT e.g. kill -s QUIT <PID> or CTRL+\ """ print("Dumping stack traces for all threads in PID {}".format(os.getpid())) id_to_name = dict([(th.ident, th.name) for th in threading.enumerate()]) co...
Creates a dag run for the specified dag: param args:: return:
def trigger_dag(args): """ Creates a dag run for the specified dag :param args: :return: """ log = LoggingMixin().log try: message = api_client.trigger_dag(dag_id=args.dag_id, run_id=args.run_id, conf=a...
Deletes all DB records related to the specified dag: param args:: return:
def delete_dag(args): """ Deletes all DB records related to the specified dag :param args: :return: """ log = LoggingMixin().log if args.yes or input( "This will drop all existing records related to the specified DAG. " "Proceed? (y/n)").upper() == "Y": try: ...
Returns the unmet dependencies for a task instance from the perspective of the scheduler ( i. e. why a task instance doesn t get scheduled and then queued by the scheduler and then run by an executor ). >>> airflow task_failed_deps tutorial sleep 2015 - 01 - 01 Task instance dependencies not met: Dagrun Running: Task i...
def task_failed_deps(args): """ Returns the unmet dependencies for a task instance from the perspective of the scheduler (i.e. why a task instance doesn't get scheduled and then queued by the scheduler, and then run by an executor). >>> airflow task_failed_deps tutorial sleep 2015-01-01 Task ins...
Returns the state of a TaskInstance at the command line. >>> airflow task_state tutorial sleep 2015 - 01 - 01 success
def task_state(args): """ Returns the state of a TaskInstance at the command line. >>> airflow task_state tutorial sleep 2015-01-01 success """ dag = get_dag(args) task = dag.get_task(task_id=args.task_id) ti = TaskInstance(task, args.execution_date) print(ti.current_state())
Returns the state of a DagRun at the command line. >>> airflow dag_state tutorial 2015 - 01 - 01T00: 00: 00. 000000 running
def dag_state(args): """ Returns the state of a DagRun at the command line. >>> airflow dag_state tutorial 2015-01-01T00:00:00.000000 running """ dag = get_dag(args) dr = DagRun.find(dag.dag_id, execution_date=args.execution_date) print(dr[0].state if len(dr) > 0 else None)
Returns the next execution datetime of a DAG at the command line. >>> airflow next_execution tutorial 2018 - 08 - 31 10: 38: 00
def next_execution(args): """ Returns the next execution datetime of a DAG at the command line. >>> airflow next_execution tutorial 2018-08-31 10:38:00 """ dag = get_dag(args) if dag.is_paused: print("[INFO] Please be reminded this DAG is PAUSED now.") if dag.latest_execution_d...
Runs forever monitoring the child processes of
def restart_workers(gunicorn_master_proc, num_workers_expected, master_timeout): """ Runs forever, monitoring the child processes of @gunicorn_master_proc and restarting workers occasionally. Each iteration of the loop traverses one edge of this state transition diagram, where each state (node) repr...
Retrieves connection to Cloud Translate
def get_conn(self): """ Retrieves connection to Cloud Translate :return: Google Cloud Translate client object. :rtype: Client """ if not self._client: self._client = Client(credentials=self._get_credentials()) return self._client
Translate a string or list of strings.
def translate( self, values, target_language, format_=None, source_language=None, model=None ): """Translate a string or list of strings. See https://cloud.google.com/translate/docs/translating-text :type values: str or list :param values: String or list of strings to trans...
Execute the bash command in a temporary directory which will be cleaned afterwards
def execute(self, context): """ Execute the bash command in a temporary directory which will be cleaned afterwards """ self.log.info('Tmp dir root location: \n %s', gettempdir()) # Prepare env for child process. if self.env is None: self.env = os.envi...
Retrieves a resource containing information about a Cloud SQL instance.
def get_instance(self, instance, project_id=None): """ Retrieves a resource containing information about a Cloud SQL instance. :param instance: Database instance ID. This does not include the project ID. :type instance: str :param project_id: Project ID of the project that conta...
Creates a new Cloud SQL instance.
def create_instance(self, body, project_id=None): """ Creates a new Cloud SQL instance. :param body: Body required by the Cloud SQL insert API, as described in https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/insert#request-body. :type body: dict :...
Updates settings of a Cloud SQL instance.
def patch_instance(self, body, instance, project_id=None): """ Updates settings of a Cloud SQL instance. Caution: This is not a partial update, so you must include values for all the settings that you want to retain. :param body: Body required by the Cloud SQL patch API, as des...
Deletes a Cloud SQL instance.
def delete_instance(self, instance, project_id=None): """ Deletes a Cloud SQL instance. :param project_id: Project ID of the project that contains the instance. If set to None or missing, the default project_id from the GCP connection is used. :type project_id: str :...
Retrieves a database resource from a Cloud SQL instance.
def get_database(self, instance, database, project_id=None): """ Retrieves a database resource from a Cloud SQL instance. :param instance: Database instance ID. This does not include the project ID. :type instance: str :param database: Name of the database in the instance. ...
Creates a new database inside a Cloud SQL instance.
def create_database(self, instance, body, project_id=None): """ Creates a new database inside a Cloud SQL instance. :param instance: Database instance ID. This does not include the project ID. :type instance: str :param body: The request body, as described in https:/...
Updates a database resource inside a Cloud SQL instance.
def patch_database(self, instance, database, body, project_id=None): """ Updates a database resource inside a Cloud SQL instance. This method supports patch semantics. See https://cloud.google.com/sql/docs/mysql/admin-api/how-tos/performance#patch. :param instance: Database ins...
Deletes a database from a Cloud SQL instance.
def delete_database(self, instance, database, project_id=None): """ Deletes a database from a Cloud SQL instance. :param instance: Database instance ID. This does not include the project ID. :type instance: str :param database: Name of the database to be deleted in the instance....
Exports data from a Cloud SQL instance to a Cloud Storage bucket as a SQL dump or CSV file.
def export_instance(self, instance, body, project_id=None): """ Exports data from a Cloud SQL instance to a Cloud Storage bucket as a SQL dump or CSV file. :param instance: Database instance ID of the Cloud SQL instance. This does not include the project ID. :type in...
Waits for the named operation to complete - checks status of the asynchronous call.
def _wait_for_operation_to_complete(self, project_id, operation_name): """ Waits for the named operation to complete - checks status of the asynchronous call. :param project_id: Project ID of the project that contains the instance. :type project_id: str :param operation_...
Starts Cloud SQL Proxy.
def start_proxy(self): """ Starts Cloud SQL Proxy. You have to remember to stop the proxy if you started it! """ self._download_sql_proxy_if_needed() if self.sql_proxy_process: raise AirflowException("The sql proxy is already running: {}".format( ...
Stops running proxy.
def stop_proxy(self): """ Stops running proxy. You should stop the proxy after you stop using it. """ if not self.sql_proxy_process: raise AirflowException("The sql proxy is not started yet") else: self.log.info("Stopping the cloud_sql_proxy pid: ...
Returns version of the Cloud SQL Proxy.
def get_proxy_version(self): """ Returns version of the Cloud SQL Proxy. """ self._download_sql_proxy_if_needed() command_to_run = [self.sql_proxy_path] command_to_run.extend(['--version']) command_to_run.extend(self._get_credential_parameters()) result = ...
Create connection in the Connection table according to whether it uses proxy TCP UNIX sockets SSL. Connection ID will be randomly generated.
def create_connection(self, session=None): """ Create connection in the Connection table, according to whether it uses proxy, TCP, UNIX sockets, SSL. Connection ID will be randomly generated. :param session: Session of the SQL Alchemy ORM (automatically generated with ...
Retrieves the dynamically created connection from the Connection table.
def retrieve_connection(self, session=None): """ Retrieves the dynamically created connection from the Connection table. :param session: Session of the SQL Alchemy ORM (automatically generated with decorator). """ self.log.info("Retrieving connection %s",...
Delete the dynamically created connection from the Connection table.
def delete_connection(self, session=None): """ Delete the dynamically created connection from the Connection table. :param session: Session of the SQL Alchemy ORM (automatically generated with decorator). """ self.log.info("Deleting connection %s", self.d...
Retrieve Cloud SQL Proxy runner. It is used to manage the proxy lifecycle per task.
def get_sqlproxy_runner(self): """ Retrieve Cloud SQL Proxy runner. It is used to manage the proxy lifecycle per task. :return: The Cloud SQL Proxy runner. :rtype: CloudSqlProxyRunner """ if not self.use_proxy: raise AirflowException("Proxy runner can...
Retrieve database hook. This is the actual Postgres or MySQL database hook that uses proxy or connects directly to the Google Cloud SQL database.
def get_database_hook(self): """ Retrieve database hook. This is the actual Postgres or MySQL database hook that uses proxy or connects directly to the Google Cloud SQL database. """ if self.database_type == 'postgres': self.db_hook = PostgresHook(postgres_conn_id=sel...
Clean up database hook after it was used.
def cleanup_database_hook(self): """ Clean up database hook after it was used. """ if self.database_type == 'postgres': if hasattr(self.db_hook, 'conn') and self.db_hook.conn and self.db_hook.conn.notices: for output in self.db_hook.conn...
Reserve free TCP port to be used by Cloud SQL Proxy
def reserve_free_tcp_port(self): """ Reserve free TCP port to be used by Cloud SQL Proxy """ self.reserved_tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.reserved_tcp_socket.bind(('127.0.0.1', 0)) self.sql_proxy_tcp_port = self.reserved_tcp_socket.get...