code stringlengths 54 334k | docs stringlengths 18 26.2k |
|---|---|
def get_vid_from_url(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 \
parse_query_param(url, 'v') or \
par... | [python] Extracts video ID from URL. |
def sina_xml_to_url_list(xml_data):
rawurl = []
dom = parseString(xml_data)
for node in dom.getElementsByTagName('durl'):
url = node.getElementsByTagName('url')[0]
rawurl.append(url.childNodes[0].data)
return rawurl | [python] str->list
Convert XML to URL List.
From Biligrab. |
def makeMimi(upid):
strSeed = "gGddgPfeaf_gzyr"
prehash = upid + "_" + strSeed
return md5(prehash.encode('utf-8')).hexdigest() | [python] From http://cdn37.atwikiimg.com/sitescript/pub/dksitescript/FC2.site.js
Also com.hps.util.fc2.FC2EncrptUtil.makeMimiLocal
L110 |
def dailymotion_download(url, output_dir='.', merge=True, info_only=False, **kwargs):
html = get_content(rebuilt_url(url))
info = json.loads(match1(html, r'qualities":({.+?}),"'))
title = match1(html, r'"video_title"\s*:\s*"([^"]+)"') or \
match1(html, r'"title"\s*:\s*"([^"]+)"')
title... | [python] Downloads Dailymotion videos by URL. |
def sina_download_by_vid(vid, title=None, output_dir='.', merge=True, info_only=False):
xml = api_req(vid)
urls, name, size = video_info(xml)
if urls is None:
log.wtf(name)
title = name
print_info(site_info, title, 'flv', size)
if not info_only:
download_urls(urls, title, 'f... | [python] Downloads a Sina video by its unique vid.
http://video.sina.com.cn/ |
def sina_download_by_vkey(vkey, title=None, output_dir='.', merge=True, info_only=False):
url = 'http://video.sina.com/v/flvideo/%s_0.flv' % vkey
type, ext, size = url_info(url)
print_info(site_info, title, 'flv', size)
if not info_only:
download_urls([url], title, 'flv', size, output_dir... | [python] Downloads a Sina video by its unique vkey.
http://video.sina.com/ |
def sina_download(url, output_dir='.', merge=True, info_only=False, **kwargs):
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 None:
video_page = get_content(url)... | [python] Downloads Sina videos by URL. |
def download_by_id(self, vid = '', title = None, output_dir='.', merge=True, info_only=False,**kwargs):
assert vid
self.prepare(vid = vid, title = title, **kwargs)
self.extract(**kwargs)
self.download(output_dir = output_dir,
merge = merge,
... | [python] 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... |
def get_vid_from_url(self, url):
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 self.get_room_id_from_url(hit.group(1))
html ... | [python] Extracts video ID from live.qq.com. |
def sprint(text, *colors):
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 | [python] Format text with color or other effects into ANSI escaped string. |
def print_log(text, *colors):
sys.stderr.write(sprint("{}: {}".format(script_name, text), *colors) + "\n") | [python] Print a log message to standard error. |
def e(message, exit_code=None):
print_log(message, YELLOW, BOLD)
if exit_code is not None:
sys.exit(exit_code) | [python] Print an error log message. |
def wtf(message, exit_code=1):
print_log(message, RED, BOLD)
if exit_code is not None:
sys.exit(exit_code) | [python] What a Terrible Failure! |
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... | [python] 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... |
def ckplayer_get_info_by_xml(ckinfo):
e = ET.XML(ckinfo)
video_dict = {'title': '',
#'duration': 0,
'links': [],
'size': 0,
'flashvars': '',}
dictified = dictify(e)['ckplayer']
if 'info' in dictified:
if '_text' in dict... | [python] str->dict
Information for CKPlayer API content. |
def get_video_url_from_video_id(video_id):
# 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, 1)
data[index] = t
def tmp():
rand_num ... | [python] Splicing URLs according to video ID to get video details |
def get_vid_from_url(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 | [python] Extracts video ID from URL. |
def get_mgtv_real_url(url):
content = loads(get_content(url))
m3u_url = content['info']
split = urlsplit(m3u_url)
base_url = "{scheme}://{netloc}{path}/".format(scheme = split[0],
netloc = split[1],
... | [python] str->list of str
Give you the real URLs. |
def get_head(repo_path):
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, commit
except:
return None | [python] Get (branch, commit) from HEAD of a git repo. |
def legitimize(text, os=detect_os()):
# POSIX systems
text = text.translate({
0: None,
ord('/'): '-',
ord('|'): '-',
})
# FIXME: do some filesystem detection
if os == 'windows' or os == 'cygwin' or os == 'wsl':
# Windows (non-POSIX namespace)
text = tex... | [python] Converts a string to a valid filename. |
def get_terminal_size():
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) | [python] Get (width, height) of the current terminal. |
def cbs_download(url, output_dir='.', merge=True, info_only=False, **kwargs):
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_pid(pid, title, output_dir=output_dir, me... | [python] Downloads CBS videos by URL. |
def download(self, **kwargs):
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']:
# Display the stream
stream_... | [python] Override the original one
Ugly ugly dirty hack |
def acfun_download_by_vid(vid, title, output_dir='.', merge=True, info_only=False, **kwargs):
#first call the main parasing API
info = json.loads(get_content('http://www.acfun.cn/video/getVideo.aspx?id=' + vid))
sourceType = info['sourceType']
#decide sourceId to know which extractor to use
... | [python] 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. |
def main_dev(**kwargs):
# 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.GetoptError as e:
log.wtf("""
[Fatal] {}.
... | [python] Main entry point.
you-get-dev |
def ffmpeg_download_stream(files, title, ext, params={}, output_dir='.', stream=True):
output = title + '.' + ext
if not (output_dir == '.'):
output = output_dir + '/' + output
print('Downloading streaming content with FFmpeg, press q to stop recording...')
if stream:
ffmpeg_param... | [python] 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 match1(text, *patterns):
if len(patterns) == 1:
pattern = patterns[0]
match = re.search(pattern, text)
if match:
return match.group(1)
else:
return None
else:
ret = []
for pattern in patterns:
match = re.search(pattern... | [python] 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).
When more than one ... |
def matchall(text, patterns):
ret = []
for pattern in patterns:
match = re.findall(pattern, text)
ret += match
return ret | [python] 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. |
def parse_query_param(url, param):
try:
return parse.parse_qs(parse.urlparse(url).query)[param][0]
except:
return None | [python] 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. |
def ungzip(data):
from io import BytesIO
import gzip
buffer = BytesIO(data)
f = gzip.GzipFile(fileobj=buffer)
return f.read() | [python] Decompresses data for Content-Encoding: gzip. |
def undeflate(data):
import zlib
decompressobj = zlib.decompressobj(-zlib.MAX_WBITS)
return decompressobj.decompress(data)+decompressobj.flush() | [python] Decompresses data for Content-Encoding: deflate.
(the zlib compression is used.) |
def get_content(url, headers={}, decoded=True):
logging.debug('get_content: %s' % url)
req = request.Request(url, headers=headers)
if cookies:
cookies.add_cookie_header(req)
req.headers.update(req.unredirected_hdrs)
response = urlopen_with_retry(req)
data = response.read()
... | [python] 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:
The content as a string. |
def post_content(url, headers={}, post_data={}, decoded=True, **kwargs):
if kwargs.get('post_data_raw'):
logging.debug('post_content: %s\npost_data_raw: %s' % (url, kwargs['post_data_raw']))
else:
logging.debug('post_content: %s\npost_data: %s' % (url, post_data))
req = request.Request... | [python] 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-Type.
Returns:
The content as a string. |
def parse_host(host):
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 = o.port or 0
return (hostname, port) | [python] Parses host name and port number from a string. |
def print_more_compatible(*args, **kwargs):
import builtins as __builtin__
# nothing happens on py3.3 and later
if sys.version_info[:2] >= (3, 3):
return __builtin__.print(*args, **kwargs)
# in lower pyver (e.g. 3.2.x), remove 'flush' keyword and flush it as requested
doFlush = kwargs.... | [python] 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 _wanmen_get_title_by_json_topic_part(json_content, tIndex, pIndex):
return '_'.join([json_content[0]['name'],
json_content[0]['Topics'][tIndex]['name'],
json_content[0]['Topics'][tIndex]['Parts'][pIndex]['name']]) | [python] JSON, int, int, int->str
Get a proper title with courseid+topicID+partID. |
def wanmen_download_by_course(json_api_content, output_dir='.', merge=True, info_only=False, **kwargs):
for tIndex in range(len(json_api_content[0]['Topics'])):
for pIndex in range(len(json_api_content[0]['Topics'][tIndex]['Parts'])):
wanmen_download_by_course_topic_part(json_api_content,
... | [python] int->None
Download a WHOLE course.
Reuse the API call to save time. |
def wanmen_download_by_course_topic_part(json_api_content, tIndex, pIndex, output_dir='.', merge=True, info_only=False, **kwargs):
html = json_api_content
title = _wanmen_get_title_by_json_topic_part(html,
tIndex,
... | [python] int, int, int->None
Download ONE PART of the course. |
def get_streams_by_id(account_number, video_id):
endpoint = 'https://edge.api.brightcove.com/playback/v1/accounts/{account_number}/videos/{video_id}'.format(account_number = account_number, video_id = video_id)
fake_header_id = fake_headers
#is this somehow related to the time? Magic...... | [python] 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 "startswit... |
def has_task(self, task_instance):
if task_instance.key in self.queued_tasks or task_instance.key in self.running:
return True | [python] 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 |
def get_event_buffer(self, dag_ids=None):
cleared_events = dict()
if dag_ids is None:
cleared_events = self.event_buffer
self.event_buffer = dict()
else:
for key in list(self.event_buffer.keys()):
dag_id, _, _, _ = key
... | [python] 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
:return: a dict of events |
def _get_conn_params(self):
conn = self.get_connection(self.snowflake_conn_id)
account = conn.extra_dejson.get('account', None)
warehouse = conn.extra_dejson.get('warehouse', None)
database = conn.extra_dejson.get('database', None)
region = conn.extra_dejson.get("region"... | [python] one method to fetch connection params as a dict
used in get_uri() and get_connection() |
def get_uri(self):
conn_config = self._get_conn_params()
uri = 'snowflake://{user}:{password}@{account}/{database}/'
uri += '{schema}?warehouse={warehouse}&role={role}'
return uri.format(**conn_config) | [python] override DbApiHook get_uri method for get_sqlalchemy_engine() |
def get_conn(self):
conn_config = self._get_conn_params()
conn = snowflake.connector.connect(**conn_config)
return conn | [python] Returns a snowflake.connection object |
def _get_aws_credentials(self):
if self.snowflake_conn_id:
connection_object = self.get_connection(self.snowflake_conn_id)
if 'aws_secret_access_key' in connection_object.extra_dejson:
aws_access_key_id = connection_object.extra_dejson.get(
'a... | [python] returns aws_access_key_id, aws_secret_access_key
from extra
intended to be used by external import and export statements |
def _get_field(self, field_name, default=None):
full_field_name = 'extra__grpc__{}'.format(field_name)
if full_field_name in self.extras:
return self.extras[full_field_name]
else:
return default | [python] 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 copy_expert(self, sql, filename, open=open):
if not os.path.isfile(filename):
with open(filename, 'w'):
pass
with open(filename, 'r+') as f:
with closing(self.get_conn()) as conn:
with closing(conn.cursor()) as cur:
... | [python] 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 creates an empty
file and no data is loaded, but the oper... |
def bulk_load(self, table, tmp_file):
self.copy_expert("COPY {table} FROM STDIN".format(table=table), tmp_file) | [python] Loads a tab-delimited file into a database table |
def bulk_dump(self, table, tmp_file):
self.copy_expert("COPY {table} TO STDOUT".format(table=table), tmp_file) | [python] Dumps a database table into a tab-delimited file |
def execute(self, context):
hook = GoogleCloudStorageHook(
google_cloud_storage_conn_id=self.google_cloud_storage_conn_id,
delegate_to=self.delegate_to)
hook.upload(
bucket_name=self.bucket,
object_name=self.dst,
mime_type=self.mime_t... | [python] Uploads the file to Google cloud storage |
def max_partition(
table, schema="default", field=None, filter_map=None,
metastore_conn_id='metastore_default'):
from airflow.hooks.hive_hooks import HiveMetastoreHook
if '.' in table:
schema, table = table.split('.')
hh = HiveMetastoreHook(metastore_conn_id=metastore_conn_id)
... | [python] 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 the dot
notation as in "my_database.my_table", if a dot is found,
the schema param is disregarded
:type table: st... |
def _closest_date(target_dt, date_list, before_target=None):
fb = lambda d: target_dt - d if d <= target_dt else datetime.timedelta.max
fa = lambda d: d - target_dt if d >= target_dt else datetime.timedelta.max
fnone = lambda d: target_dt - d if d < target_dt else d - target_dt
if before_target is ... | [python] 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 of dates to search
:type date_list: list[datetime.date]
... |
def closest_ds_partition(
table, ds, before=True, schema="default",
metastore_conn_id='metastore_default'):
from airflow.hooks.hive_hooks import HiveMetastoreHook
if '.' in table:
schema, table = table.split('.')
hh = HiveMetastoreHook(metastore_conn_id=metastore_conn_id)
pa... | [python] 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
:type table: str
:param ds: A datestamp ``%Y-%m-%d`` e.g. ``yyyy-mm-dd``
:type ds: list[datetime.date]
:param before... |
def get_conn(self):
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 conn.schema or ''
}
if not conn.port:
... | [python] Returns a mysql connection object |
def bulk_load(self, table, tmp_file):
conn = self.get_conn()
cur = conn.cursor()
cur.execute("""
LOAD DATA LOCAL INFILE '{tmp_file}'
INTO TABLE {table}
""".format(tmp_file=tmp_file, table=table))
conn.commit() | [python] Loads a tab-delimited file into a database table |
def is_bucket_updated(self, current_num_objects):
if current_num_objects > self.previous_num_objects:
# When new objects arrived, reset the inactivity_seconds
# previous_num_objects for the next poke.
self.log.info(
'''
New objects fo... | [python] 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_objects: int |
def sigquit_handler(sig, frame):
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()])
code = []
for thread_id, stack in sys._current_frames().items():
code.append("\n# Thread: {}({})"
... | [python] Helps debug deadlocks by printing stacktraces when this gets a SIGQUIT
e.g. kill -s QUIT <PID> or CTRL+\ |
def trigger_dag(args):
log = LoggingMixin().log
try:
message = api_client.trigger_dag(dag_id=args.dag_id,
run_id=args.run_id,
conf=args.conf,
execution_date=args.exec_date)
... | [python] Creates a dag run for the specified dag
:param args:
:return: |
def delete_dag(args):
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:
message = api_client.delete_dag(dag_id=args.dag_id)
except IOError as err:
... | [python] Deletes all DB records related to the specified dag
:param args:
:return: |
def task_failed_deps(args):
dag = get_dag(args)
task = dag.get_task(task_id=args.task_id)
ti = TaskInstance(task, args.execution_date)
dep_context = DepContext(deps=SCHEDULER_DEPS)
failed_deps = list(ti.get_failed_dep_statuses(dep_context=dep_context))
# TODO, Do we want to print or log th... | [python] 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:
... |
def task_state(args):
dag = get_dag(args)
task = dag.get_task(task_id=args.task_id)
ti = TaskInstance(task, args.execution_date)
print(ti.current_state()) | [python] Returns the state of a TaskInstance at the command line.
>>> airflow task_state tutorial sleep 2015-01-01
success |
def dag_state(args):
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) | [python] Returns the state of a DagRun at the command line.
>>> airflow dag_state tutorial 2015-01-01T00:00:00.000000
running |
def next_execution(args):
dag = get_dag(args)
if dag.is_paused:
print("[INFO] Please be reminded this DAG is PAUSED now.")
if dag.latest_execution_date:
next_execution_dttm = dag.following_schedule(dag.latest_execution_date)
if next_execution_dttm is None:
print("... | [python] Returns the next execution datetime of a DAG at the command line.
>>> airflow next_execution tutorial
2018-08-31 10:38:00 |
def restart_workers(gunicorn_master_proc, num_workers_expected, master_timeout):
def wait_until_true(fn, timeout=0):
"""
Sleeps until fn is true
"""
t = time.time()
while not fn():
if 0 < timeout <= time.time() - t:
raise AirflowWebServerTime... | [python] 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) represents
[ num_ready_workers_running / num_workers_running ]. We expect most time ... |
def get_conn(self):
if not self._client:
self._client = Client(credentials=self._get_credentials())
return self._client | [python] Retrieves connection to Cloud Translate
:return: Google Cloud Translate client object.
:rtype: Client |
def translate(
self, values, target_language, format_=None, source_language=None, model=None
):
client = self.get_conn()
return client.translate(
values=values,
target_language=target_language,
format_=format_,
source_language=source_... | [python] 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 translate.
:type target_language: str
:param target_language: The language to translate results in... |
def execute(self, context):
self.log.info('Tmp dir root location: \n %s', gettempdir())
# Prepare env for child process.
if self.env is None:
self.env = os.environ.copy()
airflow_context_vars = context_to_airflow_vars(context, in_env_var_format=True)
self.l... | [python] Execute the bash command in a temporary directory
which will be cleaned afterwards |
def get_instance(self, instance, project_id=None):
return self.get_conn().instances().get(
project=project_id,
instance=instance
).execute(num_retries=self.num_retries) | [python] 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 contains the instance. If set
to None or missing, the d... |
def create_instance(self, body, project_id=None):
response = self.get_conn().instances().insert(
project=project_id,
body=body
).execute(num_retries=self.num_retries)
operation_name = response["name"]
self._wait_for_operation_to_complete(project_id=projec... | [python] 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
:param project_id: Project ID of the project that contains the... |
def patch_instance(self, body, instance, project_id=None):
response = self.get_conn().instances().patch(
project=project_id,
instance=instance,
body=body
).execute(num_retries=self.num_retries)
operation_name = response["name"]
self._wait_for_... | [python] 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 described in
https://cloud.google.com/sql/docs/mysql/admin-ap... |
def delete_instance(self, instance, project_id=None):
response = self.get_conn().instances().delete(
project=project_id,
instance=instance,
).execute(num_retries=self.num_retries)
operation_name = response["name"]
self._wait_for_operation_to_complete(proj... | [python] 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
:param instance: Cloud SQL instance ID. This does not include the ... |
def get_database(self, instance, database, project_id=None):
return self.get_conn().databases().get(
project=project_id,
instance=instance,
database=database
).execute(num_retries=self.num_retries) | [python] 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.
:type database: str
:param project_id: Project ID of the proj... |
def create_database(self, instance, body, project_id=None):
response = self.get_conn().databases().insert(
project=project_id,
instance=instance,
body=body
).execute(num_retries=self.num_retries)
operation_name = response["name"]
self._wait_fo... | [python] 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://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/databases/insert#req... |
def patch_database(self, instance, database, body, project_id=None):
response = self.get_conn().databases().patch(
project=project_id,
instance=instance,
database=database,
body=body
).execute(num_retries=self.num_retries)
operation_name =... | [python] 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 instance ID. This does not include the project ID.
:type instance: str
... |
def delete_database(self, instance, database, project_id=None):
response = self.get_conn().databases().delete(
project=project_id,
instance=instance,
database=database
).execute(num_retries=self.num_retries)
operation_name = response["name"]
s... | [python] 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.
:type database: str
:param project_id: Project ID of the p... |
def export_instance(self, instance, body, project_id=None):
try:
response = self.get_conn().instances().export(
project=project_id,
instance=instance,
body=body
).execute(num_retries=self.num_retries)
operation_name = r... | [python] 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 instance: str
:param body: The request body, as described in
... |
def _wait_for_operation_to_complete(self, project_id, operation_name):
service = self.get_conn()
while True:
operation_response = service.operations().get(
project=project_id,
operation=operation_name,
).execute(num_retries=self.num_retrie... | [python] 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_name: Name of the operation.
:type operation_name: str
:return: No... |
def start_proxy(self):
self._download_sql_proxy_if_needed()
if self.sql_proxy_process:
raise AirflowException("The sql proxy is already running: {}".format(
self.sql_proxy_process))
else:
command_to_run = [self.sql_proxy_path]
command_... | [python] Starts Cloud SQL Proxy.
You have to remember to stop the proxy if you started it! |
def stop_proxy(self):
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: %s",
self.sql_proxy_process.pid)
self.sql_proxy_process.kill()
... | [python] Stops running proxy.
You should stop the proxy after you stop using it. |
def get_proxy_version(self):
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 = subprocess.check_output(command_to_run).decode('utf-8')
... | [python] Returns version of the Cloud SQL Proxy. |
def create_connection(self, session=None):
connection = Connection(conn_id=self.db_conn_id)
uri = self._generate_connection_uri()
self.log.info("Creating connection %s", self.db_conn_id)
connection.parse_from_uri(uri)
session.add(connection)
session.commit() | [python] 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
decorator). |
def retrieve_connection(self, session=None):
self.log.info("Retrieving connection %s", self.db_conn_id)
connections = session.query(Connection).filter(
Connection.conn_id == self.db_conn_id)
if connections.count():
return connections[0]
return None | [python] Retrieves the dynamically created connection from the Connection table.
:param session: Session of the SQL Alchemy ORM (automatically generated with
decorator). |
def delete_connection(self, session=None):
self.log.info("Deleting connection %s", self.db_conn_id)
connections = session.query(Connection).filter(
Connection.conn_id == self.db_conn_id)
if connections.count():
connection = connections[0]
session.dele... | [python] Delete the dynamically created connection from the Connection table.
:param session: Session of the SQL Alchemy ORM (automatically generated with
decorator). |
def get_sqlproxy_runner(self):
if not self.use_proxy:
raise AirflowException("Proxy runner can only be retrieved in case of use_proxy = True")
return CloudSqlProxyRunner(
path_prefix=self.sql_proxy_unique_path,
instance_specification=self._get_sqlproxy_instan... | [python] Retrieve Cloud SQL Proxy runner. It is used to manage the proxy
lifecycle per task.
:return: The Cloud SQL Proxy runner.
:rtype: CloudSqlProxyRunner |
def get_database_hook(self):
if self.database_type == 'postgres':
self.db_hook = PostgresHook(postgres_conn_id=self.db_conn_id,
schema=self.database)
else:
self.db_hook = MySqlHook(mysql_conn_id=self.db_conn_id,
... | [python] 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 cleanup_database_hook(self):
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.notices:
self.log.info(output) | [python] Clean up database hook after it was used. |
def reserve_free_tcp_port(self):
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.getsockname()[1] | [python] Reserve free TCP port to be used by Cloud SQL Proxy |
def _normalize_mlengine_job_id(job_id):
# Add a prefix when a job_id starts with a digit or a template
match = re.search(r'\d|\{{2}', job_id)
if match and match.start() == 0:
job = 'z_{}'.format(job_id)
else:
job = job_id
# Clean up 'bad' characters except templates
tracke... | [python] Replaces invalid MLEngine job_id characters with '_'.
This also adds a leading 'z' in case job_id starts with an invalid
character.
Args:
job_id: A job_id str that may have invalid characters.
Returns:
A valid job_id representation. |
def _get_error_code(self, e):
try:
matches = self.error_code_pattern.match(str(e))
code = int(matches.group(0))
return code
except ValueError:
return e | [python] Extract error code from ftp exception |
def _integrate_plugins():
import sys
from airflow.plugins_manager import sensors_modules
for sensors_module in sensors_modules:
sys.modules[sensors_module.__name__] = sensors_module
globals()[sensors_module._name] = sensors_module | [python] Integrate plugins to the context |
def clear_dag_runs():
session = settings.Session()
drs = session.query(DagRun).filter(
DagRun.dag_id.in_(DAG_IDS),
).all()
for dr in drs:
logging.info('Deleting DagRun :: {}'.format(dr))
session.delete(dr) | [python] Remove any existing DAG runs for the perf test DAGs. |
def clear_dag_task_instances():
session = settings.Session()
TI = TaskInstance
tis = (
session
.query(TI)
.filter(TI.dag_id.in_(DAG_IDS))
.all()
)
for ti in tis:
logging.info('Deleting TaskInstance :: {}'.format(ti))
session.delete(ti)
session... | [python] Remove any existing task instances for the perf test DAGs. |
def set_dags_paused_state(is_paused):
session = settings.Session()
dms = session.query(DagModel).filter(
DagModel.dag_id.in_(DAG_IDS))
for dm in dms:
logging.info('Setting DAG :: {} is_paused={}'.format(dm, is_paused))
dm.is_paused = is_paused
session.commit() | [python] Toggle the pause state of the DAGs in the test. |
def print_stats(self):
session = settings.Session()
TI = TaskInstance
tis = (
session
.query(TI)
.filter(TI.dag_id.in_(DAG_IDS))
.all()
)
successful_tis = [x for x in tis if x.state == State.SUCCESS]
ti_perf = [(ti.... | [python] Print operational metrics for the scheduler test. |
def heartbeat(self):
super(SchedulerMetricsJob, self).heartbeat()
session = settings.Session()
# Get all the relevant task instances
TI = TaskInstance
successful_tis = (
session
.query(TI)
.filter(TI.dag_id.in_(DAG_IDS))
.f... | [python] Override the scheduler heartbeat to determine when the test is complete |
def get_dag_run_state(dag_id, execution_date):
dagbag = DagBag()
# Check DAG exists.
if dag_id not in dagbag.dags:
error_message = "Dag id {} not found".format(dag_id)
raise DagNotFound(error_message)
# Get DAG object and check Task Exists
dag = dagbag.get_dag(dag_id)
# ... | [python] Return the task object identified by the given dag_id and task_id. |
def create_evaluate_ops(task_prefix,
data_format,
input_paths,
prediction_path,
metric_fn_and_keys,
validate_fn,
batch_prediction_job_id=None,
project_i... | [python] Creates Operators needed for model evaluation and returns.
It gets prediction over inputs via Cloud ML Engine BatchPrediction API by
calling MLEngineBatchPredictionOperator, then summarize and validate
the result via Cloud Dataflow using DataFlowPythonOperator.
For details and pricing about B... |
def mkdirs(path, mode):
try:
o_umask = os.umask(0)
os.makedirs(path, mode)
except OSError:
if not os.path.isdir(path):
raise
finally:
os.umask(o_umask) | [python] Creates the directory specified by path, creating intermediate directories
as necessary. If directory already exists, this is a no-op.
:param path: The directory to create
:type path: str
:param mode: The mode to give to the directory e.g. 0o755, ignores umask
:type mode: int |
def _convert_to_float_if_possible(s):
try:
ret = float(s)
except (ValueError, TypeError):
ret = s
return ret | [python] A small helper function to convert a string to a numeric value
if appropriate
:param s: the string to be converted
:type s: str |
def utcnow():
# pendulum utcnow() is not used as that sets a TimezoneInfo object
# instead of a Timezone. This is not pickable and also creates issues
# when using replace()
d = dt.datetime.utcnow()
d = d.replace(tzinfo=utc)
return d | [python] Get the current date and time in UTC
:return: |
End of preview. Expand in Data Studio
- Downloads last month
- 9