id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
29,700 | Miserlou/Zappa | zappa/core.py | Zappa.stack_outputs | def stack_outputs(self, name):
"""
Given a name, describes CloudFront stacks and returns dict of the stack Outputs
, else returns an empty dict.
"""
try:
stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0]
return {x['OutputKey']: x['OutputValue'] for x in stack['Outputs']}
except botocore.client.ClientError:
return {} | python | def stack_outputs(self, name):
"""
Given a name, describes CloudFront stacks and returns dict of the stack Outputs
, else returns an empty dict.
"""
try:
stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0]
return {x['OutputKey']: x['OutputValue'] for x in stack['Outputs']}
except botocore.client.ClientError:
return {} | [
"def",
"stack_outputs",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"stack",
"=",
"self",
".",
"cf_client",
".",
"describe_stacks",
"(",
"StackName",
"=",
"name",
")",
"[",
"'Stacks'",
"]",
"[",
"0",
"]",
"return",
"{",
"x",
"[",
"'OutputKey'",
"... | Given a name, describes CloudFront stacks and returns dict of the stack Outputs
, else returns an empty dict. | [
"Given",
"a",
"name",
"describes",
"CloudFront",
"stacks",
"and",
"returns",
"dict",
"of",
"the",
"stack",
"Outputs",
"else",
"returns",
"an",
"empty",
"dict",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2239-L2248 |
29,701 | Miserlou/Zappa | zappa/core.py | Zappa.get_api_url | def get_api_url(self, lambda_name, stage_name):
"""
Given a lambda_name and stage_name, return a valid API URL.
"""
api_id = self.get_api_id(lambda_name)
if api_id:
return "https://{}.execute-api.{}.amazonaws.com/{}".format(api_id, self.boto_session.region_name, stage_name)
else:
return None | python | def get_api_url(self, lambda_name, stage_name):
"""
Given a lambda_name and stage_name, return a valid API URL.
"""
api_id = self.get_api_id(lambda_name)
if api_id:
return "https://{}.execute-api.{}.amazonaws.com/{}".format(api_id, self.boto_session.region_name, stage_name)
else:
return None | [
"def",
"get_api_url",
"(",
"self",
",",
"lambda_name",
",",
"stage_name",
")",
":",
"api_id",
"=",
"self",
".",
"get_api_id",
"(",
"lambda_name",
")",
"if",
"api_id",
":",
"return",
"\"https://{}.execute-api.{}.amazonaws.com/{}\"",
".",
"format",
"(",
"api_id",
... | Given a lambda_name and stage_name, return a valid API URL. | [
"Given",
"a",
"lambda_name",
"and",
"stage_name",
"return",
"a",
"valid",
"API",
"URL",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2251-L2259 |
29,702 | Miserlou/Zappa | zappa/core.py | Zappa.get_api_id | def get_api_id(self, lambda_name):
"""
Given a lambda_name, return the API id.
"""
try:
response = self.cf_client.describe_stack_resource(StackName=lambda_name,
LogicalResourceId='Api')
return response['StackResourceDetail'].get('PhysicalResourceId', None)
except: # pragma: no cover
try:
# Try the old method (project was probably made on an older, non CF version)
response = self.apigateway_client.get_rest_apis(limit=500)
for item in response['items']:
if item['name'] == lambda_name:
return item['id']
logger.exception('Could not get API ID.')
return None
except: # pragma: no cover
# We don't even have an API deployed. That's okay!
return None | python | def get_api_id(self, lambda_name):
"""
Given a lambda_name, return the API id.
"""
try:
response = self.cf_client.describe_stack_resource(StackName=lambda_name,
LogicalResourceId='Api')
return response['StackResourceDetail'].get('PhysicalResourceId', None)
except: # pragma: no cover
try:
# Try the old method (project was probably made on an older, non CF version)
response = self.apigateway_client.get_rest_apis(limit=500)
for item in response['items']:
if item['name'] == lambda_name:
return item['id']
logger.exception('Could not get API ID.')
return None
except: # pragma: no cover
# We don't even have an API deployed. That's okay!
return None | [
"def",
"get_api_id",
"(",
"self",
",",
"lambda_name",
")",
":",
"try",
":",
"response",
"=",
"self",
".",
"cf_client",
".",
"describe_stack_resource",
"(",
"StackName",
"=",
"lambda_name",
",",
"LogicalResourceId",
"=",
"'Api'",
")",
"return",
"response",
"[",... | Given a lambda_name, return the API id. | [
"Given",
"a",
"lambda_name",
"return",
"the",
"API",
"id",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2261-L2282 |
29,703 | Miserlou/Zappa | zappa/core.py | Zappa.create_domain_name | def create_domain_name(self,
domain_name,
certificate_name,
certificate_body=None,
certificate_private_key=None,
certificate_chain=None,
certificate_arn=None,
lambda_name=None,
stage=None,
base_path=None):
"""
Creates the API GW domain and returns the resulting DNS name.
"""
# This is a Let's Encrypt or custom certificate
if not certificate_arn:
agw_response = self.apigateway_client.create_domain_name(
domainName=domain_name,
certificateName=certificate_name,
certificateBody=certificate_body,
certificatePrivateKey=certificate_private_key,
certificateChain=certificate_chain
)
# This is an AWS ACM-hosted Certificate
else:
agw_response = self.apigateway_client.create_domain_name(
domainName=domain_name,
certificateName=certificate_name,
certificateArn=certificate_arn
)
api_id = self.get_api_id(lambda_name)
if not api_id:
raise LookupError("No API URL to certify found - did you deploy?")
self.apigateway_client.create_base_path_mapping(
domainName=domain_name,
basePath='' if base_path is None else base_path,
restApiId=api_id,
stage=stage
)
return agw_response['distributionDomainName'] | python | def create_domain_name(self,
domain_name,
certificate_name,
certificate_body=None,
certificate_private_key=None,
certificate_chain=None,
certificate_arn=None,
lambda_name=None,
stage=None,
base_path=None):
"""
Creates the API GW domain and returns the resulting DNS name.
"""
# This is a Let's Encrypt or custom certificate
if not certificate_arn:
agw_response = self.apigateway_client.create_domain_name(
domainName=domain_name,
certificateName=certificate_name,
certificateBody=certificate_body,
certificatePrivateKey=certificate_private_key,
certificateChain=certificate_chain
)
# This is an AWS ACM-hosted Certificate
else:
agw_response = self.apigateway_client.create_domain_name(
domainName=domain_name,
certificateName=certificate_name,
certificateArn=certificate_arn
)
api_id = self.get_api_id(lambda_name)
if not api_id:
raise LookupError("No API URL to certify found - did you deploy?")
self.apigateway_client.create_base_path_mapping(
domainName=domain_name,
basePath='' if base_path is None else base_path,
restApiId=api_id,
stage=stage
)
return agw_response['distributionDomainName'] | [
"def",
"create_domain_name",
"(",
"self",
",",
"domain_name",
",",
"certificate_name",
",",
"certificate_body",
"=",
"None",
",",
"certificate_private_key",
"=",
"None",
",",
"certificate_chain",
"=",
"None",
",",
"certificate_arn",
"=",
"None",
",",
"lambda_name",
... | Creates the API GW domain and returns the resulting DNS name. | [
"Creates",
"the",
"API",
"GW",
"domain",
"and",
"returns",
"the",
"resulting",
"DNS",
"name",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2284-L2326 |
29,704 | Miserlou/Zappa | zappa/core.py | Zappa.update_route53_records | def update_route53_records(self, domain_name, dns_name):
"""
Updates Route53 Records following GW domain creation
"""
zone_id = self.get_hosted_zone_id_for_domain(domain_name)
is_apex = self.route53.get_hosted_zone(Id=zone_id)['HostedZone']['Name'][:-1] == domain_name
if is_apex:
record_set = {
'Name': domain_name,
'Type': 'A',
'AliasTarget': {
'HostedZoneId': 'Z2FDTNDATAQYW2', # This is a magic value that means "CloudFront"
'DNSName': dns_name,
'EvaluateTargetHealth': False
}
}
else:
record_set = {
'Name': domain_name,
'Type': 'CNAME',
'ResourceRecords': [
{
'Value': dns_name
}
],
'TTL': 60
}
# Related: https://github.com/boto/boto3/issues/157
# and: http://docs.aws.amazon.com/Route53/latest/APIReference/CreateAliasRRSAPI.html
# and policy: https://spin.atomicobject.com/2016/04/28/route-53-hosted-zone-managment/
# pure_zone_id = zone_id.split('/hostedzone/')[1]
# XXX: ClientError: An error occurred (InvalidChangeBatch) when calling the ChangeResourceRecordSets operation:
# Tried to create an alias that targets d1awfeji80d0k2.cloudfront.net., type A in zone Z1XWOQP59BYF6Z,
# but the alias target name does not lie within the target zone
response = self.route53.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch={
'Changes': [
{
'Action': 'UPSERT',
'ResourceRecordSet': record_set
}
]
}
)
return response | python | def update_route53_records(self, domain_name, dns_name):
"""
Updates Route53 Records following GW domain creation
"""
zone_id = self.get_hosted_zone_id_for_domain(domain_name)
is_apex = self.route53.get_hosted_zone(Id=zone_id)['HostedZone']['Name'][:-1] == domain_name
if is_apex:
record_set = {
'Name': domain_name,
'Type': 'A',
'AliasTarget': {
'HostedZoneId': 'Z2FDTNDATAQYW2', # This is a magic value that means "CloudFront"
'DNSName': dns_name,
'EvaluateTargetHealth': False
}
}
else:
record_set = {
'Name': domain_name,
'Type': 'CNAME',
'ResourceRecords': [
{
'Value': dns_name
}
],
'TTL': 60
}
# Related: https://github.com/boto/boto3/issues/157
# and: http://docs.aws.amazon.com/Route53/latest/APIReference/CreateAliasRRSAPI.html
# and policy: https://spin.atomicobject.com/2016/04/28/route-53-hosted-zone-managment/
# pure_zone_id = zone_id.split('/hostedzone/')[1]
# XXX: ClientError: An error occurred (InvalidChangeBatch) when calling the ChangeResourceRecordSets operation:
# Tried to create an alias that targets d1awfeji80d0k2.cloudfront.net., type A in zone Z1XWOQP59BYF6Z,
# but the alias target name does not lie within the target zone
response = self.route53.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch={
'Changes': [
{
'Action': 'UPSERT',
'ResourceRecordSet': record_set
}
]
}
)
return response | [
"def",
"update_route53_records",
"(",
"self",
",",
"domain_name",
",",
"dns_name",
")",
":",
"zone_id",
"=",
"self",
".",
"get_hosted_zone_id_for_domain",
"(",
"domain_name",
")",
"is_apex",
"=",
"self",
".",
"route53",
".",
"get_hosted_zone",
"(",
"Id",
"=",
... | Updates Route53 Records following GW domain creation | [
"Updates",
"Route53",
"Records",
"following",
"GW",
"domain",
"creation"
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2328-L2377 |
29,705 | Miserlou/Zappa | zappa/core.py | Zappa.update_domain_name | def update_domain_name(self,
domain_name,
certificate_name=None,
certificate_body=None,
certificate_private_key=None,
certificate_chain=None,
certificate_arn=None,
lambda_name=None,
stage=None,
route53=True,
base_path=None):
"""
This updates your certificate information for an existing domain,
with similar arguments to boto's update_domain_name API Gateway api.
It returns the resulting new domain information including the new certificate's ARN
if created during this process.
Previously, this method involved downtime that could take up to 40 minutes
because the API Gateway api only allowed this by deleting, and then creating it.
Related issues: https://github.com/Miserlou/Zappa/issues/590
https://github.com/Miserlou/Zappa/issues/588
https://github.com/Miserlou/Zappa/pull/458
https://github.com/Miserlou/Zappa/issues/882
https://github.com/Miserlou/Zappa/pull/883
"""
print("Updating domain name!")
certificate_name = certificate_name + str(time.time())
api_gateway_domain = self.apigateway_client.get_domain_name(domainName=domain_name)
if not certificate_arn\
and certificate_body and certificate_private_key and certificate_chain:
acm_certificate = self.acm_client.import_certificate(Certificate=certificate_body,
PrivateKey=certificate_private_key,
CertificateChain=certificate_chain)
certificate_arn = acm_certificate['CertificateArn']
self.update_domain_base_path_mapping(domain_name, lambda_name, stage, base_path)
return self.apigateway_client.update_domain_name(domainName=domain_name,
patchOperations=[
{"op" : "replace",
"path" : "/certificateName",
"value" : certificate_name},
{"op" : "replace",
"path" : "/certificateArn",
"value" : certificate_arn}
]) | python | def update_domain_name(self,
domain_name,
certificate_name=None,
certificate_body=None,
certificate_private_key=None,
certificate_chain=None,
certificate_arn=None,
lambda_name=None,
stage=None,
route53=True,
base_path=None):
"""
This updates your certificate information for an existing domain,
with similar arguments to boto's update_domain_name API Gateway api.
It returns the resulting new domain information including the new certificate's ARN
if created during this process.
Previously, this method involved downtime that could take up to 40 minutes
because the API Gateway api only allowed this by deleting, and then creating it.
Related issues: https://github.com/Miserlou/Zappa/issues/590
https://github.com/Miserlou/Zappa/issues/588
https://github.com/Miserlou/Zappa/pull/458
https://github.com/Miserlou/Zappa/issues/882
https://github.com/Miserlou/Zappa/pull/883
"""
print("Updating domain name!")
certificate_name = certificate_name + str(time.time())
api_gateway_domain = self.apigateway_client.get_domain_name(domainName=domain_name)
if not certificate_arn\
and certificate_body and certificate_private_key and certificate_chain:
acm_certificate = self.acm_client.import_certificate(Certificate=certificate_body,
PrivateKey=certificate_private_key,
CertificateChain=certificate_chain)
certificate_arn = acm_certificate['CertificateArn']
self.update_domain_base_path_mapping(domain_name, lambda_name, stage, base_path)
return self.apigateway_client.update_domain_name(domainName=domain_name,
patchOperations=[
{"op" : "replace",
"path" : "/certificateName",
"value" : certificate_name},
{"op" : "replace",
"path" : "/certificateArn",
"value" : certificate_arn}
]) | [
"def",
"update_domain_name",
"(",
"self",
",",
"domain_name",
",",
"certificate_name",
"=",
"None",
",",
"certificate_body",
"=",
"None",
",",
"certificate_private_key",
"=",
"None",
",",
"certificate_chain",
"=",
"None",
",",
"certificate_arn",
"=",
"None",
",",
... | This updates your certificate information for an existing domain,
with similar arguments to boto's update_domain_name API Gateway api.
It returns the resulting new domain information including the new certificate's ARN
if created during this process.
Previously, this method involved downtime that could take up to 40 minutes
because the API Gateway api only allowed this by deleting, and then creating it.
Related issues: https://github.com/Miserlou/Zappa/issues/590
https://github.com/Miserlou/Zappa/issues/588
https://github.com/Miserlou/Zappa/pull/458
https://github.com/Miserlou/Zappa/issues/882
https://github.com/Miserlou/Zappa/pull/883 | [
"This",
"updates",
"your",
"certificate",
"information",
"for",
"an",
"existing",
"domain",
"with",
"similar",
"arguments",
"to",
"boto",
"s",
"update_domain_name",
"API",
"Gateway",
"api",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2379-L2429 |
29,706 | Miserlou/Zappa | zappa/core.py | Zappa.update_domain_base_path_mapping | def update_domain_base_path_mapping(self, domain_name, lambda_name, stage, base_path):
"""
Update domain base path mapping on API Gateway if it was changed
"""
api_id = self.get_api_id(lambda_name)
if not api_id:
print("Warning! Can't update base path mapping!")
return
base_path_mappings = self.apigateway_client.get_base_path_mappings(domainName=domain_name)
found = False
for base_path_mapping in base_path_mappings.get('items', []):
if base_path_mapping['restApiId'] == api_id and base_path_mapping['stage'] == stage:
found = True
if base_path_mapping['basePath'] != base_path:
self.apigateway_client.update_base_path_mapping(domainName=domain_name,
basePath=base_path_mapping['basePath'],
patchOperations=[
{"op" : "replace",
"path" : "/basePath",
"value" : '' if base_path is None else base_path}
])
if not found:
self.apigateway_client.create_base_path_mapping(
domainName=domain_name,
basePath='' if base_path is None else base_path,
restApiId=api_id,
stage=stage
) | python | def update_domain_base_path_mapping(self, domain_name, lambda_name, stage, base_path):
"""
Update domain base path mapping on API Gateway if it was changed
"""
api_id = self.get_api_id(lambda_name)
if not api_id:
print("Warning! Can't update base path mapping!")
return
base_path_mappings = self.apigateway_client.get_base_path_mappings(domainName=domain_name)
found = False
for base_path_mapping in base_path_mappings.get('items', []):
if base_path_mapping['restApiId'] == api_id and base_path_mapping['stage'] == stage:
found = True
if base_path_mapping['basePath'] != base_path:
self.apigateway_client.update_base_path_mapping(domainName=domain_name,
basePath=base_path_mapping['basePath'],
patchOperations=[
{"op" : "replace",
"path" : "/basePath",
"value" : '' if base_path is None else base_path}
])
if not found:
self.apigateway_client.create_base_path_mapping(
domainName=domain_name,
basePath='' if base_path is None else base_path,
restApiId=api_id,
stage=stage
) | [
"def",
"update_domain_base_path_mapping",
"(",
"self",
",",
"domain_name",
",",
"lambda_name",
",",
"stage",
",",
"base_path",
")",
":",
"api_id",
"=",
"self",
".",
"get_api_id",
"(",
"lambda_name",
")",
"if",
"not",
"api_id",
":",
"print",
"(",
"\"Warning! Ca... | Update domain base path mapping on API Gateway if it was changed | [
"Update",
"domain",
"base",
"path",
"mapping",
"on",
"API",
"Gateway",
"if",
"it",
"was",
"changed"
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2431-L2458 |
29,707 | Miserlou/Zappa | zappa/core.py | Zappa.get_all_zones | def get_all_zones(self):
"""Same behaviour of list_host_zones, but transparently handling pagination."""
zones = {'HostedZones': []}
new_zones = self.route53.list_hosted_zones(MaxItems='100')
while new_zones['IsTruncated']:
zones['HostedZones'] += new_zones['HostedZones']
new_zones = self.route53.list_hosted_zones(Marker=new_zones['NextMarker'], MaxItems='100')
zones['HostedZones'] += new_zones['HostedZones']
return zones | python | def get_all_zones(self):
"""Same behaviour of list_host_zones, but transparently handling pagination."""
zones = {'HostedZones': []}
new_zones = self.route53.list_hosted_zones(MaxItems='100')
while new_zones['IsTruncated']:
zones['HostedZones'] += new_zones['HostedZones']
new_zones = self.route53.list_hosted_zones(Marker=new_zones['NextMarker'], MaxItems='100')
zones['HostedZones'] += new_zones['HostedZones']
return zones | [
"def",
"get_all_zones",
"(",
"self",
")",
":",
"zones",
"=",
"{",
"'HostedZones'",
":",
"[",
"]",
"}",
"new_zones",
"=",
"self",
".",
"route53",
".",
"list_hosted_zones",
"(",
"MaxItems",
"=",
"'100'",
")",
"while",
"new_zones",
"[",
"'IsTruncated'",
"]",
... | Same behaviour of list_host_zones, but transparently handling pagination. | [
"Same",
"behaviour",
"of",
"list_host_zones",
"but",
"transparently",
"handling",
"pagination",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2460-L2470 |
29,708 | Miserlou/Zappa | zappa/core.py | Zappa.get_domain_name | def get_domain_name(self, domain_name, route53=True):
"""
Scan our hosted zones for the record of a given name.
Returns the record entry, else None.
"""
# Make sure api gateway domain is present
try:
self.apigateway_client.get_domain_name(domainName=domain_name)
except Exception:
return None
if not route53:
return True
try:
zones = self.get_all_zones()
for zone in zones['HostedZones']:
records = self.route53.list_resource_record_sets(HostedZoneId=zone['Id'])
for record in records['ResourceRecordSets']:
if record['Type'] in ('CNAME', 'A') and record['Name'][:-1] == domain_name:
return record
except Exception as e:
return None
##
# Old, automatic logic.
# If re-introduced, should be moved to a new function.
# Related ticket: https://github.com/Miserlou/Zappa/pull/458
##
# We may be in a position where Route53 doesn't have a domain, but the API Gateway does.
# We need to delete this before we can create the new Route53.
# try:
# api_gateway_domain = self.apigateway_client.get_domain_name(domainName=domain_name)
# self.apigateway_client.delete_domain_name(domainName=domain_name)
# except Exception:
# pass
return None | python | def get_domain_name(self, domain_name, route53=True):
"""
Scan our hosted zones for the record of a given name.
Returns the record entry, else None.
"""
# Make sure api gateway domain is present
try:
self.apigateway_client.get_domain_name(domainName=domain_name)
except Exception:
return None
if not route53:
return True
try:
zones = self.get_all_zones()
for zone in zones['HostedZones']:
records = self.route53.list_resource_record_sets(HostedZoneId=zone['Id'])
for record in records['ResourceRecordSets']:
if record['Type'] in ('CNAME', 'A') and record['Name'][:-1] == domain_name:
return record
except Exception as e:
return None
##
# Old, automatic logic.
# If re-introduced, should be moved to a new function.
# Related ticket: https://github.com/Miserlou/Zappa/pull/458
##
# We may be in a position where Route53 doesn't have a domain, but the API Gateway does.
# We need to delete this before we can create the new Route53.
# try:
# api_gateway_domain = self.apigateway_client.get_domain_name(domainName=domain_name)
# self.apigateway_client.delete_domain_name(domainName=domain_name)
# except Exception:
# pass
return None | [
"def",
"get_domain_name",
"(",
"self",
",",
"domain_name",
",",
"route53",
"=",
"True",
")",
":",
"# Make sure api gateway domain is present",
"try",
":",
"self",
".",
"apigateway_client",
".",
"get_domain_name",
"(",
"domainName",
"=",
"domain_name",
")",
"except",... | Scan our hosted zones for the record of a given name.
Returns the record entry, else None. | [
"Scan",
"our",
"hosted",
"zones",
"for",
"the",
"record",
"of",
"a",
"given",
"name",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2472-L2513 |
29,709 | Miserlou/Zappa | zappa/core.py | Zappa.get_credentials_arn | def get_credentials_arn(self):
"""
Given our role name, get and set the credentials_arn.
"""
role = self.iam.Role(self.role_name)
self.credentials_arn = role.arn
return role, self.credentials_arn | python | def get_credentials_arn(self):
"""
Given our role name, get and set the credentials_arn.
"""
role = self.iam.Role(self.role_name)
self.credentials_arn = role.arn
return role, self.credentials_arn | [
"def",
"get_credentials_arn",
"(",
"self",
")",
":",
"role",
"=",
"self",
".",
"iam",
".",
"Role",
"(",
"self",
".",
"role_name",
")",
"self",
".",
"credentials_arn",
"=",
"role",
".",
"arn",
"return",
"role",
",",
"self",
".",
"credentials_arn"
] | Given our role name, get and set the credentials_arn. | [
"Given",
"our",
"role",
"name",
"get",
"and",
"set",
"the",
"credentials_arn",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2519-L2526 |
29,710 | Miserlou/Zappa | zappa/core.py | Zappa.create_iam_roles | def create_iam_roles(self):
"""
Create and defines the IAM roles and policies necessary for Zappa.
If the IAM role already exists, it will be updated if necessary.
"""
attach_policy_obj = json.loads(self.attach_policy)
assume_policy_obj = json.loads(self.assume_policy)
if self.extra_permissions:
for permission in self.extra_permissions:
attach_policy_obj['Statement'].append(dict(permission))
self.attach_policy = json.dumps(attach_policy_obj)
updated = False
# Create the role if needed
try:
role, credentials_arn = self.get_credentials_arn()
except botocore.client.ClientError:
print("Creating " + self.role_name + " IAM Role..")
role = self.iam.create_role(
RoleName=self.role_name,
AssumeRolePolicyDocument=self.assume_policy
)
self.credentials_arn = role.arn
updated = True
# create or update the role's policies if needed
policy = self.iam.RolePolicy(self.role_name, 'zappa-permissions')
try:
if policy.policy_document != attach_policy_obj:
print("Updating zappa-permissions policy on " + self.role_name + " IAM Role.")
policy.put(PolicyDocument=self.attach_policy)
updated = True
except botocore.client.ClientError:
print("Creating zappa-permissions policy on " + self.role_name + " IAM Role.")
policy.put(PolicyDocument=self.attach_policy)
updated = True
if role.assume_role_policy_document != assume_policy_obj and \
set(role.assume_role_policy_document['Statement'][0]['Principal']['Service']) != set(assume_policy_obj['Statement'][0]['Principal']['Service']):
print("Updating assume role policy on " + self.role_name + " IAM Role.")
self.iam_client.update_assume_role_policy(
RoleName=self.role_name,
PolicyDocument=self.assume_policy
)
updated = True
return self.credentials_arn, updated | python | def create_iam_roles(self):
"""
Create and defines the IAM roles and policies necessary for Zappa.
If the IAM role already exists, it will be updated if necessary.
"""
attach_policy_obj = json.loads(self.attach_policy)
assume_policy_obj = json.loads(self.assume_policy)
if self.extra_permissions:
for permission in self.extra_permissions:
attach_policy_obj['Statement'].append(dict(permission))
self.attach_policy = json.dumps(attach_policy_obj)
updated = False
# Create the role if needed
try:
role, credentials_arn = self.get_credentials_arn()
except botocore.client.ClientError:
print("Creating " + self.role_name + " IAM Role..")
role = self.iam.create_role(
RoleName=self.role_name,
AssumeRolePolicyDocument=self.assume_policy
)
self.credentials_arn = role.arn
updated = True
# create or update the role's policies if needed
policy = self.iam.RolePolicy(self.role_name, 'zappa-permissions')
try:
if policy.policy_document != attach_policy_obj:
print("Updating zappa-permissions policy on " + self.role_name + " IAM Role.")
policy.put(PolicyDocument=self.attach_policy)
updated = True
except botocore.client.ClientError:
print("Creating zappa-permissions policy on " + self.role_name + " IAM Role.")
policy.put(PolicyDocument=self.attach_policy)
updated = True
if role.assume_role_policy_document != assume_policy_obj and \
set(role.assume_role_policy_document['Statement'][0]['Principal']['Service']) != set(assume_policy_obj['Statement'][0]['Principal']['Service']):
print("Updating assume role policy on " + self.role_name + " IAM Role.")
self.iam_client.update_assume_role_policy(
RoleName=self.role_name,
PolicyDocument=self.assume_policy
)
updated = True
return self.credentials_arn, updated | [
"def",
"create_iam_roles",
"(",
"self",
")",
":",
"attach_policy_obj",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"attach_policy",
")",
"assume_policy_obj",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"assume_policy",
")",
"if",
"self",
".",
"extra_permis... | Create and defines the IAM roles and policies necessary for Zappa.
If the IAM role already exists, it will be updated if necessary. | [
"Create",
"and",
"defines",
"the",
"IAM",
"roles",
"and",
"policies",
"necessary",
"for",
"Zappa",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2528-L2581 |
29,711 | Miserlou/Zappa | zappa/core.py | Zappa._clear_policy | def _clear_policy(self, lambda_name):
"""
Remove obsolete policy statements to prevent policy from bloating over the limit after repeated updates.
"""
try:
policy_response = self.lambda_client.get_policy(
FunctionName=lambda_name
)
if policy_response['ResponseMetadata']['HTTPStatusCode'] == 200:
statement = json.loads(policy_response['Policy'])['Statement']
for s in statement:
delete_response = self.lambda_client.remove_permission(
FunctionName=lambda_name,
StatementId=s['Sid']
)
if delete_response['ResponseMetadata']['HTTPStatusCode'] != 204:
logger.error('Failed to delete an obsolete policy statement: {}'.format(policy_response))
else:
logger.debug('Failed to load Lambda function policy: {}'.format(policy_response))
except ClientError as e:
if e.args[0].find('ResourceNotFoundException') > -1:
logger.debug('No policy found, must be first run.')
else:
logger.error('Unexpected client error {}'.format(e.args[0])) | python | def _clear_policy(self, lambda_name):
"""
Remove obsolete policy statements to prevent policy from bloating over the limit after repeated updates.
"""
try:
policy_response = self.lambda_client.get_policy(
FunctionName=lambda_name
)
if policy_response['ResponseMetadata']['HTTPStatusCode'] == 200:
statement = json.loads(policy_response['Policy'])['Statement']
for s in statement:
delete_response = self.lambda_client.remove_permission(
FunctionName=lambda_name,
StatementId=s['Sid']
)
if delete_response['ResponseMetadata']['HTTPStatusCode'] != 204:
logger.error('Failed to delete an obsolete policy statement: {}'.format(policy_response))
else:
logger.debug('Failed to load Lambda function policy: {}'.format(policy_response))
except ClientError as e:
if e.args[0].find('ResourceNotFoundException') > -1:
logger.debug('No policy found, must be first run.')
else:
logger.error('Unexpected client error {}'.format(e.args[0])) | [
"def",
"_clear_policy",
"(",
"self",
",",
"lambda_name",
")",
":",
"try",
":",
"policy_response",
"=",
"self",
".",
"lambda_client",
".",
"get_policy",
"(",
"FunctionName",
"=",
"lambda_name",
")",
"if",
"policy_response",
"[",
"'ResponseMetadata'",
"]",
"[",
... | Remove obsolete policy statements to prevent policy from bloating over the limit after repeated updates. | [
"Remove",
"obsolete",
"policy",
"statements",
"to",
"prevent",
"policy",
"from",
"bloating",
"over",
"the",
"limit",
"after",
"repeated",
"updates",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2583-L2606 |
29,712 | Miserlou/Zappa | zappa/core.py | Zappa.create_event_permission | def create_event_permission(self, lambda_name, principal, source_arn):
"""
Create permissions to link to an event.
Related: http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-configure-event-source.html
"""
logger.debug('Adding new permission to invoke Lambda function: {}'.format(lambda_name))
permission_response = self.lambda_client.add_permission(
FunctionName=lambda_name,
StatementId=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)),
Action='lambda:InvokeFunction',
Principal=principal,
SourceArn=source_arn,
)
if permission_response['ResponseMetadata']['HTTPStatusCode'] != 201:
print('Problem creating permission to invoke Lambda function')
return None # XXX: Raise?
return permission_response | python | def create_event_permission(self, lambda_name, principal, source_arn):
"""
Create permissions to link to an event.
Related: http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-configure-event-source.html
"""
logger.debug('Adding new permission to invoke Lambda function: {}'.format(lambda_name))
permission_response = self.lambda_client.add_permission(
FunctionName=lambda_name,
StatementId=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)),
Action='lambda:InvokeFunction',
Principal=principal,
SourceArn=source_arn,
)
if permission_response['ResponseMetadata']['HTTPStatusCode'] != 201:
print('Problem creating permission to invoke Lambda function')
return None # XXX: Raise?
return permission_response | [
"def",
"create_event_permission",
"(",
"self",
",",
"lambda_name",
",",
"principal",
",",
"source_arn",
")",
":",
"logger",
".",
"debug",
"(",
"'Adding new permission to invoke Lambda function: {}'",
".",
"format",
"(",
"lambda_name",
")",
")",
"permission_response",
... | Create permissions to link to an event.
Related: http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-configure-event-source.html | [
"Create",
"permissions",
"to",
"link",
"to",
"an",
"event",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2612-L2631 |
29,713 | Miserlou/Zappa | zappa/core.py | Zappa.get_event_name | def get_event_name(lambda_name, name):
"""
Returns an AWS-valid Lambda event name.
"""
return '{prefix:.{width}}-{postfix}'.format(prefix=lambda_name, width=max(0, 63 - len(name)), postfix=name)[:64] | python | def get_event_name(lambda_name, name):
"""
Returns an AWS-valid Lambda event name.
"""
return '{prefix:.{width}}-{postfix}'.format(prefix=lambda_name, width=max(0, 63 - len(name)), postfix=name)[:64] | [
"def",
"get_event_name",
"(",
"lambda_name",
",",
"name",
")",
":",
"return",
"'{prefix:.{width}}-{postfix}'",
".",
"format",
"(",
"prefix",
"=",
"lambda_name",
",",
"width",
"=",
"max",
"(",
"0",
",",
"63",
"-",
"len",
"(",
"name",
")",
")",
",",
"postf... | Returns an AWS-valid Lambda event name. | [
"Returns",
"an",
"AWS",
"-",
"valid",
"Lambda",
"event",
"name",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2790-L2795 |
29,714 | Miserlou/Zappa | zappa/core.py | Zappa.get_hashed_rule_name | def get_hashed_rule_name(event, function, lambda_name):
"""
Returns an AWS-valid CloudWatch rule name using a digest of the event name, lambda name, and function.
This allows support for rule names that may be longer than the 64 char limit.
"""
event_name = event.get('name', function)
name_hash = hashlib.sha1('{}-{}'.format(lambda_name, event_name).encode('UTF-8')).hexdigest()
return Zappa.get_event_name(name_hash, function) | python | def get_hashed_rule_name(event, function, lambda_name):
"""
Returns an AWS-valid CloudWatch rule name using a digest of the event name, lambda name, and function.
This allows support for rule names that may be longer than the 64 char limit.
"""
event_name = event.get('name', function)
name_hash = hashlib.sha1('{}-{}'.format(lambda_name, event_name).encode('UTF-8')).hexdigest()
return Zappa.get_event_name(name_hash, function) | [
"def",
"get_hashed_rule_name",
"(",
"event",
",",
"function",
",",
"lambda_name",
")",
":",
"event_name",
"=",
"event",
".",
"get",
"(",
"'name'",
",",
"function",
")",
"name_hash",
"=",
"hashlib",
".",
"sha1",
"(",
"'{}-{}'",
".",
"format",
"(",
"lambda_n... | Returns an AWS-valid CloudWatch rule name using a digest of the event name, lambda name, and function.
This allows support for rule names that may be longer than the 64 char limit. | [
"Returns",
"an",
"AWS",
"-",
"valid",
"CloudWatch",
"rule",
"name",
"using",
"a",
"digest",
"of",
"the",
"event",
"name",
"lambda",
"name",
"and",
"function",
".",
"This",
"allows",
"support",
"for",
"rule",
"names",
"that",
"may",
"be",
"longer",
"than",
... | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2798-L2805 |
29,715 | Miserlou/Zappa | zappa/core.py | Zappa.delete_rule | def delete_rule(self, rule_name):
"""
Delete a CWE rule.
This deletes them, but they will still show up in the AWS console.
Annoying.
"""
logger.debug('Deleting existing rule {}'.format(rule_name))
# All targets must be removed before
# we can actually delete the rule.
try:
targets = self.events_client.list_targets_by_rule(Rule=rule_name)
except botocore.exceptions.ClientError as e:
# This avoids misbehavior if low permissions, related: https://github.com/Miserlou/Zappa/issues/286
error_code = e.response['Error']['Code']
if error_code == 'AccessDeniedException':
raise
else:
logger.debug('No target found for this rule: {} {}'.format(rule_name, e.args[0]))
return
if 'Targets' in targets and targets['Targets']:
self.events_client.remove_targets(Rule=rule_name, Ids=[x['Id'] for x in targets['Targets']])
else: # pragma: no cover
logger.debug('No target to delete')
# Delete our rule.
self.events_client.delete_rule(Name=rule_name) | python | def delete_rule(self, rule_name):
"""
Delete a CWE rule.
This deletes them, but they will still show up in the AWS console.
Annoying.
"""
logger.debug('Deleting existing rule {}'.format(rule_name))
# All targets must be removed before
# we can actually delete the rule.
try:
targets = self.events_client.list_targets_by_rule(Rule=rule_name)
except botocore.exceptions.ClientError as e:
# This avoids misbehavior if low permissions, related: https://github.com/Miserlou/Zappa/issues/286
error_code = e.response['Error']['Code']
if error_code == 'AccessDeniedException':
raise
else:
logger.debug('No target found for this rule: {} {}'.format(rule_name, e.args[0]))
return
if 'Targets' in targets and targets['Targets']:
self.events_client.remove_targets(Rule=rule_name, Ids=[x['Id'] for x in targets['Targets']])
else: # pragma: no cover
logger.debug('No target to delete')
# Delete our rule.
self.events_client.delete_rule(Name=rule_name) | [
"def",
"delete_rule",
"(",
"self",
",",
"rule_name",
")",
":",
"logger",
".",
"debug",
"(",
"'Deleting existing rule {}'",
".",
"format",
"(",
"rule_name",
")",
")",
"# All targets must be removed before",
"# we can actually delete the rule.",
"try",
":",
"targets",
"... | Delete a CWE rule.
This deletes them, but they will still show up in the AWS console.
Annoying. | [
"Delete",
"a",
"CWE",
"rule",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2807-L2836 |
29,716 | Miserlou/Zappa | zappa/core.py | Zappa.get_event_rule_names_for_lambda | def get_event_rule_names_for_lambda(self, lambda_arn):
"""
Get all of the rule names associated with a lambda function.
"""
response = self.events_client.list_rule_names_by_target(TargetArn=lambda_arn)
rule_names = response['RuleNames']
# Iterate when the results are paginated
while 'NextToken' in response:
response = self.events_client.list_rule_names_by_target(TargetArn=lambda_arn,
NextToken=response['NextToken'])
rule_names.extend(response['RuleNames'])
return rule_names | python | def get_event_rule_names_for_lambda(self, lambda_arn):
"""
Get all of the rule names associated with a lambda function.
"""
response = self.events_client.list_rule_names_by_target(TargetArn=lambda_arn)
rule_names = response['RuleNames']
# Iterate when the results are paginated
while 'NextToken' in response:
response = self.events_client.list_rule_names_by_target(TargetArn=lambda_arn,
NextToken=response['NextToken'])
rule_names.extend(response['RuleNames'])
return rule_names | [
"def",
"get_event_rule_names_for_lambda",
"(",
"self",
",",
"lambda_arn",
")",
":",
"response",
"=",
"self",
".",
"events_client",
".",
"list_rule_names_by_target",
"(",
"TargetArn",
"=",
"lambda_arn",
")",
"rule_names",
"=",
"response",
"[",
"'RuleNames'",
"]",
"... | Get all of the rule names associated with a lambda function. | [
"Get",
"all",
"of",
"the",
"rule",
"names",
"associated",
"with",
"a",
"lambda",
"function",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2838-L2849 |
29,717 | Miserlou/Zappa | zappa/core.py | Zappa.get_event_rules_for_lambda | def get_event_rules_for_lambda(self, lambda_arn):
"""
Get all of the rule details associated with this function.
"""
rule_names = self.get_event_rule_names_for_lambda(lambda_arn=lambda_arn)
return [self.events_client.describe_rule(Name=r) for r in rule_names] | python | def get_event_rules_for_lambda(self, lambda_arn):
"""
Get all of the rule details associated with this function.
"""
rule_names = self.get_event_rule_names_for_lambda(lambda_arn=lambda_arn)
return [self.events_client.describe_rule(Name=r) for r in rule_names] | [
"def",
"get_event_rules_for_lambda",
"(",
"self",
",",
"lambda_arn",
")",
":",
"rule_names",
"=",
"self",
".",
"get_event_rule_names_for_lambda",
"(",
"lambda_arn",
"=",
"lambda_arn",
")",
"return",
"[",
"self",
".",
"events_client",
".",
"describe_rule",
"(",
"Na... | Get all of the rule details associated with this function. | [
"Get",
"all",
"of",
"the",
"rule",
"details",
"associated",
"with",
"this",
"function",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2851-L2856 |
29,718 | Miserlou/Zappa | zappa/core.py | Zappa.unschedule_events | def unschedule_events(self, events, lambda_arn=None, lambda_name=None, excluded_source_services=None):
excluded_source_services = excluded_source_services or []
"""
Given a list of events, unschedule these CloudWatch Events.
'events' is a list of dictionaries, where the dict must contains the string
of a 'function' and the string of the event 'expression', and an optional 'name' and 'description'.
"""
self._clear_policy(lambda_name)
rule_names = self.get_event_rule_names_for_lambda(lambda_arn=lambda_arn)
for rule_name in rule_names:
self.delete_rule(rule_name)
print('Unscheduled ' + rule_name + '.')
non_cwe = [e for e in events if 'event_source' in e]
for event in non_cwe:
# TODO: This WILL miss non CW events that have been deployed but changed names. Figure out a way to remove
# them no matter what.
# These are non CWE event sources.
function = event['function']
name = event.get('name', function)
event_source = event.get('event_source', function)
service = self.service_from_arn(event_source['arn'])
# DynamoDB and Kinesis streams take quite a while to setup after they are created and do not need to be
# re-scheduled when a new Lambda function is deployed. Therefore, they should not be removed during zappa
# update or zappa schedule.
if service not in excluded_source_services:
remove_event_source(
event_source,
lambda_arn,
function,
self.boto_session
)
print("Removed event {}{}.".format(
name,
" ({})".format(str(event_source['events'])) if 'events' in event_source else '')
) | python | def unschedule_events(self, events, lambda_arn=None, lambda_name=None, excluded_source_services=None):
excluded_source_services = excluded_source_services or []
"""
Given a list of events, unschedule these CloudWatch Events.
'events' is a list of dictionaries, where the dict must contains the string
of a 'function' and the string of the event 'expression', and an optional 'name' and 'description'.
"""
self._clear_policy(lambda_name)
rule_names = self.get_event_rule_names_for_lambda(lambda_arn=lambda_arn)
for rule_name in rule_names:
self.delete_rule(rule_name)
print('Unscheduled ' + rule_name + '.')
non_cwe = [e for e in events if 'event_source' in e]
for event in non_cwe:
# TODO: This WILL miss non CW events that have been deployed but changed names. Figure out a way to remove
# them no matter what.
# These are non CWE event sources.
function = event['function']
name = event.get('name', function)
event_source = event.get('event_source', function)
service = self.service_from_arn(event_source['arn'])
# DynamoDB and Kinesis streams take quite a while to setup after they are created and do not need to be
# re-scheduled when a new Lambda function is deployed. Therefore, they should not be removed during zappa
# update or zappa schedule.
if service not in excluded_source_services:
remove_event_source(
event_source,
lambda_arn,
function,
self.boto_session
)
print("Removed event {}{}.".format(
name,
" ({})".format(str(event_source['events'])) if 'events' in event_source else '')
) | [
"def",
"unschedule_events",
"(",
"self",
",",
"events",
",",
"lambda_arn",
"=",
"None",
",",
"lambda_name",
"=",
"None",
",",
"excluded_source_services",
"=",
"None",
")",
":",
"excluded_source_services",
"=",
"excluded_source_services",
"or",
"[",
"]",
"self",
... | Given a list of events, unschedule these CloudWatch Events.
'events' is a list of dictionaries, where the dict must contains the string
of a 'function' and the string of the event 'expression', and an optional 'name' and 'description'. | [
"Given",
"a",
"list",
"of",
"events",
"unschedule",
"these",
"CloudWatch",
"Events",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2858-L2895 |
29,719 | Miserlou/Zappa | zappa/core.py | Zappa.create_async_sns_topic | def create_async_sns_topic(self, lambda_name, lambda_arn):
"""
Create the SNS-based async topic.
"""
topic_name = get_topic_name(lambda_name)
# Create SNS topic
topic_arn = self.sns_client.create_topic(
Name=topic_name)['TopicArn']
# Create subscription
self.sns_client.subscribe(
TopicArn=topic_arn,
Protocol='lambda',
Endpoint=lambda_arn
)
# Add Lambda permission for SNS to invoke function
self.create_event_permission(
lambda_name=lambda_name,
principal='sns.amazonaws.com',
source_arn=topic_arn
)
# Add rule for SNS topic as a event source
add_event_source(
event_source={
"arn": topic_arn,
"events": ["sns:Publish"]
},
lambda_arn=lambda_arn,
target_function="zappa.asynchronous.route_task",
boto_session=self.boto_session
)
return topic_arn | python | def create_async_sns_topic(self, lambda_name, lambda_arn):
"""
Create the SNS-based async topic.
"""
topic_name = get_topic_name(lambda_name)
# Create SNS topic
topic_arn = self.sns_client.create_topic(
Name=topic_name)['TopicArn']
# Create subscription
self.sns_client.subscribe(
TopicArn=topic_arn,
Protocol='lambda',
Endpoint=lambda_arn
)
# Add Lambda permission for SNS to invoke function
self.create_event_permission(
lambda_name=lambda_name,
principal='sns.amazonaws.com',
source_arn=topic_arn
)
# Add rule for SNS topic as a event source
add_event_source(
event_source={
"arn": topic_arn,
"events": ["sns:Publish"]
},
lambda_arn=lambda_arn,
target_function="zappa.asynchronous.route_task",
boto_session=self.boto_session
)
return topic_arn | [
"def",
"create_async_sns_topic",
"(",
"self",
",",
"lambda_name",
",",
"lambda_arn",
")",
":",
"topic_name",
"=",
"get_topic_name",
"(",
"lambda_name",
")",
"# Create SNS topic",
"topic_arn",
"=",
"self",
".",
"sns_client",
".",
"create_topic",
"(",
"Name",
"=",
... | Create the SNS-based async topic. | [
"Create",
"the",
"SNS",
"-",
"based",
"async",
"topic",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2901-L2931 |
29,720 | Miserlou/Zappa | zappa/core.py | Zappa.remove_async_sns_topic | def remove_async_sns_topic(self, lambda_name):
"""
Remove the async SNS topic.
"""
topic_name = get_topic_name(lambda_name)
removed_arns = []
for sub in self.sns_client.list_subscriptions()['Subscriptions']:
if topic_name in sub['TopicArn']:
self.sns_client.delete_topic(TopicArn=sub['TopicArn'])
removed_arns.append(sub['TopicArn'])
return removed_arns | python | def remove_async_sns_topic(self, lambda_name):
"""
Remove the async SNS topic.
"""
topic_name = get_topic_name(lambda_name)
removed_arns = []
for sub in self.sns_client.list_subscriptions()['Subscriptions']:
if topic_name in sub['TopicArn']:
self.sns_client.delete_topic(TopicArn=sub['TopicArn'])
removed_arns.append(sub['TopicArn'])
return removed_arns | [
"def",
"remove_async_sns_topic",
"(",
"self",
",",
"lambda_name",
")",
":",
"topic_name",
"=",
"get_topic_name",
"(",
"lambda_name",
")",
"removed_arns",
"=",
"[",
"]",
"for",
"sub",
"in",
"self",
".",
"sns_client",
".",
"list_subscriptions",
"(",
")",
"[",
... | Remove the async SNS topic. | [
"Remove",
"the",
"async",
"SNS",
"topic",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2933-L2943 |
29,721 | Miserlou/Zappa | zappa/core.py | Zappa.create_async_dynamodb_table | def create_async_dynamodb_table(self, table_name, read_capacity, write_capacity):
"""
Create the DynamoDB table for async task return values
"""
try:
dynamodb_table = self.dynamodb_client.describe_table(TableName=table_name)
return False, dynamodb_table
# catch this exception (triggered if the table doesn't exist)
except botocore.exceptions.ClientError:
dynamodb_table = self.dynamodb_client.create_table(
AttributeDefinitions=[
{
'AttributeName': 'id',
'AttributeType': 'S'
}
],
TableName=table_name,
KeySchema=[
{
'AttributeName': 'id',
'KeyType': 'HASH'
},
],
ProvisionedThroughput = {
'ReadCapacityUnits': read_capacity,
'WriteCapacityUnits': write_capacity
}
)
if dynamodb_table:
try:
self._set_async_dynamodb_table_ttl(table_name)
except botocore.exceptions.ClientError:
# this fails because the operation is async, so retry
time.sleep(10)
self._set_async_dynamodb_table_ttl(table_name)
return True, dynamodb_table | python | def create_async_dynamodb_table(self, table_name, read_capacity, write_capacity):
"""
Create the DynamoDB table for async task return values
"""
try:
dynamodb_table = self.dynamodb_client.describe_table(TableName=table_name)
return False, dynamodb_table
# catch this exception (triggered if the table doesn't exist)
except botocore.exceptions.ClientError:
dynamodb_table = self.dynamodb_client.create_table(
AttributeDefinitions=[
{
'AttributeName': 'id',
'AttributeType': 'S'
}
],
TableName=table_name,
KeySchema=[
{
'AttributeName': 'id',
'KeyType': 'HASH'
},
],
ProvisionedThroughput = {
'ReadCapacityUnits': read_capacity,
'WriteCapacityUnits': write_capacity
}
)
if dynamodb_table:
try:
self._set_async_dynamodb_table_ttl(table_name)
except botocore.exceptions.ClientError:
# this fails because the operation is async, so retry
time.sleep(10)
self._set_async_dynamodb_table_ttl(table_name)
return True, dynamodb_table | [
"def",
"create_async_dynamodb_table",
"(",
"self",
",",
"table_name",
",",
"read_capacity",
",",
"write_capacity",
")",
":",
"try",
":",
"dynamodb_table",
"=",
"self",
".",
"dynamodb_client",
".",
"describe_table",
"(",
"TableName",
"=",
"table_name",
")",
"return... | Create the DynamoDB table for async task return values | [
"Create",
"the",
"DynamoDB",
"table",
"for",
"async",
"task",
"return",
"values"
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L2960-L2997 |
29,722 | Miserlou/Zappa | zappa/core.py | Zappa.fetch_logs | def fetch_logs(self, lambda_name, filter_pattern='', limit=10000, start_time=0):
"""
Fetch the CloudWatch logs for a given Lambda name.
"""
log_name = '/aws/lambda/' + lambda_name
streams = self.logs_client.describe_log_streams(
logGroupName=log_name,
descending=True,
orderBy='LastEventTime'
)
all_streams = streams['logStreams']
all_names = [stream['logStreamName'] for stream in all_streams]
events = []
response = {}
while not response or 'nextToken' in response:
extra_args = {}
if 'nextToken' in response:
extra_args['nextToken'] = response['nextToken']
# Amazon uses millisecond epoch for some reason.
# Thanks, Jeff.
start_time = start_time * 1000
end_time = int(time.time()) * 1000
response = self.logs_client.filter_log_events(
logGroupName=log_name,
logStreamNames=all_names,
startTime=start_time,
endTime=end_time,
filterPattern=filter_pattern,
limit=limit,
interleaved=True, # Does this actually improve performance?
**extra_args
)
if response and 'events' in response:
events += response['events']
return sorted(events, key=lambda k: k['timestamp']) | python | def fetch_logs(self, lambda_name, filter_pattern='', limit=10000, start_time=0):
"""
Fetch the CloudWatch logs for a given Lambda name.
"""
log_name = '/aws/lambda/' + lambda_name
streams = self.logs_client.describe_log_streams(
logGroupName=log_name,
descending=True,
orderBy='LastEventTime'
)
all_streams = streams['logStreams']
all_names = [stream['logStreamName'] for stream in all_streams]
events = []
response = {}
while not response or 'nextToken' in response:
extra_args = {}
if 'nextToken' in response:
extra_args['nextToken'] = response['nextToken']
# Amazon uses millisecond epoch for some reason.
# Thanks, Jeff.
start_time = start_time * 1000
end_time = int(time.time()) * 1000
response = self.logs_client.filter_log_events(
logGroupName=log_name,
logStreamNames=all_names,
startTime=start_time,
endTime=end_time,
filterPattern=filter_pattern,
limit=limit,
interleaved=True, # Does this actually improve performance?
**extra_args
)
if response and 'events' in response:
events += response['events']
return sorted(events, key=lambda k: k['timestamp']) | [
"def",
"fetch_logs",
"(",
"self",
",",
"lambda_name",
",",
"filter_pattern",
"=",
"''",
",",
"limit",
"=",
"10000",
",",
"start_time",
"=",
"0",
")",
":",
"log_name",
"=",
"'/aws/lambda/'",
"+",
"lambda_name",
"streams",
"=",
"self",
".",
"logs_client",
".... | Fetch the CloudWatch logs for a given Lambda name. | [
"Fetch",
"the",
"CloudWatch",
"logs",
"for",
"a",
"given",
"Lambda",
"name",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L3010-L3049 |
29,723 | Miserlou/Zappa | zappa/core.py | Zappa.remove_log_group | def remove_log_group(self, group_name):
"""
Filter all log groups that match the name given in log_filter.
"""
print("Removing log group: {}".format(group_name))
try:
self.logs_client.delete_log_group(logGroupName=group_name)
except botocore.exceptions.ClientError as e:
print("Couldn't remove '{}' because of: {}".format(group_name, e)) | python | def remove_log_group(self, group_name):
"""
Filter all log groups that match the name given in log_filter.
"""
print("Removing log group: {}".format(group_name))
try:
self.logs_client.delete_log_group(logGroupName=group_name)
except botocore.exceptions.ClientError as e:
print("Couldn't remove '{}' because of: {}".format(group_name, e)) | [
"def",
"remove_log_group",
"(",
"self",
",",
"group_name",
")",
":",
"print",
"(",
"\"Removing log group: {}\"",
".",
"format",
"(",
"group_name",
")",
")",
"try",
":",
"self",
".",
"logs_client",
".",
"delete_log_group",
"(",
"logGroupName",
"=",
"group_name",
... | Filter all log groups that match the name given in log_filter. | [
"Filter",
"all",
"log",
"groups",
"that",
"match",
"the",
"name",
"given",
"in",
"log_filter",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L3051-L3059 |
29,724 | Miserlou/Zappa | zappa/core.py | Zappa.remove_api_gateway_logs | def remove_api_gateway_logs(self, project_name):
"""
Removed all logs that are assigned to a given rest api id.
"""
for rest_api in self.get_rest_apis(project_name):
for stage in self.apigateway_client.get_stages(restApiId=rest_api['id'])['item']:
self.remove_log_group('API-Gateway-Execution-Logs_{}/{}'.format(rest_api['id'], stage['stageName'])) | python | def remove_api_gateway_logs(self, project_name):
"""
Removed all logs that are assigned to a given rest api id.
"""
for rest_api in self.get_rest_apis(project_name):
for stage in self.apigateway_client.get_stages(restApiId=rest_api['id'])['item']:
self.remove_log_group('API-Gateway-Execution-Logs_{}/{}'.format(rest_api['id'], stage['stageName'])) | [
"def",
"remove_api_gateway_logs",
"(",
"self",
",",
"project_name",
")",
":",
"for",
"rest_api",
"in",
"self",
".",
"get_rest_apis",
"(",
"project_name",
")",
":",
"for",
"stage",
"in",
"self",
".",
"apigateway_client",
".",
"get_stages",
"(",
"restApiId",
"="... | Removed all logs that are assigned to a given rest api id. | [
"Removed",
"all",
"logs",
"that",
"are",
"assigned",
"to",
"a",
"given",
"rest",
"api",
"id",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L3067-L3073 |
29,725 | Miserlou/Zappa | zappa/core.py | Zappa.get_hosted_zone_id_for_domain | def get_hosted_zone_id_for_domain(self, domain):
"""
Get the Hosted Zone ID for a given domain.
"""
all_zones = self.get_all_zones()
return self.get_best_match_zone(all_zones, domain) | python | def get_hosted_zone_id_for_domain(self, domain):
"""
Get the Hosted Zone ID for a given domain.
"""
all_zones = self.get_all_zones()
return self.get_best_match_zone(all_zones, domain) | [
"def",
"get_hosted_zone_id_for_domain",
"(",
"self",
",",
"domain",
")",
":",
"all_zones",
"=",
"self",
".",
"get_all_zones",
"(",
")",
"return",
"self",
".",
"get_best_match_zone",
"(",
"all_zones",
",",
"domain",
")"
] | Get the Hosted Zone ID for a given domain. | [
"Get",
"the",
"Hosted",
"Zone",
"ID",
"for",
"a",
"given",
"domain",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L3079-L3085 |
29,726 | Miserlou/Zappa | zappa/core.py | Zappa.get_best_match_zone | def get_best_match_zone(all_zones, domain):
"""Return zone id which name is closer matched with domain name."""
# Related: https://github.com/Miserlou/Zappa/issues/459
public_zones = [zone for zone in all_zones['HostedZones'] if not zone['Config']['PrivateZone']]
zones = {zone['Name'][:-1]: zone['Id'] for zone in public_zones if zone['Name'][:-1] in domain}
if zones:
keys = max(zones.keys(), key=lambda a: len(a)) # get longest key -- best match.
return zones[keys]
else:
return None | python | def get_best_match_zone(all_zones, domain):
"""Return zone id which name is closer matched with domain name."""
# Related: https://github.com/Miserlou/Zappa/issues/459
public_zones = [zone for zone in all_zones['HostedZones'] if not zone['Config']['PrivateZone']]
zones = {zone['Name'][:-1]: zone['Id'] for zone in public_zones if zone['Name'][:-1] in domain}
if zones:
keys = max(zones.keys(), key=lambda a: len(a)) # get longest key -- best match.
return zones[keys]
else:
return None | [
"def",
"get_best_match_zone",
"(",
"all_zones",
",",
"domain",
")",
":",
"# Related: https://github.com/Miserlou/Zappa/issues/459",
"public_zones",
"=",
"[",
"zone",
"for",
"zone",
"in",
"all_zones",
"[",
"'HostedZones'",
"]",
"if",
"not",
"zone",
"[",
"'Config'",
"... | Return zone id which name is closer matched with domain name. | [
"Return",
"zone",
"id",
"which",
"name",
"is",
"closer",
"matched",
"with",
"domain",
"name",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L3088-L3099 |
29,727 | Miserlou/Zappa | zappa/core.py | Zappa.remove_dns_challenge_txt | def remove_dns_challenge_txt(self, zone_id, domain, txt_challenge):
"""
Remove DNS challenge TXT.
"""
print("Deleting DNS challenge..")
resp = self.route53.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch=self.get_dns_challenge_change_batch('DELETE', domain, txt_challenge)
)
return resp | python | def remove_dns_challenge_txt(self, zone_id, domain, txt_challenge):
"""
Remove DNS challenge TXT.
"""
print("Deleting DNS challenge..")
resp = self.route53.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch=self.get_dns_challenge_change_batch('DELETE', domain, txt_challenge)
)
return resp | [
"def",
"remove_dns_challenge_txt",
"(",
"self",
",",
"zone_id",
",",
"domain",
",",
"txt_challenge",
")",
":",
"print",
"(",
"\"Deleting DNS challenge..\"",
")",
"resp",
"=",
"self",
".",
"route53",
".",
"change_resource_record_sets",
"(",
"HostedZoneId",
"=",
"zo... | Remove DNS challenge TXT. | [
"Remove",
"DNS",
"challenge",
"TXT",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L3113-L3123 |
29,728 | Miserlou/Zappa | zappa/core.py | Zappa.load_credentials | def load_credentials(self, boto_session=None, profile_name=None):
"""
Load AWS credentials.
An optional boto_session can be provided, but that's usually for testing.
An optional profile_name can be provided for config files that have multiple sets
of credentials.
"""
# Automatically load credentials from config or environment
if not boto_session:
# If provided, use the supplied profile name.
if profile_name:
self.boto_session = boto3.Session(profile_name=profile_name, region_name=self.aws_region)
elif os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY'):
region_name = os.environ.get('AWS_DEFAULT_REGION') or self.aws_region
session_kw = {
"aws_access_key_id": os.environ.get('AWS_ACCESS_KEY_ID'),
"aws_secret_access_key": os.environ.get('AWS_SECRET_ACCESS_KEY'),
"region_name": region_name,
}
# If we're executing in a role, AWS_SESSION_TOKEN will be present, too.
if os.environ.get("AWS_SESSION_TOKEN"):
session_kw["aws_session_token"] = os.environ.get("AWS_SESSION_TOKEN")
self.boto_session = boto3.Session(**session_kw)
else:
self.boto_session = boto3.Session(region_name=self.aws_region)
logger.debug("Loaded boto session from config: %s", boto_session)
else:
logger.debug("Using provided boto session: %s", boto_session)
self.boto_session = boto_session
# use provided session's region in case it differs
self.aws_region = self.boto_session.region_name
if self.boto_session.region_name not in LAMBDA_REGIONS:
print("Warning! AWS Lambda may not be available in this AWS Region!")
if self.boto_session.region_name not in API_GATEWAY_REGIONS:
print("Warning! AWS API Gateway may not be available in this AWS Region!") | python | def load_credentials(self, boto_session=None, profile_name=None):
"""
Load AWS credentials.
An optional boto_session can be provided, but that's usually for testing.
An optional profile_name can be provided for config files that have multiple sets
of credentials.
"""
# Automatically load credentials from config or environment
if not boto_session:
# If provided, use the supplied profile name.
if profile_name:
self.boto_session = boto3.Session(profile_name=profile_name, region_name=self.aws_region)
elif os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY'):
region_name = os.environ.get('AWS_DEFAULT_REGION') or self.aws_region
session_kw = {
"aws_access_key_id": os.environ.get('AWS_ACCESS_KEY_ID'),
"aws_secret_access_key": os.environ.get('AWS_SECRET_ACCESS_KEY'),
"region_name": region_name,
}
# If we're executing in a role, AWS_SESSION_TOKEN will be present, too.
if os.environ.get("AWS_SESSION_TOKEN"):
session_kw["aws_session_token"] = os.environ.get("AWS_SESSION_TOKEN")
self.boto_session = boto3.Session(**session_kw)
else:
self.boto_session = boto3.Session(region_name=self.aws_region)
logger.debug("Loaded boto session from config: %s", boto_session)
else:
logger.debug("Using provided boto session: %s", boto_session)
self.boto_session = boto_session
# use provided session's region in case it differs
self.aws_region = self.boto_session.region_name
if self.boto_session.region_name not in LAMBDA_REGIONS:
print("Warning! AWS Lambda may not be available in this AWS Region!")
if self.boto_session.region_name not in API_GATEWAY_REGIONS:
print("Warning! AWS API Gateway may not be available in this AWS Region!") | [
"def",
"load_credentials",
"(",
"self",
",",
"boto_session",
"=",
"None",
",",
"profile_name",
"=",
"None",
")",
":",
"# Automatically load credentials from config or environment",
"if",
"not",
"boto_session",
":",
"# If provided, use the supplied profile name.",
"if",
"pro... | Load AWS credentials.
An optional boto_session can be provided, but that's usually for testing.
An optional profile_name can be provided for config files that have multiple sets
of credentials. | [
"Load",
"AWS",
"credentials",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/core.py#L3161-L3204 |
29,729 | Miserlou/Zappa | zappa/letsencrypt.py | get_cert_and_update_domain | def get_cert_and_update_domain(
zappa_instance,
lambda_name,
api_stage,
domain=None,
manual=False,
):
"""
Main cert installer path.
"""
try:
create_domain_key()
create_domain_csr(domain)
get_cert(zappa_instance)
create_chained_certificate()
with open('{}/signed.crt'.format(gettempdir())) as f:
certificate_body = f.read()
with open('{}/domain.key'.format(gettempdir())) as f:
certificate_private_key = f.read()
with open('{}/intermediate.pem'.format(gettempdir())) as f:
certificate_chain = f.read()
if not manual:
if domain:
if not zappa_instance.get_domain_name(domain):
zappa_instance.create_domain_name(
domain_name=domain,
certificate_name=domain + "-Zappa-LE-Cert",
certificate_body=certificate_body,
certificate_private_key=certificate_private_key,
certificate_chain=certificate_chain,
certificate_arn=None,
lambda_name=lambda_name,
stage=api_stage
)
print("Created a new domain name. Please note that it can take up to 40 minutes for this domain to be created and propagated through AWS, but it requires no further work on your part.")
else:
zappa_instance.update_domain_name(
domain_name=domain,
certificate_name=domain + "-Zappa-LE-Cert",
certificate_body=certificate_body,
certificate_private_key=certificate_private_key,
certificate_chain=certificate_chain,
certificate_arn=None,
lambda_name=lambda_name,
stage=api_stage
)
else:
print("Cerificate body:\n")
print(certificate_body)
print("\nCerificate private key:\n")
print(certificate_private_key)
print("\nCerificate chain:\n")
print(certificate_chain)
except Exception as e:
print(e)
return False
return True | python | def get_cert_and_update_domain(
zappa_instance,
lambda_name,
api_stage,
domain=None,
manual=False,
):
"""
Main cert installer path.
"""
try:
create_domain_key()
create_domain_csr(domain)
get_cert(zappa_instance)
create_chained_certificate()
with open('{}/signed.crt'.format(gettempdir())) as f:
certificate_body = f.read()
with open('{}/domain.key'.format(gettempdir())) as f:
certificate_private_key = f.read()
with open('{}/intermediate.pem'.format(gettempdir())) as f:
certificate_chain = f.read()
if not manual:
if domain:
if not zappa_instance.get_domain_name(domain):
zappa_instance.create_domain_name(
domain_name=domain,
certificate_name=domain + "-Zappa-LE-Cert",
certificate_body=certificate_body,
certificate_private_key=certificate_private_key,
certificate_chain=certificate_chain,
certificate_arn=None,
lambda_name=lambda_name,
stage=api_stage
)
print("Created a new domain name. Please note that it can take up to 40 minutes for this domain to be created and propagated through AWS, but it requires no further work on your part.")
else:
zappa_instance.update_domain_name(
domain_name=domain,
certificate_name=domain + "-Zappa-LE-Cert",
certificate_body=certificate_body,
certificate_private_key=certificate_private_key,
certificate_chain=certificate_chain,
certificate_arn=None,
lambda_name=lambda_name,
stage=api_stage
)
else:
print("Cerificate body:\n")
print(certificate_body)
print("\nCerificate private key:\n")
print(certificate_private_key)
print("\nCerificate chain:\n")
print(certificate_chain)
except Exception as e:
print(e)
return False
return True | [
"def",
"get_cert_and_update_domain",
"(",
"zappa_instance",
",",
"lambda_name",
",",
"api_stage",
",",
"domain",
"=",
"None",
",",
"manual",
"=",
"False",
",",
")",
":",
"try",
":",
"create_domain_key",
"(",
")",
"create_domain_csr",
"(",
"domain",
")",
"get_c... | Main cert installer path. | [
"Main",
"cert",
"installer",
"path",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/letsencrypt.py#L47-L112 |
29,730 | Miserlou/Zappa | zappa/letsencrypt.py | parse_account_key | def parse_account_key():
"""Parse account key to get public key"""
LOGGER.info("Parsing account key...")
cmd = [
'openssl', 'rsa',
'-in', os.path.join(gettempdir(), 'account.key'),
'-noout',
'-text'
]
devnull = open(os.devnull, 'wb')
return subprocess.check_output(cmd, stderr=devnull) | python | def parse_account_key():
"""Parse account key to get public key"""
LOGGER.info("Parsing account key...")
cmd = [
'openssl', 'rsa',
'-in', os.path.join(gettempdir(), 'account.key'),
'-noout',
'-text'
]
devnull = open(os.devnull, 'wb')
return subprocess.check_output(cmd, stderr=devnull) | [
"def",
"parse_account_key",
"(",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"Parsing account key...\"",
")",
"cmd",
"=",
"[",
"'openssl'",
",",
"'rsa'",
",",
"'-in'",
",",
"os",
".",
"path",
".",
"join",
"(",
"gettempdir",
"(",
")",
",",
"'account.key'",
")... | Parse account key to get public key | [
"Parse",
"account",
"key",
"to",
"get",
"public",
"key"
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/letsencrypt.py#L151-L161 |
29,731 | Miserlou/Zappa | zappa/letsencrypt.py | parse_csr | def parse_csr():
"""
Parse certificate signing request for domains
"""
LOGGER.info("Parsing CSR...")
cmd = [
'openssl', 'req',
'-in', os.path.join(gettempdir(), 'domain.csr'),
'-noout',
'-text'
]
devnull = open(os.devnull, 'wb')
out = subprocess.check_output(cmd, stderr=devnull)
domains = set([])
common_name = re.search(r"Subject:.*? CN\s?=\s?([^\s,;/]+)", out.decode('utf8'))
if common_name is not None:
domains.add(common_name.group(1))
subject_alt_names = re.search(r"X509v3 Subject Alternative Name: \n +([^\n]+)\n", out.decode('utf8'), re.MULTILINE | re.DOTALL)
if subject_alt_names is not None:
for san in subject_alt_names.group(1).split(", "):
if san.startswith("DNS:"):
domains.add(san[4:])
return domains | python | def parse_csr():
"""
Parse certificate signing request for domains
"""
LOGGER.info("Parsing CSR...")
cmd = [
'openssl', 'req',
'-in', os.path.join(gettempdir(), 'domain.csr'),
'-noout',
'-text'
]
devnull = open(os.devnull, 'wb')
out = subprocess.check_output(cmd, stderr=devnull)
domains = set([])
common_name = re.search(r"Subject:.*? CN\s?=\s?([^\s,;/]+)", out.decode('utf8'))
if common_name is not None:
domains.add(common_name.group(1))
subject_alt_names = re.search(r"X509v3 Subject Alternative Name: \n +([^\n]+)\n", out.decode('utf8'), re.MULTILINE | re.DOTALL)
if subject_alt_names is not None:
for san in subject_alt_names.group(1).split(", "):
if san.startswith("DNS:"):
domains.add(san[4:])
return domains | [
"def",
"parse_csr",
"(",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"Parsing CSR...\"",
")",
"cmd",
"=",
"[",
"'openssl'",
",",
"'req'",
",",
"'-in'",
",",
"os",
".",
"path",
".",
"join",
"(",
"gettempdir",
"(",
")",
",",
"'domain.csr'",
")",
",",
"'-no... | Parse certificate signing request for domains | [
"Parse",
"certificate",
"signing",
"request",
"for",
"domains"
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/letsencrypt.py#L164-L187 |
29,732 | Miserlou/Zappa | zappa/letsencrypt.py | get_boulder_header | def get_boulder_header(key_bytes):
"""
Use regular expressions to find crypto values from parsed account key,
and return a header we can send to our Boulder instance.
"""
pub_hex, pub_exp = re.search(
r"modulus:\n\s+00:([a-f0-9\:\s]+?)\npublicExponent: ([0-9]+)",
key_bytes.decode('utf8'), re.MULTILINE | re.DOTALL).groups()
pub_exp = "{0:x}".format(int(pub_exp))
pub_exp = "0{0}".format(pub_exp) if len(pub_exp) % 2 else pub_exp
header = {
"alg": "RS256",
"jwk": {
"e": _b64(binascii.unhexlify(pub_exp.encode("utf-8"))),
"kty": "RSA",
"n": _b64(binascii.unhexlify(re.sub(r"(\s|:)", "", pub_hex).encode("utf-8"))),
},
}
return header | python | def get_boulder_header(key_bytes):
"""
Use regular expressions to find crypto values from parsed account key,
and return a header we can send to our Boulder instance.
"""
pub_hex, pub_exp = re.search(
r"modulus:\n\s+00:([a-f0-9\:\s]+?)\npublicExponent: ([0-9]+)",
key_bytes.decode('utf8'), re.MULTILINE | re.DOTALL).groups()
pub_exp = "{0:x}".format(int(pub_exp))
pub_exp = "0{0}".format(pub_exp) if len(pub_exp) % 2 else pub_exp
header = {
"alg": "RS256",
"jwk": {
"e": _b64(binascii.unhexlify(pub_exp.encode("utf-8"))),
"kty": "RSA",
"n": _b64(binascii.unhexlify(re.sub(r"(\s|:)", "", pub_hex).encode("utf-8"))),
},
}
return header | [
"def",
"get_boulder_header",
"(",
"key_bytes",
")",
":",
"pub_hex",
",",
"pub_exp",
"=",
"re",
".",
"search",
"(",
"r\"modulus:\\n\\s+00:([a-f0-9\\:\\s]+?)\\npublicExponent: ([0-9]+)\"",
",",
"key_bytes",
".",
"decode",
"(",
"'utf8'",
")",
",",
"re",
".",
"MULTILINE... | Use regular expressions to find crypto values from parsed account key,
and return a header we can send to our Boulder instance. | [
"Use",
"regular",
"expressions",
"to",
"find",
"crypto",
"values",
"from",
"parsed",
"account",
"key",
"and",
"return",
"a",
"header",
"we",
"can",
"send",
"to",
"our",
"Boulder",
"instance",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/letsencrypt.py#L190-L209 |
29,733 | Miserlou/Zappa | zappa/letsencrypt.py | register_account | def register_account():
"""
Agree to LE TOS
"""
LOGGER.info("Registering account...")
code, result = _send_signed_request(DEFAULT_CA + "/acme/new-reg", {
"resource": "new-reg",
"agreement": "https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf",
})
if code == 201: # pragma: no cover
LOGGER.info("Registered!")
elif code == 409: # pragma: no cover
LOGGER.info("Already registered!")
else: # pragma: no cover
raise ValueError("Error registering: {0} {1}".format(code, result)) | python | def register_account():
"""
Agree to LE TOS
"""
LOGGER.info("Registering account...")
code, result = _send_signed_request(DEFAULT_CA + "/acme/new-reg", {
"resource": "new-reg",
"agreement": "https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf",
})
if code == 201: # pragma: no cover
LOGGER.info("Registered!")
elif code == 409: # pragma: no cover
LOGGER.info("Already registered!")
else: # pragma: no cover
raise ValueError("Error registering: {0} {1}".format(code, result)) | [
"def",
"register_account",
"(",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"Registering account...\"",
")",
"code",
",",
"result",
"=",
"_send_signed_request",
"(",
"DEFAULT_CA",
"+",
"\"/acme/new-reg\"",
",",
"{",
"\"resource\"",
":",
"\"new-reg\"",
",",
"\"agreemen... | Agree to LE TOS | [
"Agree",
"to",
"LE",
"TOS"
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/letsencrypt.py#L212-L226 |
29,734 | Miserlou/Zappa | zappa/letsencrypt.py | get_cert | def get_cert(zappa_instance, log=LOGGER, CA=DEFAULT_CA):
"""
Call LE to get a new signed CA.
"""
out = parse_account_key()
header = get_boulder_header(out)
accountkey_json = json.dumps(header['jwk'], sort_keys=True, separators=(',', ':'))
thumbprint = _b64(hashlib.sha256(accountkey_json.encode('utf8')).digest())
# find domains
domains = parse_csr()
# get the certificate domains and expiration
register_account()
# verify each domain
for domain in domains:
log.info("Verifying {0}...".format(domain))
# get new challenge
code, result = _send_signed_request(CA + "/acme/new-authz", {
"resource": "new-authz",
"identifier": {"type": "dns", "value": domain},
})
if code != 201:
raise ValueError("Error requesting challenges: {0} {1}".format(code, result))
challenge = [ch for ch in json.loads(result.decode('utf8'))['challenges'] if ch['type'] == "dns-01"][0]
token = re.sub(r"[^A-Za-z0-9_\-]", "_", challenge['token'])
keyauthorization = "{0}.{1}".format(token, thumbprint).encode('utf-8')
# sha256_b64
digest = _b64(hashlib.sha256(keyauthorization).digest())
zone_id = zappa_instance.get_hosted_zone_id_for_domain(domain)
if not zone_id:
raise ValueError("Could not find Zone ID for: " + domain)
zappa_instance.set_dns_challenge_txt(zone_id, domain, digest) # resp is unused
print("Waiting for DNS to propagate..")
# What's optimal here?
# import time # double import; import in loop; shadowed import
time.sleep(45)
# notify challenge are met
code, result = _send_signed_request(challenge['uri'], {
"resource": "challenge",
"keyAuthorization": keyauthorization.decode('utf-8'),
})
if code != 202:
raise ValueError("Error triggering challenge: {0} {1}".format(code, result))
# wait for challenge to be verified
verify_challenge(challenge['uri'])
# Challenge verified, clean up R53
zappa_instance.remove_dns_challenge_txt(zone_id, domain, digest)
# Sign
result = sign_certificate()
# Encode to PEM format
encode_certificate(result)
return True | python | def get_cert(zappa_instance, log=LOGGER, CA=DEFAULT_CA):
"""
Call LE to get a new signed CA.
"""
out = parse_account_key()
header = get_boulder_header(out)
accountkey_json = json.dumps(header['jwk'], sort_keys=True, separators=(',', ':'))
thumbprint = _b64(hashlib.sha256(accountkey_json.encode('utf8')).digest())
# find domains
domains = parse_csr()
# get the certificate domains and expiration
register_account()
# verify each domain
for domain in domains:
log.info("Verifying {0}...".format(domain))
# get new challenge
code, result = _send_signed_request(CA + "/acme/new-authz", {
"resource": "new-authz",
"identifier": {"type": "dns", "value": domain},
})
if code != 201:
raise ValueError("Error requesting challenges: {0} {1}".format(code, result))
challenge = [ch for ch in json.loads(result.decode('utf8'))['challenges'] if ch['type'] == "dns-01"][0]
token = re.sub(r"[^A-Za-z0-9_\-]", "_", challenge['token'])
keyauthorization = "{0}.{1}".format(token, thumbprint).encode('utf-8')
# sha256_b64
digest = _b64(hashlib.sha256(keyauthorization).digest())
zone_id = zappa_instance.get_hosted_zone_id_for_domain(domain)
if not zone_id:
raise ValueError("Could not find Zone ID for: " + domain)
zappa_instance.set_dns_challenge_txt(zone_id, domain, digest) # resp is unused
print("Waiting for DNS to propagate..")
# What's optimal here?
# import time # double import; import in loop; shadowed import
time.sleep(45)
# notify challenge are met
code, result = _send_signed_request(challenge['uri'], {
"resource": "challenge",
"keyAuthorization": keyauthorization.decode('utf-8'),
})
if code != 202:
raise ValueError("Error triggering challenge: {0} {1}".format(code, result))
# wait for challenge to be verified
verify_challenge(challenge['uri'])
# Challenge verified, clean up R53
zappa_instance.remove_dns_challenge_txt(zone_id, domain, digest)
# Sign
result = sign_certificate()
# Encode to PEM format
encode_certificate(result)
return True | [
"def",
"get_cert",
"(",
"zappa_instance",
",",
"log",
"=",
"LOGGER",
",",
"CA",
"=",
"DEFAULT_CA",
")",
":",
"out",
"=",
"parse_account_key",
"(",
")",
"header",
"=",
"get_boulder_header",
"(",
"out",
")",
"accountkey_json",
"=",
"json",
".",
"dumps",
"(",... | Call LE to get a new signed CA. | [
"Call",
"LE",
"to",
"get",
"a",
"new",
"signed",
"CA",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/letsencrypt.py#L229-L293 |
29,735 | Miserlou/Zappa | zappa/letsencrypt.py | verify_challenge | def verify_challenge(uri):
"""
Loop until our challenge is verified, else fail.
"""
while True:
try:
resp = urlopen(uri)
challenge_status = json.loads(resp.read().decode('utf8'))
except IOError as e:
raise ValueError("Error checking challenge: {0} {1}".format(
e.code, json.loads(e.read().decode('utf8'))))
if challenge_status['status'] == "pending":
time.sleep(2)
elif challenge_status['status'] == "valid":
LOGGER.info("Domain verified!")
break
else:
raise ValueError("Domain challenge did not pass: {0}".format(
challenge_status)) | python | def verify_challenge(uri):
"""
Loop until our challenge is verified, else fail.
"""
while True:
try:
resp = urlopen(uri)
challenge_status = json.loads(resp.read().decode('utf8'))
except IOError as e:
raise ValueError("Error checking challenge: {0} {1}".format(
e.code, json.loads(e.read().decode('utf8'))))
if challenge_status['status'] == "pending":
time.sleep(2)
elif challenge_status['status'] == "valid":
LOGGER.info("Domain verified!")
break
else:
raise ValueError("Domain challenge did not pass: {0}".format(
challenge_status)) | [
"def",
"verify_challenge",
"(",
"uri",
")",
":",
"while",
"True",
":",
"try",
":",
"resp",
"=",
"urlopen",
"(",
"uri",
")",
"challenge_status",
"=",
"json",
".",
"loads",
"(",
"resp",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf8'",
")",
")",
"... | Loop until our challenge is verified, else fail. | [
"Loop",
"until",
"our",
"challenge",
"is",
"verified",
"else",
"fail",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/letsencrypt.py#L296-L314 |
29,736 | Miserlou/Zappa | zappa/letsencrypt.py | sign_certificate | 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'
]
devnull = open(os.devnull, 'wb')
csr_der = subprocess.check_output(cmd, stderr=devnull)
code, result = _send_signed_request(DEFAULT_CA + "/acme/new-cert", {
"resource": "new-cert",
"csr": _b64(csr_der),
})
if code != 201:
raise ValueError("Error signing certificate: {0} {1}".format(code, result))
LOGGER.info("Certificate signed!")
return result | python | 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'
]
devnull = open(os.devnull, 'wb')
csr_der = subprocess.check_output(cmd, stderr=devnull)
code, result = _send_signed_request(DEFAULT_CA + "/acme/new-cert", {
"resource": "new-cert",
"csr": _b64(csr_der),
})
if code != 201:
raise ValueError("Error signing certificate: {0} {1}".format(code, result))
LOGGER.info("Certificate signed!")
return result | [
"def",
"sign_certificate",
"(",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"Signing certificate...\"",
")",
"cmd",
"=",
"[",
"'openssl'",
",",
"'req'",
",",
"'-in'",
",",
"os",
".",
"path",
".",
"join",
"(",
"gettempdir",
"(",
")",
",",
"'domain.csr'",
")",... | Get the new certificate.
Returns the signed bytes. | [
"Get",
"the",
"new",
"certificate",
".",
"Returns",
"the",
"signed",
"bytes",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/letsencrypt.py#L317-L339 |
29,737 | Miserlou/Zappa | zappa/letsencrypt.py | _send_signed_request | 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(header)
protected["nonce"] = urlopen(DEFAULT_CA + "/directory").headers['Replay-Nonce']
protected64 = _b64(json.dumps(protected).encode('utf8'))
cmd = [
'openssl', 'dgst',
'-sha256',
'-sign', os.path.join(gettempdir(), 'account.key')
]
proc = subprocess.Popen(
cmd,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
out, err = proc.communicate("{0}.{1}".format(protected64, payload64).encode('utf8'))
if proc.returncode != 0: # pragma: no cover
raise IOError("OpenSSL Error: {0}".format(err))
data = json.dumps({
"header": header, "protected": protected64,
"payload": payload64, "signature": _b64(out),
})
try:
resp = urlopen(url, data.encode('utf8'))
return resp.getcode(), resp.read()
except IOError as e:
return getattr(e, "code", None), getattr(e, "read", e.__str__)() | python | 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(header)
protected["nonce"] = urlopen(DEFAULT_CA + "/directory").headers['Replay-Nonce']
protected64 = _b64(json.dumps(protected).encode('utf8'))
cmd = [
'openssl', 'dgst',
'-sha256',
'-sign', os.path.join(gettempdir(), 'account.key')
]
proc = subprocess.Popen(
cmd,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
out, err = proc.communicate("{0}.{1}".format(protected64, payload64).encode('utf8'))
if proc.returncode != 0: # pragma: no cover
raise IOError("OpenSSL Error: {0}".format(err))
data = json.dumps({
"header": header, "protected": protected64,
"payload": payload64, "signature": _b64(out),
})
try:
resp = urlopen(url, data.encode('utf8'))
return resp.getcode(), resp.read()
except IOError as e:
return getattr(e, "code", None), getattr(e, "read", e.__str__)() | [
"def",
"_send_signed_request",
"(",
"url",
",",
"payload",
")",
":",
"payload64",
"=",
"_b64",
"(",
"json",
".",
"dumps",
"(",
"payload",
")",
".",
"encode",
"(",
"'utf8'",
")",
")",
"out",
"=",
"parse_account_key",
"(",
")",
"header",
"=",
"get_boulder_... | Helper function to make signed requests to Boulder | [
"Helper",
"function",
"to",
"make",
"signed",
"requests",
"to",
"Boulder"
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/letsencrypt.py#L366-L398 |
29,738 | Miserlou/Zappa | zappa/cli.py | shamelessly_promote | 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("know", fg='green', bold=True) + "! :D")
click.echo("File bug reports on " + click.style("GitHub", bold=True) + " here: "
+ click.style("https://github.com/Miserlou/Zappa", fg='cyan', bold=True))
click.echo("And join our " + click.style("Slack", bold=True) + " channel here: "
+ click.style("https://slack.zappa.io", fg='cyan', bold=True))
click.echo("Love!,")
click.echo(" ~ Team " + click.style("Zappa", bold=True) + "!") | python | 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("know", fg='green', bold=True) + "! :D")
click.echo("File bug reports on " + click.style("GitHub", bold=True) + " here: "
+ click.style("https://github.com/Miserlou/Zappa", fg='cyan', bold=True))
click.echo("And join our " + click.style("Slack", bold=True) + " channel here: "
+ click.style("https://slack.zappa.io", fg='cyan', bold=True))
click.echo("Love!,")
click.echo(" ~ Team " + click.style("Zappa", bold=True) + "!") | [
"def",
"shamelessly_promote",
"(",
")",
":",
"click",
".",
"echo",
"(",
"\"Need \"",
"+",
"click",
".",
"style",
"(",
"\"help\"",
",",
"fg",
"=",
"'green'",
",",
"bold",
"=",
"True",
")",
"+",
"\"? Found a \"",
"+",
"click",
".",
"style",
"(",
"\"bug\"... | Shamelessly promote our little community. | [
"Shamelessly",
"promote",
"our",
"little",
"community",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2744-L2757 |
29,739 | Miserlou/Zappa | zappa/cli.py | handle | 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: no cover
cli.on_exit()
sys.exit(130)
except Exception as e:
cli.on_exit()
click.echo("Oh no! An " + click.style("error occurred", fg='red', bold=True) + "! :(")
click.echo("\n==============\n")
import traceback
traceback.print_exc()
click.echo("\n==============\n")
shamelessly_promote()
sys.exit(-1) | python | 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: no cover
cli.on_exit()
sys.exit(130)
except Exception as e:
cli.on_exit()
click.echo("Oh no! An " + click.style("error occurred", fg='red', bold=True) + "! :(")
click.echo("\n==============\n")
import traceback
traceback.print_exc()
click.echo("\n==============\n")
shamelessly_promote()
sys.exit(-1) | [
"def",
"handle",
"(",
")",
":",
"# pragma: no cover",
"try",
":",
"cli",
"=",
"ZappaCLI",
"(",
")",
"sys",
".",
"exit",
"(",
"cli",
".",
"handle",
"(",
")",
")",
"except",
"SystemExit",
"as",
"e",
":",
"# pragma: no cover",
"cli",
".",
"on_exit",
"(",
... | Main program execution handler. | [
"Main",
"program",
"execution",
"handler",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2772-L2797 |
29,740 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.stage_config | 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_stages:
raise RuntimeError(stage + " has already been extended to these settings. "
"There is a circular extends within the settings file.")
extended_stages.append(stage)
try:
stage_settings = dict(self.zappa_settings[stage].copy())
except KeyError:
raise ClickException("Cannot extend settings for undefined stage '" + stage + "'.")
extends_stage = self.zappa_settings[stage].get('extends', None)
if not extends_stage:
return stage_settings
extended_settings = get_stage_setting(stage=extends_stage, extended_stages=extended_stages)
extended_settings.update(stage_settings)
return extended_settings
settings = get_stage_setting(stage=self.api_stage)
# Backwards compatible for delete_zip setting that was more explicitly named delete_local_zip
if u'delete_zip' in settings:
settings[u'delete_local_zip'] = settings.get(u'delete_zip')
settings.update(self.stage_config_overrides)
return settings | python | 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_stages:
raise RuntimeError(stage + " has already been extended to these settings. "
"There is a circular extends within the settings file.")
extended_stages.append(stage)
try:
stage_settings = dict(self.zappa_settings[stage].copy())
except KeyError:
raise ClickException("Cannot extend settings for undefined stage '" + stage + "'.")
extends_stage = self.zappa_settings[stage].get('extends', None)
if not extends_stage:
return stage_settings
extended_settings = get_stage_setting(stage=extends_stage, extended_stages=extended_stages)
extended_settings.update(stage_settings)
return extended_settings
settings = get_stage_setting(stage=self.api_stage)
# Backwards compatible for delete_zip setting that was more explicitly named delete_local_zip
if u'delete_zip' in settings:
settings[u'delete_local_zip'] = settings.get(u'delete_zip')
settings.update(self.stage_config_overrides)
return settings | [
"def",
"stage_config",
"(",
"self",
")",
":",
"def",
"get_stage_setting",
"(",
"stage",
",",
"extended_stages",
"=",
"None",
")",
":",
"if",
"extended_stages",
"is",
"None",
":",
"extended_stages",
"=",
"[",
"]",
"if",
"stage",
"in",
"extended_stages",
":",
... | A shortcut property for settings of a stage. | [
"A",
"shortcut",
"property",
"for",
"settings",
"of",
"a",
"stage",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L127-L161 |
29,741 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.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 script
if self.prebuild_script:
self.execute_prebuild_script()
# Create the Lambda Zip
self.create_package(output)
self.callback('zip')
size = human_size(os.path.getsize(self.zip_path))
click.echo(click.style("Package created", fg="green", bold=True) + ": " + click.style(self.zip_path, bold=True) + " (" + size + ")") | python | 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 script
if self.prebuild_script:
self.execute_prebuild_script()
# Create the Lambda Zip
self.create_package(output)
self.callback('zip')
size = human_size(os.path.getsize(self.zip_path))
click.echo(click.style("Package created", fg="green", bold=True) + ": " + click.style(self.zip_path, bold=True) + " (" + size + ")") | [
"def",
"package",
"(",
"self",
",",
"output",
"=",
"None",
")",
":",
"# 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",
")",... | Only build the package | [
"Only",
"build",
"the",
"package"
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L626-L642 |
29,742 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.template | 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("Role ARN is required to template.")
self.zappa.credentials_arn = role_arn
# Create the template!
template = self.zappa.create_stack_template(
lambda_arn=lambda_arn,
lambda_name=self.lambda_name,
api_key_required=self.api_key_required,
iam_authorization=self.iam_authorization,
authorizer=self.authorizer,
cors_options=self.cors,
description=self.apigateway_description,
policy=self.apigateway_policy,
endpoint_configuration=self.endpoint_configuration
)
if not output:
template_file = self.lambda_name + '-template-' + str(int(time.time())) + '.json'
else:
template_file = output
with open(template_file, 'wb') as out:
out.write(bytes(template.to_json(indent=None, separators=(',',':')), "utf-8"))
if not json:
click.echo(click.style("Template created", fg="green", bold=True) + ": " + click.style(template_file, bold=True))
else:
with open(template_file, 'r') as out:
print(out.read()) | python | 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("Role ARN is required to template.")
self.zappa.credentials_arn = role_arn
# Create the template!
template = self.zappa.create_stack_template(
lambda_arn=lambda_arn,
lambda_name=self.lambda_name,
api_key_required=self.api_key_required,
iam_authorization=self.iam_authorization,
authorizer=self.authorizer,
cors_options=self.cors,
description=self.apigateway_description,
policy=self.apigateway_policy,
endpoint_configuration=self.endpoint_configuration
)
if not output:
template_file = self.lambda_name + '-template-' + str(int(time.time())) + '.json'
else:
template_file = output
with open(template_file, 'wb') as out:
out.write(bytes(template.to_json(indent=None, separators=(',',':')), "utf-8"))
if not json:
click.echo(click.style("Template created", fg="green", bold=True) + ": " + click.style(template_file, bold=True))
else:
with open(template_file, 'r') as out:
print(out.read()) | [
"def",
"template",
"(",
"self",
",",
"lambda_arn",
",",
"role_arn",
",",
"output",
"=",
"None",
",",
"json",
"=",
"False",
")",
":",
"if",
"not",
"lambda_arn",
":",
"raise",
"ClickException",
"(",
"\"Lambda ARN is required to template.\"",
")",
"if",
"not",
... | Only build the template file. | [
"Only",
"build",
"the",
"template",
"file",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L644-L681 |
29,743 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.rollback | 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, versions_back=revision)
print("Done!") | python | 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, versions_back=revision)
print("Done!") | [
"def",
"rollback",
"(",
"self",
",",
"revision",
")",
":",
"print",
"(",
"\"Rolling back..\"",
")",
"self",
".",
"zappa",
".",
"rollback_lambda_function_version",
"(",
"self",
".",
"lambda_name",
",",
"versions_back",
"=",
"revision",
")",
"print",
"(",
"\"Don... | Rollsback the currently deploy lambda code to a previous revision. | [
"Rollsback",
"the",
"currently",
"deploy",
"lambda",
"code",
"to",
"a",
"previous",
"revision",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1057-L1066 |
29,744 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.tail | 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 any new logs
"""
try:
since_stamp = string_to_timestamp(since)
last_since = since_stamp
while True:
new_logs = self.zappa.fetch_logs(
self.lambda_name,
start_time=since_stamp,
limit=limit,
filter_pattern=filter_pattern,
)
new_logs = [ e for e in new_logs if e['timestamp'] > last_since ]
self.print_logs(new_logs, colorize, http, non_http, force_colorize)
if not keep_open:
break
if new_logs:
last_since = new_logs[-1]['timestamp']
time.sleep(1)
except KeyboardInterrupt: # pragma: no cover
# Die gracefully
try:
sys.exit(0)
except SystemExit:
os._exit(130) | python | 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 any new logs
"""
try:
since_stamp = string_to_timestamp(since)
last_since = since_stamp
while True:
new_logs = self.zappa.fetch_logs(
self.lambda_name,
start_time=since_stamp,
limit=limit,
filter_pattern=filter_pattern,
)
new_logs = [ e for e in new_logs if e['timestamp'] > last_since ]
self.print_logs(new_logs, colorize, http, non_http, force_colorize)
if not keep_open:
break
if new_logs:
last_since = new_logs[-1]['timestamp']
time.sleep(1)
except KeyboardInterrupt: # pragma: no cover
# Die gracefully
try:
sys.exit(0)
except SystemExit:
os._exit(130) | [
"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 any new logs | [
"Tail",
"this",
"function",
"s",
"logs",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1068-L1100 |
29,745 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.undeploy | 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':
return
if self.use_alb:
self.zappa.undeploy_lambda_alb(self.lambda_name)
if self.use_apigateway:
if remove_logs:
self.zappa.remove_api_gateway_logs(self.lambda_name)
domain_name = self.stage_config.get('domain', None)
base_path = self.stage_config.get('base_path', None)
# Only remove the api key when not specified
if self.api_key_required and self.api_key is None:
api_id = self.zappa.get_api_id(self.lambda_name)
self.zappa.remove_api_key(api_id, self.api_stage)
gateway_id = self.zappa.undeploy_api_gateway(
self.lambda_name,
domain_name=domain_name,
base_path=base_path
)
self.unschedule() # removes event triggers, including warm up event.
self.zappa.delete_lambda_function(self.lambda_name)
if remove_logs:
self.zappa.remove_lambda_function_logs(self.lambda_name)
click.echo(click.style("Done", fg="green", bold=True) + "!") | python | 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':
return
if self.use_alb:
self.zappa.undeploy_lambda_alb(self.lambda_name)
if self.use_apigateway:
if remove_logs:
self.zappa.remove_api_gateway_logs(self.lambda_name)
domain_name = self.stage_config.get('domain', None)
base_path = self.stage_config.get('base_path', None)
# Only remove the api key when not specified
if self.api_key_required and self.api_key is None:
api_id = self.zappa.get_api_id(self.lambda_name)
self.zappa.remove_api_key(api_id, self.api_stage)
gateway_id = self.zappa.undeploy_api_gateway(
self.lambda_name,
domain_name=domain_name,
base_path=base_path
)
self.unschedule() # removes event triggers, including warm up event.
self.zappa.delete_lambda_function(self.lambda_name)
if remove_logs:
self.zappa.remove_lambda_function_logs(self.lambda_name)
click.echo(click.style("Done", fg="green", bold=True) + "!") | [
"def",
"undeploy",
"(",
"self",
",",
"no_confirm",
"=",
"False",
",",
"remove_logs",
"=",
"False",
")",
":",
"if",
"not",
"no_confirm",
":",
"# pragma: no cover",
"confirm",
"=",
"input",
"(",
"\"Are you sure you want to undeploy? [y/n] \"",
")",
"if",
"confirm",
... | Tear down an existing deployment. | [
"Tear",
"down",
"an",
"existing",
"deployment",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1102-L1139 |
29,746 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.update_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 triggers:
lambda_configs.add(trigger['source'].split('_')[0])
self.zappa.update_cognito(self.lambda_name, user_pool, lambda_configs, self.lambda_arn) | python | 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 triggers:
lambda_configs.add(trigger['source'].split('_')[0])
self.zappa.update_cognito(self.lambda_name, user_pool, lambda_configs, self.lambda_arn) | [
"def",
"update_cognito_triggers",
"(",
"self",
")",
":",
"if",
"self",
".",
"cognito",
":",
"user_pool",
"=",
"self",
".",
"cognito",
".",
"get",
"(",
"'user_pool'",
")",
"triggers",
"=",
"self",
".",
"cognito",
".",
"get",
"(",
"'triggers'",
",",
"[",
... | Update any cognito triggers | [
"Update",
"any",
"cognito",
"triggers"
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1141-L1151 |
29,747 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.schedule | 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:
if not isinstance(events, list): # pragma: no cover
print("Events must be supplied as a list.")
return
for event in events:
self.collision_warning(event.get('function'))
if self.stage_config.get('keep_warm', True):
if not events:
events = []
keep_warm_rate = self.stage_config.get('keep_warm_expression', "rate(4 minutes)")
events.append({'name': 'zappa-keep-warm',
'function': 'handler.keep_warm_callback',
'expression': keep_warm_rate,
'description': 'Zappa Keep Warm - {}'.format(self.lambda_name)})
if events:
try:
function_response = self.zappa.lambda_client.get_function(FunctionName=self.lambda_name)
except botocore.exceptions.ClientError as e: # pragma: no cover
click.echo(click.style("Function does not exist", fg="yellow") + ", please " +
click.style("deploy", bold=True) + "first. Ex:" +
click.style("zappa deploy {}.".format(self.api_stage), bold=True))
sys.exit(-1)
print("Scheduling..")
self.zappa.schedule_events(
lambda_arn=function_response['Configuration']['FunctionArn'],
lambda_name=self.lambda_name,
events=events
)
# Add async tasks SNS
if self.stage_config.get('async_source', None) == 'sns' \
and self.stage_config.get('async_resources', True):
self.lambda_arn = self.zappa.get_lambda_function(
function_name=self.lambda_name)
topic_arn = self.zappa.create_async_sns_topic(
lambda_name=self.lambda_name,
lambda_arn=self.lambda_arn
)
click.echo('SNS Topic created: %s' % topic_arn)
# Add async tasks DynamoDB
table_name = self.stage_config.get('async_response_table', False)
read_capacity = self.stage_config.get('async_response_table_read_capacity', 1)
write_capacity = self.stage_config.get('async_response_table_write_capacity', 1)
if table_name and self.stage_config.get('async_resources', True):
created, response_table = self.zappa.create_async_dynamodb_table(
table_name, read_capacity, write_capacity)
if created:
click.echo('DynamoDB table created: %s' % table_name)
else:
click.echo('DynamoDB table exists: %s' % table_name)
provisioned_throughput = response_table['Table']['ProvisionedThroughput']
if provisioned_throughput['ReadCapacityUnits'] != read_capacity or \
provisioned_throughput['WriteCapacityUnits'] != write_capacity:
click.echo(click.style(
"\nWarning! Existing DynamoDB table ({}) does not match configured capacity.\n".format(table_name),
fg='red'
)) | python | 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:
if not isinstance(events, list): # pragma: no cover
print("Events must be supplied as a list.")
return
for event in events:
self.collision_warning(event.get('function'))
if self.stage_config.get('keep_warm', True):
if not events:
events = []
keep_warm_rate = self.stage_config.get('keep_warm_expression', "rate(4 minutes)")
events.append({'name': 'zappa-keep-warm',
'function': 'handler.keep_warm_callback',
'expression': keep_warm_rate,
'description': 'Zappa Keep Warm - {}'.format(self.lambda_name)})
if events:
try:
function_response = self.zappa.lambda_client.get_function(FunctionName=self.lambda_name)
except botocore.exceptions.ClientError as e: # pragma: no cover
click.echo(click.style("Function does not exist", fg="yellow") + ", please " +
click.style("deploy", bold=True) + "first. Ex:" +
click.style("zappa deploy {}.".format(self.api_stage), bold=True))
sys.exit(-1)
print("Scheduling..")
self.zappa.schedule_events(
lambda_arn=function_response['Configuration']['FunctionArn'],
lambda_name=self.lambda_name,
events=events
)
# Add async tasks SNS
if self.stage_config.get('async_source', None) == 'sns' \
and self.stage_config.get('async_resources', True):
self.lambda_arn = self.zappa.get_lambda_function(
function_name=self.lambda_name)
topic_arn = self.zappa.create_async_sns_topic(
lambda_name=self.lambda_name,
lambda_arn=self.lambda_arn
)
click.echo('SNS Topic created: %s' % topic_arn)
# Add async tasks DynamoDB
table_name = self.stage_config.get('async_response_table', False)
read_capacity = self.stage_config.get('async_response_table_read_capacity', 1)
write_capacity = self.stage_config.get('async_response_table_write_capacity', 1)
if table_name and self.stage_config.get('async_resources', True):
created, response_table = self.zappa.create_async_dynamodb_table(
table_name, read_capacity, write_capacity)
if created:
click.echo('DynamoDB table created: %s' % table_name)
else:
click.echo('DynamoDB table exists: %s' % table_name)
provisioned_throughput = response_table['Table']['ProvisionedThroughput']
if provisioned_throughput['ReadCapacityUnits'] != read_capacity or \
provisioned_throughput['WriteCapacityUnits'] != write_capacity:
click.echo(click.style(
"\nWarning! Existing DynamoDB table ({}) does not match configured capacity.\n".format(table_name),
fg='red'
)) | [
"def",
"schedule",
"(",
"self",
")",
":",
"events",
"=",
"self",
".",
"stage_config",
".",
"get",
"(",
"'events'",
",",
"[",
"]",
")",
"if",
"events",
":",
"if",
"not",
"isinstance",
"(",
"events",
",",
"list",
")",
":",
"# pragma: no cover",
"print",
... | Given a a list of functions and a schedule to execute them,
setup up regular execution. | [
"Given",
"a",
"a",
"list",
"of",
"functions",
"and",
"a",
"schedule",
"to",
"execute",
"them",
"setup",
"up",
"regular",
"execution",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1153-L1223 |
29,748 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.unschedule | 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 []).
events = self.stage_config.get('events', [])
if not isinstance(events, list): # pragma: no cover
print("Events must be supplied as a list.")
return
function_arn = None
try:
function_response = self.zappa.lambda_client.get_function(FunctionName=self.lambda_name)
function_arn = function_response['Configuration']['FunctionArn']
except botocore.exceptions.ClientError as e: # pragma: no cover
raise ClickException("Function does not exist, you should deploy first. Ex: zappa deploy {}. "
"Proceeding to unschedule CloudWatch based events.".format(self.api_stage))
print("Unscheduling..")
self.zappa.unschedule_events(
lambda_name=self.lambda_name,
lambda_arn=function_arn,
events=events,
)
# Remove async task SNS
if self.stage_config.get('async_source', None) == 'sns' \
and self.stage_config.get('async_resources', True):
removed_arns = self.zappa.remove_async_sns_topic(self.lambda_name)
click.echo('SNS Topic removed: %s' % ', '.join(removed_arns)) | python | 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 []).
events = self.stage_config.get('events', [])
if not isinstance(events, list): # pragma: no cover
print("Events must be supplied as a list.")
return
function_arn = None
try:
function_response = self.zappa.lambda_client.get_function(FunctionName=self.lambda_name)
function_arn = function_response['Configuration']['FunctionArn']
except botocore.exceptions.ClientError as e: # pragma: no cover
raise ClickException("Function does not exist, you should deploy first. Ex: zappa deploy {}. "
"Proceeding to unschedule CloudWatch based events.".format(self.api_stage))
print("Unscheduling..")
self.zappa.unschedule_events(
lambda_name=self.lambda_name,
lambda_arn=function_arn,
events=events,
)
# Remove async task SNS
if self.stage_config.get('async_source', None) == 'sns' \
and self.stage_config.get('async_resources', True):
removed_arns = self.zappa.remove_async_sns_topic(self.lambda_name)
click.echo('SNS Topic removed: %s' % ', '.join(removed_arns)) | [
"def",
"unschedule",
"(",
"self",
")",
":",
"# Run even if events are not defined to remove previously existing ones (thus default to []).",
"events",
"=",
"self",
".",
"stage_config",
".",
"get",
"(",
"'events'",
",",
"[",
"]",
")",
"if",
"not",
"isinstance",
"(",
"e... | Given a a list of scheduled functions,
tear down their regular execution. | [
"Given",
"a",
"a",
"list",
"of",
"scheduled",
"functions",
"tear",
"down",
"their",
"regular",
"execution",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1225-L1258 |
29,749 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.invoke | 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 string of python to execute directly
# manage, which is a Django-specific management command invocation
key = command if command is not None else 'command'
if raw_python:
command = {'raw_command': function_name}
else:
command = {key: function_name}
# Can't use hjson
import json as json
response = self.zappa.invoke_lambda_function(
self.lambda_name,
json.dumps(command),
invocation_type='RequestResponse',
)
if 'LogResult' in response:
if no_color:
print(base64.b64decode(response['LogResult']))
else:
decoded = base64.b64decode(response['LogResult']).decode()
formatted = self.format_invoke_command(decoded)
colorized = self.colorize_invoke_command(formatted)
print(colorized)
else:
print(response)
# For a successful request FunctionError is not in response.
# https://github.com/Miserlou/Zappa/pull/1254/
if 'FunctionError' in response:
raise ClickException(
"{} error occurred while invoking command.".format(response['FunctionError'])
) | python | 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 string of python to execute directly
# manage, which is a Django-specific management command invocation
key = command if command is not None else 'command'
if raw_python:
command = {'raw_command': function_name}
else:
command = {key: function_name}
# Can't use hjson
import json as json
response = self.zappa.invoke_lambda_function(
self.lambda_name,
json.dumps(command),
invocation_type='RequestResponse',
)
if 'LogResult' in response:
if no_color:
print(base64.b64decode(response['LogResult']))
else:
decoded = base64.b64decode(response['LogResult']).decode()
formatted = self.format_invoke_command(decoded)
colorized = self.colorize_invoke_command(formatted)
print(colorized)
else:
print(response)
# For a successful request FunctionError is not in response.
# https://github.com/Miserlou/Zappa/pull/1254/
if 'FunctionError' in response:
raise ClickException(
"{} error occurred while invoking command.".format(response['FunctionError'])
) | [
"def",
"invoke",
"(",
"self",
",",
"function_name",
",",
"raw_python",
"=",
"False",
",",
"command",
"=",
"None",
",",
"no_color",
"=",
"False",
")",
":",
"# There are three likely scenarios for 'command' here:",
"# command, which is a modular function path",
"# raw_c... | Invoke a remote function. | [
"Invoke",
"a",
"remote",
"function",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1260-L1300 |
29,750 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.colorize_invoke_command | def colorize_invoke_command(self, string):
"""
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().
"""
final_string = string
try:
# Line headers
try:
for token in ['START', 'END', 'REPORT', '[DEBUG]']:
if token in final_string:
format_string = '[{}]'
# match whole words only
pattern = r'\b{}\b'
if token == '[DEBUG]':
format_string = '{}'
pattern = re.escape(token)
repl = click.style(
format_string.format(token),
bold=True,
fg='cyan'
)
final_string = re.sub(
pattern.format(token), repl, final_string
)
except Exception: # pragma: no cover
pass
# Green bold Tokens
try:
for token in [
'Zappa Event:',
'RequestId:',
'Version:',
'Duration:',
'Billed',
'Memory Size:',
'Max Memory Used:'
]:
if token in final_string:
final_string = final_string.replace(token, click.style(
token,
bold=True,
fg='green'
))
except Exception: # pragma: no cover
pass
# UUIDs
for token in final_string.replace('\t', ' ').split(' '):
try:
if token.count('-') is 4 and token.replace('-', '').isalnum():
final_string = final_string.replace(
token,
click.style(token, fg='magenta')
)
except Exception: # pragma: no cover
pass
return final_string
except Exception:
return string | python | def colorize_invoke_command(self, string):
"""
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().
"""
final_string = string
try:
# Line headers
try:
for token in ['START', 'END', 'REPORT', '[DEBUG]']:
if token in final_string:
format_string = '[{}]'
# match whole words only
pattern = r'\b{}\b'
if token == '[DEBUG]':
format_string = '{}'
pattern = re.escape(token)
repl = click.style(
format_string.format(token),
bold=True,
fg='cyan'
)
final_string = re.sub(
pattern.format(token), repl, final_string
)
except Exception: # pragma: no cover
pass
# Green bold Tokens
try:
for token in [
'Zappa Event:',
'RequestId:',
'Version:',
'Duration:',
'Billed',
'Memory Size:',
'Max Memory Used:'
]:
if token in final_string:
final_string = final_string.replace(token, click.style(
token,
bold=True,
fg='green'
))
except Exception: # pragma: no cover
pass
# UUIDs
for token in final_string.replace('\t', ' ').split(' '):
try:
if token.count('-') is 4 and token.replace('-', '').isalnum():
final_string = final_string.replace(
token,
click.style(token, fg='magenta')
)
except Exception: # pragma: no cover
pass
return final_string
except Exception:
return string | [
"def",
"colorize_invoke_command",
"(",
"self",
",",
"string",
")",
":",
"final_string",
"=",
"string",
"try",
":",
"# Line headers",
"try",
":",
"for",
"token",
"in",
"[",
"'START'",
",",
"'END'",
",",
"'REPORT'",
",",
"'[DEBUG]'",
"]",
":",
"if",
"token",... | 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(). | [
"Apply",
"various",
"heuristics",
"to",
"return",
"a",
"colorized",
"version",
"the",
"invoke",
"command",
"string",
".",
"If",
"these",
"fail",
"simply",
"return",
"the",
"string",
"in",
"plaintext",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1321-L1387 |
29,751 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.check_environment | 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():
if not isinstance(v, basestring):
non_strings.append(k)
if non_strings:
raise ValueError("The following environment variables are not strings: {}".format(", ".join(non_strings)))
else:
return True | python | 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():
if not isinstance(v, basestring):
non_strings.append(k)
if non_strings:
raise ValueError("The following environment variables are not strings: {}".format(", ".join(non_strings)))
else:
return True | [
"def",
"check_environment",
"(",
"self",
",",
"environment",
")",
":",
"non_strings",
"=",
"[",
"]",
"for",
"(",
"k",
",",
"v",
")",
"in",
"environment",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"basestring",
")",
":",
... | Make sure the environment contains only strings
(since putenv needs a string) | [
"Make",
"sure",
"the",
"environment",
"contains",
"only",
"strings"
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1534-L1548 |
29,752 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.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()
return | python | 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()
return | [
"def",
"shell",
"(",
"self",
")",
":",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"\"NOTICE!\"",
",",
"fg",
"=",
"\"yellow\"",
",",
"bold",
"=",
"True",
")",
"+",
"\" This is a \"",
"+",
"click",
".",
"style",
"(",
"\"local\"",
",",
"fg",... | Spawn a debug shell. | [
"Spawn",
"a",
"debug",
"shell",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1924-L1930 |
29,753 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.callback | def callback(self, position):
"""
Allows the execution of custom code between creation of the zip file and deployment to AWS.
:return: None
"""
callbacks = self.stage_config.get('callbacks', {})
callback = callbacks.get(position)
if callback:
(mod_path, cb_func_name) = callback.rsplit('.', 1)
try: # Prefer callback in working directory
if mod_path.count('.') >= 1: # Callback function is nested in a folder
(mod_folder_path, mod_name) = mod_path.rsplit('.', 1)
mod_folder_path_fragments = mod_folder_path.split('.')
working_dir = os.path.join(os.getcwd(), *mod_folder_path_fragments)
else:
mod_name = mod_path
working_dir = os.getcwd()
working_dir_importer = pkgutil.get_importer(working_dir)
module_ = working_dir_importer.find_module(mod_name).load_module(mod_name)
except (ImportError, AttributeError):
try: # Callback func might be in virtualenv
module_ = importlib.import_module(mod_path)
except ImportError: # pragma: no cover
raise ClickException(click.style("Failed ", fg="red") + 'to ' + click.style(
"import {position} callback ".format(position=position),
bold=True) + 'module: "{mod_path}"'.format(mod_path=click.style(mod_path, bold=True)))
if not hasattr(module_, cb_func_name): # pragma: no cover
raise ClickException(click.style("Failed ", fg="red") + 'to ' + click.style(
"find {position} callback ".format(position=position), bold=True) + 'function: "{cb_func_name}" '.format(
cb_func_name=click.style(cb_func_name, bold=True)) + 'in module "{mod_path}"'.format(mod_path=mod_path))
cb_func = getattr(module_, cb_func_name)
cb_func(self) | python | def callback(self, position):
"""
Allows the execution of custom code between creation of the zip file and deployment to AWS.
:return: None
"""
callbacks = self.stage_config.get('callbacks', {})
callback = callbacks.get(position)
if callback:
(mod_path, cb_func_name) = callback.rsplit('.', 1)
try: # Prefer callback in working directory
if mod_path.count('.') >= 1: # Callback function is nested in a folder
(mod_folder_path, mod_name) = mod_path.rsplit('.', 1)
mod_folder_path_fragments = mod_folder_path.split('.')
working_dir = os.path.join(os.getcwd(), *mod_folder_path_fragments)
else:
mod_name = mod_path
working_dir = os.getcwd()
working_dir_importer = pkgutil.get_importer(working_dir)
module_ = working_dir_importer.find_module(mod_name).load_module(mod_name)
except (ImportError, AttributeError):
try: # Callback func might be in virtualenv
module_ = importlib.import_module(mod_path)
except ImportError: # pragma: no cover
raise ClickException(click.style("Failed ", fg="red") + 'to ' + click.style(
"import {position} callback ".format(position=position),
bold=True) + 'module: "{mod_path}"'.format(mod_path=click.style(mod_path, bold=True)))
if not hasattr(module_, cb_func_name): # pragma: no cover
raise ClickException(click.style("Failed ", fg="red") + 'to ' + click.style(
"find {position} callback ".format(position=position), bold=True) + 'function: "{cb_func_name}" '.format(
cb_func_name=click.style(cb_func_name, bold=True)) + 'in module "{mod_path}"'.format(mod_path=mod_path))
cb_func = getattr(module_, cb_func_name)
cb_func(self) | [
"def",
"callback",
"(",
"self",
",",
"position",
")",
":",
"callbacks",
"=",
"self",
".",
"stage_config",
".",
"get",
"(",
"'callbacks'",
",",
"{",
"}",
")",
"callback",
"=",
"callbacks",
".",
"get",
"(",
"position",
")",
"if",
"callback",
":",
"(",
... | Allows the execution of custom code between creation of the zip file and deployment to AWS.
:return: None | [
"Allows",
"the",
"execution",
"of",
"custom",
"code",
"between",
"creation",
"of",
"the",
"zip",
"file",
"and",
"deployment",
"to",
"AWS",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1936-L1977 |
29,754 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.check_for_update | 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)
if updateable:
click.echo(click.style("Important!", fg="yellow", bold=True) +
" A new version of " + click.style("Zappa", bold=True) + " is available!")
click.echo("Upgrade with: " + click.style("pip install zappa --upgrade", bold=True))
click.echo("Visit the project page on GitHub to see the latest changes: " +
click.style("https://github.com/Miserlou/Zappa", bold=True))
except Exception as e: # pragma: no cover
print(e)
return | python | 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)
if updateable:
click.echo(click.style("Important!", fg="yellow", bold=True) +
" A new version of " + click.style("Zappa", bold=True) + " is available!")
click.echo("Upgrade with: " + click.style("pip install zappa --upgrade", bold=True))
click.echo("Visit the project page on GitHub to see the latest changes: " +
click.style("https://github.com/Miserlou/Zappa", bold=True))
except Exception as e: # pragma: no cover
print(e)
return | [
"def",
"check_for_update",
"(",
"self",
")",
":",
"try",
":",
"version",
"=",
"pkg_resources",
".",
"require",
"(",
"\"zappa\"",
")",
"[",
"0",
"]",
".",
"version",
"updateable",
"=",
"check_new_version_available",
"(",
"version",
")",
"if",
"updateable",
":... | Print a warning if there's a new Zappa version available. | [
"Print",
"a",
"warning",
"if",
"there",
"s",
"a",
"new",
"Zappa",
"version",
"available",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L1979-L1994 |
29,755 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.load_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 your zappa_settings file or call `zappa init`.")
path, ext = os.path.splitext(settings_file)
if ext == '.yml' or ext == '.yaml':
with open(settings_file) as yaml_file:
try:
self.zappa_settings = yaml.load(yaml_file)
except ValueError: # pragma: no cover
raise ValueError("Unable to load the Zappa settings YAML. It may be malformed.")
elif ext == '.toml':
with open(settings_file) as toml_file:
try:
self.zappa_settings = toml.load(toml_file)
except ValueError: # pragma: no cover
raise ValueError("Unable to load the Zappa settings TOML. It may be malformed.")
else:
with open(settings_file) as json_file:
try:
self.zappa_settings = json.load(json_file)
except ValueError: # pragma: no cover
raise ValueError("Unable to load the Zappa settings JSON. It may be malformed.") | python | 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 your zappa_settings file or call `zappa init`.")
path, ext = os.path.splitext(settings_file)
if ext == '.yml' or ext == '.yaml':
with open(settings_file) as yaml_file:
try:
self.zappa_settings = yaml.load(yaml_file)
except ValueError: # pragma: no cover
raise ValueError("Unable to load the Zappa settings YAML. It may be malformed.")
elif ext == '.toml':
with open(settings_file) as toml_file:
try:
self.zappa_settings = toml.load(toml_file)
except ValueError: # pragma: no cover
raise ValueError("Unable to load the Zappa settings TOML. It may be malformed.")
else:
with open(settings_file) as json_file:
try:
self.zappa_settings = json.load(json_file)
except ValueError: # pragma: no cover
raise ValueError("Unable to load the Zappa settings JSON. It may be malformed.") | [
"def",
"load_settings_file",
"(",
"self",
",",
"settings_file",
"=",
"None",
")",
":",
"if",
"not",
"settings_file",
":",
"settings_file",
"=",
"self",
".",
"get_json_or_yaml_settings",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"settings_... | Load our settings file. | [
"Load",
"our",
"settings",
"file",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2163-L2191 |
29,756 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.print_logs | 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']
if "START RequestId" in message:
continue
if "REPORT RequestId" in message:
continue
if "END RequestId" in message:
continue
if not colorize and not force_colorize:
if http:
if self.is_http_log_entry(message.strip()):
print("[" + str(timestamp) + "] " + message.strip())
elif non_http:
if not self.is_http_log_entry(message.strip()):
print("[" + str(timestamp) + "] " + message.strip())
else:
print("[" + str(timestamp) + "] " + message.strip())
else:
if http:
if self.is_http_log_entry(message.strip()):
click.echo(click.style("[", fg='cyan') + click.style(str(timestamp), bold=True) + click.style("]", fg='cyan') + self.colorize_log_entry(message.strip()), color=force_colorize)
elif non_http:
if not self.is_http_log_entry(message.strip()):
click.echo(click.style("[", fg='cyan') + click.style(str(timestamp), bold=True) + click.style("]", fg='cyan') + self.colorize_log_entry(message.strip()), color=force_colorize)
else:
click.echo(click.style("[", fg='cyan') + click.style(str(timestamp), bold=True) + click.style("]", fg='cyan') + self.colorize_log_entry(message.strip()), color=force_colorize) | python | 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']
if "START RequestId" in message:
continue
if "REPORT RequestId" in message:
continue
if "END RequestId" in message:
continue
if not colorize and not force_colorize:
if http:
if self.is_http_log_entry(message.strip()):
print("[" + str(timestamp) + "] " + message.strip())
elif non_http:
if not self.is_http_log_entry(message.strip()):
print("[" + str(timestamp) + "] " + message.strip())
else:
print("[" + str(timestamp) + "] " + message.strip())
else:
if http:
if self.is_http_log_entry(message.strip()):
click.echo(click.style("[", fg='cyan') + click.style(str(timestamp), bold=True) + click.style("]", fg='cyan') + self.colorize_log_entry(message.strip()), color=force_colorize)
elif non_http:
if not self.is_http_log_entry(message.strip()):
click.echo(click.style("[", fg='cyan') + click.style(str(timestamp), bold=True) + click.style("]", fg='cyan') + self.colorize_log_entry(message.strip()), color=force_colorize)
else:
click.echo(click.style("[", fg='cyan') + click.style(str(timestamp), bold=True) + click.style("]", fg='cyan') + self.colorize_log_entry(message.strip()), color=force_colorize) | [
"def",
"print_logs",
"(",
"self",
",",
"logs",
",",
"colorize",
"=",
"True",
",",
"http",
"=",
"False",
",",
"non_http",
"=",
"False",
",",
"force_colorize",
"=",
"None",
")",
":",
"for",
"log",
"in",
"logs",
":",
"timestamp",
"=",
"log",
"[",
"'time... | Parse, filter and print logs to the console. | [
"Parse",
"filter",
"and",
"print",
"logs",
"to",
"the",
"console",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2481-L2514 |
29,757 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.is_http_log_entry | 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
for token in string.replace('\t', ' ').split(' '):
try:
if (token.count('.') is 3 and token.replace('.', '').isnumeric()):
return True
except Exception: # pragma: no cover
pass
return False | python | 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
for token in string.replace('\t', ' ').split(' '):
try:
if (token.count('.') is 3 and token.replace('.', '').isnumeric()):
return True
except Exception: # pragma: no cover
pass
return False | [
"def",
"is_http_log_entry",
"(",
"self",
",",
"string",
")",
":",
"# Debug event filter",
"if",
"'Zappa Event'",
"in",
"string",
":",
"return",
"False",
"# IP address filter",
"for",
"token",
"in",
"string",
".",
"replace",
"(",
"'\\t'",
",",
"' '",
")",
".",
... | Determines if a log entry is an HTTP-formatted log string or not. | [
"Determines",
"if",
"a",
"log",
"entry",
"is",
"an",
"HTTP",
"-",
"formatted",
"log",
"string",
"or",
"not",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2516-L2532 |
29,758 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.colorize_log_entry | 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.
"""
final_string = string
try:
# First, do stuff in square brackets
inside_squares = re.findall(r'\[([^]]*)\]', string)
for token in inside_squares:
if token in ['CRITICAL', 'ERROR', 'WARNING', 'DEBUG', 'INFO', 'NOTSET']:
final_string = final_string.replace('[' + token + ']', click.style("[", fg='cyan') + click.style(token, fg='cyan', bold=True) + click.style("]", fg='cyan'))
else:
final_string = final_string.replace('[' + token + ']', click.style("[", fg='cyan') + click.style(token, bold=True) + click.style("]", fg='cyan'))
# Then do quoted strings
quotes = re.findall(r'"[^"]*"', string)
for token in quotes:
final_string = final_string.replace(token, click.style(token, fg="yellow"))
# And UUIDs
for token in final_string.replace('\t', ' ').split(' '):
try:
if token.count('-') is 4 and token.replace('-', '').isalnum():
final_string = final_string.replace(token, click.style(token, fg="magenta"))
except Exception: # pragma: no cover
pass
# And IP addresses
try:
if token.count('.') is 3 and token.replace('.', '').isnumeric():
final_string = final_string.replace(token, click.style(token, fg="red"))
except Exception: # pragma: no cover
pass
# And status codes
try:
if token in ['200']:
final_string = final_string.replace(token, click.style(token, fg="green"))
if token in ['400', '401', '403', '404', '405', '500']:
final_string = final_string.replace(token, click.style(token, fg="red"))
except Exception: # pragma: no cover
pass
# And Zappa Events
try:
if "Zappa Event:" in final_string:
final_string = final_string.replace("Zappa Event:", click.style("Zappa Event:", bold=True, fg="green"))
except Exception: # pragma: no cover
pass
# And dates
for token in final_string.split('\t'):
try:
is_date = parser.parse(token)
final_string = final_string.replace(token, click.style(token, fg="green"))
except Exception: # pragma: no cover
pass
final_string = final_string.replace('\t', ' ').replace(' ', ' ')
if final_string[0] != ' ':
final_string = ' ' + final_string
return final_string
except Exception as e: # pragma: no cover
return string | python | 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.
"""
final_string = string
try:
# First, do stuff in square brackets
inside_squares = re.findall(r'\[([^]]*)\]', string)
for token in inside_squares:
if token in ['CRITICAL', 'ERROR', 'WARNING', 'DEBUG', 'INFO', 'NOTSET']:
final_string = final_string.replace('[' + token + ']', click.style("[", fg='cyan') + click.style(token, fg='cyan', bold=True) + click.style("]", fg='cyan'))
else:
final_string = final_string.replace('[' + token + ']', click.style("[", fg='cyan') + click.style(token, bold=True) + click.style("]", fg='cyan'))
# Then do quoted strings
quotes = re.findall(r'"[^"]*"', string)
for token in quotes:
final_string = final_string.replace(token, click.style(token, fg="yellow"))
# And UUIDs
for token in final_string.replace('\t', ' ').split(' '):
try:
if token.count('-') is 4 and token.replace('-', '').isalnum():
final_string = final_string.replace(token, click.style(token, fg="magenta"))
except Exception: # pragma: no cover
pass
# And IP addresses
try:
if token.count('.') is 3 and token.replace('.', '').isnumeric():
final_string = final_string.replace(token, click.style(token, fg="red"))
except Exception: # pragma: no cover
pass
# And status codes
try:
if token in ['200']:
final_string = final_string.replace(token, click.style(token, fg="green"))
if token in ['400', '401', '403', '404', '405', '500']:
final_string = final_string.replace(token, click.style(token, fg="red"))
except Exception: # pragma: no cover
pass
# And Zappa Events
try:
if "Zappa Event:" in final_string:
final_string = final_string.replace("Zappa Event:", click.style("Zappa Event:", bold=True, fg="green"))
except Exception: # pragma: no cover
pass
# And dates
for token in final_string.split('\t'):
try:
is_date = parser.parse(token)
final_string = final_string.replace(token, click.style(token, fg="green"))
except Exception: # pragma: no cover
pass
final_string = final_string.replace('\t', ' ').replace(' ', ' ')
if final_string[0] != ' ':
final_string = ' ' + final_string
return final_string
except Exception as e: # pragma: no cover
return string | [
"def",
"colorize_log_entry",
"(",
"self",
",",
"string",
")",
":",
"final_string",
"=",
"string",
"try",
":",
"# First, do stuff in square brackets",
"inside_squares",
"=",
"re",
".",
"findall",
"(",
"r'\\[([^]]*)\\]'",
",",
"string",
")",
"for",
"token",
"in",
... | Apply various heuristics to return a colorized version of a string.
If these fail, simply return the string in plaintext. | [
"Apply",
"various",
"heuristics",
"to",
"return",
"a",
"colorized",
"version",
"of",
"a",
"string",
".",
"If",
"these",
"fail",
"simply",
"return",
"the",
"string",
"in",
"plaintext",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2537-L2603 |
29,759 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.execute_prebuild_script | 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 directory
if pb_mod_path.count('.') >= 1: # Prebuild script func is nested in a folder
(mod_folder_path, mod_name) = pb_mod_path.rsplit('.', 1)
mod_folder_path_fragments = mod_folder_path.split('.')
working_dir = os.path.join(os.getcwd(), *mod_folder_path_fragments)
else:
mod_name = pb_mod_path
working_dir = os.getcwd()
working_dir_importer = pkgutil.get_importer(working_dir)
module_ = working_dir_importer.find_module(mod_name).load_module(mod_name)
except (ImportError, AttributeError):
try: # Prebuild func might be in virtualenv
module_ = importlib.import_module(pb_mod_path)
except ImportError: # pragma: no cover
raise ClickException(click.style("Failed ", fg="red") + 'to ' + click.style(
"import prebuild script ", bold=True) + 'module: "{pb_mod_path}"'.format(
pb_mod_path=click.style(pb_mod_path, bold=True)))
if not hasattr(module_, pb_func): # pragma: no cover
raise ClickException(click.style("Failed ", fg="red") + 'to ' + click.style(
"find prebuild script ", bold=True) + 'function: "{pb_func}" '.format(
pb_func=click.style(pb_func, bold=True)) + 'in module "{pb_mod_path}"'.format(
pb_mod_path=pb_mod_path))
prebuild_function = getattr(module_, pb_func)
prebuild_function() | python | 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 directory
if pb_mod_path.count('.') >= 1: # Prebuild script func is nested in a folder
(mod_folder_path, mod_name) = pb_mod_path.rsplit('.', 1)
mod_folder_path_fragments = mod_folder_path.split('.')
working_dir = os.path.join(os.getcwd(), *mod_folder_path_fragments)
else:
mod_name = pb_mod_path
working_dir = os.getcwd()
working_dir_importer = pkgutil.get_importer(working_dir)
module_ = working_dir_importer.find_module(mod_name).load_module(mod_name)
except (ImportError, AttributeError):
try: # Prebuild func might be in virtualenv
module_ = importlib.import_module(pb_mod_path)
except ImportError: # pragma: no cover
raise ClickException(click.style("Failed ", fg="red") + 'to ' + click.style(
"import prebuild script ", bold=True) + 'module: "{pb_mod_path}"'.format(
pb_mod_path=click.style(pb_mod_path, bold=True)))
if not hasattr(module_, pb_func): # pragma: no cover
raise ClickException(click.style("Failed ", fg="red") + 'to ' + click.style(
"find prebuild script ", bold=True) + 'function: "{pb_func}" '.format(
pb_func=click.style(pb_func, bold=True)) + 'in module "{pb_mod_path}"'.format(
pb_mod_path=pb_mod_path))
prebuild_function = getattr(module_, pb_func)
prebuild_function() | [
"def",
"execute_prebuild_script",
"(",
"self",
")",
":",
"(",
"pb_mod_path",
",",
"pb_func",
")",
"=",
"self",
".",
"prebuild_script",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"try",
":",
"# Prefer prebuild script in working directory",
"if",
"pb_mod_path",
"."... | Parse and execute the prebuild_script from the zappa_settings. | [
"Parse",
"and",
"execute",
"the",
"prebuild_script",
"from",
"the",
"zappa_settings",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2605-L2641 |
29,760 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.collision_warning | def collision_warning(self, item):
"""
Given a string, print a warning if this could
collide with a Zappa core package module.
Use for app functions and events.
"""
namespace_collisions = [
"zappa.", "wsgi.", "middleware.", "handler.", "util.", "letsencrypt.", "cli."
]
for namespace_collision in namespace_collisions:
if item.startswith(namespace_collision):
click.echo(click.style("Warning!", fg="red", bold=True) +
" You may have a namespace collision between " +
click.style(item, bold=True) +
" and " +
click.style(namespace_collision, bold=True) +
"! You may want to rename that file.") | python | def collision_warning(self, item):
"""
Given a string, print a warning if this could
collide with a Zappa core package module.
Use for app functions and events.
"""
namespace_collisions = [
"zappa.", "wsgi.", "middleware.", "handler.", "util.", "letsencrypt.", "cli."
]
for namespace_collision in namespace_collisions:
if item.startswith(namespace_collision):
click.echo(click.style("Warning!", fg="red", bold=True) +
" You may have a namespace collision between " +
click.style(item, bold=True) +
" and " +
click.style(namespace_collision, bold=True) +
"! You may want to rename that file.") | [
"def",
"collision_warning",
"(",
"self",
",",
"item",
")",
":",
"namespace_collisions",
"=",
"[",
"\"zappa.\"",
",",
"\"wsgi.\"",
",",
"\"middleware.\"",
",",
"\"handler.\"",
",",
"\"util.\"",
",",
"\"letsencrypt.\"",
",",
"\"cli.\"",
"]",
"for",
"namespace_collis... | Given a string, print a warning if this could
collide with a Zappa core package module.
Use for app functions and events. | [
"Given",
"a",
"string",
"print",
"a",
"warning",
"if",
"this",
"could",
"collide",
"with",
"a",
"Zappa",
"core",
"package",
"module",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2643-L2661 |
29,761 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.check_venv | 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:
raise ClickException(
click.style("Zappa", bold=True) + " requires an " + click.style("active virtual environment", bold=True, fg="red") + "!\n" +
"Learn more about virtual environments here: " + click.style("http://docs.python-guide.org/en/latest/dev/virtualenvs/", bold=False, fg="cyan")) | python | 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:
raise ClickException(
click.style("Zappa", bold=True) + " requires an " + click.style("active virtual environment", bold=True, fg="red") + "!\n" +
"Learn more about virtual environments here: " + click.style("http://docs.python-guide.org/en/latest/dev/virtualenvs/", bold=False, fg="cyan")) | [
"def",
"check_venv",
"(",
"self",
")",
":",
"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",
... | Ensure we're inside a virtualenv. | [
"Ensure",
"we",
"re",
"inside",
"a",
"virtualenv",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2679-L2689 |
29,762 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.silence | def silence(self):
"""
Route all stdout to null.
"""
sys.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, 'w') | python | def silence(self):
"""
Route all stdout to null.
"""
sys.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, 'w') | [
"def",
"silence",
"(",
"self",
")",
":",
"sys",
".",
"stdout",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
"sys",
".",
"stderr",
"=",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")"
] | Route all stdout to null. | [
"Route",
"all",
"stdout",
"to",
"null",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2691-L2697 |
29,763 | Miserlou/Zappa | zappa/cli.py | ZappaCLI.touch_endpoint | 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
# connect to the service, print a warning and let the user know
# to check it manually.
# See: https://github.com/Miserlou/Zappa/pull/1719#issuecomment-471341565
if 'PRIVATE' in self.stage_config.get('endpoint_configuration', []):
print(
click.style("Warning!", fg="yellow", bold=True) +
" Since you're deploying a private API Gateway endpoint,"
" Zappa cannot determine if your function is returning "
" a correct status code. You should check your API's response"
" manually before considering this deployment complete."
)
return
touch_path = self.stage_config.get('touch_path', '/')
req = requests.get(endpoint_url + touch_path)
# Sometimes on really large packages, it can take 60-90 secs to be
# ready and requests will return 504 status_code until ready.
# So, if we get a 504 status code, rerun the request up to 4 times or
# until we don't get a 504 error
if req.status_code == 504:
i = 0
status_code = 504
while status_code == 504 and i <= 4:
req = requests.get(endpoint_url + touch_path)
status_code = req.status_code
i += 1
if req.status_code >= 500:
raise ClickException(click.style("Warning!", fg="red", bold=True) +
" Status check on the deployed lambda failed." +
" A GET request to '" + touch_path + "' yielded a " +
click.style(str(req.status_code), fg="red", bold=True) + " response code.") | python | 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
# connect to the service, print a warning and let the user know
# to check it manually.
# See: https://github.com/Miserlou/Zappa/pull/1719#issuecomment-471341565
if 'PRIVATE' in self.stage_config.get('endpoint_configuration', []):
print(
click.style("Warning!", fg="yellow", bold=True) +
" Since you're deploying a private API Gateway endpoint,"
" Zappa cannot determine if your function is returning "
" a correct status code. You should check your API's response"
" manually before considering this deployment complete."
)
return
touch_path = self.stage_config.get('touch_path', '/')
req = requests.get(endpoint_url + touch_path)
# Sometimes on really large packages, it can take 60-90 secs to be
# ready and requests will return 504 status_code until ready.
# So, if we get a 504 status code, rerun the request up to 4 times or
# until we don't get a 504 error
if req.status_code == 504:
i = 0
status_code = 504
while status_code == 504 and i <= 4:
req = requests.get(endpoint_url + touch_path)
status_code = req.status_code
i += 1
if req.status_code >= 500:
raise ClickException(click.style("Warning!", fg="red", bold=True) +
" Status check on the deployed lambda failed." +
" A GET request to '" + touch_path + "' yielded a " +
click.style(str(req.status_code), fg="red", bold=True) + " response code.") | [
"def",
"touch_endpoint",
"(",
"self",
",",
"endpoint_url",
")",
":",
"# Private APIGW endpoints most likely can't be reached by a deployer",
"# unless they're connected to the VPC by VPN. Instead of trying",
"# connect to the service, print a warning and let the user know",
"# to check it manu... | Test the deployed endpoint with a GET request. | [
"Test",
"the",
"deployed",
"endpoint",
"with",
"a",
"GET",
"request",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/cli.py#L2699-L2738 |
29,764 | Miserlou/Zappa | zappa/middleware.py | all_casings | def all_casings(input_string):
"""
Permute all casings of a given string.
A pretty algorithm, via @Amber
http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python
"""
if not input_string:
yield ""
else:
first = input_string[:1]
if first.lower() == first.upper():
for sub_casing in all_casings(input_string[1:]):
yield first + sub_casing
else:
for sub_casing in all_casings(input_string[1:]):
yield first.lower() + sub_casing
yield first.upper() + sub_casing | python | def all_casings(input_string):
"""
Permute all casings of a given string.
A pretty algorithm, via @Amber
http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python
"""
if not input_string:
yield ""
else:
first = input_string[:1]
if first.lower() == first.upper():
for sub_casing in all_casings(input_string[1:]):
yield first + sub_casing
else:
for sub_casing in all_casings(input_string[1:]):
yield first.lower() + sub_casing
yield first.upper() + sub_casing | [
"def",
"all_casings",
"(",
"input_string",
")",
":",
"if",
"not",
"input_string",
":",
"yield",
"\"\"",
"else",
":",
"first",
"=",
"input_string",
"[",
":",
"1",
"]",
"if",
"first",
".",
"lower",
"(",
")",
"==",
"first",
".",
"upper",
"(",
")",
":",
... | Permute all casings of a given string.
A pretty algorithm, via @Amber
http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python | [
"Permute",
"all",
"casings",
"of",
"a",
"given",
"string",
"."
] | 3ccf7490a8d8b8fa74a61ee39bf44234f3567739 | https://github.com/Miserlou/Zappa/blob/3ccf7490a8d8b8fa74a61ee39bf44234f3567739/zappa/middleware.py#L4-L21 |
29,765 | binux/pyspider | pyspider/libs/response.py | get_encoding | 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 = params['charset'].strip("'\"")
if not encoding:
content = utils.pretty_unicode(content[:1000]) if six.PY3 else content
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]',
flags=re.I)
pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]',
flags=re.I)
xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
encoding = (charset_re.findall(content) +
pragma_re.findall(content) +
xml_re.findall(content))
encoding = encoding and encoding[0] or None
return encoding | python | 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 = params['charset'].strip("'\"")
if not encoding:
content = utils.pretty_unicode(content[:1000]) if six.PY3 else content
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]',
flags=re.I)
pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]',
flags=re.I)
xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
encoding = (charset_re.findall(content) +
pragma_re.findall(content) +
xml_re.findall(content))
encoding = encoding and encoding[0] or None
return encoding | [
"def",
"get_encoding",
"(",
"headers",
",",
"content",
")",
":",
"encoding",
"=",
"None",
"content_type",
"=",
"headers",
".",
"get",
"(",
"'content-type'",
")",
"if",
"content_type",
":",
"_",
",",
"params",
"=",
"cgi",
".",
"parse_header",
"(",
"content_... | Get encoding from request headers or page head. | [
"Get",
"encoding",
"from",
"request",
"headers",
"or",
"page",
"head",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/response.py#L211-L234 |
29,766 | binux/pyspider | pyspider/libs/response.py | Response.encoding | def encoding(self):
"""
encoding of Response.content.
if Response.encoding is None, encoding will be guessed
by header or content or chardet if available.
"""
if hasattr(self, '_encoding'):
return self._encoding
# content is unicode
if isinstance(self.content, six.text_type):
return 'unicode'
# Try charset from content-type or content
encoding = get_encoding(self.headers, self.content)
# Fallback to auto-detected encoding.
if not encoding and chardet is not None:
encoding = chardet.detect(self.content[:600])['encoding']
if encoding and encoding.lower() == 'gb2312':
encoding = 'gb18030'
self._encoding = encoding or 'utf-8'
return self._encoding | python | def encoding(self):
"""
encoding of Response.content.
if Response.encoding is None, encoding will be guessed
by header or content or chardet if available.
"""
if hasattr(self, '_encoding'):
return self._encoding
# content is unicode
if isinstance(self.content, six.text_type):
return 'unicode'
# Try charset from content-type or content
encoding = get_encoding(self.headers, self.content)
# Fallback to auto-detected encoding.
if not encoding and chardet is not None:
encoding = chardet.detect(self.content[:600])['encoding']
if encoding and encoding.lower() == 'gb2312':
encoding = 'gb18030'
self._encoding = encoding or 'utf-8'
return self._encoding | [
"def",
"encoding",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_encoding'",
")",
":",
"return",
"self",
".",
"_encoding",
"# content is unicode",
"if",
"isinstance",
"(",
"self",
".",
"content",
",",
"six",
".",
"text_type",
")",
":",
"re... | encoding of Response.content.
if Response.encoding is None, encoding will be guessed
by header or content or chardet if available. | [
"encoding",
"of",
"Response",
".",
"content",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/response.py#L61-L86 |
29,767 | binux/pyspider | pyspider/libs/response.py | Response.json | 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:
self._json = None
return self._json | python | 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:
self._json = None
return self._json | [
"def",
"json",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_json'",
")",
":",
"return",
"self",
".",
"_json",
"try",
":",
"self",
".",
"_json",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"text",
"or",
"self",
".",
"content",
")"... | Returns the json-encoded content of the response, if any. | [
"Returns",
"the",
"json",
"-",
"encoded",
"content",
"of",
"the",
"response",
"if",
"any",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/response.py#L129-L137 |
29,768 | binux/pyspider | pyspider/libs/response.py | Response.doc | 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))
return doc | python | 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))
return doc | [
"def",
"doc",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_doc'",
")",
":",
"return",
"self",
".",
"_doc",
"elements",
"=",
"self",
".",
"etree",
"doc",
"=",
"self",
".",
"_doc",
"=",
"PyQuery",
"(",
"elements",
")",
"doc",
".",
"... | Returns a PyQuery object of the response's content | [
"Returns",
"a",
"PyQuery",
"object",
"of",
"the",
"response",
"s",
"content"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/response.py#L140-L147 |
29,769 | binux/pyspider | pyspider/libs/response.py | Response.etree | 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)
self._elements = lxml.html.fromstring(self.content, parser=parser)
except LookupError:
# lxml would raise LookupError when encoding not supported
# try fromstring without encoding instead.
# on windows, unicode is not availabe as encoding for lxml
self._elements = lxml.html.fromstring(self.content)
if isinstance(self._elements, lxml.etree._ElementTree):
self._elements = self._elements.getroot()
return self._elements | python | 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)
self._elements = lxml.html.fromstring(self.content, parser=parser)
except LookupError:
# lxml would raise LookupError when encoding not supported
# try fromstring without encoding instead.
# on windows, unicode is not availabe as encoding for lxml
self._elements = lxml.html.fromstring(self.content)
if isinstance(self._elements, lxml.etree._ElementTree):
self._elements = self._elements.getroot()
return self._elements | [
"def",
"etree",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_elements'",
")",
":",
"try",
":",
"parser",
"=",
"lxml",
".",
"html",
".",
"HTMLParser",
"(",
"encoding",
"=",
"self",
".",
"encoding",
")",
"self",
".",
"_elements",... | Returns a lxml object of the response's content that can be selected by xpath | [
"Returns",
"a",
"lxml",
"object",
"of",
"the",
"response",
"s",
"content",
"that",
"can",
"be",
"selected",
"by",
"xpath"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/response.py#L150-L163 |
29,770 | binux/pyspider | pyspider/libs/base_handler.py | not_send_status | 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 wrapper(self, response, task):
self._extinfo['not_send_status'] = True
function = func.__get__(self, self.__class__)
return self._run_func(function, response, task)
return wrapper | python | 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 wrapper(self, response, task):
self._extinfo['not_send_status'] = True
function = func.__get__(self, self.__class__)
return self._run_func(function, response, task)
return wrapper | [
"def",
"not_send_status",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"response",
",",
"task",
")",
":",
"self",
".",
"_extinfo",
"[",
"'not_send_status'",
"]",
"=",
"True",
"function",
"... | Do not send process status package back to scheduler.
It's used by callbacks like on_message, on_result etc... | [
"Do",
"not",
"send",
"process",
"status",
"package",
"back",
"to",
"scheduler",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/base_handler.py#L35-L46 |
29,771 | binux/pyspider | pyspider/libs/base_handler.py | 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 _config is None:
_config = {}
_config.update(kwargs)
def wrapper(func):
func._config = _config
return func
return wrapper | python | 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 _config is None:
_config = {}
_config.update(kwargs)
def wrapper(func):
func._config = _config
return func
return wrapper | [
"def",
"config",
"(",
"_config",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_config",
"is",
"None",
":",
"_config",
"=",
"{",
"}",
"_config",
".",
"update",
"(",
"kwargs",
")",
"def",
"wrapper",
"(",
"func",
")",
":",
"func",
".",
"_c... | A decorator for setting the default kwargs of `BaseHandler.crawl`.
Any self.crawl with this callback will use this config. | [
"A",
"decorator",
"for",
"setting",
"the",
"default",
"kwargs",
"of",
"BaseHandler",
".",
"crawl",
".",
"Any",
"self",
".",
"crawl",
"with",
"this",
"callback",
"will",
"use",
"this",
"config",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/base_handler.py#L49-L61 |
29,772 | binux/pyspider | pyspider/libs/base_handler.py | every | 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 by meta class
func.is_cronjob = True
# collect interval and unify to seconds, it's used in meta class. See the
# comments in meta class.
func.tick = minutes * 60 + seconds
return func
if inspect.isfunction(minutes):
func = minutes
minutes = 1
seconds = 0
return wrapper(func)
if minutes is NOTSET:
if seconds is NOTSET:
minutes = 1
seconds = 0
else:
minutes = 0
if seconds is NOTSET:
seconds = 0
return wrapper | python | 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 by meta class
func.is_cronjob = True
# collect interval and unify to seconds, it's used in meta class. See the
# comments in meta class.
func.tick = minutes * 60 + seconds
return func
if inspect.isfunction(minutes):
func = minutes
minutes = 1
seconds = 0
return wrapper(func)
if minutes is NOTSET:
if seconds is NOTSET:
minutes = 1
seconds = 0
else:
minutes = 0
if seconds is NOTSET:
seconds = 0
return wrapper | [
"def",
"every",
"(",
"minutes",
"=",
"NOTSET",
",",
"seconds",
"=",
"NOTSET",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"# mark the function with variable 'is_cronjob=True', the function would be",
"# collected into the list Handler._cron_jobs by meta class",
"func",... | method will been called every minutes or seconds | [
"method",
"will",
"been",
"called",
"every",
"minutes",
"or",
"seconds"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/base_handler.py#L68-L97 |
29,773 | binux/pyspider | pyspider/message_queue/rabbitmq.py | catch_error | 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 ImportError:
connect_exceptions = ()
connect_exceptions += (
select.error,
socket.error,
amqp.ConnectionError
)
def wrap(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except connect_exceptions as e:
logging.error('RabbitMQ error: %r, reconnect.', e)
self.reconnect()
return func(self, *args, **kwargs)
return wrap | python | 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 ImportError:
connect_exceptions = ()
connect_exceptions += (
select.error,
socket.error,
amqp.ConnectionError
)
def wrap(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except connect_exceptions as e:
logging.error('RabbitMQ error: %r, reconnect.', e)
self.reconnect()
return func(self, *args, **kwargs)
return wrap | [
"def",
"catch_error",
"(",
"func",
")",
":",
"import",
"amqp",
"try",
":",
"import",
"pika",
".",
"exceptions",
"connect_exceptions",
"=",
"(",
"pika",
".",
"exceptions",
".",
"ConnectionClosed",
",",
"pika",
".",
"exceptions",
".",
"AMQPConnectionError",
",",... | Catch errors of rabbitmq then reconnect | [
"Catch",
"errors",
"of",
"rabbitmq",
"then",
"reconnect"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/message_queue/rabbitmq.py#L24-L49 |
29,774 | binux/pyspider | pyspider/scheduler/task_queue.py | TaskQueue.get | 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.desc()
except Queue.Empty:
self.mutex.release()
return None
task.exetime = now + self.processing_timeout
self.processing.put(task)
self.mutex.release()
return task.taskid | python | 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.desc()
except Queue.Empty:
self.mutex.release()
return None
task.exetime = now + self.processing_timeout
self.processing.put(task)
self.mutex.release()
return task.taskid | [
"def",
"get",
"(",
"self",
")",
":",
"if",
"self",
".",
"bucket",
".",
"get",
"(",
")",
"<",
"1",
":",
"return",
"None",
"now",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"mutex",
".",
"acquire",
"(",
")",
"try",
":",
"task",
"=",
"self... | Get a task from queue when bucket available | [
"Get",
"a",
"task",
"from",
"queue",
"when",
"bucket",
"available"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/task_queue.py#L227-L242 |
29,775 | binux/pyspider | pyspider/scheduler/task_queue.py | TaskQueue.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 | python | 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 | [
"def",
"done",
"(",
"self",
",",
"taskid",
")",
":",
"if",
"taskid",
"in",
"self",
".",
"processing",
":",
"self",
".",
"mutex",
".",
"acquire",
"(",
")",
"if",
"taskid",
"in",
"self",
".",
"processing",
":",
"del",
"self",
".",
"processing",
"[",
... | Mark task done | [
"Mark",
"task",
"done"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/task_queue.py#L244-L252 |
29,776 | binux/pyspider | pyspider/scheduler/task_queue.py | TaskQueue.is_processing | def is_processing(self, taskid):
'''
return True if taskid is in processing
'''
return taskid in self.processing and self.processing[taskid].taskid | python | def is_processing(self, taskid):
'''
return True if taskid is in processing
'''
return taskid in self.processing and self.processing[taskid].taskid | [
"def",
"is_processing",
"(",
"self",
",",
"taskid",
")",
":",
"return",
"taskid",
"in",
"self",
".",
"processing",
"and",
"self",
".",
"processing",
"[",
"taskid",
"]",
".",
"taskid"
] | return True if taskid is in processing | [
"return",
"True",
"if",
"taskid",
"is",
"in",
"processing"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/task_queue.py#L272-L276 |
29,777 | binux/pyspider | pyspider/processor/processor.py | ProcessorResult.logstr | 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(record))
else:
if record.exc_info:
a, b, tb = record.exc_info
tb = hide_me(tb, globals())
record.exc_info = a, b, tb
result.append(pretty_unicode(formater.format(record)))
result.append(u'\n')
return u''.join(result) | python | 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(record))
else:
if record.exc_info:
a, b, tb = record.exc_info
tb = hide_me(tb, globals())
record.exc_info = a, b, tb
result.append(pretty_unicode(formater.format(record)))
result.append(u'\n')
return u''.join(result) | [
"def",
"logstr",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"formater",
"=",
"LogFormatter",
"(",
"color",
"=",
"False",
")",
"for",
"record",
"in",
"self",
".",
"logs",
":",
"if",
"isinstance",
"(",
"record",
",",
"six",
".",
"string_types",
")... | handler the log records to formatted string | [
"handler",
"the",
"log",
"records",
"to",
"formatted",
"string"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/processor.py#L44-L59 |
29,778 | binux/pyspider | pyspider/message_queue/__init__.py | connect_message_queue | def connect_message_queue(name, url=None, maxsize=0, lazy_limit=True):
"""
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,...,hostn:portn (for redis 3.x in cluster mode)
kombu:
kombu+transport://userid:password@hostname:port/virtual_host
see http://kombu.readthedocs.org/en/latest/userguide/connections.html#urls
builtin:
None
"""
if not url:
from pyspider.libs.multiprocessing_queue import Queue
return Queue(maxsize=maxsize)
parsed = urlparse.urlparse(url)
if parsed.scheme == 'amqp':
from .rabbitmq import Queue
return Queue(name, url, maxsize=maxsize, lazy_limit=lazy_limit)
elif parsed.scheme == 'beanstalk':
from .beanstalk import Queue
return Queue(name, host=parsed.netloc, maxsize=maxsize)
elif parsed.scheme == 'redis':
from .redis_queue import Queue
if ',' in parsed.netloc:
"""
redis in cluster mode (there is no concept of 'db' in cluster mode)
ex. redis://host1:port1,host2:port2,...,hostn:portn
"""
cluster_nodes = []
for netloc in parsed.netloc.split(','):
cluster_nodes.append({'host': netloc.split(':')[0], 'port': int(netloc.split(':')[1])})
return Queue(name=name, maxsize=maxsize, lazy_limit=lazy_limit, cluster_nodes=cluster_nodes)
else:
db = parsed.path.lstrip('/').split('/')
try:
db = int(db[0])
except:
logging.warning('redis DB must zero-based numeric index, using 0 instead')
db = 0
password = parsed.password or None
return Queue(name=name, host=parsed.hostname, port=parsed.port, db=db, maxsize=maxsize, password=password, lazy_limit=lazy_limit)
elif url.startswith('kombu+'):
url = url[len('kombu+'):]
from .kombu_queue import Queue
return Queue(name, url, maxsize=maxsize, lazy_limit=lazy_limit)
else:
raise Exception('unknown connection url: %s', url) | python | def connect_message_queue(name, url=None, maxsize=0, lazy_limit=True):
"""
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,...,hostn:portn (for redis 3.x in cluster mode)
kombu:
kombu+transport://userid:password@hostname:port/virtual_host
see http://kombu.readthedocs.org/en/latest/userguide/connections.html#urls
builtin:
None
"""
if not url:
from pyspider.libs.multiprocessing_queue import Queue
return Queue(maxsize=maxsize)
parsed = urlparse.urlparse(url)
if parsed.scheme == 'amqp':
from .rabbitmq import Queue
return Queue(name, url, maxsize=maxsize, lazy_limit=lazy_limit)
elif parsed.scheme == 'beanstalk':
from .beanstalk import Queue
return Queue(name, host=parsed.netloc, maxsize=maxsize)
elif parsed.scheme == 'redis':
from .redis_queue import Queue
if ',' in parsed.netloc:
"""
redis in cluster mode (there is no concept of 'db' in cluster mode)
ex. redis://host1:port1,host2:port2,...,hostn:portn
"""
cluster_nodes = []
for netloc in parsed.netloc.split(','):
cluster_nodes.append({'host': netloc.split(':')[0], 'port': int(netloc.split(':')[1])})
return Queue(name=name, maxsize=maxsize, lazy_limit=lazy_limit, cluster_nodes=cluster_nodes)
else:
db = parsed.path.lstrip('/').split('/')
try:
db = int(db[0])
except:
logging.warning('redis DB must zero-based numeric index, using 0 instead')
db = 0
password = parsed.password or None
return Queue(name=name, host=parsed.hostname, port=parsed.port, db=db, maxsize=maxsize, password=password, lazy_limit=lazy_limit)
elif url.startswith('kombu+'):
url = url[len('kombu+'):]
from .kombu_queue import Queue
return Queue(name, url, maxsize=maxsize, lazy_limit=lazy_limit)
else:
raise Exception('unknown connection url: %s', url) | [
"def",
"connect_message_queue",
"(",
"name",
",",
"url",
"=",
"None",
",",
"maxsize",
"=",
"0",
",",
"lazy_limit",
"=",
"True",
")",
":",
"if",
"not",
"url",
":",
"from",
"pyspider",
".",
"libs",
".",
"multiprocessing_queue",
"import",
"Queue",
"return",
... | 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,...,hostn:portn (for redis 3.x in cluster mode)
kombu:
kombu+transport://userid:password@hostname:port/virtual_host
see http://kombu.readthedocs.org/en/latest/userguide/connections.html#urls
builtin:
None | [
"create",
"connection",
"to",
"message",
"queue"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/message_queue/__init__.py#L16-L78 |
29,779 | binux/pyspider | pyspider/libs/utils.py | hide_me | 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 e:
logging.exception(e)
tb = base_tb
if not tb:
tb = base_tb
return tb | python | 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 e:
logging.exception(e)
tb = base_tb
if not tb:
tb = base_tb
return tb | [
"def",
"hide_me",
"(",
"tb",
",",
"g",
"=",
"globals",
"(",
")",
")",
":",
"base_tb",
"=",
"tb",
"try",
":",
"while",
"tb",
"and",
"tb",
".",
"tb_frame",
".",
"f_globals",
"is",
"not",
"g",
":",
"tb",
"=",
"tb",
".",
"tb_next",
"while",
"tb",
"... | Hide stack traceback of given stack | [
"Hide",
"stack",
"traceback",
"of",
"given",
"stack"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L38-L51 |
29,780 | binux/pyspider | pyspider/libs/utils.py | run_in_subprocess | 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 thread | python | 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 thread | [
"def",
"run_in_subprocess",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"multiprocessing",
"import",
"Process",
"thread",
"=",
"Process",
"(",
"target",
"=",
"func",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
... | Run function in subprocess, return a Process object | [
"Run",
"function",
"in",
"subprocess",
"return",
"a",
"Process",
"object"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L63-L69 |
29,781 | binux/pyspider | pyspider/libs/utils.py | utf8 | 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.text_type):
return string.encode('utf8')
elif isinstance(string, six.binary_type):
return string
else:
return six.text_type(string).encode('utf8') | python | 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.text_type):
return string.encode('utf8')
elif isinstance(string, six.binary_type):
return string
else:
return six.text_type(string).encode('utf8') | [
"def",
"utf8",
"(",
"string",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"text_type",
")",
":",
"return",
"string",
".",
"encode",
"(",
"'utf8'",
")",
"elif",
"isinstance",
"(",
"string",
",",
"six",
".",
"binary_type",
")",
":",
"... | Make sure string is utf8 encoded bytes.
If parameter is a object, object.__str__ will been called before encode as bytes | [
"Make",
"sure",
"string",
"is",
"utf8",
"encoded",
"bytes",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L213-L224 |
29,782 | binux/pyspider | pyspider/libs/utils.py | text | 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 called
"""
if isinstance(string, six.text_type):
return string
elif isinstance(string, six.binary_type):
return string.decode(encoding)
else:
return six.text_type(string) | python | 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 called
"""
if isinstance(string, six.text_type):
return string
elif isinstance(string, six.binary_type):
return string.decode(encoding)
else:
return six.text_type(string) | [
"def",
"text",
"(",
"string",
",",
"encoding",
"=",
"'utf8'",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"text_type",
")",
":",
"return",
"string",
"elif",
"isinstance",
"(",
"string",
",",
"six",
".",
"binary_type",
")",
":",
"retur... | Make sure string is unicode type, decode with given encoding if it's not.
If parameter is a object, object.__str__ will been called | [
"Make",
"sure",
"string",
"is",
"unicode",
"type",
"decode",
"with",
"given",
"encoding",
"if",
"it",
"s",
"not",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L227-L238 |
29,783 | binux/pyspider | pyspider/libs/utils.py | pretty_unicode | 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 string.decode("utf8")
except UnicodeDecodeError:
return string.decode('Latin-1').encode('unicode_escape').decode("utf8") | python | 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 string.decode("utf8")
except UnicodeDecodeError:
return string.decode('Latin-1').encode('unicode_escape').decode("utf8") | [
"def",
"pretty_unicode",
"(",
"string",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"text_type",
")",
":",
"return",
"string",
"try",
":",
"return",
"string",
".",
"decode",
"(",
"\"utf8\"",
")",
"except",
"UnicodeDecodeError",
":",
"retu... | Make sure string is unicode, try to decode with utf8, or unicode escaped string if failed. | [
"Make",
"sure",
"string",
"is",
"unicode",
"try",
"to",
"decode",
"with",
"utf8",
"or",
"unicode",
"escaped",
"string",
"if",
"failed",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L241-L250 |
29,784 | binux/pyspider | pyspider/libs/utils.py | 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(string, six.text_type):
return string
try:
return string.decode("utf8")
except UnicodeDecodeError:
return '[BASE64-DATA]' + base64.b64encode(string) + '[/BASE64-DATA]' | python | 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(string, six.text_type):
return string
try:
return string.decode("utf8")
except UnicodeDecodeError:
return '[BASE64-DATA]' + base64.b64encode(string) + '[/BASE64-DATA]' | [
"def",
"unicode_string",
"(",
"string",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"text_type",
")",
":",
"return",
"string",
"try",
":",
"return",
"string",
".",
"decode",
"(",
"\"utf8\"",
")",
"except",
"UnicodeDecodeError",
":",
"retu... | Make sure string is unicode, try to default with utf8, or base64 if failed.
can been decode by `decode_unicode_string` | [
"Make",
"sure",
"string",
"is",
"unicode",
"try",
"to",
"default",
"with",
"utf8",
"or",
"base64",
"if",
"failed",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L253-L264 |
29,785 | binux/pyspider | pyspider/libs/utils.py | unicode_dict | 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 | python | 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 | [
"def",
"unicode_dict",
"(",
"_dict",
")",
":",
"r",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"_dict",
")",
":",
"r",
"[",
"unicode_obj",
"(",
"k",
")",
"]",
"=",
"unicode_obj",
"(",
"v",
")",
"return",
"r"
] | Make sure keys and values of dict is unicode. | [
"Make",
"sure",
"keys",
"and",
"values",
"of",
"dict",
"is",
"unicode",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L267-L274 |
29,786 | binux/pyspider | pyspider/libs/utils.py | decode_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 string | python | 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 string | [
"def",
"decode_unicode_string",
"(",
"string",
")",
":",
"if",
"string",
".",
"startswith",
"(",
"'[BASE64-DATA]'",
")",
"and",
"string",
".",
"endswith",
"(",
"'[/BASE64-DATA]'",
")",
":",
"return",
"base64",
".",
"b64decode",
"(",
"string",
"[",
"len",
"("... | Decode string encoded by `unicode_string` | [
"Decode",
"string",
"encoded",
"by",
"unicode_string"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L307-L313 |
29,787 | binux/pyspider | pyspider/libs/utils.py | load_object | 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)
else:
module = __import__(module_name, globals(), locals(), [object_name])
return getattr(module, object_name) | python | 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)
else:
module = __import__(module_name, globals(), locals(), [object_name])
return getattr(module, object_name) | [
"def",
"load_object",
"(",
"name",
")",
":",
"if",
"\".\"",
"not",
"in",
"name",
":",
"raise",
"Exception",
"(",
"'load object need module.object'",
")",
"module_name",
",",
"object_name",
"=",
"name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"if",
"six",... | Load object from module | [
"Load",
"object",
"from",
"module"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L359-L370 |
29,788 | binux/pyspider | pyspider/libs/utils.py | get_python_console | 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 not caller:
logging.error("can't find caller who start this console.")
caller = frame
namespace = dict(caller.f_globals)
namespace.update(caller.f_locals)
try:
from IPython.terminal.interactiveshell import TerminalInteractiveShell
shell = TerminalInteractiveShell(user_ns=namespace)
except ImportError:
try:
import readline
import rlcompleter
readline.set_completer(rlcompleter.Completer(namespace).complete)
readline.parse_and_bind("tab: complete")
except ImportError:
pass
import code
shell = code.InteractiveConsole(namespace)
shell._quit = False
def exit():
shell._quit = True
def readfunc(prompt=""):
if shell._quit:
raise EOFError
return six.moves.input(prompt)
# inject exit method
shell.ask_exit = exit
shell.raw_input = readfunc
return shell | python | 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 not caller:
logging.error("can't find caller who start this console.")
caller = frame
namespace = dict(caller.f_globals)
namespace.update(caller.f_locals)
try:
from IPython.terminal.interactiveshell import TerminalInteractiveShell
shell = TerminalInteractiveShell(user_ns=namespace)
except ImportError:
try:
import readline
import rlcompleter
readline.set_completer(rlcompleter.Completer(namespace).complete)
readline.parse_and_bind("tab: complete")
except ImportError:
pass
import code
shell = code.InteractiveConsole(namespace)
shell._quit = False
def exit():
shell._quit = True
def readfunc(prompt=""):
if shell._quit:
raise EOFError
return six.moves.input(prompt)
# inject exit method
shell.ask_exit = exit
shell.raw_input = readfunc
return shell | [
"def",
"get_python_console",
"(",
"namespace",
"=",
"None",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"import",
"inspect",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"caller",
"=",
"frame",
".",
"f_back",
"if",
"not",
"caller",
":",
"l... | Return a interactive python console instance with caller's stack | [
"Return",
"a",
"interactive",
"python",
"console",
"instance",
"with",
"caller",
"s",
"stack"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L373-L415 |
29,789 | binux/pyspider | pyspider/libs/utils.py | python_console | 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.error("can't find caller who start this console.")
caller = frame
namespace = dict(caller.f_globals)
namespace.update(caller.f_locals)
return get_python_console(namespace=namespace).interact() | python | 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.error("can't find caller who start this console.")
caller = frame
namespace = dict(caller.f_globals)
namespace.update(caller.f_locals)
return get_python_console(namespace=namespace).interact() | [
"def",
"python_console",
"(",
"namespace",
"=",
"None",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"import",
"inspect",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"caller",
"=",
"frame",
".",
"f_back",
"if",
"not",
"caller",
":",
"loggi... | Start a interactive python console with caller's stack | [
"Start",
"a",
"interactive",
"python",
"console",
"with",
"caller",
"s",
"stack"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L418-L431 |
29,790 | binux/pyspider | pyspider/libs/wsgi_xmlrpc.py | WSGIXMLRPCApplication.handler | 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:
start_response("400 Bad request", [('Content-Type', 'text/plain')])
return [''] | python | 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:
start_response("400 Bad request", [('Content-Type', 'text/plain')])
return [''] | [
"def",
"handler",
"(",
"self",
",",
"environ",
",",
"start_response",
")",
":",
"if",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
"==",
"'POST'",
":",
"return",
"self",
".",
"handle_POST",
"(",
"environ",
",",
"start_response",
")",
"else",
":",
"start_response... | XMLRPC service for windmill browser core to communicate with | [
"XMLRPC",
"service",
"for",
"windmill",
"browser",
"core",
"to",
"communicate",
"with"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/wsgi_xmlrpc.py#L48-L55 |
29,791 | binux/pyspider | pyspider/database/__init__.py | connect_database | def connect_database(url):
"""
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+type://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
more: http://docs.mongodb.org/manual/reference/connection-string/
sqlalchemy:
sqlalchemy+postgresql+type://user:passwd@host:port/database
sqlalchemy+mysql+mysqlconnector+type://user:passwd@host:port/database
more: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html
redis:
redis+taskdb://host:port/db
elasticsearch:
elasticsearch+type://host:port/?index=pyspider
local:
local+projectdb://filepath,filepath
type:
taskdb
projectdb
resultdb
"""
db = _connect_database(url)
db.copy = lambda: _connect_database(url)
return db | python | def connect_database(url):
"""
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+type://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
more: http://docs.mongodb.org/manual/reference/connection-string/
sqlalchemy:
sqlalchemy+postgresql+type://user:passwd@host:port/database
sqlalchemy+mysql+mysqlconnector+type://user:passwd@host:port/database
more: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html
redis:
redis+taskdb://host:port/db
elasticsearch:
elasticsearch+type://host:port/?index=pyspider
local:
local+projectdb://filepath,filepath
type:
taskdb
projectdb
resultdb
"""
db = _connect_database(url)
db.copy = lambda: _connect_database(url)
return db | [
"def",
"connect_database",
"(",
"url",
")",
":",
"db",
"=",
"_connect_database",
"(",
"url",
")",
"db",
".",
"copy",
"=",
"lambda",
":",
"_connect_database",
"(",
"url",
")",
"return",
"db"
] | 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+type://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
more: http://docs.mongodb.org/manual/reference/connection-string/
sqlalchemy:
sqlalchemy+postgresql+type://user:passwd@host:port/database
sqlalchemy+mysql+mysqlconnector+type://user:passwd@host:port/database
more: http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html
redis:
redis+taskdb://host:port/db
elasticsearch:
elasticsearch+type://host:port/?index=pyspider
local:
local+projectdb://filepath,filepath
type:
taskdb
projectdb
resultdb | [
"create",
"database",
"object",
"by",
"url"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/database/__init__.py#L11-L46 |
29,792 | binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler._update_projects | 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.projectdb.check_update(self._last_update_project):
self._update_project(project)
logger.debug("project: %s updated.", project['name'])
self._force_update_project = False
self._last_update_project = now | python | 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.projectdb.check_update(self._last_update_project):
self._update_project(project)
logger.debug("project: %s updated.", project['name'])
self._force_update_project = False
self._last_update_project = now | [
"def",
"_update_projects",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"(",
"not",
"self",
".",
"_force_update_project",
"and",
"self",
".",
"_last_update_project",
"+",
"self",
".",
"UPDATE_PROJECT_INTERVAL",
">",
"now",
")",
"... | Check project update | [
"Check",
"project",
"update"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L206-L218 |
29,793 | binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler._update_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['name']]
if project._send_on_get_info:
# update project runtime info from processor by sending a _on_get_info
# request, result is in status_page.track.save
project._send_on_get_info = False
self.on_select_task({
'taskid': '_on_get_info',
'project': project.name,
'url': 'data:,_on_get_info',
'status': self.taskdb.SUCCESS,
'fetch': {
'save': self.get_info_attributes,
},
'process': {
'callback': '_on_get_info',
},
})
# load task queue when project is running and delete task_queue when project is stoped
if project.active:
if not project.task_loaded:
self._load_tasks(project)
project.task_loaded = True
else:
if project.task_loaded:
project.task_queue = TaskQueue()
project.task_loaded = False
if project not in self._cnt['all']:
self._update_project_cnt(project.name) | python | 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['name']]
if project._send_on_get_info:
# update project runtime info from processor by sending a _on_get_info
# request, result is in status_page.track.save
project._send_on_get_info = False
self.on_select_task({
'taskid': '_on_get_info',
'project': project.name,
'url': 'data:,_on_get_info',
'status': self.taskdb.SUCCESS,
'fetch': {
'save': self.get_info_attributes,
},
'process': {
'callback': '_on_get_info',
},
})
# load task queue when project is running and delete task_queue when project is stoped
if project.active:
if not project.task_loaded:
self._load_tasks(project)
project.task_loaded = True
else:
if project.task_loaded:
project.task_queue = TaskQueue()
project.task_loaded = False
if project not in self._cnt['all']:
self._update_project_cnt(project.name) | [
"def",
"_update_project",
"(",
"self",
",",
"project",
")",
":",
"if",
"project",
"[",
"'name'",
"]",
"not",
"in",
"self",
".",
"projects",
":",
"self",
".",
"projects",
"[",
"project",
"[",
"'name'",
"]",
"]",
"=",
"Project",
"(",
"self",
",",
"proj... | update one project | [
"update",
"one",
"project"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L222-L259 |
29,794 | binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler._load_tasks | 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']
_schedule = task.get('schedule', self.default_schedule)
priority = _schedule.get('priority', self.default_schedule['priority'])
exetime = _schedule.get('exetime', self.default_schedule['exetime'])
task_queue.put(taskid, priority, exetime)
project.task_loaded = True
logger.debug('project: %s loaded %d tasks.', project.name, len(task_queue))
if project not in self._cnt['all']:
self._update_project_cnt(project.name)
self._cnt['all'].value((project.name, 'pending'), len(project.task_queue)) | python | 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']
_schedule = task.get('schedule', self.default_schedule)
priority = _schedule.get('priority', self.default_schedule['priority'])
exetime = _schedule.get('exetime', self.default_schedule['exetime'])
task_queue.put(taskid, priority, exetime)
project.task_loaded = True
logger.debug('project: %s loaded %d tasks.', project.name, len(task_queue))
if project not in self._cnt['all']:
self._update_project_cnt(project.name)
self._cnt['all'].value((project.name, 'pending'), len(project.task_queue)) | [
"def",
"_load_tasks",
"(",
"self",
",",
"project",
")",
":",
"task_queue",
"=",
"project",
".",
"task_queue",
"for",
"task",
"in",
"self",
".",
"taskdb",
".",
"load_tasks",
"(",
"self",
".",
"taskdb",
".",
"ACTIVE",
",",
"project",
".",
"name",
",",
"s... | load tasks from database | [
"load",
"tasks",
"from",
"database"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L263-L280 |
29,795 | binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler.task_verify | 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
'''
for each in ('taskid', 'project', 'url', ):
if each not in task or not task[each]:
logger.error('%s not in task: %.200r', each, task)
return False
if task['project'] not in self.projects:
logger.error('unknown project: %s', task['project'])
return False
project = self.projects[task['project']]
if not project.active:
logger.error('project %s not started, please set status to RUNNING or DEBUG',
task['project'])
return False
return True | python | 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
'''
for each in ('taskid', 'project', 'url', ):
if each not in task or not task[each]:
logger.error('%s not in task: %.200r', each, task)
return False
if task['project'] not in self.projects:
logger.error('unknown project: %s', task['project'])
return False
project = self.projects[task['project']]
if not project.active:
logger.error('project %s not started, please set status to RUNNING or DEBUG',
task['project'])
return False
return True | [
"def",
"task_verify",
"(",
"self",
",",
"task",
")",
":",
"for",
"each",
"in",
"(",
"'taskid'",
",",
"'project'",
",",
"'url'",
",",
")",
":",
"if",
"each",
"not",
"in",
"task",
"or",
"not",
"task",
"[",
"each",
"]",
":",
"logger",
".",
"error",
... | return False if any of 'taskid', 'project', 'url' is not in task dict
or project in not in task_queue | [
"return",
"False",
"if",
"any",
"of",
"taskid",
"project",
"url",
"is",
"not",
"in",
"task",
"dict",
"or",
"project",
"in",
"not",
"in",
"task_queue"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L297-L315 |
29,796 | binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler.put_task | 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']),
exetime=_schedule.get('exetime', self.default_schedule['exetime'])
) | python | 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']),
exetime=_schedule.get('exetime', self.default_schedule['exetime'])
) | [
"def",
"put_task",
"(",
"self",
",",
"task",
")",
":",
"_schedule",
"=",
"task",
".",
"get",
"(",
"'schedule'",
",",
"self",
".",
"default_schedule",
")",
"self",
".",
"projects",
"[",
"task",
"[",
"'project'",
"]",
"]",
".",
"task_queue",
".",
"put",
... | put task to task queue | [
"put",
"task",
"to",
"task",
"queue"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L325-L332 |
29,797 | binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler.send_task | 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.put_nowait(task)
except Queue.Full:
if force:
self._send_buffer.appendleft(task)
else:
raise | python | 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.put_nowait(task)
except Queue.Full:
if force:
self._send_buffer.appendleft(task)
else:
raise | [
"def",
"send_task",
"(",
"self",
",",
"task",
",",
"force",
"=",
"True",
")",
":",
"try",
":",
"self",
".",
"out_queue",
".",
"put_nowait",
"(",
"task",
")",
"except",
"Queue",
".",
"Full",
":",
"if",
"force",
":",
"self",
".",
"_send_buffer",
".",
... | dispatch task to fetcher
out queue may have size limit to prevent block, a send_buffer is used | [
"dispatch",
"task",
"to",
"fetcher"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L334-L346 |
29,798 | binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler._check_task_done | 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 'track' in task:
if task['project'] not in self.projects:
continue
project = self.projects[task['project']]
project.on_get_info(task['track'].get('save') or {})
logger.info(
'%s on_get_info %r', task['project'], task['track'].get('save', {})
)
continue
elif not self.task_verify(task):
continue
self.on_task_status(task)
cnt += 1
except Queue.Empty:
pass
return cnt | python | 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 'track' in task:
if task['project'] not in self.projects:
continue
project = self.projects[task['project']]
project.on_get_info(task['track'].get('save') or {})
logger.info(
'%s on_get_info %r', task['project'], task['track'].get('save', {})
)
continue
elif not self.task_verify(task):
continue
self.on_task_status(task)
cnt += 1
except Queue.Empty:
pass
return cnt | [
"def",
"_check_task_done",
"(",
"self",
")",
":",
"cnt",
"=",
"0",
"try",
":",
"while",
"True",
":",
"task",
"=",
"self",
".",
"status_queue",
".",
"get_nowait",
"(",
")",
"# check _on_get_info result here",
"if",
"task",
".",
"get",
"(",
"'taskid'",
")",
... | Check status queue | [
"Check",
"status",
"queue"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L348-L370 |
29,799 | binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler._check_request | 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.is_processing(task['taskid']):
todo.append(task)
else:
self.on_request(task)
self._postpone_request = todo
tasks = {}
while len(tasks) < self.LOOP_LIMIT:
try:
task = self.newtask_queue.get_nowait()
except Queue.Empty:
break
if isinstance(task, list):
_tasks = task
else:
_tasks = (task, )
for task in _tasks:
if not self.task_verify(task):
continue
if task['taskid'] in self.projects[task['project']].task_queue:
if not task.get('schedule', {}).get('force_update', False):
logger.debug('ignore newtask %(project)s:%(taskid)s %(url)s', task)
continue
if task['taskid'] in tasks:
if not task.get('schedule', {}).get('force_update', False):
continue
tasks[task['taskid']] = task
for task in itervalues(tasks):
self.on_request(task)
return len(tasks) | python | 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.is_processing(task['taskid']):
todo.append(task)
else:
self.on_request(task)
self._postpone_request = todo
tasks = {}
while len(tasks) < self.LOOP_LIMIT:
try:
task = self.newtask_queue.get_nowait()
except Queue.Empty:
break
if isinstance(task, list):
_tasks = task
else:
_tasks = (task, )
for task in _tasks:
if not self.task_verify(task):
continue
if task['taskid'] in self.projects[task['project']].task_queue:
if not task.get('schedule', {}).get('force_update', False):
logger.debug('ignore newtask %(project)s:%(taskid)s %(url)s', task)
continue
if task['taskid'] in tasks:
if not task.get('schedule', {}).get('force_update', False):
continue
tasks[task['taskid']] = task
for task in itervalues(tasks):
self.on_request(task)
return len(tasks) | [
"def",
"_check_request",
"(",
"self",
")",
":",
"# check _postpone_request first",
"todo",
"=",
"[",
"]",
"for",
"task",
"in",
"self",
".",
"_postpone_request",
":",
"if",
"task",
"[",
"'project'",
"]",
"not",
"in",
"self",
".",
"projects",
":",
"continue",
... | Check new task queue | [
"Check",
"new",
"task",
"queue"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L374-L417 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.