本文整理汇总了Python中rfc822.formatdate函数的典型用法代码示例。如果您正苦于以下问题:Python formatdate函数的具体用法?Python formatdate怎么用?Python formatdate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了formatdate函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: generate_headers
def generate_headers(self):
"""generate_headers() -> [(name:string, value:string)]
Generate a list of headers to be returned as part of the response.
"""
headers = []
# "Status" header must come first.
headers.append(("Status", "%03d %s" % (self.status_code,
self.reason_phrase)))
for name, value in self.headers.items():
headers.append((name.title(), value))
# All the "Set-Cookie" headers.
if self.cookies:
headers.extend(self._gen_cookie_headers())
# Date header
now = time.time()
if not self.headers.has_key("date"):
headers.append(("Date", formatdate(now)))
# Cache directives
if self.cache is None:
pass # don't mess with the expires header
elif not self.headers.has_key("expires"):
if self.cache > 0:
expire_date = formatdate(now + self.cache)
else:
expire_date = "-1" # allowed by HTTP spec and may work better
# with some clients
headers.append(("Expires", expire_date))
return headers
开发者ID:assad2012,项目名称:douban-quixote,代码行数:35,代码来源:http_response.py
示例2: expiredate
def expiredate(seconds, value):
'''Expire date headers for cache control.
@param seconds Seconds
@param value Value for Cache-Control header
'''
now = time.time()
return {'Cache-Control':value % seconds, 'Date':rfc822.formatdate(now),
'Expires':rfc822.formatdate(now + seconds)}
开发者ID:lcrees,项目名称:wsgistate,代码行数:9,代码来源:cache.py
示例3: process_response
def process_response(self, request, response):
stamp = getattr(response, 'sph_lastmodified', None)
if not stamp: return response
import rfc822
import calendar
if stamp is True:
val = rfc822.formatdate()
else:
val = rfc822.formatdate(calendar.timegm(stamp.timetuple()))
response['Last-Modified'] = val
response['Cache-Control'] = 'private, must-revalidate, max-age=0'
return response
开发者ID:hmm,项目名称:sct-communitytools,代码行数:13,代码来源:middleware.py
示例4: test_get_email
def test_get_email(self):
# make a complex query.
dt = formatdate(time.mktime(datetime.datetime(year=1975, month=1, day=1).timetuple()))
c = {
"BIRTH_DATE": {"$gte": dt},
}
g = {
"TRUE_HUGO_SYMBOL": "BRCA2"
}
rule = {
'USER_ID': self.user_id,
'TEAM_ID': self.team_id,
'clinical_filter': c,
'genomic_filter': g,
'protocol_id': '13-615',
'label': 'test',
'status': 1,
'temporary': False
}
# insert it.
r, status_code = self.post('filter', rule)
self.assert201(status_code)
# return the id.
filter_id = r['_id']
# get the matches.
for match in self.db['match'].find({"FILTER_ID": ObjectId(filter_id)}):
assert len(match['EMAIL_SUBJECT']) > 0
开发者ID:dfci,项目名称:matchminer-api,代码行数:31,代码来源:test_match.py
示例5: items
def items(self):
request = self.request
catalog = getUtility(ICatalog)
results = catalog.searchResults(
searchContext=(self.context,),
sort_on='effective', sort_order='reverse',
draftContent = {'any_of': (False,)},
typeType = {'any_of': ('News Item',)})[:15]
for item in results:
url = absoluteURL(item, request)
info = {
'title': item.title,
'description': item.description,
'guid': '%s/'%url,
'pubDate': rfc822.formatdate(time.mktime(item.date.timetuple())),
'isPermaLink': True}
principal = IOwnership(item).owner
if principal is not None:
profile = IPersonalProfile(principal)
info['author'] = u'%s (%s)'%(profile.email, profile.title)
yield info
开发者ID:Zojax,项目名称:zojax.contenttype.newsitem,代码行数:26,代码来源:feeds.py
示例6: outbound
def outbound(response):
if 'user' in response.request.context:
user = response.request.context['user']
if not isinstance(user, User):
raise Response(400, "If you define 'user' in a simplate it has to "
"be a User instance.")
else:
user = User()
if user.ANON: # user is anonymous
if 'session' not in response.request.headers.cookie:
# no cookie in the request, don't set one on response
return
else:
# expired cookie in the request, instruct browser to delete it
response.headers.cookie['session'] = ''
expires = 0
else: # user is authenticated
user = User.from_session_token(user.session_token)
response.headers['Expires'] = BEGINNING_OF_EPOCH # don't cache
response.headers.cookie['session'] = user.session_token
expires = time.time() + TIMEOUT
user.session_expires = datetime.datetime.fromtimestamp(expires)\
.replace(tzinfo=pytz.utc)
db.session.add(user)
db.session.commit()
cookie = response.headers.cookie['session']
# I am not setting domain, because it is supposed to default to what we
# want: the domain of the object requested.
#cookie['domain']
cookie['path'] = '/'
cookie['expires'] = rfc822.formatdate(expires)
cookie['httponly'] = "Yes, please."
开发者ID:kirang89,项目名称:www.gittip.com,代码行数:34,代码来源:authentication.py
示例7: __call__
def __call__(self, request):
stat = os.stat(self.path)
last_modified = formatdate(stat.st_mtime)
if last_modified == request.get_header('If-Modified-Since'):
# handle exact match of If-Modified-Since header
request.response.set_status(304)
return ''
# Set the Content-Type for the response and return the file's contents.
request.response.set_content_type(self.mime_type)
if self.encoding:
request.response.set_header("Content-Encoding", self.encoding)
request.response.set_header('Last-Modified', last_modified)
if self.cache_time is None:
request.response.cache = None # don't set the Expires header
else:
# explicitly allow client to cache page by setting the Expires
# header, this is even more efficient than the using
# Last-Modified/If-Modified-Since since the browser does not need
# to contact the server
request.response.cache = self.cache_time
return FileStream(open(self.path, 'rb'), stat.st_size)
开发者ID:carmackjia,项目名称:douban-quixote,代码行数:25,代码来源:util.py
示例8: open_local_file
def open_local_file(self, req):
import mimetypes
import mimetools
host = req.get_host()
file = req.get_selector()
localfile = urllib.url2pathname(file)
stats = os.stat(localfile)
size = stats[stat.ST_SIZE]
modified = rfc822.formatdate(stats[stat.ST_MTIME])
mtype = mimetypes.guess_type(file)[0]
if host:
host, port = urllib.splitport(host)
if port or socket.gethostbyname(host) not in self.get_names():
raise urllib2.URLError('file not on local host')
fo = open(localfile,'rb')
brange = req.headers.get('Range', None)
brange = range_header_to_tuple(brange)
assert brange != ()
if brange:
(fb, lb) = brange
if lb == '':
lb = size
if fb < 0 or fb > size or lb > size:
raise RangeError('Requested Range Not Satisfiable')
size = (lb - fb)
fo = RangeableFileObject(fo, (fb, lb))
headers = mimetools.Message(StringIO(
'Content-Type: %s\nContent-Length: %d\nLast-Modified: %s\n' %
(mtype or 'text/plain', size, modified)))
return urllib.addinfourl(fo, headers, 'file:'+file)
开发者ID:c0ns0le,项目名称:cygwin,代码行数:30,代码来源:byterange.py
示例9: __init__
def __init__(self, **opts):
"""
Constructs SendGrid Message object.
Args:
to: Recipient
to_name: Recipient name
from: Sender
subject: Email title
text: Email body
html: Email body
bcc: Recipient
reply_to: Reply address
date: Set date
headers: Set headers
x-smtpapi: Set SG custom header
files: Attachments
"""
super(Mail, self).__init__()
self.to = opts.get('to', [])
self.to_name = opts.get('to_name', [])
self.from_email = opts.get('from_email', '')
self.from_name = opts.get('from_name', '')
self.subject = opts.get('subject', '')
self.text = opts.get('text', '')
self.html = opts.get('html', '')
self.bcc = opts.get('bcc', [])
self.reply_to = opts.get('reply_to', '')
self.files = opts.get('files', {})
self.headers = opts.get('headers', '')
self.date = opts.get('date', rfc822.formatdate())
开发者ID:cirocosta,项目名称:sendgrid-python,代码行数:32,代码来源:message.py
示例10: get_media_internal
def get_media_internal (request, path, use_cache=True) :
statobj = os.stat(path)
(st_mtime, st_size, ) = (statobj[stat.ST_MTIME], statobj[stat.ST_SIZE], )
if not django_static.was_modified_since(
request.META.get("HTTP_IF_MODIFIED_SINCE", None), st_mtime, st_size) :
status_code = 304
mimetype = None
contents = None
else :
status_code = 200
if use_cache :
__argument = request.GET.copy()
# We use cache. If you did not enable the caching, nothing will be happended.
__path_cache = urllib.quote("%s?%s" % (path, __argument.urlencode()), "")
__response = cache.get(__path_cache)
if __response :
return (None, None, status_code, None, __response, )
# get media type
mimetype = mimetypes.guess_type(path)[0]
__media_type = "func_%s" % mimetype.replace("/", "_").replace("-", "__")
if globals().has_key(__media_type) :
fn = globals().get(__media_type)
else :
__media_type = mimetype.split("/")[0]
fn = globals().get("func_%s" % __media_type, func_default)
contents = fn(request, path)
return (contents, mimetype, status_code, rfc822.formatdate(st_mtime), None, )
开发者ID:mic101,项目名称:django-dynamic-media-serve,代码行数:34,代码来源:__init__.py
示例11: test_post_dt
def test_post_dt(self):
# make a complex query.
dt = formatdate(time.mktime(datetime.datetime(year=2000, month=1, day=1).timetuple()))
c = {
"BIRTH_DATE": {"$gte": dt},
}
rule = {
'USER_ID': self.user_id,
'TEAM_ID': self.team_id,
'clinical_filter': c,
'label': 'test',
'temporary': True,
'status': 1
}
# insert it.
r, status_code = self.post('filter', rule)
self.assert201(status_code)
# run the filter_doc manually.
dt = datetime.datetime(year=2000, month=1, day=1)
c = {
"BIRTH_DATE": {"$gte": dt}
}
self.cbio.match(c=c)
assert self.cbio.match_df.shape[0] == r['num_matches']
开发者ID:dfci,项目名称:matchminer-api,代码行数:27,代码来源:test_filter.py
示例12: do_new
def do_new(self, line):
"""new subject
create a new note"""
if len(line) < 1:
print "Note needs a subject"
return
fd = NamedTemporaryFile()
note_contents = edit_note(fd)
ids = self._get_ids()
new_message = email.message.Message()
new_message['Subject'] = line
new_message['From'] = self._mail_from
new_message['Mime-Version'] = '1.0 (Apple Message framework v1278)'
new_message['X-Apple-Mail-Remote-Attachments'] = 'YES'
new_message['Content-Transfer-Encoding'] = '7bit'
new_message['X-Uniform-Type-Identifier'] = 'com.apple.mail-note'
new_message['X-Apple-Base-Url'] = "x-msg://%d/" % (int(ids[-1])+1)
new_message['Date'] = rfc822.formatdate(time.time())
new_message.set_payload(note_contents)
self.connect()
self._conn.append('Notes', '', imaplib.Time2Internaldate(
time.time()), str(new_message))
开发者ID:gwklok,项目名称:mapplenotes,代码行数:27,代码来源:mapplenotes.py
示例13: outbound
def outbound(response):
csrf_token = response.request.context.get('csrf_token')
# If csrf_token is unset, then inbound was never called, probaby because
# another inbound hook short-circuited.
if csrf_token is None:
return response
# Set the CSRF cookie even if it's already set, so we renew
# the expiry timer.
response.headers.cookie['csrf_token'] = csrf_token
cookie = response.headers.cookie['csrf_token']
# I am not setting domain, because it is supposed to default to what we
# want: the domain of the object requested.
#cookie['domain']
cookie['path'] = '/'
cookie['expires'] = rfc822.formatdate(time.time() + TIMEOUT)
#cookie['httponly'] = "Yes, please." Want js access for this.
# Content varies with the CSRF cookie, so set the Vary header.
patch_vary_headers(response, ('Cookie',))
开发者ID:ChimeraCoder,项目名称:www.gittip.com,代码行数:26,代码来源:csrf.py
示例14: items
def items(self):
request = self.request
results = getUtility(ICatalog).searchResults(
traversablePath={'any_of':(self.context,)},
type={'any_of': ('forum.topic',)},
sort_order='reverse', sort_on='modified',
isDraft={'any_of': (False,)})[:30]
for item in results:
url = absoluteURL(item, request)
info = {
'title': item.title,
'description': item[TOPIC_FIRST_MESSAGE].text.cooked,
'guid': '%s/'%url,
'pubDate': rfc822.formatdate(time.mktime(
IDCTimes(item).modified.timetuple())),
'isPermaLink': True}
principal = IOwnership(item).owner
if principal is not None:
profile = IPersonalProfile(principal)
info['author'] = u'%s (%s)'%(profile.email, profile.title)
yield info
开发者ID:Zojax,项目名称:zojax.forum,代码行数:26,代码来源:feeds.py
示例15: items
def items(self):
request = self.request
auth = getUtility(IAuthentication)
discussion = IContentDiscussion(self.context)
for idx in discussion:
comment = discussion[idx]
url = absoluteURL(comment.content, request)
info = {
'link': '%s/'%url,
'description': comment.comment,
'guid': '%s/#comments%s'%(url, comment.__name__),
'pubDate': rfc822.formatdate(time.mktime(comment.date.timetuple())),
'isPermaLink': True}
author = u'Unknown'
try:
principal = auth.getPrincipal(comment.author)
profile = IPersonalProfile(principal)
author = profile.title
info['author'] = u'%s (%s)'%(profile.email, author)
except PrincipalLookupError:
pass
info['title'] = _('by ${author}', mapping={'author': author})
yield info
开发者ID:Zojax,项目名称:zojax.content.discussion,代码行数:27,代码来源:feeds.py
示例16: createEvent
def createEvent(evType, tstamp, name = None, contextList = [],
entityList = []):
"""
Create an XML element representing an event. Returns the XML object
It expects:
evType: Enum
tstamp: datetime object
name : string
contextList: List of context elements
entityList: List of entity elements
"""
result = etree.Element('event')
result.attrib['type'] = eventName(evType)
if tstamp == None:
tstamp = datetime.datetime.now()
result.attrib['datetime'] = rfc822.formatdate(rfc822.mktime_tz(rfc822.parsedate_tz(tstamp.strftime("%a, %d %b %Y %H:%M:%S"))))
if name != None:
result.attrib['name'] = name
for el in entityList + contextList:
result.append(el)
# Create the ID
m = hashlib.sha1()
m.update(etree.tostring(result))
result.attrib['id'] = m.hexdigest()
return result
开发者ID:dleony,项目名称:PLA,代码行数:31,代码来源:camoutput.py
示例17: _insert_match_large
def _insert_match_large(self):
# make a complex query.
dt = formatdate(time.mktime(datetime.datetime(year=1975, month=1, day=1).timetuple()))
c = {
"BIRTH_DATE": {"$gte": dt},
}
g = {
"TRUE_HUGO_SYMBOL": "BRCA2"
}
rule = {
'USER_ID': self.user_id,
'TEAM_ID': self.team_id,
'clinical_filter': c,
'genomic_filter': g,
'label': 'test',
'status': 1,
'temporary': False
}
# insert it.
r, status_code = self.post('filter', rule)
self.assert201(status_code)
# return the id.
return r['_id']
开发者ID:dfci,项目名称:matchminer-api,代码行数:26,代码来源:test_match.py
示例18: set_last_modified
def set_last_modified(t):
""" t - datetime
"""
web.header('Last-Modified',
rfc822.formatdate(
time.mktime(t.timetuple())+1e-6*t.microsecond)
)
开发者ID:rnd0101,项目名称:urbanmediator,代码行数:7,代码来源:webutil.py
示例19: __call__
def __call__(self):
if not self.follow_symlinks and os.path.islink(self.path):
raise errors.TraversalError(private_msg="Path %r is a symlink"
% self.path)
request = quixote.get_request()
response = quixote.get_response()
if self.cache_time is None:
response.set_expires(None) # don't set the Expires header
else:
# explicitly allow client to cache page by setting the Expires
# header, this is even more efficient than the using
# Last-Modified/If-Modified-Since since the browser does not need
# to contact the server
response.set_expires(seconds=self.cache_time)
try:
stat = os.stat(self.path)
except OSError:
raise errors.TraversalError
last_modified = formatdate(stat.st_mtime)
if last_modified == request.get_header('If-Modified-Since'):
# handle exact match of If-Modified-Since header
response.set_status(304)
return ''
# Set the Content-Type for the response and return the file's contents.
response.set_content_type(self.mime_type)
if self.encoding:
response.set_header("Content-Encoding", self.encoding)
response.set_header('Last-Modified', last_modified)
return FileStream(open(self.path, 'rb'), stat.st_size)
开发者ID:nascheme,项目名称:quixote,代码行数:34,代码来源:util.py
示例20: get
def get(self, thumb_data, url_path):
self.response.headers['Cache-Control'] = 'public, max-age=31553600' # One Year
self.response.headers['Expires'] = rfc822.formatdate(time.mktime((datetime.datetime.now() + datetime.timedelta(360)).timetuple()))
self.response.headers['Content-Type'] = "image/jpeg"
if 'If-Modified-Since' in self.request.headers or 'If-None-Match' in self.request.headers:
self.response.set_status(304)
return
domain = self.request.get('domain', DOMAINS[0])
if domain not in DOMAINS:
self.response.out.write('Bad Request. Invalid domain %s' % domain)
self.response.set_status(400)
return
thumb_data = thumb_data.split('x')
thumb_data = [float(i) for i in thumb_data]
url = 'http://%s/%s' % (domain, url_path)
logging.info('retrieving %s' % url)
response = urlfetch.fetch(url=url,
deadline=10,
)
# Error handling
if response.status_code!=200:
self.response.headers = response.headers
self.response.out.write(response.content)
self.response.set_status(response.status_code)
return
thumb = response.content
self.response.headers['ETag'] = '"%s"' % (url_path,)
self.response.headers['Cache-Control'] = 'public, max-age=31536000' # One Year
thumb = generate_thumbnail(thumb, *thumb_data)
self.response.out.write(thumb)
开发者ID:burgalon,项目名称:thumbnail-service,代码行数:34,代码来源:thumbnail-service.py
注:本文中的rfc822.formatdate函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论