本文整理汇总了Python中pyrfc3339.generate函数的典型用法代码示例。如果您正苦于以下问题:Python generate函数的具体用法?Python generate怎么用?Python generate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了generate函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: current_calendar_events
def current_calendar_events(calId, time_window=1):
http = httplib2.Http()
service = build(serviceName='calendar', version='v3', http=http,
developerKey='AIzaSyA96dI1CPIUEuzgi3-_H8dQVyM34rak5vE')
# get a list of all events +/- the specified number of days from now
now = datetime.utcnow().replace(tzinfo=pytz.utc)
diffTime = timedelta(days=time_window)
queryStart = now - diffTime
queryEnd = now + diffTime
dayStartString = pyrfc3339.generate(queryStart)
dayEndString = pyrfc3339.generate(queryEnd)
events = service.events().list(calendarId=calId, singleEvents=True, timeMin=dayStartString, timeMax=dayEndString, orderBy='updated').execute()
eventList = []
for event in events['items']:
endTime = pyrfc3339.parse(event['end']['dateTime'])
startTime = pyrfc3339.parse(event['start']['dateTime'])
if now > startTime and now < endTime:
eventList.append(event)
return eventList
开发者ID:Br3nda,项目名称:hackPump,代码行数:26,代码来源:calendar_events.py
示例2: run
def run(cls, info):
import pyrfc3339
from datetime import datetime
import pytz
labels = {}
labels['name'] = info.manifest.name.format(**info.manifest_vars)
# Inspired by https://github.com/projectatomic/ContainerApplicationGenericLabels
# See here for the discussion on the debian-cloud mailing list
# https://lists.debian.org/debian-cloud/2015/05/msg00071.html
labels['architecture'] = info.manifest.system['architecture']
labels['build-date'] = pyrfc3339.generate(datetime.utcnow().replace(tzinfo=pytz.utc))
if 'labels' in info.manifest.provider:
for label, value in info.manifest.provider['labels'].items():
labels[label] = value.format(**info.manifest_vars)
# pipes.quote converts newlines into \n rather than just prefixing
# it with a backslash, so we need to escape manually
def escape(value):
value = value.replace('"', '\\"')
value = value.replace('\n', '\\\n')
value = '"' + value + '"'
return value
kv_pairs = [label + '=' + escape(value) for label, value in labels.items()]
# Add some nice newlines and indentation
info._docker['dockerfile'] += 'LABEL ' + ' \\\n '.join(kv_pairs) + '\n'
开发者ID:KellerFuchs,项目名称:bootstrap-vz,代码行数:25,代码来源:image.py
示例3: display_report
def display_report(report, format):
report = CadorsReport.query.get_or_404(report)
if format == 'atom':
reports = process_report_atom([report])
feed_timestamp = generate(report.last_updated, accept_naive=True)
response = make_response(
render_template('feed.xml',
reports=reports,
feed_timestamp=feed_timestamp))
response.mimetype = "application/atom+xml"
elif format == 'json':
response = make_response(json.dumps(
{'report': report},
indent=None if request.is_xhr else 2,
default=json_default))
response.mimetype = "application/json"
elif format == 'html':
response = make_response(
render_template('single_report.html',
report=report))
elif format == 'kml':
response = make_response(render_template('kml.xml', report=report))
response.mimetype = "application/vnd.google-earth.kml+xml"
response.last_modified = report.last_updated
return prepare_response(response, 43200)
开发者ID:kurtraschke,项目名称:cadors-parse,代码行数:27,代码来源:report.py
示例4: dump
def dump(obj):
def seq(obj):
return " ".join([dump(i) for i in obj])
if isinstance(obj, TaggedElement):
return str(obj)
elif obj is None:
return "nil"
elif isinstance(obj, bool):
if obj:
return "true"
else:
return "false"
elif isinstance(obj, (int, long, float)):
return str(obj)
elif isinstance(obj, decimal.Decimal):
return "{}M".format(obj)
elif isinstance(obj, (Keyword, Symbol)):
return str(obj)
elif isinstance(obj, basestring):
return '"{}"'.format(obj)
elif isinstance(obj, tuple):
return "({})".format(seq(obj))
elif isinstance(obj, list):
return "[{}]".format(seq(obj))
elif isinstance(obj, set):
return "#{{{}}}".format(seq(obj))
elif isinstance(obj, dict):
return "{{{}}}".format(seq(itertools.chain.from_iterable(obj.items())))
elif isinstance(obj, datetime.datetime):
return '#inst "{}"'.format(pyrfc3339.generate(obj))
elif isinstance(obj, uuid.UUID):
return '#uuid "{}"'.format(obj)
else:
raise NotImplementedError("Don't know how to handle {} : {}", type(obj), obj)
开发者ID:Roger,项目名称:y,代码行数:35,代码来源:edn_dump.py
示例5: py_to_go_cookie
def py_to_go_cookie(py_cookie):
'''Convert a python cookie to the JSON-marshalable Go-style cookie form.'''
# TODO (perhaps):
# HttpOnly
# Creation
# LastAccess
# Updated
# not done properly: CanonicalHost.
go_cookie = {
'Name': py_cookie.name,
'Value': py_cookie.value,
'Domain': py_cookie.domain,
'HostOnly': not py_cookie.domain_specified,
'Persistent': not py_cookie.discard,
'Secure': py_cookie.secure,
'CanonicalHost': py_cookie.domain,
}
if py_cookie.path_specified:
go_cookie['Path'] = py_cookie.path
if py_cookie.expires is not None:
unix_time = datetime.datetime.fromtimestamp(py_cookie.expires)
# Note: fromtimestamp bizarrely produces a time without
# a time zone, so we need to use accept_naive.
go_cookie['Expires'] = pyrfc3339.generate(unix_time, accept_naive=True)
return go_cookie
开发者ID:juju-solutions,项目名称:python-libjuju,代码行数:25,代码来源:gocookies.py
示例6: udump
def udump(obj,
string_encoding=DEFAULT_INPUT_ENCODING,
keyword_keys=False,
sort_keys=False,
sort_sets=False):
kwargs = {
"string_encoding": string_encoding,
"keyword_keys": keyword_keys,
"sort_keys": sort_keys,
"sort_sets": sort_sets,
}
if obj is None:
return 'nil'
elif isinstance(obj, bool):
return 'true' if obj else 'false'
elif isinstance(obj, (int, long, float)):
return unicode(obj)
elif isinstance(obj, decimal.Decimal):
return '{}M'.format(obj)
elif isinstance(obj, (Keyword, Symbol)):
return unicode(obj)
# CAVEAT LECTOR! In Python 3 'basestring' is alised to 'str' above.
# Furthermore, in Python 2 bytes is an instance of 'str'/'basestring' while
# in Python 3 it is not.
elif isinstance(obj, bytes):
return unicode_escape(obj.decode(string_encoding))
elif isinstance(obj, basestring):
return unicode_escape(obj)
elif isinstance(obj, tuple):
return '({})'.format(seq(obj, **kwargs))
elif isinstance(obj, (list, ImmutableList)):
return '[{}]'.format(seq(obj, **kwargs))
elif isinstance(obj, set) or isinstance(obj, frozenset):
if sort_sets:
obj = sorted(obj)
return '#{{{}}}'.format(seq(obj, **kwargs))
elif isinstance(obj, dict) or isinstance(obj, ImmutableDict):
pairs = obj.items()
if sort_keys:
pairs = sorted(pairs, key=lambda p: str(p[0]))
if keyword_keys:
pairs = ((Keyword(k) if isinstance(k, (bytes, basestring)) else k, v) for k, v in pairs)
return '{{{}}}'.format(seq(itertools.chain.from_iterable(pairs), **kwargs))
elif isinstance(obj, fractions.Fraction):
return '{}/{}'.format(obj.numerator, obj.denominator)
elif isinstance(obj, datetime.datetime):
return '#inst "{}"'.format(pyrfc3339.generate(obj, microseconds=True))
elif isinstance(obj, datetime.date):
return '#inst "{}"'.format(obj.isoformat())
elif isinstance(obj, uuid.UUID):
return '#uuid "{}"'.format(obj)
elif isinstance(obj, TaggedElement):
return unicode(obj)
raise NotImplementedError(
u"encountered object of type '{}' for which no known encoding is available: {}".format(
type(obj), repr(obj)))
开发者ID:swaroopch,项目名称:edn_format,代码行数:59,代码来源:edn_dump.py
示例7: test_generate_microseconds
def test_generate_microseconds(self):
'''
Test generating timestamps with microseconds.
'''
dt = datetime(2009, 1, 1, 10, 2, 3, 500000, pytz.utc)
timestamp = generate(dt, microseconds=True)
eq_(timestamp, '2009-01-01T10:02:03.500000Z')
开发者ID:Roger,项目名称:y,代码行数:8,代码来源:tests.py
示例8: process_report_atom
def process_report_atom(reports):
out = []
for report in reports:
report.authors = set([narrative.author_name for narrative \
in report.narrative_parts])
report.atom_ts = generate(report.last_updated, accept_naive=True)
out.append(report)
return out
开发者ID:kurtraschke,项目名称:cadors-parse,代码行数:8,代码来源:util.py
示例9: time_before_caveat
def time_before_caveat(t):
'''Return a caveat that specifies that the time that it is checked at
should be before t.
:param t is a a UTC date in - use datetime.utcnow, not datetime.now
'''
return _first_party(COND_TIME_BEFORE,
pyrfc3339.generate(t, accept_naive=True,
microseconds=True))
开发者ID:go-macaroon-bakery,项目名称:py-macaroon-bakery,代码行数:9,代码来源:_caveat.py
示例10: test_generate_local_parse_local
def test_generate_local_parse_local(self):
'''
Generate a local timestamp and parse it into a local datetime.
'''
eastern = pytz.timezone('US/Eastern')
dt1 = eastern.localize(datetime.utcnow())
dt2 = parse(generate(dt1, utc=False, microseconds=True), utc=False)
eq_(dt1, dt2)
开发者ID:Roger,项目名称:y,代码行数:9,代码来源:tests.py
示例11: serialize_date_or_time
def serialize_date_or_time(obj):
if isinstance(obj, datetime.datetime):
obj = normalize_datetime(obj)
return pyrfc3339.generate(obj, utc=False)
elif isinstance(obj, datetime.date):
return obj.strftime('%Y-%m-%d')
elif isinstance(obj, datetime.time):
# XXX super ugly
if obj.tzinfo is None:
obj = obj.replace(tzinfo=LOCAL_TZ)
dd = datetime.datetime.now()
dd = dd.replace(hour=obj.hour, minute=obj.minute,
second=obj.second, tzinfo=obj.tzinfo)
dd = normalize_datetime(dd)
ss = pyrfc3339.generate(dd, utc=False)
return ss.split('T', 1)[1]
else:
return None
开发者ID:mesrut,项目名称:openblock,代码行数:18,代码来源:views.py
示例12: create_slice
def create_slice(self, client_cert, credentials, fields, options):
"""
Create a slice object.
Generate fields for a new object:
* SLICE_URN: retrieve the hostname from the Flask AMsoil plugin
and form into a valid URN
* SLICE_UID: generate a new UUID4 value
* SLICE_CREATION: get the time now and convert it into RFC3339 form
* SLICE_EXPIRED: slice object has just been created, so it is has not
yet expired
"""
self._resource_manager_tools.validate_credentials(credentials)
geniutil = pm.getService('geniutil')
#<UT> Shall we enforce existence of project to which this new slice would belong?
#The information about project is sent in fields under SLICE_PROJECT_URN key
config = pm.getService('config')
hostname = config.get('flask.cbas_hostname')
slice_urn = geniutil.encode_urn(hostname, 'slice', str(fields.get('SLICE_NAME')))
fields['SLICE_URN'] = slice_urn
fields['SLICE_UID'] = str(uuid.uuid4())
fields['SLICE_CREATION'] = pyrfc3339.generate(datetime.datetime.utcnow().replace(tzinfo=pytz.utc))
fields['SLICE_EXPIRED'] = False
#Generating Slice certificate
s_cert, s_pu, s_pr = geniutil.create_certificate(slice_urn, self._sa_pr, self._sa_c)
fields['SLICE_CERTIFICATE'] = s_cert
#Try to get the user credentials for use as owner
user_cert = geniutil.extract_owner_certificate(credentials)
#Extract user info from his certificate
user_urn, user_uuid, user_email = geniutil.extract_certificate_info(user_cert)
#Get the privileges user would get as owner in the slice credential
user_pri = self._delegate_tools.get_default_privilege_list(role_='LEAD', context_='SLICE')
#Create slice cred for owner
slice_cred = geniutil.create_credential_ex(owner_cert=user_cert, target_cert=s_cert, issuer_key=self._sa_pr,
issuer_cert=self._sa_c, privileges_list=user_pri, expiration=self.CRED_EXPIRY)
#Let's make the owner as LEAD
fields['SLICE_LEAD'] = user_urn
#Finally, create slice object
ret_values = self._resource_manager_tools.object_create(self.AUTHORITY_NAME, fields, 'slice')
#Add slice credentials to the return values
ret_values['SLICE_CREDENTIALS'] = slice_cred
#Create SLICE_MEMBER object
options = {'members_to_add' : [{'SLICE_MEMBER' : user_urn, 'SLICE_CREDENTIALS': slice_cred, 'SLICE_CERTIFICATE': s_cert, 'SLICE_ROLE': 'LEAD'}]}
self._resource_manager_tools.member_modify(self.AUTHORITY_NAME, 'slice_member', slice_urn, options, 'SLICE_MEMBER', 'SLICE_URN')
return ret_values
开发者ID:pentikousis,项目名称:C-BAS-framework,代码行数:56,代码来源:osliceauthorityresourcemanager.py
示例13: test_generate_utc_parse_utc
def test_generate_utc_parse_utc(self):
'''
Generate a UTC timestamp and parse it into a UTC datetime.
'''
dt1 = datetime.utcnow()
dt1 = dt1.replace(tzinfo=pytz.utc)
dt2 = parse(generate(dt1, microseconds=True))
eq_(dt1, dt2)
开发者ID:Roger,项目名称:y,代码行数:10,代码来源:tests.py
示例14: test_items_filter_daterange_rfc3339
def test_items_filter_daterange_rfc3339(self):
import pyrfc3339
import pytz
zone = "US/Pacific"
local_tz = pytz.timezone(zone)
with self.settings(TIME_ZONE=zone):
# create some items, they will have
# dates spaced apart by one day, newest first
schema1 = Schema.objects.get(slug="type1")
items = _make_items(4, schema1)
for item in items:
item.save()
# filter out the first and last item by constraining
# the date range to the inner two items.
# (Use local timezone for consistency with _make_items())
startdate = pyrfc3339.generate(items[2].pub_date.replace(tzinfo=local_tz))
enddate = pyrfc3339.generate(items[1].pub_date.replace(tzinfo=local_tz))
# filter both ends
qs = "?startdate=%s&enddate=%s" % (startdate, enddate)
response = self.client.get(reverse("items_json") + qs)
self.assertEqual(response.status_code, 200)
ritems = simplejson.loads(response.content)
self.assertEqual(len(ritems["features"]), 2)
assert self._items_exist_in_result(items[1:3], ritems)
# startdate only
qs = "?startdate=%s" % startdate
response = self.client.get(reverse("items_json") + qs)
self.assertEqual(response.status_code, 200)
ritems = simplejson.loads(response.content)
assert len(ritems["features"]) == 3
assert self._items_exist_in_result(items[:-1], ritems)
# enddate only
qs = "?enddate=%s" % enddate
response = self.client.get(reverse("items_json") + qs)
self.assertEqual(response.status_code, 200)
ritems = simplejson.loads(response.content)
assert len(ritems["features"]) == 3
assert self._items_exist_in_result(items[1:], ritems)
开发者ID:horshacktest,项目名称:openblock,代码行数:42,代码来源:tests.py
示例15: rfc3339
def rfc3339(cls, datetime):
"""Returns ``datetime`` formatted as a rfc3339 string.
:param datetime datetime: The date time to convert
:returns: the rfc3339 formatted string
:rtype: str
"""
datetime_localized = cls.EASTERN.localize(datetime)
return generate(datetime_localized, utc=False)
开发者ID:benlowkh,项目名称:adi-website,代码行数:11,代码来源:google_calendar_resource_builder.py
示例16: utc_roundtrip
def utc_roundtrip(self, tz_name):
'''
Generates a local datetime using the given timezone,
produces a local timestamp from the datetime, parses the timestamp
to a UTC datetime, and verifies that the two datetimes are equal.
'''
tzinfo = pytz.timezone(tz_name)
dt1 = tzinfo.localize(datetime.utcnow())
timestamp = generate(dt1, utc=False, microseconds=True)
dt2 = parse(timestamp)
eq_(dt1, dt2)
开发者ID:Roger,项目名称:y,代码行数:12,代码来源:tests.py
示例17: create_project
def create_project(self, client_cert, credentials, fields, options):
"""
Create a project object.
Generate fields for a new object:
* PROJECT_URN: retrieve the hostname from the Flask AMsoil plugin
and form into a valid URN
* PROJECT_UID: generate a new UUID4 value
* PROJECT_CREATION: get the time now and convert it into RFC3339 form
* PROJECT_EXPIRED: project object has just been created, so it is
has not yet expired
"""
config = pm.getService('config')
hostname = config.get('flask.cbas_hostname')
p_urn = 'urn:publicid:IDN+' + hostname + '+project+' + fields.get('PROJECT_NAME')
fields['PROJECT_URN'] = p_urn
fields['PROJECT_UID'] = str(uuid.uuid4())
fields['PROJECT_CREATION'] = pyrfc3339.generate(datetime.datetime.utcnow().replace(tzinfo=pytz.utc))
fields['PROJECT_EXPIRED'] = False
#<UT>
geniutil = pm.getService('geniutil')
#Generating Project Certificate
p_cert, p_pu, p_pr = geniutil.create_certificate(p_urn, self._sa_pr, self._sa_c)
fields['PROJECT_CERTIFICATE'] = p_cert
#Try to get the user credentials for use as owner
user_cert = geniutil.extract_owner_certificate(credentials)
#Extract user info from his certificate
user_urn, user_uuid, user_email = geniutil.extract_certificate_info(user_cert)
#Get the privileges user would get as owner in the project credential
user_pri = self._delegate_tools.get_default_privilege_list(role_='LEAD', context_='PROJECT')
#Create project cred for owner
p_creds = geniutil.create_credential_ex(owner_cert=user_cert, target_cert=p_cert, issuer_key=self._sa_pr, issuer_cert=self._sa_c, privileges_list=user_pri,
expiration=OSliceAuthorityResourceManager.CRED_EXPIRY)
#Let's make the owner as LEAD
fields['PROJECT_LEAD'] = user_urn
#Finally, create project object
ret_values = self._resource_manager_tools.object_create(self.AUTHORITY_NAME, fields, 'project')
#Add Project credentials to ret values
ret_values['PROJECT_CREDENTIALS'] = p_creds
#Create PROJECT_MEMBER object
options = {'members_to_add' : [{'PROJECT_MEMBER': user_urn, 'PROJECT_CREDENTIALS': p_creds, 'PROJECT_ROLE': 'LEAD'}]}
self._resource_manager_tools.member_modify(self.AUTHORITY_NAME, 'project_member', p_urn, options, 'PROJECT_MEMBER', 'PROJECT_URN')
return ret_values
开发者ID:pentikousis,项目名称:C-BAS-framework,代码行数:53,代码来源:osliceauthorityresourcemanager.py
示例18: run_freebusy_query
def run_freebusy_query(self, users, start_time=None, end_time=None, postfix=None, **kwargs):
""" Returns the result of executing a freebusy query
@param users: collection of strings representing ONID usernames
@param start_time: datetime object representing start of interval
@param end_time: datetime object representing end of interval
@param postfic: string reprenting email address postfix
@returns: Returns a dictionary of Google freebusy calendars keyed to
EMAIL ADDRESSES, not ONIDs.
"""
if postfix is None:
postfix = EMAIL_POSTFIX
self.onids = [user + postfix for user in users]
ids = [{"id": onid} for onid in self.onids]
start_time, end_time = self._format_start_end(start_time, end_time)
# Create strings from datetime objects so that we can pass them to the
# Google freebusy API
start_time_str = generate(start_time)
end_time_str = generate(end_time)
# Create the freebusy API and store in the object
self.api = self.service.freebusy()
# Create the freebusy query body
query = self.build_freebusy_query(ids, start_time_str, end_time_str, **kwargs)
# Create the request and store the result in the object
self.request = self.api.query(body=query)
# Return the executed request
calendars = self.request.execute()
# TODO: handle non-existent users, and other errors.
return calendars
开发者ID:BaxterStockman,项目名称:cloudendar,代码行数:39,代码来源:gapi.py
示例19: create_sliver_info
def create_sliver_info(self, credentials, fields, options):
"""
Create a sliver information object.
"""
# Verify the uniqueness of sliver urn
lookup_results = self._resource_manager_tools.object_lookup(
self.AUTHORITY_NAME, "sliver_info", {"SLIVER_INFO_URN": fields["SLIVER_INFO_URN"]}, {}
)
if len(lookup_results) > 0:
raise self.gfed_ex.GFedv2DuplicateError("A sliver_info with specified urn already exists.")
# Add creation info
fields["SLIVER_INFO_CREATION"] = pyrfc3339.generate(datetime.datetime.utcnow().replace(tzinfo=pytz.utc))
return self._resource_manager_tools.object_create(self.AUTHORITY_NAME, fields, "sliver_info")
开发者ID:EICT,项目名称:C-BAS,代码行数:14,代码来源:osliceauthorityresourcemanager.py
示例20: create_slice
def create_slice(self, client_cert, credentials, fields, options):
"""
Create a slice object.
Generate fields for a new object:
* SLICE_URN: retrieve the hostname from the Flask AMsoil plugin
and form into a valid URN
* SLICE_UID: generate a new UUID4 value
* SLICE_CREATION: get the time now and convert it into RFC3339 form
* SLICE_EXPIRED: slice object has just been created, so it is has not
yet expired
"""
u_c = None
#credentials_testing = credentials #self._resource_manager_tools.read_file(OSliceAuthorityResourceManager.KEY_PATH + "credentials_test")
root = ET.fromstring(credentials[0]['SFA']) #FIXME: short-term solution to fix string handling, take first credential of SFA format
#print '-->'
#print credentials
#print '<--'
self._resource_manager_tools.validate_credentials(credentials)
config = pm.getService('config')
geniutil = pm.getService('geniutil')
hostname = config.get('flask.hostname')
fields['SLICE_URN'] = geniutil.encode_urn(OSliceAuthorityResourceManager.AUTHORITY_NAME, 'slice', str(fields.get('SLICE_NAME')))
fields['SLICE_UID'] = str(uuid.uuid4())
fields['SLICE_CREATION'] = pyrfc3339.generate(datetime.datetime.utcnow().replace(tzinfo=pytz.utc))
fields['SLICE_EXPIRED'] = False
#Generating Slice Credentials
s_c, s_pu, s_pr = geniutil.create_certificate(fields['SLICE_URN'], self._sa_pr, self._sa_c)
#default owner is slice itself
u_c = s_c
#Try to get the user credentials for use as owner
for child in root:
if child.tag == 'credential':
u_c = child[2].text
break
fields['SLICE_CREDENTIALS'] = geniutil.create_credential(u_c, s_c, self._sa_pr, self._sa_c, "slice",
OSliceAuthorityResourceManager.CRED_EXPIRY)
return self._resource_manager_tools.object_create(self.AUTHORITY_NAME, fields, 'slice')
开发者ID:fp7-alien,项目名称:C-BAS,代码行数:47,代码来源:osliceauthorityresourcemanager.py
注:本文中的pyrfc3339.generate函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论