code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
#!/usr/bin/python
import cgi, re, os, posixpath, mimetypes
from mako.lookup import TemplateLookup
from mako import exceptions
root = './'
port = 8000
error_style = 'html' # select 'text' for plaintext error reporting
lookup = TemplateLookup(directories=[root + 'templates', root + 'htdocs'], filesystem_checks=True, module_directory='./modules')
def serve(environ, start_response):
"""serves requests using the WSGI callable interface."""
fieldstorage = cgi.FieldStorage(
fp = environ['wsgi.input'],
environ = environ,
keep_blank_values = True
)
d = dict([(k, getfield(fieldstorage[k])) for k in fieldstorage])
uri = environ.get('PATH_INFO', '/')
if not uri:
uri = '/index.html'
else:
uri = re.sub(r'^/$', '/index.html', uri)
if re.match(r'.*\.html$', uri):
try:
template = lookup.get_template(uri)
start_response("200 OK", [('Content-type','text/html')])
return [template.render(**d)]
except exceptions.TopLevelLookupException:
start_response("404 Not Found", [])
return ["Cant find template '%s'" % uri]
except:
if error_style == 'text':
start_response("200 OK", [('Content-type','text/plain')])
return [exceptions.text_error_template().render()]
else:
start_response("200 OK", [('Content-type','text/html')])
return [exceptions.html_error_template().render()]
else:
u = re.sub(r'^\/+', '', uri)
filename = os.path.join(root, u)
start_response("200 OK", [('Content-type',guess_type(uri))])
return [file(filename).read()]
def getfield(f):
"""convert values from cgi.Field objects to plain values."""
if isinstance(f, list):
return [getfield(x) for x in f]
else:
return f.value
extensions_map = mimetypes.types_map.copy()
extensions_map.update({
'': 'text/html', # Default
})
def guess_type(path):
"""return a mimetype for the given path based on file extension."""
base, ext = posixpath.splitext(path)
if ext in extensions_map:
return extensions_map[ext]
ext = ext.lower()
if ext in extensions_map:
return extensions_map[ext]
else:
return extensions_map['']
if __name__ == '__main__':
import wsgiref.simple_server
server = wsgiref.simple_server.make_server('', port, serve)
print "Server listening on port %d" % port
server.serve_forever()
| Python |
#!/usr/bin/env python
def render(data):
from mako.template import Template
from mako.lookup import TemplateLookup
lookup = TemplateLookup(["."])
return Template(data, lookup=lookup).render()
def main(argv=None):
from os.path import isfile
from sys import stdin
if argv is None:
import sys
argv = sys.argv
from optparse import OptionParser
parser = OptionParser("usage: %prog [FILENAME]")
opts, args = parser.parse_args(argv[1:])
if len(args) not in (0, 1):
parser.error("wrong number of arguments") # Will exit
if (len(args) == 0) or (args[0] == "-"):
fo = stdin
else:
filename = args[0]
if not isfile(filename):
raise SystemExit("error: can't find %s" % filename)
fo = open(filename)
data = fo.read()
print render(data)
if __name__ == "__main__":
main()
| Python |
from setuptools import setup, find_packages
import os
import re
import sys
extra = {}
if sys.version_info >= (3, 0):
extra.update(
use_2to3=True,
)
v = open(os.path.join(os.path.dirname(__file__), 'mako', '__init__.py'))
VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(v.read()).group(1)
v.close()
setup(name='Mako',
version=VERSION,
description="A super-fast templating language that borrows the \
best ideas from the existing templating languages.",
long_description="""\
Mako is a template library written in Python. It provides a familiar, non-XML
syntax which compiles into Python modules for maximum performance. Mako's
syntax and API borrows from the best ideas of many others, including Django
templates, Cheetah, Myghty, and Genshi. Conceptually, Mako is an embedded
Python (i.e. Python Server Page) language, which refines the familiar ideas
of componentized layout and inheritance to produce one of the most
straightforward and flexible models available, while also maintaining close
ties to Python calling and scoping semantics.
""",
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
keywords='wsgi myghty mako',
author='Mike Bayer',
author_email='mike@zzzcomputing.com',
url='http://www.makotemplates.org/',
license='MIT',
packages=find_packages('.', exclude=['examples*', 'test*']),
scripts=['scripts/mako-render'],
tests_require = ['nose >= 0.11'],
test_suite = "nose.collector",
zip_safe=False,
install_requires=[
'MarkupSafe>=0.9.2',
],
extras_require = {'beaker':['Beaker>=1.1']},
entry_points="""
[python.templating.engines]
mako = mako.ext.turbogears:TGPlugin
[pygments.lexers]
mako = mako.ext.pygmentplugin:MakoLexer
html+mako = mako.ext.pygmentplugin:MakoHtmlLexer
xml+mako = mako.ext.pygmentplugin:MakoXmlLexer
js+mako = mako.ext.pygmentplugin:MakoJavascriptLexer
css+mako = mako.ext.pygmentplugin:MakoCssLexer
[babel.extractors]
mako = mako.ext.babelplugin:extract
""",
**extra
)
| Python |
"""
gae-pytz
========
pytz has a severe performance problem that impedes its usage on Google App
Engine. This is caused because pytz.__init__ builds a list of available
zoneinfos checking the entire zoneinfo database (which means: it tries to open
hundreds of files). This is done in the module globals, so it is not easily
avoidable. And it is far from ideal to do this in App Engine - app
initialization becomes unacceptable if every time we import pytz it checks
500+ files.
In this alternative version, pytz is highly optimized for App Engine, following
ideas from several recipes around:
- database files are not automatically reads when the module is imported
- the database files are loaded using zipimport to reduce number of files
- it uses memcache to cache already loaded zoneinfos
This results in almost unnoticeable load time and makes pytz usable on App
Engine.
"""
from setuptools import setup, find_packages
setup(
name='gaepytz',
version='2011h',
url='http://code.google.com/p/gae-pytz/',
license='MIT',
author='Rodrigo Moraes',
author_email='rodrigo.moraes@gmail.com',
description='A version of pytz that works well on Google App Engine.',
long_description=__doc__,
zip_safe=False,
platforms='any',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
packages=['pytz'],
include_package_data=True,
package_data={'': ['*.zip']},
)
| Python |
'''
Reference tzinfo implementations from the Python docs.
Used for testing against as they are only correct for the years
1987 to 2006. Do not use these for real code.
'''
from datetime import tzinfo, timedelta, datetime
from pytz import utc, UTC, HOUR, ZERO
# A class building tzinfo objects for fixed-offset time zones.
# Note that FixedOffset(0, "UTC") is a different way to build a
# UTC tzinfo object.
class FixedOffset(tzinfo):
"""Fixed offset in minutes east from UTC."""
def __init__(self, offset, name):
self.__offset = timedelta(minutes = offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return ZERO
# A class capturing the platform's idea of local time.
import time as _time
STDOFFSET = timedelta(seconds = -_time.timezone)
if _time.daylight:
DSTOFFSET = timedelta(seconds = -_time.altzone)
else:
DSTOFFSET = STDOFFSET
DSTDIFF = DSTOFFSET - STDOFFSET
class LocalTimezone(tzinfo):
def utcoffset(self, dt):
if self._isdst(dt):
return DSTOFFSET
else:
return STDOFFSET
def dst(self, dt):
if self._isdst(dt):
return DSTDIFF
else:
return ZERO
def tzname(self, dt):
return _time.tzname[self._isdst(dt)]
def _isdst(self, dt):
tt = (dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
dt.weekday(), 0, -1)
stamp = _time.mktime(tt)
tt = _time.localtime(stamp)
return tt.tm_isdst > 0
Local = LocalTimezone()
# A complete implementation of current DST rules for major US time zones.
def first_sunday_on_or_after(dt):
days_to_go = 6 - dt.weekday()
if days_to_go:
dt += timedelta(days_to_go)
return dt
# In the US, DST starts at 2am (standard time) on the first Sunday in April.
DSTSTART = datetime(1, 4, 1, 2)
# and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct.
# which is the first Sunday on or after Oct 25.
DSTEND = datetime(1, 10, 25, 1)
class USTimeZone(tzinfo):
def __init__(self, hours, reprname, stdname, dstname):
self.stdoffset = timedelta(hours=hours)
self.reprname = reprname
self.stdname = stdname
self.dstname = dstname
def __repr__(self):
return self.reprname
def tzname(self, dt):
if self.dst(dt):
return self.dstname
else:
return self.stdname
def utcoffset(self, dt):
return self.stdoffset + self.dst(dt)
def dst(self, dt):
if dt is None or dt.tzinfo is None:
# An exception may be sensible here, in one or both cases.
# It depends on how you want to treat them. The default
# fromutc() implementation (called by the default astimezone()
# implementation) passes a datetime with dt.tzinfo is self.
return ZERO
assert dt.tzinfo is self
# Find first Sunday in April & the last in October.
start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))
end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))
# Can't compare naive to aware objects, so strip the timezone from
# dt first.
if start <= dt.replace(tzinfo=None) < end:
return HOUR
else:
return ZERO
Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
Central = USTimeZone(-6, "Central", "CST", "CDT")
Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
Pacific = USTimeZone(-8, "Pacific", "PST", "PDT")
| Python |
"""
A pytz version that runs smoothly on Google App Engine.
Based on http://appengine-cookbook.appspot.com/recipe/caching-pytz-helper/
To use, add pytz to your path normally, but import it from the gae module:
from pytz.gae import pytz
Applied patches:
- The zoneinfo dir is removed from pytz, as this module includes a ziped
version of it.
- pytz is monkey patched to load zoneinfos from a zipfile.
- pytz is patched to not check all zoneinfo files when loaded. This is
sad, I wish that was lazy, so it could be monkey patched. As it is,
the zipfile patch doesn't work and it'll spend resources checking
hundreds of files that we know aren't there.
pytz caches loaded zoneinfos, and this module will additionally cache them
in memcache to avoid unzipping constantly. The cache key includes the
OLSON_VERSION so it is invalidated when pytz is updated.
"""
import os
import logging
import pytz
import zipfile
from cStringIO import StringIO
# Fake memcache for when we're not running under the SDK, likely a script.
class memcache(object):
@classmethod
def add(*args, **kwargs):
pass
@classmethod
def get(*args, **kwargs):
return None
try:
# Don't use memcache outside of Google App Engine or with GAE's dev server.
if not os.environ.get('SERVER_SOFTWARE', '').startswith('Development'):
from google.appengine.api import memcache
except ImportError:
pass
zoneinfo = None
zoneinfo_path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'zoneinfo.zip'))
def get_zoneinfo():
"""Cache the opened zipfile in the module."""
global zoneinfo
if zoneinfo is None:
zoneinfo = zipfile.ZipFile(zoneinfo_path)
return zoneinfo
class TimezoneLoader(object):
"""A loader that that reads timezones using ZipFile."""
def __init__(self):
self.available = {}
def open_resource(self, name):
"""Opens a resource from the zoneinfo subdir for reading."""
name_parts = name.lstrip('/').split('/')
if os.path.pardir in name_parts:
raise ValueError('Bad path segment: %r' % os.path.pardir)
cache_key = 'pytz.zoneinfo.%s.%s' % (pytz.OLSON_VERSION, name)
zonedata = memcache.get(cache_key)
if zonedata is None:
zonedata = get_zoneinfo().read('zoneinfo/' + '/'.join(name_parts))
memcache.add(cache_key, zonedata)
logging.info('Added timezone to memcache: %s' % cache_key)
else:
logging.info('Loaded timezone from memcache: %s' % cache_key)
return StringIO(zonedata)
def resource_exists(self, name):
"""Return true if the given resource exists"""
if name not in self.available:
try:
get_zoneinfo().getinfo('zoneinfo/' + name)
self.available[name] = True
except KeyError:
self.available[name] = False
return self.available[name]
pytz.loader = TimezoneLoader()
| Python |
'''
datetime.tzinfo timezone definitions generated from the
Olson timezone database:
ftp://elsie.nci.nih.gov/pub/tz*.tar.gz
See the datetime section of the Python Library Reference for information
on how to use these modules.
'''
# The Olson database is updated several times a year.
OLSON_VERSION = '2010h'
VERSION = OLSON_VERSION
# Version format for a patch release - only one so far.
#VERSION = OLSON_VERSION + '.2'
__version__ = OLSON_VERSION
OLSEN_VERSION = OLSON_VERSION # Old releases had this misspelling
__all__ = [
'timezone', 'utc', 'country_timezones', 'country_names',
'AmbiguousTimeError', 'InvalidTimeError',
'NonExistentTimeError', 'UnknownTimeZoneError',
'all_timezones', 'all_timezones_set',
'common_timezones', 'common_timezones_set',
'loader',
]
import sys, datetime, os.path, gettext
from UserDict import DictMixin
from UserList import UserList
try:
from pkg_resources import resource_stream
except ImportError:
resource_stream = None
from tzinfo import AmbiguousTimeError, InvalidTimeError, NonExistentTimeError
from tzinfo import unpickler
from tzfile import build_tzinfo
# Use 2.3 sets module implementation if set builtin is not available
try:
set
except NameError:
from sets import Set as set
class TimezoneLoader(object):
def __init__(self):
self.available = {}
def open_resource(self, name):
"""Open a resource from the zoneinfo subdir for reading.
Uses the pkg_resources module if available and no standard file
found at the calculated location.
"""
name_parts = name.lstrip('/').split('/')
for part in name_parts:
if part == os.path.pardir or os.path.sep in part:
raise ValueError('Bad path segment: %r' % part)
filename = os.path.join(os.path.dirname(__file__),
'zoneinfo', *name_parts)
if not os.path.exists(filename) and resource_stream is not None:
# http://bugs.launchpad.net/bugs/383171 - we avoid using this
# unless absolutely necessary to help when a broken version of
# pkg_resources is installed.
return resource_stream(__name__, 'zoneinfo/' + name)
return open(filename, 'rb')
def resource_exists(self, name):
"""Return true if the given resource exists"""
if name not in self.available:
try:
self.open_resource(name)
self.available[name] = True
except IOError:
self.available[name] = False
return self.available[name]
loader = TimezoneLoader()
def open_resource(name):
return loader.open_resource(name)
def resource_exists(name):
return loader.resource_exists(name)
# Enable this when we get some translations?
# We want an i18n API that is useful to programs using Python's gettext
# module, as well as the Zope3 i18n package. Perhaps we should just provide
# the POT file and translations, and leave it up to callers to make use
# of them.
#
# t = gettext.translation(
# 'pytz', os.path.join(os.path.dirname(__file__), 'locales'),
# fallback=True
# )
# def _(timezone_name):
# """Translate a timezone name using the current locale, returning Unicode"""
# return t.ugettext(timezone_name)
class UnknownTimeZoneError(KeyError):
'''Exception raised when pytz is passed an unknown timezone.
>>> isinstance(UnknownTimeZoneError(), LookupError)
True
This class is actually a subclass of KeyError to provide backwards
compatibility with code relying on the undocumented behavior of earlier
pytz releases.
>>> isinstance(UnknownTimeZoneError(), KeyError)
True
'''
pass
_tzinfo_cache = {}
def timezone(zone):
r''' Return a datetime.tzinfo implementation for the given timezone
>>> from datetime import datetime, timedelta
>>> utc = timezone('UTC')
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> timezone(u'US/Eastern') is eastern
True
>>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
>>> loc_dt = utc_dt.astimezone(eastern)
>>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'
>>> loc_dt.strftime(fmt)
'2002-10-27 01:00:00 EST (-0500)'
>>> (loc_dt - timedelta(minutes=10)).strftime(fmt)
'2002-10-27 00:50:00 EST (-0500)'
>>> eastern.normalize(loc_dt - timedelta(minutes=10)).strftime(fmt)
'2002-10-27 01:50:00 EDT (-0400)'
>>> (loc_dt + timedelta(minutes=10)).strftime(fmt)
'2002-10-27 01:10:00 EST (-0500)'
Raises UnknownTimeZoneError if passed an unknown zone.
>>> timezone('Asia/Shangri-La')
Traceback (most recent call last):
...
UnknownTimeZoneError: 'Asia/Shangri-La'
>>> timezone(u'\N{TRADE MARK SIGN}')
Traceback (most recent call last):
...
UnknownTimeZoneError: u'\u2122'
'''
if zone.upper() == 'UTC':
return utc
try:
zone = zone.encode('US-ASCII')
except UnicodeEncodeError:
# All valid timezones are ASCII
raise UnknownTimeZoneError(zone)
zone = _unmunge_zone(zone)
if zone not in _tzinfo_cache:
if resource_exists(zone):
_tzinfo_cache[zone] = build_tzinfo(zone, open_resource(zone))
else:
raise UnknownTimeZoneError(zone)
return _tzinfo_cache[zone]
def _unmunge_zone(zone):
"""Undo the time zone name munging done by older versions of pytz."""
return zone.replace('_plus_', '+').replace('_minus_', '-')
ZERO = datetime.timedelta(0)
HOUR = datetime.timedelta(hours=1)
class UTC(datetime.tzinfo):
"""UTC
Identical to the reference UTC implementation given in Python docs except
that it unpickles using the single module global instance defined beneath
this class declaration.
Also contains extra attributes and methods to match other pytz tzinfo
instances.
"""
zone = "UTC"
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
def __reduce__(self):
return _UTC, ()
def localize(self, dt, is_dst=False):
'''Convert naive time to local time'''
if dt.tzinfo is not None:
raise ValueError, 'Not naive datetime (tzinfo is already set)'
return dt.replace(tzinfo=self)
def normalize(self, dt, is_dst=False):
'''Correct the timezone information on the given datetime'''
if dt.tzinfo is None:
raise ValueError, 'Naive time - no tzinfo set'
return dt.replace(tzinfo=self)
def __repr__(self):
return "<UTC>"
def __str__(self):
return "UTC"
UTC = utc = UTC() # UTC is a singleton
def _UTC():
"""Factory function for utc unpickling.
Makes sure that unpickling a utc instance always returns the same
module global.
These examples belong in the UTC class above, but it is obscured; or in
the README.txt, but we are not depending on Python 2.4 so integrating
the README.txt examples with the unit tests is not trivial.
>>> import datetime, pickle
>>> dt = datetime.datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc)
>>> naive = dt.replace(tzinfo=None)
>>> p = pickle.dumps(dt, 1)
>>> naive_p = pickle.dumps(naive, 1)
>>> len(p), len(naive_p), len(p) - len(naive_p)
(60, 43, 17)
>>> new = pickle.loads(p)
>>> new == dt
True
>>> new is dt
False
>>> new.tzinfo is dt.tzinfo
True
>>> utc is UTC is timezone('UTC')
True
>>> utc is timezone('GMT')
False
"""
return utc
_UTC.__safe_for_unpickling__ = True
def _p(*args):
"""Factory function for unpickling pytz tzinfo instances.
Just a wrapper around tzinfo.unpickler to save a few bytes in each pickle
by shortening the path.
"""
return unpickler(*args)
_p.__safe_for_unpickling__ = True
class _LazyDict(DictMixin):
"""Dictionary populated on first use."""
data = None
def __getitem__(self, key):
if self.data is None:
self._fill()
return self.data[key.upper()]
def keys(self):
if self.data is None:
self._fill()
return self.data.keys()
class _LazyList(UserList):
def __init__(self, func):
self._data = None
self._build = func
def data(self):
if self._data is None:
self._data = self._build()
return self._data
data = property(data)
class _CountryTimezoneDict(_LazyDict):
"""Map ISO 3166 country code to a list of timezone names commonly used
in that country.
iso3166_code is the two letter code used to identify the country.
>>> country_timezones['ch']
['Europe/Zurich']
>>> country_timezones['CH']
['Europe/Zurich']
>>> country_timezones[u'ch']
['Europe/Zurich']
>>> country_timezones['XXX']
Traceback (most recent call last):
...
KeyError: 'XXX'
Previously, this information was exposed as a function rather than a
dictionary. This is still supported::
>>> country_timezones('nz')
['Pacific/Auckland', 'Pacific/Chatham']
"""
def __call__(self, iso3166_code):
"""Backwards compatibility."""
return self[iso3166_code]
def _fill(self):
data = {}
zone_tab = open_resource('zone.tab')
for line in zone_tab:
if line.startswith('#'):
continue
code, coordinates, zone = line.split(None, 4)[:3]
if not resource_exists(zone):
continue
try:
data[code].append(zone)
except KeyError:
data[code] = [zone]
self.data = data
country_timezones = _CountryTimezoneDict()
class _CountryNameDict(_LazyDict):
'''Dictionary proving ISO3166 code -> English name.
>>> country_names['au']
'Australia'
'''
def _fill(self):
data = {}
zone_tab = open_resource('iso3166.tab')
for line in zone_tab.readlines():
if line.startswith('#'):
continue
code, name = line.split(None, 1)
data[code] = name.strip()
self.data = data
country_names = _CountryNameDict()
# Time-zone info based solely on fixed offsets
class _FixedOffset(datetime.tzinfo):
zone = None # to match the standard pytz API
def __init__(self, minutes):
if abs(minutes) >= 1440:
raise ValueError("absolute offset is too large", minutes)
self._minutes = minutes
self._offset = datetime.timedelta(minutes=minutes)
def utcoffset(self, dt):
return self._offset
def __reduce__(self):
return FixedOffset, (self._minutes, )
def dst(self, dt):
return None
def tzname(self, dt):
return None
def __repr__(self):
return 'pytz.FixedOffset(%d)' % self._minutes
def localize(self, dt, is_dst=False):
'''Convert naive time to local time'''
if dt.tzinfo is not None:
raise ValueError, 'Not naive datetime (tzinfo is already set)'
return dt.replace(tzinfo=self)
def normalize(self, dt, is_dst=False):
'''Correct the timezone information on the given datetime'''
if dt.tzinfo is None:
raise ValueError, 'Naive time - no tzinfo set'
return dt.replace(tzinfo=self)
def FixedOffset(offset, _tzinfos = {}):
"""return a fixed-offset timezone based off a number of minutes.
>>> one = FixedOffset(-330)
>>> one
pytz.FixedOffset(-330)
>>> one.utcoffset(datetime.datetime.now())
datetime.timedelta(-1, 66600)
>>> two = FixedOffset(1380)
>>> two
pytz.FixedOffset(1380)
>>> two.utcoffset(datetime.datetime.now())
datetime.timedelta(0, 82800)
The datetime.timedelta must be between the range of -1 and 1 day,
non-inclusive.
>>> FixedOffset(1440)
Traceback (most recent call last):
...
ValueError: ('absolute offset is too large', 1440)
>>> FixedOffset(-1440)
Traceback (most recent call last):
...
ValueError: ('absolute offset is too large', -1440)
An offset of 0 is special-cased to return UTC.
>>> FixedOffset(0) is UTC
True
There should always be only one instance of a FixedOffset per timedelta.
This should be true for multiple creation calls.
>>> FixedOffset(-330) is one
True
>>> FixedOffset(1380) is two
True
It should also be true for pickling.
>>> import pickle
>>> pickle.loads(pickle.dumps(one)) is one
True
>>> pickle.loads(pickle.dumps(two)) is two
True
"""
if offset == 0:
return UTC
info = _tzinfos.get(offset)
if info is None:
# We haven't seen this one before. we need to save it.
# Use setdefault to avoid a race condition and make sure we have
# only one
info = _tzinfos.setdefault(offset, _FixedOffset(offset))
return info
FixedOffset.__safe_for_unpickling__ = True
def _test():
import doctest, os, sys
sys.path.insert(0, os.pardir)
import pytz
return doctest.testmod(pytz)
if __name__ == '__main__':
_test()
all_timezones_unfiltered = \
['Africa/Abidjan',
'Africa/Accra',
'Africa/Addis_Ababa',
'Africa/Algiers',
'Africa/Asmara',
'Africa/Asmera',
'Africa/Bamako',
'Africa/Bangui',
'Africa/Banjul',
'Africa/Bissau',
'Africa/Blantyre',
'Africa/Brazzaville',
'Africa/Bujumbura',
'Africa/Cairo',
'Africa/Casablanca',
'Africa/Ceuta',
'Africa/Conakry',
'Africa/Dakar',
'Africa/Dar_es_Salaam',
'Africa/Djibouti',
'Africa/Douala',
'Africa/El_Aaiun',
'Africa/Freetown',
'Africa/Gaborone',
'Africa/Harare',
'Africa/Johannesburg',
'Africa/Kampala',
'Africa/Khartoum',
'Africa/Kigali',
'Africa/Kinshasa',
'Africa/Lagos',
'Africa/Libreville',
'Africa/Lome',
'Africa/Luanda',
'Africa/Lubumbashi',
'Africa/Lusaka',
'Africa/Malabo',
'Africa/Maputo',
'Africa/Maseru',
'Africa/Mbabane',
'Africa/Mogadishu',
'Africa/Monrovia',
'Africa/Nairobi',
'Africa/Ndjamena',
'Africa/Niamey',
'Africa/Nouakchott',
'Africa/Ouagadougou',
'Africa/Porto-Novo',
'Africa/Sao_Tome',
'Africa/Timbuktu',
'Africa/Tripoli',
'Africa/Tunis',
'Africa/Windhoek',
'America/Adak',
'America/Anchorage',
'America/Anguilla',
'America/Antigua',
'America/Araguaina',
'America/Argentina/Buenos_Aires',
'America/Argentina/Catamarca',
'America/Argentina/ComodRivadavia',
'America/Argentina/Cordoba',
'America/Argentina/Jujuy',
'America/Argentina/La_Rioja',
'America/Argentina/Mendoza',
'America/Argentina/Rio_Gallegos',
'America/Argentina/Salta',
'America/Argentina/San_Juan',
'America/Argentina/San_Luis',
'America/Argentina/Tucuman',
'America/Argentina/Ushuaia',
'America/Aruba',
'America/Asuncion',
'America/Atikokan',
'America/Atka',
'America/Bahia',
'America/Barbados',
'America/Belem',
'America/Belize',
'America/Blanc-Sablon',
'America/Boa_Vista',
'America/Bogota',
'America/Boise',
'America/Buenos_Aires',
'America/Cambridge_Bay',
'America/Campo_Grande',
'America/Cancun',
'America/Caracas',
'America/Catamarca',
'America/Cayenne',
'America/Cayman',
'America/Chicago',
'America/Chihuahua',
'America/Coral_Harbour',
'America/Cordoba',
'America/Costa_Rica',
'America/Cuiaba',
'America/Curacao',
'America/Danmarkshavn',
'America/Dawson',
'America/Dawson_Creek',
'America/Denver',
'America/Detroit',
'America/Dominica',
'America/Edmonton',
'America/Eirunepe',
'America/El_Salvador',
'America/Ensenada',
'America/Fort_Wayne',
'America/Fortaleza',
'America/Glace_Bay',
'America/Godthab',
'America/Goose_Bay',
'America/Grand_Turk',
'America/Grenada',
'America/Guadeloupe',
'America/Guatemala',
'America/Guayaquil',
'America/Guyana',
'America/Halifax',
'America/Havana',
'America/Hermosillo',
'America/Indiana/Indianapolis',
'America/Indiana/Knox',
'America/Indiana/Marengo',
'America/Indiana/Petersburg',
'America/Indiana/Tell_City',
'America/Indiana/Vevay',
'America/Indiana/Vincennes',
'America/Indiana/Winamac',
'America/Indianapolis',
'America/Inuvik',
'America/Iqaluit',
'America/Jamaica',
'America/Jujuy',
'America/Juneau',
'America/Kentucky/Louisville',
'America/Kentucky/Monticello',
'America/Knox_IN',
'America/La_Paz',
'America/Lima',
'America/Los_Angeles',
'America/Louisville',
'America/Maceio',
'America/Managua',
'America/Manaus',
'America/Marigot',
'America/Martinique',
'America/Mazatlan',
'America/Mendoza',
'America/Menominee',
'America/Merida',
'America/Mexico_City',
'America/Miquelon',
'America/Moncton',
'America/Monterrey',
'America/Montevideo',
'America/Montreal',
'America/Montserrat',
'America/Nassau',
'America/New_York',
'America/Nipigon',
'America/Nome',
'America/Noronha',
'America/North_Dakota/Center',
'America/North_Dakota/New_Salem',
'America/Panama',
'America/Pangnirtung',
'America/Paramaribo',
'America/Phoenix',
'America/Port-au-Prince',
'America/Port_of_Spain',
'America/Porto_Acre',
'America/Porto_Velho',
'America/Puerto_Rico',
'America/Rainy_River',
'America/Rankin_Inlet',
'America/Recife',
'America/Regina',
'America/Resolute',
'America/Rio_Branco',
'America/Rosario',
'America/Santarem',
'America/Santiago',
'America/Santo_Domingo',
'America/Sao_Paulo',
'America/Scoresbysund',
'America/Shiprock',
'America/St_Barthelemy',
'America/St_Johns',
'America/St_Kitts',
'America/St_Lucia',
'America/St_Thomas',
'America/St_Vincent',
'America/Swift_Current',
'America/Tegucigalpa',
'America/Thule',
'America/Thunder_Bay',
'America/Tijuana',
'America/Toronto',
'America/Tortola',
'America/Vancouver',
'America/Virgin',
'America/Whitehorse',
'America/Winnipeg',
'America/Yakutat',
'America/Yellowknife',
'Antarctica/Casey',
'Antarctica/Davis',
'Antarctica/DumontDUrville',
'Antarctica/Mawson',
'Antarctica/McMurdo',
'Antarctica/Palmer',
'Antarctica/Rothera',
'Antarctica/South_Pole',
'Antarctica/Syowa',
'Antarctica/Vostok',
'Arctic/Longyearbyen',
'Asia/Aden',
'Asia/Almaty',
'Asia/Amman',
'Asia/Anadyr',
'Asia/Aqtau',
'Asia/Aqtobe',
'Asia/Ashgabat',
'Asia/Ashkhabad',
'Asia/Baghdad',
'Asia/Bahrain',
'Asia/Baku',
'Asia/Bangkok',
'Asia/Beirut',
'Asia/Bishkek',
'Asia/Brunei',
'Asia/Calcutta',
'Asia/Choibalsan',
'Asia/Chongqing',
'Asia/Chungking',
'Asia/Colombo',
'Asia/Dacca',
'Asia/Damascus',
'Asia/Dhaka',
'Asia/Dili',
'Asia/Dubai',
'Asia/Dushanbe',
'Asia/Gaza',
'Asia/Harbin',
'Asia/Ho_Chi_Minh',
'Asia/Hong_Kong',
'Asia/Hovd',
'Asia/Irkutsk',
'Asia/Istanbul',
'Asia/Jakarta',
'Asia/Jayapura',
'Asia/Jerusalem',
'Asia/Kabul',
'Asia/Kamchatka',
'Asia/Karachi',
'Asia/Kashgar',
'Asia/Kathmandu',
'Asia/Katmandu',
'Asia/Kolkata',
'Asia/Krasnoyarsk',
'Asia/Kuala_Lumpur',
'Asia/Kuching',
'Asia/Kuwait',
'Asia/Macao',
'Asia/Macau',
'Asia/Magadan',
'Asia/Makassar',
'Asia/Manila',
'Asia/Muscat',
'Asia/Nicosia',
'Asia/Novokuznetsk',
'Asia/Novosibirsk',
'Asia/Omsk',
'Asia/Oral',
'Asia/Phnom_Penh',
'Asia/Pontianak',
'Asia/Pyongyang',
'Asia/Qatar',
'Asia/Qyzylorda',
'Asia/Rangoon',
'Asia/Riyadh',
'Asia/Saigon',
'Asia/Sakhalin',
'Asia/Samarkand',
'Asia/Seoul',
'Asia/Shanghai',
'Asia/Singapore',
'Asia/Taipei',
'Asia/Tashkent',
'Asia/Tbilisi',
'Asia/Tehran',
'Asia/Tel_Aviv',
'Asia/Thimbu',
'Asia/Thimphu',
'Asia/Tokyo',
'Asia/Ujung_Pandang',
'Asia/Ulaanbaatar',
'Asia/Ulan_Bator',
'Asia/Urumqi',
'Asia/Vientiane',
'Asia/Vladivostok',
'Asia/Yakutsk',
'Asia/Yekaterinburg',
'Asia/Yerevan',
'Atlantic/Azores',
'Atlantic/Bermuda',
'Atlantic/Canary',
'Atlantic/Cape_Verde',
'Atlantic/Faeroe',
'Atlantic/Faroe',
'Atlantic/Jan_Mayen',
'Atlantic/Madeira',
'Atlantic/Reykjavik',
'Atlantic/South_Georgia',
'Atlantic/St_Helena',
'Atlantic/Stanley',
'Australia/ACT',
'Australia/Adelaide',
'Australia/Brisbane',
'Australia/Broken_Hill',
'Australia/Canberra',
'Australia/Currie',
'Australia/Darwin',
'Australia/Eucla',
'Australia/Hobart',
'Australia/LHI',
'Australia/Lindeman',
'Australia/Lord_Howe',
'Australia/Melbourne',
'Australia/NSW',
'Australia/North',
'Australia/Perth',
'Australia/Queensland',
'Australia/South',
'Australia/Sydney',
'Australia/Tasmania',
'Australia/Victoria',
'Australia/West',
'Australia/Yancowinna',
'Brazil/Acre',
'Brazil/DeNoronha',
'Brazil/East',
'Brazil/West',
'CET',
'CST6CDT',
'Canada/Atlantic',
'Canada/Central',
'Canada/East-Saskatchewan',
'Canada/Eastern',
'Canada/Mountain',
'Canada/Newfoundland',
'Canada/Pacific',
'Canada/Saskatchewan',
'Canada/Yukon',
'Chile/Continental',
'Chile/EasterIsland',
'Cuba',
'EET',
'EST',
'EST5EDT',
'Egypt',
'Eire',
'Etc/GMT',
'Etc/GMT+0',
'Etc/GMT+1',
'Etc/GMT+10',
'Etc/GMT+11',
'Etc/GMT+12',
'Etc/GMT+2',
'Etc/GMT+3',
'Etc/GMT+4',
'Etc/GMT+5',
'Etc/GMT+6',
'Etc/GMT+7',
'Etc/GMT+8',
'Etc/GMT+9',
'Etc/GMT-0',
'Etc/GMT-1',
'Etc/GMT-10',
'Etc/GMT-11',
'Etc/GMT-12',
'Etc/GMT-13',
'Etc/GMT-14',
'Etc/GMT-2',
'Etc/GMT-3',
'Etc/GMT-4',
'Etc/GMT-5',
'Etc/GMT-6',
'Etc/GMT-7',
'Etc/GMT-8',
'Etc/GMT-9',
'Etc/GMT0',
'Etc/Greenwich',
'Etc/UCT',
'Etc/UTC',
'Etc/Universal',
'Etc/Zulu',
'Europe/Amsterdam',
'Europe/Andorra',
'Europe/Athens',
'Europe/Belfast',
'Europe/Belgrade',
'Europe/Berlin',
'Europe/Bratislava',
'Europe/Brussels',
'Europe/Bucharest',
'Europe/Budapest',
'Europe/Chisinau',
'Europe/Copenhagen',
'Europe/Dublin',
'Europe/Gibraltar',
'Europe/Guernsey',
'Europe/Helsinki',
'Europe/Isle_of_Man',
'Europe/Istanbul',
'Europe/Jersey',
'Europe/Kaliningrad',
'Europe/Kiev',
'Europe/Lisbon',
'Europe/Ljubljana',
'Europe/London',
'Europe/Luxembourg',
'Europe/Madrid',
'Europe/Malta',
'Europe/Mariehamn',
'Europe/Minsk',
'Europe/Monaco',
'Europe/Moscow',
'Europe/Nicosia',
'Europe/Oslo',
'Europe/Paris',
'Europe/Podgorica',
'Europe/Prague',
'Europe/Riga',
'Europe/Rome',
'Europe/Samara',
'Europe/San_Marino',
'Europe/Sarajevo',
'Europe/Simferopol',
'Europe/Skopje',
'Europe/Sofia',
'Europe/Stockholm',
'Europe/Tallinn',
'Europe/Tirane',
'Europe/Tiraspol',
'Europe/Uzhgorod',
'Europe/Vaduz',
'Europe/Vatican',
'Europe/Vienna',
'Europe/Vilnius',
'Europe/Volgograd',
'Europe/Warsaw',
'Europe/Zagreb',
'Europe/Zaporozhye',
'Europe/Zurich',
'GB',
'GB-Eire',
'GMT',
'GMT+0',
'GMT-0',
'GMT0',
'Greenwich',
'HST',
'Hongkong',
'Iceland',
'Indian/Antananarivo',
'Indian/Chagos',
'Indian/Christmas',
'Indian/Cocos',
'Indian/Comoro',
'Indian/Kerguelen',
'Indian/Mahe',
'Indian/Maldives',
'Indian/Mauritius',
'Indian/Mayotte',
'Indian/Reunion',
'Iran',
'Israel',
'Jamaica',
'Japan',
'Kwajalein',
'Libya',
'MET',
'MST',
'MST7MDT',
'Mexico/BajaNorte',
'Mexico/BajaSur',
'Mexico/General',
'NZ',
'NZ-CHAT',
'Navajo',
'PRC',
'PST8PDT',
'Pacific/Apia',
'Pacific/Auckland',
'Pacific/Chatham',
'Pacific/Easter',
'Pacific/Efate',
'Pacific/Enderbury',
'Pacific/Fakaofo',
'Pacific/Fiji',
'Pacific/Funafuti',
'Pacific/Galapagos',
'Pacific/Gambier',
'Pacific/Guadalcanal',
'Pacific/Guam',
'Pacific/Honolulu',
'Pacific/Johnston',
'Pacific/Kiritimati',
'Pacific/Kosrae',
'Pacific/Kwajalein',
'Pacific/Majuro',
'Pacific/Marquesas',
'Pacific/Midway',
'Pacific/Nauru',
'Pacific/Niue',
'Pacific/Norfolk',
'Pacific/Noumea',
'Pacific/Pago_Pago',
'Pacific/Palau',
'Pacific/Pitcairn',
'Pacific/Ponape',
'Pacific/Port_Moresby',
'Pacific/Rarotonga',
'Pacific/Saipan',
'Pacific/Samoa',
'Pacific/Tahiti',
'Pacific/Tarawa',
'Pacific/Tongatapu',
'Pacific/Truk',
'Pacific/Wake',
'Pacific/Wallis',
'Pacific/Yap',
'Poland',
'Portugal',
'ROC',
'ROK',
'Singapore',
'Turkey',
'UCT',
'US/Alaska',
'US/Aleutian',
'US/Arizona',
'US/Central',
'US/East-Indiana',
'US/Eastern',
'US/Hawaii',
'US/Indiana-Starke',
'US/Michigan',
'US/Mountain',
'US/Pacific',
'US/Pacific-New',
'US/Samoa',
'UTC',
'Universal',
'W-SU',
'WET',
'Zulu']
all_timezones = _LazyList(
lambda: filter(resource_exists, all_timezones_unfiltered)
)
all_timezones_set = set(all_timezones_unfiltered) # XXX
common_timezones_unfiltered = \
['Africa/Abidjan',
'Africa/Accra',
'Africa/Addis_Ababa',
'Africa/Algiers',
'Africa/Asmara',
'Africa/Bamako',
'Africa/Bangui',
'Africa/Banjul',
'Africa/Bissau',
'Africa/Blantyre',
'Africa/Brazzaville',
'Africa/Bujumbura',
'Africa/Cairo',
'Africa/Casablanca',
'Africa/Ceuta',
'Africa/Conakry',
'Africa/Dakar',
'Africa/Dar_es_Salaam',
'Africa/Djibouti',
'Africa/Douala',
'Africa/El_Aaiun',
'Africa/Freetown',
'Africa/Gaborone',
'Africa/Harare',
'Africa/Johannesburg',
'Africa/Kampala',
'Africa/Khartoum',
'Africa/Kigali',
'Africa/Kinshasa',
'Africa/Lagos',
'Africa/Libreville',
'Africa/Lome',
'Africa/Luanda',
'Africa/Lubumbashi',
'Africa/Lusaka',
'Africa/Malabo',
'Africa/Maputo',
'Africa/Maseru',
'Africa/Mbabane',
'Africa/Mogadishu',
'Africa/Monrovia',
'Africa/Nairobi',
'Africa/Ndjamena',
'Africa/Niamey',
'Africa/Nouakchott',
'Africa/Ouagadougou',
'Africa/Porto-Novo',
'Africa/Sao_Tome',
'Africa/Tripoli',
'Africa/Tunis',
'Africa/Windhoek',
'America/Adak',
'America/Anchorage',
'America/Anguilla',
'America/Antigua',
'America/Araguaina',
'America/Argentina/Buenos_Aires',
'America/Argentina/Catamarca',
'America/Argentina/Cordoba',
'America/Argentina/Jujuy',
'America/Argentina/La_Rioja',
'America/Argentina/Mendoza',
'America/Argentina/Rio_Gallegos',
'America/Argentina/Salta',
'America/Argentina/San_Juan',
'America/Argentina/San_Luis',
'America/Argentina/Tucuman',
'America/Argentina/Ushuaia',
'America/Aruba',
'America/Asuncion',
'America/Atikokan',
'America/Bahia',
'America/Barbados',
'America/Belem',
'America/Belize',
'America/Blanc-Sablon',
'America/Boa_Vista',
'America/Bogota',
'America/Boise',
'America/Cambridge_Bay',
'America/Campo_Grande',
'America/Cancun',
'America/Caracas',
'America/Cayenne',
'America/Cayman',
'America/Chicago',
'America/Chihuahua',
'America/Costa_Rica',
'America/Cuiaba',
'America/Curacao',
'America/Danmarkshavn',
'America/Dawson',
'America/Dawson_Creek',
'America/Denver',
'America/Detroit',
'America/Dominica',
'America/Edmonton',
'America/Eirunepe',
'America/El_Salvador',
'America/Fortaleza',
'America/Glace_Bay',
'America/Godthab',
'America/Goose_Bay',
'America/Grand_Turk',
'America/Grenada',
'America/Guadeloupe',
'America/Guatemala',
'America/Guayaquil',
'America/Guyana',
'America/Halifax',
'America/Havana',
'America/Hermosillo',
'America/Indiana/Indianapolis',
'America/Indiana/Knox',
'America/Indiana/Marengo',
'America/Indiana/Petersburg',
'America/Indiana/Tell_City',
'America/Indiana/Vevay',
'America/Indiana/Vincennes',
'America/Indiana/Winamac',
'America/Inuvik',
'America/Iqaluit',
'America/Jamaica',
'America/Juneau',
'America/Kentucky/Louisville',
'America/Kentucky/Monticello',
'America/La_Paz',
'America/Lima',
'America/Los_Angeles',
'America/Maceio',
'America/Managua',
'America/Manaus',
'America/Martinique',
'America/Mazatlan',
'America/Menominee',
'America/Merida',
'America/Mexico_City',
'America/Miquelon',
'America/Moncton',
'America/Monterrey',
'America/Montevideo',
'America/Montreal',
'America/Montserrat',
'America/Nassau',
'America/New_York',
'America/Nipigon',
'America/Nome',
'America/Noronha',
'America/North_Dakota/Center',
'America/North_Dakota/New_Salem',
'America/Panama',
'America/Pangnirtung',
'America/Paramaribo',
'America/Phoenix',
'America/Port-au-Prince',
'America/Port_of_Spain',
'America/Porto_Velho',
'America/Puerto_Rico',
'America/Rainy_River',
'America/Rankin_Inlet',
'America/Recife',
'America/Regina',
'America/Resolute',
'America/Rio_Branco',
'America/Santarem',
'America/Santiago',
'America/Santo_Domingo',
'America/Sao_Paulo',
'America/Scoresbysund',
'America/St_Johns',
'America/St_Kitts',
'America/St_Lucia',
'America/St_Thomas',
'America/St_Vincent',
'America/Swift_Current',
'America/Tegucigalpa',
'America/Thule',
'America/Thunder_Bay',
'America/Tijuana',
'America/Toronto',
'America/Tortola',
'America/Vancouver',
'America/Whitehorse',
'America/Winnipeg',
'America/Yakutat',
'America/Yellowknife',
'Antarctica/Casey',
'Antarctica/Davis',
'Antarctica/DumontDUrville',
'Antarctica/Mawson',
'Antarctica/McMurdo',
'Antarctica/Palmer',
'Antarctica/Rothera',
'Antarctica/Syowa',
'Antarctica/Vostok',
'Asia/Aden',
'Asia/Almaty',
'Asia/Amman',
'Asia/Anadyr',
'Asia/Aqtau',
'Asia/Aqtobe',
'Asia/Ashgabat',
'Asia/Baghdad',
'Asia/Bahrain',
'Asia/Baku',
'Asia/Bangkok',
'Asia/Beirut',
'Asia/Bishkek',
'Asia/Brunei',
'Asia/Choibalsan',
'Asia/Chongqing',
'Asia/Colombo',
'Asia/Damascus',
'Asia/Dhaka',
'Asia/Dili',
'Asia/Dubai',
'Asia/Dushanbe',
'Asia/Gaza',
'Asia/Harbin',
'Asia/Ho_Chi_Minh',
'Asia/Hong_Kong',
'Asia/Hovd',
'Asia/Irkutsk',
'Asia/Jakarta',
'Asia/Jayapura',
'Asia/Jerusalem',
'Asia/Kabul',
'Asia/Kamchatka',
'Asia/Karachi',
'Asia/Kashgar',
'Asia/Kathmandu',
'Asia/Kolkata',
'Asia/Krasnoyarsk',
'Asia/Kuala_Lumpur',
'Asia/Kuching',
'Asia/Kuwait',
'Asia/Macau',
'Asia/Magadan',
'Asia/Makassar',
'Asia/Manila',
'Asia/Muscat',
'Asia/Nicosia',
'Asia/Novokuznetsk',
'Asia/Novosibirsk',
'Asia/Omsk',
'Asia/Oral',
'Asia/Phnom_Penh',
'Asia/Pontianak',
'Asia/Pyongyang',
'Asia/Qatar',
'Asia/Qyzylorda',
'Asia/Rangoon',
'Asia/Riyadh',
'Asia/Sakhalin',
'Asia/Samarkand',
'Asia/Seoul',
'Asia/Shanghai',
'Asia/Singapore',
'Asia/Taipei',
'Asia/Tashkent',
'Asia/Tbilisi',
'Asia/Tehran',
'Asia/Thimphu',
'Asia/Tokyo',
'Asia/Ulaanbaatar',
'Asia/Urumqi',
'Asia/Vientiane',
'Asia/Vladivostok',
'Asia/Yakutsk',
'Asia/Yekaterinburg',
'Asia/Yerevan',
'Atlantic/Azores',
'Atlantic/Bermuda',
'Atlantic/Canary',
'Atlantic/Cape_Verde',
'Atlantic/Faroe',
'Atlantic/Madeira',
'Atlantic/Reykjavik',
'Atlantic/South_Georgia',
'Atlantic/St_Helena',
'Atlantic/Stanley',
'Australia/Adelaide',
'Australia/Brisbane',
'Australia/Broken_Hill',
'Australia/Currie',
'Australia/Darwin',
'Australia/Eucla',
'Australia/Hobart',
'Australia/Lindeman',
'Australia/Lord_Howe',
'Australia/Melbourne',
'Australia/Perth',
'Australia/Sydney',
'Europe/Amsterdam',
'Europe/Andorra',
'Europe/Athens',
'Europe/Belgrade',
'Europe/Berlin',
'Europe/Brussels',
'Europe/Bucharest',
'Europe/Budapest',
'Europe/Chisinau',
'Europe/Copenhagen',
'Europe/Dublin',
'Europe/Gibraltar',
'Europe/Helsinki',
'Europe/Istanbul',
'Europe/Kaliningrad',
'Europe/Kiev',
'Europe/Lisbon',
'Europe/London',
'Europe/Luxembourg',
'Europe/Madrid',
'Europe/Malta',
'Europe/Minsk',
'Europe/Monaco',
'Europe/Moscow',
'Europe/Oslo',
'Europe/Paris',
'Europe/Prague',
'Europe/Riga',
'Europe/Rome',
'Europe/Samara',
'Europe/Simferopol',
'Europe/Sofia',
'Europe/Stockholm',
'Europe/Tallinn',
'Europe/Tirane',
'Europe/Uzhgorod',
'Europe/Vaduz',
'Europe/Vienna',
'Europe/Vilnius',
'Europe/Volgograd',
'Europe/Warsaw',
'Europe/Zaporozhye',
'Europe/Zurich',
'GMT',
'Indian/Antananarivo',
'Indian/Chagos',
'Indian/Christmas',
'Indian/Cocos',
'Indian/Comoro',
'Indian/Kerguelen',
'Indian/Mahe',
'Indian/Maldives',
'Indian/Mauritius',
'Indian/Mayotte',
'Indian/Reunion',
'Pacific/Apia',
'Pacific/Auckland',
'Pacific/Chatham',
'Pacific/Easter',
'Pacific/Efate',
'Pacific/Enderbury',
'Pacific/Fakaofo',
'Pacific/Fiji',
'Pacific/Funafuti',
'Pacific/Galapagos',
'Pacific/Gambier',
'Pacific/Guadalcanal',
'Pacific/Guam',
'Pacific/Honolulu',
'Pacific/Johnston',
'Pacific/Kiritimati',
'Pacific/Kosrae',
'Pacific/Kwajalein',
'Pacific/Majuro',
'Pacific/Marquesas',
'Pacific/Midway',
'Pacific/Nauru',
'Pacific/Niue',
'Pacific/Norfolk',
'Pacific/Noumea',
'Pacific/Pago_Pago',
'Pacific/Palau',
'Pacific/Pitcairn',
'Pacific/Ponape',
'Pacific/Port_Moresby',
'Pacific/Rarotonga',
'Pacific/Saipan',
'Pacific/Tahiti',
'Pacific/Tarawa',
'Pacific/Tongatapu',
'Pacific/Truk',
'Pacific/Wake',
'Pacific/Wallis',
'US/Alaska',
'US/Arizona',
'US/Central',
'US/Eastern',
'US/Hawaii',
'US/Mountain',
'US/Pacific',
'UTC']
common_timezones = _LazyList(
lambda: filter(resource_exists, common_timezones_unfiltered)
)
common_timezones_set = set(common_timezones_unfiltered) # XXX
| Python |
'''Base classes and helpers for building zone specific tzinfo classes'''
from datetime import datetime, timedelta, tzinfo
from bisect import bisect_right
try:
set
except NameError:
from sets import Set as set
import pytz
__all__ = []
_timedelta_cache = {}
def memorized_timedelta(seconds):
'''Create only one instance of each distinct timedelta'''
try:
return _timedelta_cache[seconds]
except KeyError:
delta = timedelta(seconds=seconds)
_timedelta_cache[seconds] = delta
return delta
_epoch = datetime.utcfromtimestamp(0)
_datetime_cache = {0: _epoch}
def memorized_datetime(seconds):
'''Create only one instance of each distinct datetime'''
try:
return _datetime_cache[seconds]
except KeyError:
# NB. We can't just do datetime.utcfromtimestamp(seconds) as this
# fails with negative values under Windows (Bug #90096)
dt = _epoch + timedelta(seconds=seconds)
_datetime_cache[seconds] = dt
return dt
_ttinfo_cache = {}
def memorized_ttinfo(*args):
'''Create only one instance of each distinct tuple'''
try:
return _ttinfo_cache[args]
except KeyError:
ttinfo = (
memorized_timedelta(args[0]),
memorized_timedelta(args[1]),
args[2]
)
_ttinfo_cache[args] = ttinfo
return ttinfo
_notime = memorized_timedelta(0)
def _to_seconds(td):
'''Convert a timedelta to seconds'''
return td.seconds + td.days * 24 * 60 * 60
class BaseTzInfo(tzinfo):
# Overridden in subclass
_utcoffset = None
_tzname = None
zone = None
def __str__(self):
return self.zone
class StaticTzInfo(BaseTzInfo):
'''A timezone that has a constant offset from UTC
These timezones are rare, as most locations have changed their
offset at some point in their history
'''
def fromutc(self, dt):
'''See datetime.tzinfo.fromutc'''
return (dt + self._utcoffset).replace(tzinfo=self)
def utcoffset(self,dt):
'''See datetime.tzinfo.utcoffset'''
return self._utcoffset
def dst(self,dt):
'''See datetime.tzinfo.dst'''
return _notime
def tzname(self,dt):
'''See datetime.tzinfo.tzname'''
return self._tzname
def localize(self, dt, is_dst=False):
'''Convert naive time to local time'''
if dt.tzinfo is not None:
raise ValueError, 'Not naive datetime (tzinfo is already set)'
return dt.replace(tzinfo=self)
def normalize(self, dt, is_dst=False):
'''Correct the timezone information on the given datetime'''
if dt.tzinfo is None:
raise ValueError, 'Naive time - no tzinfo set'
return dt.replace(tzinfo=self)
def __repr__(self):
return '<StaticTzInfo %r>' % (self.zone,)
def __reduce__(self):
# Special pickle to zone remains a singleton and to cope with
# database changes.
return pytz._p, (self.zone,)
class DstTzInfo(BaseTzInfo):
'''A timezone that has a variable offset from UTC
The offset might change if daylight savings time comes into effect,
or at a point in history when the region decides to change their
timezone definition.
'''
# Overridden in subclass
_utc_transition_times = None # Sorted list of DST transition times in UTC
_transition_info = None # [(utcoffset, dstoffset, tzname)] corresponding
# to _utc_transition_times entries
zone = None
# Set in __init__
_tzinfos = None
_dst = None # DST offset
def __init__(self, _inf=None, _tzinfos=None):
if _inf:
self._tzinfos = _tzinfos
self._utcoffset, self._dst, self._tzname = _inf
else:
_tzinfos = {}
self._tzinfos = _tzinfos
self._utcoffset, self._dst, self._tzname = self._transition_info[0]
_tzinfos[self._transition_info[0]] = self
for inf in self._transition_info[1:]:
if not _tzinfos.has_key(inf):
_tzinfos[inf] = self.__class__(inf, _tzinfos)
def fromutc(self, dt):
'''See datetime.tzinfo.fromutc'''
dt = dt.replace(tzinfo=None)
idx = max(0, bisect_right(self._utc_transition_times, dt) - 1)
inf = self._transition_info[idx]
return (dt + inf[0]).replace(tzinfo=self._tzinfos[inf])
def normalize(self, dt):
'''Correct the timezone information on the given datetime
If date arithmetic crosses DST boundaries, the tzinfo
is not magically adjusted. This method normalizes the
tzinfo to the correct one.
To test, first we need to do some setup
>>> from pytz import timezone
>>> utc = timezone('UTC')
>>> eastern = timezone('US/Eastern')
>>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'
We next create a datetime right on an end-of-DST transition point,
the instant when the wallclocks are wound back one hour.
>>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
>>> loc_dt = utc_dt.astimezone(eastern)
>>> loc_dt.strftime(fmt)
'2002-10-27 01:00:00 EST (-0500)'
Now, if we subtract a few minutes from it, note that the timezone
information has not changed.
>>> before = loc_dt - timedelta(minutes=10)
>>> before.strftime(fmt)
'2002-10-27 00:50:00 EST (-0500)'
But we can fix that by calling the normalize method
>>> before = eastern.normalize(before)
>>> before.strftime(fmt)
'2002-10-27 01:50:00 EDT (-0400)'
'''
if dt.tzinfo is None:
raise ValueError, 'Naive time - no tzinfo set'
# Convert dt in localtime to UTC
offset = dt.tzinfo._utcoffset
dt = dt.replace(tzinfo=None)
dt = dt - offset
# convert it back, and return it
return self.fromutc(dt)
def localize(self, dt, is_dst=False):
'''Convert naive time to local time.
This method should be used to construct localtimes, rather
than passing a tzinfo argument to a datetime constructor.
is_dst is used to determine the correct timezone in the ambigous
period at the end of daylight savings time.
>>> from pytz import timezone
>>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'
>>> amdam = timezone('Europe/Amsterdam')
>>> dt = datetime(2004, 10, 31, 2, 0, 0)
>>> loc_dt1 = amdam.localize(dt, is_dst=True)
>>> loc_dt2 = amdam.localize(dt, is_dst=False)
>>> loc_dt1.strftime(fmt)
'2004-10-31 02:00:00 CEST (+0200)'
>>> loc_dt2.strftime(fmt)
'2004-10-31 02:00:00 CET (+0100)'
>>> str(loc_dt2 - loc_dt1)
'1:00:00'
Use is_dst=None to raise an AmbiguousTimeError for ambiguous
times at the end of daylight savings
>>> loc_dt1 = amdam.localize(dt, is_dst=None)
Traceback (most recent call last):
[...]
AmbiguousTimeError: 2004-10-31 02:00:00
is_dst defaults to False
>>> amdam.localize(dt) == amdam.localize(dt, False)
True
is_dst is also used to determine the correct timezone in the
wallclock times jumped over at the start of daylight savings time.
>>> pacific = timezone('US/Pacific')
>>> dt = datetime(2008, 3, 9, 2, 0, 0)
>>> ploc_dt1 = pacific.localize(dt, is_dst=True)
>>> ploc_dt2 = pacific.localize(dt, is_dst=False)
>>> ploc_dt1.strftime(fmt)
'2008-03-09 02:00:00 PDT (-0700)'
>>> ploc_dt2.strftime(fmt)
'2008-03-09 02:00:00 PST (-0800)'
>>> str(ploc_dt2 - ploc_dt1)
'1:00:00'
Use is_dst=None to raise a NonExistentTimeError for these skipped
times.
>>> loc_dt1 = pacific.localize(dt, is_dst=None)
Traceback (most recent call last):
[...]
NonExistentTimeError: 2008-03-09 02:00:00
'''
if dt.tzinfo is not None:
raise ValueError, 'Not naive datetime (tzinfo is already set)'
# Find the two best possibilities.
possible_loc_dt = set()
for delta in [timedelta(days=-1), timedelta(days=1)]:
loc_dt = dt + delta
idx = max(0, bisect_right(
self._utc_transition_times, loc_dt) - 1)
inf = self._transition_info[idx]
tzinfo = self._tzinfos[inf]
loc_dt = tzinfo.normalize(dt.replace(tzinfo=tzinfo))
if loc_dt.replace(tzinfo=None) == dt:
possible_loc_dt.add(loc_dt)
if len(possible_loc_dt) == 1:
return possible_loc_dt.pop()
# If there are no possibly correct timezones, we are attempting
# to convert a time that never happened - the time period jumped
# during the start-of-DST transition period.
if len(possible_loc_dt) == 0:
# If we refuse to guess, raise an exception.
if is_dst is None:
raise NonExistentTimeError(dt)
# If we are forcing the pre-DST side of the DST transition, we
# obtain the correct timezone by winding the clock forward a few
# hours.
elif is_dst:
return self.localize(
dt + timedelta(hours=6), is_dst=True) - timedelta(hours=6)
# If we are forcing the post-DST side of the DST transition, we
# obtain the correct timezone by winding the clock back.
else:
return self.localize(
dt - timedelta(hours=6), is_dst=False) + timedelta(hours=6)
# If we get this far, we have multiple possible timezones - this
# is an ambiguous case occuring during the end-of-DST transition.
# If told to be strict, raise an exception since we have an
# ambiguous case
if is_dst is None:
raise AmbiguousTimeError(dt)
# Filter out the possiblilities that don't match the requested
# is_dst
filtered_possible_loc_dt = [
p for p in possible_loc_dt
if bool(p.tzinfo._dst) == is_dst
]
# Hopefully we only have one possibility left. Return it.
if len(filtered_possible_loc_dt) == 1:
return filtered_possible_loc_dt[0]
if len(filtered_possible_loc_dt) == 0:
filtered_possible_loc_dt = list(possible_loc_dt)
# If we get this far, we have in a wierd timezone transition
# where the clocks have been wound back but is_dst is the same
# in both (eg. Europe/Warsaw 1915 when they switched to CET).
# At this point, we just have to guess unless we allow more
# hints to be passed in (such as the UTC offset or abbreviation),
# but that is just getting silly.
#
# Choose the earliest (by UTC) applicable timezone.
def mycmp(a,b):
return cmp(
a.replace(tzinfo=None) - a.tzinfo._utcoffset,
b.replace(tzinfo=None) - b.tzinfo._utcoffset,
)
filtered_possible_loc_dt.sort(mycmp)
return filtered_possible_loc_dt[0]
def utcoffset(self, dt):
'''See datetime.tzinfo.utcoffset'''
return self._utcoffset
def dst(self, dt):
'''See datetime.tzinfo.dst'''
return self._dst
def tzname(self, dt):
'''See datetime.tzinfo.tzname'''
return self._tzname
def __repr__(self):
if self._dst:
dst = 'DST'
else:
dst = 'STD'
if self._utcoffset > _notime:
return '<DstTzInfo %r %s+%s %s>' % (
self.zone, self._tzname, self._utcoffset, dst
)
else:
return '<DstTzInfo %r %s%s %s>' % (
self.zone, self._tzname, self._utcoffset, dst
)
def __reduce__(self):
# Special pickle to zone remains a singleton and to cope with
# database changes.
return pytz._p, (
self.zone,
_to_seconds(self._utcoffset),
_to_seconds(self._dst),
self._tzname
)
class InvalidTimeError(Exception):
'''Base class for invalid time exceptions.'''
class AmbiguousTimeError(InvalidTimeError):
'''Exception raised when attempting to create an ambiguous wallclock time.
At the end of a DST transition period, a particular wallclock time will
occur twice (once before the clocks are set back, once after). Both
possibilities may be correct, unless further information is supplied.
See DstTzInfo.normalize() for more info
'''
class NonExistentTimeError(InvalidTimeError):
'''Exception raised when attempting to create a wallclock time that
cannot exist.
At the start of a DST transition period, the wallclock time jumps forward.
The instants jumped over never occur.
'''
def unpickler(zone, utcoffset=None, dstoffset=None, tzname=None):
"""Factory function for unpickling pytz tzinfo instances.
This is shared for both StaticTzInfo and DstTzInfo instances, because
database changes could cause a zones implementation to switch between
these two base classes and we can't break pickles on a pytz version
upgrade.
"""
# Raises a KeyError if zone no longer exists, which should never happen
# and would be a bug.
tz = pytz.timezone(zone)
# A StaticTzInfo - just return it
if utcoffset is None:
return tz
# This pickle was created from a DstTzInfo. We need to
# determine which of the list of tzinfo instances for this zone
# to use in order to restore the state of any datetime instances using
# it correctly.
utcoffset = memorized_timedelta(utcoffset)
dstoffset = memorized_timedelta(dstoffset)
try:
return tz._tzinfos[(utcoffset, dstoffset, tzname)]
except KeyError:
# The particular state requested in this timezone no longer exists.
# This indicates a corrupt pickle, or the timezone database has been
# corrected violently enough to make this particular
# (utcoffset,dstoffset) no longer exist in the zone, or the
# abbreviation has been changed.
pass
# See if we can find an entry differing only by tzname. Abbreviations
# get changed from the initial guess by the database maintainers to
# match reality when this information is discovered.
for localized_tz in tz._tzinfos.values():
if (localized_tz._utcoffset == utcoffset
and localized_tz._dst == dstoffset):
return localized_tz
# This (utcoffset, dstoffset) information has been removed from the
# zone. Add it back. This might occur when the database maintainers have
# corrected incorrect information. datetime instances using this
# incorrect information will continue to do so, exactly as they were
# before being pickled. This is purely an overly paranoid safety net - I
# doubt this will ever been needed in real life.
inf = (utcoffset, dstoffset, tzname)
tz._tzinfos[inf] = tz.__class__(inf, tz._tzinfos)
return tz._tzinfos[inf]
| Python |
#!/usr/bin/env python
'''
$Id: tzfile.py,v 1.8 2004/06/03 00:15:24 zenzen Exp $
'''
from cStringIO import StringIO
from datetime import datetime, timedelta
from struct import unpack, calcsize
from pytz.tzinfo import StaticTzInfo, DstTzInfo, memorized_ttinfo
from pytz.tzinfo import memorized_datetime, memorized_timedelta
def build_tzinfo(zone, fp):
head_fmt = '>4s c 15x 6l'
head_size = calcsize(head_fmt)
(magic, format, ttisgmtcnt, ttisstdcnt,leapcnt, timecnt,
typecnt, charcnt) = unpack(head_fmt, fp.read(head_size))
# Make sure it is a tzfile(5) file
assert magic == 'TZif'
# Read out the transition times, localtime indices and ttinfo structures.
data_fmt = '>%(timecnt)dl %(timecnt)dB %(ttinfo)s %(charcnt)ds' % dict(
timecnt=timecnt, ttinfo='lBB'*typecnt, charcnt=charcnt)
data_size = calcsize(data_fmt)
data = unpack(data_fmt, fp.read(data_size))
# make sure we unpacked the right number of values
assert len(data) == 2 * timecnt + 3 * typecnt + 1
transitions = [memorized_datetime(trans)
for trans in data[:timecnt]]
lindexes = list(data[timecnt:2 * timecnt])
ttinfo_raw = data[2 * timecnt:-1]
tznames_raw = data[-1]
del data
# Process ttinfo into separate structs
ttinfo = []
tznames = {}
i = 0
while i < len(ttinfo_raw):
# have we looked up this timezone name yet?
tzname_offset = ttinfo_raw[i+2]
if tzname_offset not in tznames:
nul = tznames_raw.find('\0', tzname_offset)
if nul < 0:
nul = len(tznames_raw)
tznames[tzname_offset] = tznames_raw[tzname_offset:nul]
ttinfo.append((ttinfo_raw[i],
bool(ttinfo_raw[i+1]),
tznames[tzname_offset]))
i += 3
# Now build the timezone object
if len(transitions) == 0:
ttinfo[0][0], ttinfo[0][2]
cls = type(zone, (StaticTzInfo,), dict(
zone=zone,
_utcoffset=memorized_timedelta(ttinfo[0][0]),
_tzname=ttinfo[0][2]))
else:
# Early dates use the first standard time ttinfo
i = 0
while ttinfo[i][1]:
i += 1
if ttinfo[i] == ttinfo[lindexes[0]]:
transitions[0] = datetime.min
else:
transitions.insert(0, datetime.min)
lindexes.insert(0, i)
# calculate transition info
transition_info = []
for i in range(len(transitions)):
inf = ttinfo[lindexes[i]]
utcoffset = inf[0]
if not inf[1]:
dst = 0
else:
for j in range(i-1, -1, -1):
prev_inf = ttinfo[lindexes[j]]
if not prev_inf[1]:
break
dst = inf[0] - prev_inf[0] # dst offset
if dst <= 0: # Bad dst? Look further.
for j in range(i+1, len(transitions)):
stdinf = ttinfo[lindexes[j]]
if not stdinf[1]:
dst = inf[0] - stdinf[0]
if dst > 0:
break # Found a useful std time.
tzname = inf[2]
# Round utcoffset and dst to the nearest minute or the
# datetime library will complain. Conversions to these timezones
# might be up to plus or minus 30 seconds out, but it is
# the best we can do.
utcoffset = int((utcoffset + 30) / 60) * 60
dst = int((dst + 30) / 60) * 60
transition_info.append(memorized_ttinfo(utcoffset, dst, tzname))
cls = type(zone, (DstTzInfo,), dict(
zone=zone,
_utc_transition_times=transitions,
_transition_info=transition_info))
return cls()
if __name__ == '__main__':
import os.path
from pprint import pprint
base = os.path.join(os.path.dirname(__file__), 'zoneinfo')
tz = build_tzinfo('Australia/Melbourne',
open(os.path.join(base,'Australia','Melbourne'), 'rb'))
tz = build_tzinfo('US/Eastern',
open(os.path.join(base,'US','Eastern'), 'rb'))
pprint(tz._utc_transition_times)
#print tz.asPython(4)
#print tz.transitions_mapping
| Python |
# A reaction to: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/552751
from webob import Request, Response
from webob import exc
from simplejson import loads, dumps
import traceback
import sys
class JsonRpcApp(object):
"""
Serve the given object via json-rpc (http://json-rpc.org/)
"""
def __init__(self, obj):
self.obj = obj
def __call__(self, environ, start_response):
req = Request(environ)
try:
resp = self.process(req)
except ValueError, e:
resp = exc.HTTPBadRequest(str(e))
except exc.HTTPException, e:
resp = e
return resp(environ, start_response)
def process(self, req):
if not req.method == 'POST':
raise exc.HTTPMethodNotAllowed(
"Only POST allowed",
allowed='POST')
try:
json = loads(req.body)
except ValueError, e:
raise ValueError('Bad JSON: %s' % e)
try:
method = json['method']
params = json['params']
id = json['id']
except KeyError, e:
raise ValueError(
"JSON body missing parameter: %s" % e)
if method.startswith('_'):
raise exc.HTTPForbidden(
"Bad method name %s: must not start with _" % method)
if not isinstance(params, list):
raise ValueError(
"Bad params %r: must be a list" % params)
try:
method = getattr(self.obj, method)
except AttributeError:
raise ValueError(
"No such method %s" % method)
try:
result = method(*params)
except:
text = traceback.format_exc()
exc_value = sys.exc_info()[1]
error_value = dict(
name='JSONRPCError',
code=100,
message=str(exc_value),
error=text)
return Response(
status=500,
content_type='application/json',
body=dumps(dict(result=None,
error=error_value,
id=id)))
return Response(
content_type='application/json',
body=dumps(dict(result=result,
error=None,
id=id)))
class ServerProxy(object):
"""
JSON proxy to a remote service.
"""
def __init__(self, url, proxy=None):
self._url = url
if proxy is None:
from wsgiproxy.exactproxy import proxy_exact_request
proxy = proxy_exact_request
self.proxy = proxy
def __getattr__(self, name):
if name.startswith('_'):
raise AttributeError(name)
return _Method(self, name)
def __repr__(self):
return '<%s for %s>' % (
self.__class__.__name__, self._url)
class _Method(object):
def __init__(self, parent, name):
self.parent = parent
self.name = name
def __call__(self, *args):
json = dict(method=self.name,
id=None,
params=list(args))
req = Request.blank(self.parent._url)
req.method = 'POST'
req.content_type = 'application/json'
req.body = dumps(json)
resp = req.get_response(self.parent.proxy)
if resp.status_code != 200 and not (
resp.status_code == 500
and resp.content_type == 'application/json'):
raise ProxyError(
"Error from JSON-RPC client %s: %s"
% (self.parent._url, resp.status),
resp)
json = loads(resp.body)
if json.get('error') is not None:
e = Fault(
json['error'].get('message'),
json['error'].get('code'),
json['error'].get('error'),
resp)
raise e
return json['result']
class ProxyError(Exception):
"""
Raised when a request via ServerProxy breaks
"""
def __init__(self, message, response):
Exception.__init__(self, message)
self.response = response
class Fault(Exception):
"""
Raised when there is a remote error
"""
def __init__(self, message, code, error, response):
Exception.__init__(self, message)
self.code = code
self.error = error
self.response = response
def __str__(self):
return 'Method error calling %s: %s\n%s' % (
self.response.request.url,
self.args[0],
self.error)
class DemoObject(object):
"""
Something interesting to attach to
"""
def add(self, *args):
return sum(args)
def average(self, *args):
return sum(args) / float(len(args))
def divide(self, a, b):
return a / b
def make_app(expr):
module, expression = expr.split(':', 1)
__import__(module)
module = sys.modules[module]
obj = eval(expression, module.__dict__)
return JsonRpcApp(obj)
def main(args=None):
import optparse
from wsgiref import simple_server
parser = optparse.OptionParser(
usage='%prog [OPTIONS] MODULE:EXPRESSION')
parser.add_option(
'-p', '--port', default='8080',
help='Port to serve on (default 8080)')
parser.add_option(
'-H', '--host', default='127.0.0.1',
help='Host to serve on (default localhost; 0.0.0.0 to make public)')
options, args = parser.parse_args()
if not args or len(args) > 1:
print 'You must give a single object reference'
parser.print_help()
sys.exit(2)
app = make_app(args[0])
server = simple_server.make_server(options.host, int(options.port), app)
print 'Serving on http://%s:%s' % (options.host, options.port)
server.serve_forever()
# Try python jsonrpc.py 'jsonrpc:DemoObject()'
if __name__ == '__main__':
main()
| Python |
import os
import urllib
import time
import re
from cPickle import load, dump
from webob import Request, Response, html_escape
from webob import exc
class Commenter(object):
def __init__(self, app, storage_dir):
self.app = app
self.storage_dir = storage_dir
if not os.path.exists(storage_dir):
os.makedirs(storage_dir)
def __call__(self, environ, start_response):
req = Request(environ)
if req.path_info_peek() == '.comments':
return self.process_comment(req)(environ, start_response)
# This is the base path of *this* middleware:
base_url = req.application_url
resp = req.get_response(self.app)
if resp.content_type != 'text/html' or resp.status_code != 200:
# Not an HTML response, we don't want to
# do anything to it
return resp(environ, start_response)
# Make sure the content isn't gzipped:
resp.decode_content()
comments = self.get_data(req.url)
body = resp.body
body = self.add_to_end(body, self.format_comments(comments))
body = self.add_to_end(body, self.submit_form(base_url, req))
resp.body = body
return resp(environ, start_response)
def get_data(self, url):
# Double-quoting makes the filename safe
filename = self.url_filename(url)
if not os.path.exists(filename):
return []
else:
f = open(filename, 'rb')
data = load(f)
f.close()
return data
def save_data(self, url, data):
filename = self.url_filename(url)
f = open(filename, 'wb')
dump(data, f)
f.close()
def url_filename(self, url):
return os.path.join(self.storage_dir, urllib.quote(url, ''))
_end_body_re = re.compile(r'</body.*?>', re.I|re.S)
def add_to_end(self, html, extra_html):
"""
Adds extra_html to the end of the html page (before </body>)
"""
match = self._end_body_re.search(html)
if not match:
return html + extra_html
else:
return html[:match.start()] + extra_html + html[match.start():]
def format_comments(self, comments):
if not comments:
return ''
text = []
text.append('<hr>')
text.append('<h2><a name="comment-area"></a>Comments (%s):</h2>' % len(comments))
for comment in comments:
text.append('<h3><a href="%s">%s</a> at %s:</h3>' % (
html_escape(comment['homepage']), html_escape(comment['name']),
time.strftime('%c', comment['time'])))
# Susceptible to XSS attacks!:
text.append(comment['comments'])
return ''.join(text)
def submit_form(self, base_path, req):
return '''<h2>Leave a comment:</h2>
<form action="%s/.comments" method="POST">
<input type="hidden" name="url" value="%s">
<table width="100%%">
<tr><td>Name:</td>
<td><input type="text" name="name" style="width: 100%%"></td></tr>
<tr><td>URL:</td>
<td><input type="text" name="homepage" style="width: 100%%"></td></tr>
</table>
Comments:<br>
<textarea name="comments" rows=10 style="width: 100%%"></textarea><br>
<input type="submit" value="Submit comment">
</form>
''' % (base_path, html_escape(req.url))
def process_comment(self, req):
try:
url = req.params['url']
name = req.params['name']
homepage = req.params['homepage']
comments = req.params['comments']
except KeyError, e:
resp = exc.HTTPBadRequest('Missing parameter: %s' % e)
return resp
data = self.get_data(url)
data.append(dict(
name=name,
homepage=homepage,
comments=comments,
time=time.gmtime()))
self.save_data(url, data)
resp = exc.HTTPSeeOther(location=url+'#comment-area')
return resp
if __name__ == '__main__':
import optparse
parser = optparse.OptionParser(
usage='%prog --port=PORT BASE_DIRECTORY'
)
parser.add_option(
'-p', '--port',
default='8080',
dest='port',
type='int',
help='Port to serve on (default 8080)')
parser.add_option(
'--comment-data',
default='./comments',
dest='comment_data',
help='Place to put comment data into (default ./comments/)')
options, args = parser.parse_args()
if not args:
parser.error('You must give a BASE_DIRECTORY')
base_dir = args[0]
from paste.urlparser import StaticURLParser
app = StaticURLParser(base_dir)
app = Commenter(app, options.comment_data)
from wsgiref.simple_server import make_server
httpd = make_server('localhost', options.port, app)
print 'Serving on http://localhost:%s' % options.port
try:
httpd.serve_forever()
except KeyboardInterrupt:
print '^C'
| Python |
import os
import re
from webob import Request, Response
from webob import exc
from tempita import HTMLTemplate
VIEW_TEMPLATE = HTMLTemplate("""\
<html>
<head>
<title>{{page.title}}</title>
</head>
<body>
<h1>{{page.title}}</h1>
{{if message}}
<div style="background-color: #99f">{{message}}</div>
{{endif}}
<div>{{page.content|html}}</div>
<hr>
<a href="{{req.url}}?action=edit">Edit</a>
</body>
</html>
""")
EDIT_TEMPLATE = HTMLTemplate("""\
<html>
<head>
<title>Edit: {{page.title}}</title>
</head>
<body>
{{if page.exists}}
<h1>Edit: {{page.title}}</h1>
{{else}}
<h1>Create: {{page.title}}</h1>
{{endif}}
<form action="{{req.path_url}}" method="POST">
<input type="hidden" name="mtime" value="{{page.mtime}}">
Title: <input type="text" name="title" style="width: 70%" value="{{page.title}}"><br>
Content: <input type="submit" value="Save">
<a href="{{req.path_url}}">Cancel</a>
<br>
<textarea name="content" style="width: 100%; height: 75%" rows="40">{{page.content}}</textarea>
<br>
<input type="submit" value="Save">
<a href="{{req.path_url}}">Cancel</a>
</form>
</body></html>
""")
class WikiApp(object):
view_template = VIEW_TEMPLATE
edit_template = EDIT_TEMPLATE
def __init__(self, storage_dir):
self.storage_dir = os.path.abspath(os.path.normpath(storage_dir))
def __call__(self, environ, start_response):
req = Request(environ)
action = req.params.get('action', 'view')
page = self.get_page(req.path_info)
try:
try:
meth = getattr(self, 'action_%s_%s' % (action, req.method))
except AttributeError:
raise exc.HTTPBadRequest('No such action %r' % action)
resp = meth(req, page)
except exc.HTTPException, e:
resp = e
return resp(environ, start_response)
def get_page(self, path):
path = path.lstrip('/')
if not path:
path = 'index'
path = os.path.join(self.storage_dir, path)
path = os.path.normpath(path)
if path.endswith('/'):
path += 'index'
if not path.startswith(self.storage_dir):
raise exc.HTTPBadRequest("Bad path")
path += '.html'
return Page(path)
def action_view_GET(self, req, page):
if not page.exists:
return exc.HTTPTemporaryRedirect(
location=req.url + '?action=edit')
if req.cookies.get('message'):
message = req.cookies['message']
else:
message = None
text = self.view_template.substitute(
page=page, req=req, message=message)
resp = Response(text)
if message:
resp.delete_cookie('message')
else:
resp.last_modified = page.mtime
resp.conditional_response = True
return resp
def action_view_POST(self, req, page):
submit_mtime = int(req.params.get('mtime') or '0') or None
if page.mtime != submit_mtime:
return exc.HTTPPreconditionFailed(
"The page has been updated since you started editing it")
page.set(
title=req.params['title'],
content=req.params['content'])
resp = exc.HTTPSeeOther(
location=req.path_url)
resp.set_cookie('message', 'Page updated')
return resp
def action_edit_GET(self, req, page):
text = self.edit_template.substitute(
page=page, req=req)
return Response(text)
class Page(object):
def __init__(self, filename):
self.filename = filename
@property
def exists(self):
return os.path.exists(self.filename)
@property
def title(self):
if not self.exists:
# we need to guess the title
basename = os.path.splitext(os.path.basename(self.filename))[0]
basename = re.sub(r'[_-]', ' ', basename)
return basename.capitalize()
content = self.full_content
match = re.search(r'<title>(.*?)</title>', content, re.I|re.S)
return match.group(1)
@property
def full_content(self):
f = open(self.filename, 'rb')
try:
return f.read()
finally:
f.close()
@property
def content(self):
if not self.exists:
return ''
content = self.full_content
match = re.search(r'<body[^>]*>(.*?)</body>', content, re.I|re.S)
return match.group(1)
@property
def mtime(self):
if not self.exists:
return None
else:
return os.stat(self.filename).st_mtime
def set(self, title, content):
dir = os.path.dirname(self.filename)
if not os.path.exists(dir):
os.makedirs(dir)
new_content = """<html><head><title>%s</title></head><body>%s</body></html>""" % (
title, content)
f = open(self.filename, 'wb')
f.write(new_content)
f.close()
if __name__ == '__main__':
import optparse
parser = optparse.OptionParser(
usage='%prog --port=PORT'
)
parser.add_option(
'-p', '--port',
default='8080',
dest='port',
type='int',
help='Port to serve on (default 8080)')
parser.add_option(
'--wiki-data',
default='./wiki',
dest='wiki_data',
help='Place to put wiki data into (default ./wiki/)')
options, args = parser.parse_args()
print 'Writing wiki pages to %s' % options.wiki_data
app = WikiApp(options.wiki_data)
from wsgiref.simple_server import make_server
httpd = make_server('localhost', options.port, app)
print 'Serving on http://localhost:%s' % options.port
try:
httpd.serve_forever()
except KeyboardInterrupt:
print '^C'
| Python |
import unittest
import doctest
def test_suite():
flags = doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE
return unittest.TestSuite((
doctest.DocFileSuite('test_request.txt', optionflags=flags),
doctest.DocFileSuite('test_response.txt', optionflags=flags),
doctest.DocFileSuite('test_dec.txt', optionflags=flags),
doctest.DocFileSuite('do-it-yourself.txt', optionflags=flags),
doctest.DocFileSuite('file-example.txt', optionflags=flags),
doctest.DocFileSuite('index.txt', optionflags=flags),
doctest.DocFileSuite('reference.txt', optionflags=flags),
))
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
| Python |
# -*- coding: utf-8 -*-
from webob import __version__
extensions = ['sphinx.ext.autodoc']
source_suffix = '.txt' # The suffix of source filenames.
master_doc = 'index' # The master toctree document.
project = 'WebOb'
copyright = '2011, Ian Bicking and contributors'
version = release = __version__
exclude_patterns = ['jsonrpc-example-code/*']
modindex_common_prefix = ['webob.']
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# html_favicon = ...
html_add_permalinks = False
#html_show_sourcelink = True # ?set to False?
# Content template for the index page.
#html_index = ''
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Output file base name for HTML help builder.
htmlhelp_basename = 'WebObdoc'
| Python |
from setuptools import setup
version = '1.2.2'
testing_extras = ['nose']
docs_extras = ['Sphinx']
setup(
name='WebOb',
version=version,
description="WSGI request and response object",
long_description="""\
WebOb provides wrappers around the WSGI request environment, and an
object to help create WSGI responses.
The objects map much of the specified behavior of HTTP, including
header parsing and accessors for other standard parts of the
environment.
You may install the `in-development version of WebOb
<https://github.com/Pylons/webob/zipball/master#egg=WebOb-dev>`_ with
``pip install WebOb==dev`` (or ``easy_install WebOb==dev``).
* `WebOb reference <http://docs.webob.org/en/latest/reference.html>`_
* `Bug tracker <https://github.com/Pylons/webob/issues>`_
* `Browse source code <https://github.com/Pylons/webob>`_
* `Mailing list <http://bit.ly/paste-users>`_
* `Release news <http://docs.webob.org/en/latest/news.html>`_
* `Detailed changelog <https://github.com/Pylons/webob/commits/master>`_
""",
classifiers=[
"Development Status :: 6 - Mature",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Internet :: WWW/HTTP :: WSGI",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
],
keywords='wsgi request web http',
author='Ian Bicking',
author_email='ianb@colorstudy.com',
maintainer='Sergey Schetinin',
maintainer_email='sergey@maluke.com',
url='http://webob.org/',
license='MIT',
packages=['webob'],
zip_safe=True,
test_suite='nose.collector',
tests_require=['nose'],
extras_require = {
'testing':testing_extras,
'docs':docs_extras,
},
)
| Python |
#!/usr/bin/env python
from webob.response import Response
def make_middleware(app):
from repoze.profile.profiler import AccumulatingProfileMiddleware
return AccumulatingProfileMiddleware(
app,
log_filename='/tmp/profile.log',
discard_first_request=True,
flush_at_shutdown=True,
path='/__profile__')
def simple_app(environ, start_response):
resp = Response('Hello world!')
return resp(environ, start_response)
if __name__ == '__main__':
import sys
import os
import signal
if sys.argv[1:]:
arg = sys.argv[1]
else:
arg = None
if arg in ['open', 'run']:
import subprocess
import webbrowser
import time
os.environ['SHOW_OUTPUT'] = '0'
proc = subprocess.Popen([sys.executable, __file__])
time.sleep(1)
subprocess.call(['ab', '-n', '1000', 'http://localhost:8080/'])
if arg == 'open':
webbrowser.open('http://localhost:8080/__profile__')
print('Hit ^C to end')
try:
while 1:
raw_input()
finally:
os.kill(proc.pid, signal.SIGKILL)
else:
from paste.httpserver import serve
if os.environ.get('SHOW_OUTPUT') != '0':
print('Note you can also use:)')
print(' %s %s open' % (sys.executable, __file__))
print('to run ab and open a browser (or "run" to just run ab)')
print('Now do:')
print('ab -n 1000 http://localhost:8080/')
print('wget -O - http://localhost:8080/__profile__')
serve(make_middleware(simple_app))
| Python |
#
| Python |
import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import pkg_resources
pkg_resources.require('WebOb')
| Python |
"""
Parses a variety of ``Accept-*`` headers.
These headers generally take the form of::
value1; q=0.5, value2; q=0
Where the ``q`` parameter is optional. In theory other parameters
exists, but this ignores them.
"""
import re
from webob.headers import _trans_name as header_to_key
from webob.util import (
header_docstring,
warn_deprecation,
)
part_re = re.compile(
r',\s*([^\s;,\n]+)(?:[^,]*?;\s*q=([0-9.]*))?')
def _warn_first_match():
# TODO: remove .first_match in version 1.3
warn_deprecation("Use best_match instead", '1.2', 3)
class Accept(object):
"""
Represents a generic ``Accept-*`` style header.
This object should not be modified. To add items you can use
``accept_obj + 'accept_thing'`` to get a new object
"""
def __init__(self, header_value):
self.header_value = header_value
self._parsed = list(self.parse(header_value))
self._parsed_nonzero = [(m,q) for (m,q) in self._parsed if q]
@staticmethod
def parse(value):
"""
Parse ``Accept-*`` style header.
Return iterator of ``(value, quality)`` pairs.
``quality`` defaults to 1.
"""
for match in part_re.finditer(','+value):
name = match.group(1)
if name == 'q':
continue
quality = match.group(2) or ''
if quality:
try:
quality = max(min(float(quality), 1), 0)
yield (name, quality)
continue
except ValueError:
pass
yield (name, 1)
def __repr__(self):
return '<%s(%r)>' % (self.__class__.__name__, str(self))
def __iter__(self):
for m,q in sorted(
self._parsed_nonzero,
key=lambda i: i[1],
reverse=True
):
yield m
def __str__(self):
result = []
for mask, quality in self._parsed:
if quality != 1:
mask = '%s;q=%0.*f' % (
mask, min(len(str(quality).split('.')[1]), 3), quality)
result.append(mask)
return ', '.join(result)
def __add__(self, other, reversed=False):
if isinstance(other, Accept):
other = other.header_value
if hasattr(other, 'items'):
other = sorted(other.items(), key=lambda item: -item[1])
if isinstance(other, (list, tuple)):
result = []
for item in other:
if isinstance(item, (list, tuple)):
name, quality = item
result.append('%s; q=%s' % (name, quality))
else:
result.append(item)
other = ', '.join(result)
other = str(other)
my_value = self.header_value
if reversed:
other, my_value = my_value, other
if not other:
new_value = my_value
elif not my_value:
new_value = other
else:
new_value = my_value + ', ' + other
return self.__class__(new_value)
def __radd__(self, other):
return self.__add__(other, True)
def __contains__(self, offer):
"""
Returns true if the given object is listed in the accepted
types.
"""
for mask, quality in self._parsed_nonzero:
if self._match(mask, offer):
return True
def quality(self, offer, modifier=1):
"""
Return the quality of the given offer. Returns None if there
is no match (not 0).
"""
bestq = 0
for mask, q in self._parsed:
if self._match(mask, offer):
bestq = max(bestq, q * modifier)
return bestq or None
def first_match(self, offers):
"""
DEPRECATED
Returns the first allowed offered type. Ignores quality.
Returns the first offered type if nothing else matches; or if you include None
at the end of the match list then that will be returned.
"""
_warn_first_match()
def best_match(self, offers, default_match=None):
"""
Returns the best match in the sequence of offered types.
The sequence can be a simple sequence, or you can have
``(match, server_quality)`` items in the sequence. If you
have these tuples then the client quality is multiplied by the
server_quality to get a total. If two matches have equal
weight, then the one that shows up first in the `offers` list
will be returned.
But among matches with the same quality the match to a more specific
requested type will be chosen. For example a match to text/* trumps */*.
default_match (default None) is returned if there is no intersection.
"""
best_quality = -1
best_offer = default_match
matched_by = '*/*'
for offer in offers:
if isinstance(offer, (tuple, list)):
offer, server_quality = offer
else:
server_quality = 1
for mask, quality in self._parsed_nonzero:
possible_quality = server_quality * quality
if possible_quality < best_quality:
continue
elif possible_quality == best_quality:
# 'text/plain' overrides 'message/*' overrides '*/*'
# (if all match w/ the same q=)
if matched_by.count('*') <= mask.count('*'):
continue
if self._match(mask, offer):
best_quality = possible_quality
best_offer = offer
matched_by = mask
return best_offer
def _match(self, mask, offer):
_check_offer(offer)
return mask == '*' or offer.lower() == mask.lower()
class NilAccept(object):
MasterClass = Accept
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__, self.MasterClass)
def __str__(self):
return ''
def __nonzero__(self):
return False
__bool__ = __nonzero__ # python 3
def __iter__(self):
return iter(())
def __add__(self, item):
if isinstance(item, self.MasterClass):
return item
else:
return self.MasterClass('') + item
def __radd__(self, item):
if isinstance(item, self.MasterClass):
return item
else:
return item + self.MasterClass('')
def __contains__(self, item):
_check_offer(item)
return True
def quality(self, offer, default_quality=1):
return 0
def first_match(self, offers): # pragma: no cover
_warn_first_match()
def best_match(self, offers, default_match=None):
best_quality = -1
best_offer = default_match
for offer in offers:
_check_offer(offer)
if isinstance(offer, (list, tuple)):
offer, quality = offer
else:
quality = 1
if quality > best_quality:
best_offer = offer
best_quality = quality
return best_offer
class NoAccept(NilAccept):
def __contains__(self, item):
return False
class AcceptCharset(Accept):
@staticmethod
def parse(value):
latin1_found = False
for m, q in Accept.parse(value):
_m = m.lower()
if _m == '*' or _m == 'iso-8859-1':
latin1_found = True
yield _m, q
if not latin1_found:
yield ('iso-8859-1', 1)
class AcceptLanguage(Accept):
def _match(self, mask, item):
item = item.replace('_', '-').lower()
mask = mask.lower()
return (mask == '*'
or item == mask
or item.split('-')[0] == mask
or item == mask.split('-')[0]
)
class MIMEAccept(Accept):
"""
Represents the ``Accept`` header, which is a list of mimetypes.
This class knows about mime wildcards, like ``image/*``
"""
@staticmethod
def parse(value):
for mask, q in Accept.parse(value):
try:
mask_major, mask_minor = map(lambda x: x.lower(), mask.split('/'))
except ValueError:
continue
if mask_major == '*' and mask_minor != '*':
continue
yield ("%s/%s" % (mask_major, mask_minor), q)
def accept_html(self):
"""
Returns true if any HTML-like type is accepted
"""
return ('text/html' in self
or 'application/xhtml+xml' in self
or 'application/xml' in self
or 'text/xml' in self)
accepts_html = property(accept_html) # note the plural
def _match(self, mask, offer):
"""
Check if the offer is covered by the mask
"""
_check_offer(offer)
if '*' not in mask:
return offer.lower() == mask.lower()
elif mask == '*/*':
return True
else:
assert mask.endswith('/*')
mask_major = mask[:-2].lower()
offer_major = offer.split('/', 1)[0].lower()
return offer_major == mask_major
class MIMENilAccept(NilAccept):
MasterClass = MIMEAccept
def _check_offer(offer):
if '*' in offer:
raise ValueError("The application should offer specific types, got %r" % offer)
def accept_property(header, rfc_section,
AcceptClass=Accept, NilClass=NilAccept
):
key = header_to_key(header)
doc = header_docstring(header, rfc_section)
#doc += " Converts it as a %s." % convert_name
def fget(req):
value = req.environ.get(key)
if not value:
return NilClass()
return AcceptClass(value)
def fset(req, val):
if val:
if isinstance(val, (list, tuple, dict)):
val = AcceptClass('') + val
val = str(val)
req.environ[key] = val or None
def fdel(req):
del req.environ[key]
return property(fget, fset, fdel, doc)
| Python |
from collections import MutableMapping
from webob.compat import (
iteritems_,
string_types,
)
from webob.multidict import MultiDict
__all__ = ['ResponseHeaders', 'EnvironHeaders']
class ResponseHeaders(MultiDict):
"""
Dictionary view on the response headerlist.
Keys are normalized for case and whitespace.
"""
def __getitem__(self, key):
key = key.lower()
for k, v in reversed(self._items):
if k.lower() == key:
return v
raise KeyError(key)
def getall(self, key):
key = key.lower()
result = []
for k, v in self._items:
if k.lower() == key:
result.append(v)
return result
def mixed(self):
r = self.dict_of_lists()
for key, val in iteritems_(r):
if len(val) == 1:
r[key] = val[0]
return r
def dict_of_lists(self):
r = {}
for key, val in iteritems_(self):
r.setdefault(key.lower(), []).append(val)
return r
def __setitem__(self, key, value):
norm_key = key.lower()
items = self._items
for i in range(len(items)-1, -1, -1):
if items[i][0].lower() == norm_key:
del items[i]
self._items.append((key, value))
def __delitem__(self, key):
key = key.lower()
items = self._items
found = False
for i in range(len(items)-1, -1, -1):
if items[i][0].lower() == key:
del items[i]
found = True
if not found:
raise KeyError(key)
def __contains__(self, key):
key = key.lower()
for k, v in self._items:
if k.lower() == key:
return True
return False
has_key = __contains__
def setdefault(self, key, default=None):
c_key = key.lower()
for k, v in self._items:
if k.lower() == c_key:
return v
self._items.append((key, default))
return default
def pop(self, key, *args):
if len(args) > 1:
raise TypeError("pop expected at most 2 arguments, got %s"
% repr(1 + len(args)))
key = key.lower()
for i in range(len(self._items)):
if self._items[i][0].lower() == key:
v = self._items[i][1]
del self._items[i]
return v
if args:
return args[0]
else:
raise KeyError(key)
key2header = {
'CONTENT_TYPE': 'Content-Type',
'CONTENT_LENGTH': 'Content-Length',
'HTTP_CONTENT_TYPE': 'Content_Type',
'HTTP_CONTENT_LENGTH': 'Content_Length',
}
header2key = dict([(v.upper(),k) for (k,v) in key2header.items()])
def _trans_key(key):
if not isinstance(key, string_types):
return None
elif key in key2header:
return key2header[key]
elif key.startswith('HTTP_'):
return key[5:].replace('_', '-').title()
else:
return None
def _trans_name(name):
name = name.upper()
if name in header2key:
return header2key[name]
return 'HTTP_'+name.replace('-', '_')
class EnvironHeaders(MutableMapping):
"""An object that represents the headers as present in a
WSGI environment.
This object is a wrapper (with no internal state) for a WSGI
request object, representing the CGI-style HTTP_* keys as a
dictionary. Because a CGI environment can only hold one value for
each key, this dictionary is single-valued (unlike outgoing
headers).
"""
def __init__(self, environ):
self.environ = environ
def __getitem__(self, hname):
return self.environ[_trans_name(hname)]
def __setitem__(self, hname, value):
self.environ[_trans_name(hname)] = value
def __delitem__(self, hname):
del self.environ[_trans_name(hname)]
def keys(self):
return filter(None, map(_trans_key, self.environ))
def __contains__(self, hname):
return _trans_name(hname) in self.environ
def __len__(self):
return len(list(self.keys()))
def __iter__(self):
for k in self.keys():
yield k
| Python |
import calendar
from datetime import (
date,
datetime,
timedelta,
tzinfo,
)
from email.utils import (
formatdate,
mktime_tz,
parsedate_tz,
)
import time
from webob.compat import (
integer_types,
long,
native_,
text_type,
)
__all__ = [
'UTC', 'timedelta_to_seconds',
'year', 'month', 'week', 'day', 'hour', 'minute', 'second',
'parse_date', 'serialize_date',
'parse_date_delta', 'serialize_date_delta',
]
_now = datetime.now # hook point for unit tests
class _UTC(tzinfo):
def dst(self, dt):
return timedelta(0)
def utcoffset(self, dt):
return timedelta(0)
def tzname(self, dt):
return 'UTC'
def __repr__(self):
return 'UTC'
UTC = _UTC()
def timedelta_to_seconds(td):
"""
Converts a timedelta instance to seconds.
"""
return td.seconds + (td.days*24*60*60)
day = timedelta(days=1)
week = timedelta(weeks=1)
hour = timedelta(hours=1)
minute = timedelta(minutes=1)
second = timedelta(seconds=1)
# Estimate, I know; good enough for expirations
month = timedelta(days=30)
year = timedelta(days=365)
def parse_date(value):
if not value:
return None
try:
value = native_(value)
except:
return None
t = parsedate_tz(value)
if t is None:
# Could not parse
return None
if t[-1] is None:
# No timezone given. None would mean local time, but we'll force UTC
t = t[:9] + (0,)
t = mktime_tz(t)
return datetime.fromtimestamp(t, UTC)
def serialize_date(dt):
if isinstance(dt, (bytes, text_type)):
return native_(dt)
if isinstance(dt, timedelta):
dt = _now() + dt
if isinstance(dt, (datetime, date)):
dt = dt.timetuple()
if isinstance(dt, (tuple, time.struct_time)):
dt = calendar.timegm(dt)
if not (isinstance(dt, float) or isinstance(dt, integer_types)):
raise ValueError(
"You must pass in a datetime, date, time tuple, or integer object, "
"not %r" % dt)
return formatdate(dt, usegmt=True)
def parse_date_delta(value):
"""
like parse_date, but also handle delta seconds
"""
if not value:
return None
try:
value = int(value)
except ValueError:
return parse_date(value)
else:
return _now() + timedelta(seconds=value)
def serialize_date_delta(value):
if isinstance(value, (float, int, long)):
return str(int(value))
else:
return serialize_date(value)
| Python |
import collections
from datetime import (
date,
datetime,
timedelta,
)
import re
import string
import time
from webob.compat import (
PY3,
text_type,
bytes_,
text_,
native_,
string_types,
)
__all__ = ['Cookie']
_marker = object()
class RequestCookies(collections.MutableMapping):
_cache_key = 'webob._parsed_cookies'
def __init__(self, environ):
self._environ = environ
@property
def _cache(self):
env = self._environ
header = env.get('HTTP_COOKIE', '')
cache, cache_header = env.get(self._cache_key, ({}, None))
if cache_header == header:
return cache
d = lambda b: b.decode('utf8')
cache = dict((d(k), d(v)) for k,v in parse_cookie(header))
env[self._cache_key] = (cache, header)
return cache
def _mutate_header(self, name, value):
header = self._environ.get('HTTP_COOKIE')
had_header = header is not None
header = header or ''
if PY3: # pragma: no cover
header = header.encode('latin-1')
bytes_name = bytes_(name, 'ascii')
if value is None:
replacement = None
else:
bytes_val = _quote(bytes_(value, 'utf-8'))
replacement = bytes_name + b'=' + bytes_val
matches = _rx_cookie.finditer(header)
found = False
for match in matches:
start, end = match.span()
match_name = match.group(1)
if match_name == bytes_name:
found = True
if replacement is None: # remove value
header = header[:start].rstrip(b' ;') + header[end:]
else: # replace value
header = header[:start] + replacement + header[end:]
break
else:
if replacement is not None:
if header:
header += b'; ' + replacement
else:
header = replacement
if header:
self._environ['HTTP_COOKIE'] = native_(header, 'latin-1')
elif had_header:
self._environ['HTTP_COOKIE'] = ''
return found
def _valid_cookie_name(self, name):
if not isinstance(name, string_types):
raise TypeError(name, 'cookie name must be a string')
if not isinstance(name, text_type):
name = text_(name, 'utf-8')
try:
bytes_cookie_name = bytes_(name, 'ascii')
except UnicodeEncodeError:
raise TypeError('cookie name must be encodable to ascii')
if not _valid_cookie_name(bytes_cookie_name):
raise TypeError('cookie name must be valid according to RFC 2109')
return name
def __setitem__(self, name, value):
name = self._valid_cookie_name(name)
if not isinstance(value, string_types):
raise ValueError(value, 'cookie value must be a string')
if not isinstance(value, text_type):
try:
value = text_(value, 'utf-8')
except UnicodeDecodeError:
raise ValueError(
value, 'cookie value must be utf-8 binary or unicode')
self._mutate_header(name, value)
def __getitem__(self, name):
return self._cache[name]
def get(self, name, default=None):
return self._cache.get(name, default)
def __delitem__(self, name):
name = self._valid_cookie_name(name)
found = self._mutate_header(name, None)
if not found:
raise KeyError(name)
def keys(self):
return self._cache.keys()
def values(self):
return self._cache.values()
def items(self):
return self._cache.items()
if not PY3:
def iterkeys(self):
return self._cache.iterkeys()
def itervalues(self):
return self._cache.itervalues()
def iteritems(self):
return self._cache.iteritems()
def __contains__(self, name):
return name in self._cache
def __iter__(self):
return self._cache.__iter__()
def __len__(self):
return len(self._cache)
def clear(self):
self._environ['HTTP_COOKIE'] = ''
def __repr__(self):
return '<RequestCookies (dict-like) with values %r>' % (self._cache,)
class Cookie(dict):
def __init__(self, input=None):
if input:
self.load(input)
def load(self, data):
morsel = {}
for key, val in _parse_cookie(data):
if key.lower() in _c_keys:
morsel[key] = val
else:
morsel = self.add(key, val)
def add(self, key, val):
if not isinstance(key, bytes):
key = key.encode('ascii', 'replace')
if not _valid_cookie_name(key):
return {}
r = Morsel(key, val)
dict.__setitem__(self, key, r)
return r
__setitem__ = add
def serialize(self, full=True):
return '; '.join(m.serialize(full) for m in self.values())
def values(self):
return [m for _, m in sorted(self.items())]
__str__ = serialize
def __repr__(self):
return '<%s: [%s]>' % (self.__class__.__name__,
', '.join(map(repr, self.values())))
def _parse_cookie(data):
if PY3: # pragma: no cover
data = data.encode('latin-1')
for key, val in _rx_cookie.findall(data):
yield key, _unquote(val)
def parse_cookie(data):
"""
Parse cookies ignoring anything except names and values
"""
return ((k,v) for k,v in _parse_cookie(data) if _valid_cookie_name(k))
def cookie_property(key, serialize=lambda v: v):
def fset(self, v):
self[key] = serialize(v)
return property(lambda self: self[key], fset)
def serialize_max_age(v):
if isinstance(v, timedelta):
v = str(v.seconds + v.days*24*60*60)
elif isinstance(v, int):
v = str(v)
return bytes_(v)
def serialize_cookie_date(v):
if v is None:
return None
elif isinstance(v, bytes):
return v
elif isinstance(v, text_type):
return v.encode('ascii')
elif isinstance(v, int):
v = timedelta(seconds=v)
if isinstance(v, timedelta):
v = datetime.utcnow() + v
if isinstance(v, (datetime, date)):
v = v.timetuple()
r = time.strftime('%%s, %d-%%s-%Y %H:%M:%S GMT', v)
return bytes_(r % (weekdays[v[6]], months[v[1]]), 'ascii')
class Morsel(dict):
__slots__ = ('name', 'value')
def __init__(self, name, value):
assert _valid_cookie_name(name)
assert isinstance(value, bytes)
self.name = name
self.value = value
self.update(dict.fromkeys(_c_keys, None))
path = cookie_property(b'path')
domain = cookie_property(b'domain')
comment = cookie_property(b'comment')
expires = cookie_property(b'expires', serialize_cookie_date)
max_age = cookie_property(b'max-age', serialize_max_age)
httponly = cookie_property(b'httponly', bool)
secure = cookie_property(b'secure', bool)
def __setitem__(self, k, v):
k = bytes_(k.lower(), 'ascii')
if k in _c_keys:
dict.__setitem__(self, k, v)
def serialize(self, full=True):
result = []
add = result.append
add(self.name + b'=' + _quote(self.value))
if full:
for k in _c_valkeys:
v = self[k]
if v:
add(_c_renames[k]+b'='+_quote(v))
expires = self[b'expires']
if expires:
add(b'expires=' + expires)
if self.secure:
add(b'secure')
if self.httponly:
add(b'HttpOnly')
return native_(b'; '.join(result), 'ascii')
__str__ = serialize
def __repr__(self):
return '<%s: %s=%r>' % (self.__class__.__name__,
native_(self.name),
native_(self.value)
)
_c_renames = {
b"path" : b"Path",
b"comment" : b"Comment",
b"domain" : b"Domain",
b"max-age" : b"Max-Age",
}
_c_valkeys = sorted(_c_renames)
_c_keys = set(_c_renames)
_c_keys.update([b'expires', b'secure', b'httponly'])
#
# parsing
#
_re_quoted = r'"(?:\\"|.)*?"' # any doublequoted string
_legal_special_chars = "~!@#$%^&*()_+=-`.?|:/(){}<>'"
_re_legal_char = r"[\w\d%s]" % re.escape(_legal_special_chars)
_re_expires_val = r"\w{3},\s[\w\d-]{9,11}\s[\d:]{8}\sGMT"
_re_cookie_str_key = r"(%s+?)" % _re_legal_char
_re_cookie_str_equal = r"\s*=\s*"
_re_unquoted_val = r"(?:%s|\\(?:[0-3][0-7][0-7]|.))*" % _re_legal_char
_re_cookie_str_val = r"(%s|%s|%s)" % (_re_quoted, _re_expires_val,
_re_unquoted_val)
_re_cookie_str = _re_cookie_str_key + _re_cookie_str_equal + _re_cookie_str_val
_rx_cookie = re.compile(bytes_(_re_cookie_str, 'ascii'))
_rx_unquote = re.compile(bytes_(r'\\([0-3][0-7][0-7]|.)', 'ascii'))
_bchr = (lambda i: bytes([i])) if PY3 else chr
_ch_unquote_map = dict((bytes_('%03o' % i), _bchr(i))
for i in range(256)
)
_ch_unquote_map.update((v, v) for v in list(_ch_unquote_map.values()))
_b_dollar_sign = 36 if PY3 else '$'
_b_quote_mark = 34 if PY3 else '"'
def _unquote(v):
#assert isinstance(v, bytes)
if v and v[0] == v[-1] == _b_quote_mark:
v = v[1:-1]
return _rx_unquote.sub(_ch_unquote, v)
def _ch_unquote(m):
return _ch_unquote_map[m.group(1)]
#
# serializing
#
# these chars can be in cookie value w/o causing it to be quoted
_no_escape_special_chars = "!#$%&'*+-.^_`|~/"
_no_escape_chars = (string.ascii_letters + string.digits +
_no_escape_special_chars)
_no_escape_bytes = bytes_(_no_escape_chars)
# these chars never need to be quoted
_escape_noop_chars = _no_escape_chars + ': '
# this is a map used to escape the values
_escape_map = dict((chr(i), '\\%03o' % i) for i in range(256))
_escape_map.update(zip(_escape_noop_chars, _escape_noop_chars))
_escape_map['"'] = r'\"'
_escape_map['\\'] = r'\\'
if PY3: # pragma: no cover
# convert to {int -> bytes}
_escape_map = dict((ord(k), bytes_(v, 'ascii')) for k, v in _escape_map.items())
_escape_char = _escape_map.__getitem__
weekdays = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
months = (None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec')
_notrans_binary = b' '*256
def _needs_quoting(v):
return v.translate(_notrans_binary, _no_escape_bytes)
def _quote(v):
#assert isinstance(v, bytes)
if _needs_quoting(v):
return b'"' + b''.join(map(_escape_char, v)) + b'"'
return v
def _valid_cookie_name(key):
return isinstance(key, bytes) and not (
_needs_quoting(key)
or key[0] == _b_dollar_sign
or key.lower() in _c_keys
)
| Python |
import mimetypes
import os
from webob import exc
from webob.dec import wsgify
from webob.response import Response
__all__ = [
'FileApp', 'DirectoryApp',
]
mimetypes._winreg = None # do not load mimetypes from windows registry
mimetypes.add_type('text/javascript', '.js') # stdlib default is application/x-javascript
mimetypes.add_type('image/x-icon', '.ico') # not among defaults
BLOCK_SIZE = 1<<16
class FileApp(object):
"""An application that will send the file at the given filename.
Adds a mime type based on `mimetypes.guess_type()`.
"""
def __init__(self, filename, **kw):
self.filename = filename
content_type, content_encoding = mimetypes.guess_type(filename)
kw.setdefault('content_type', content_type)
kw.setdefault('content_encoding', content_encoding)
kw.setdefault('accept_ranges', 'bytes')
self.kw = kw
# Used for testing purpose
self._open = open
@wsgify
def __call__(self, req):
if req.method not in ('GET', 'HEAD'):
return exc.HTTPMethodNotAllowed("You cannot %s a file" %
req.method)
try:
stat = os.stat(self.filename)
except (IOError, OSError) as e:
msg = "Can't open %r: %s" % (self.filename, e)
return exc.HTTPNotFound(comment=msg)
try:
file = self._open(self.filename, 'rb')
except (IOError, OSError) as e:
msg = "You are not permitted to view this file (%s)" % e
return exc.HTTPForbidden(msg)
if 'wsgi.file_wrapper' in req.environ:
app_iter = req.environ['wsgi.file_wrapper'](file, BLOCK_SIZE)
else:
app_iter = FileIter(file)
return Response(
app_iter = app_iter,
content_length = stat.st_size,
last_modified = stat.st_mtime,
#@@ etag
**self.kw
).conditional_response_app
class FileIter(object):
def __init__(self, file):
self.file = file
def app_iter_range(self, seek=None, limit=None, block_size=None):
"""Iter over the content of the file.
You can set the `seek` parameter to read the file starting from a
specific position.
You can set the `limit` parameter to read the file up to specific
position.
Finally, you can change the number of bytes read at once by setting the
`block_size` parameter.
"""
if block_size is None:
block_size = BLOCK_SIZE
if seek:
self.file.seek(seek)
if limit is not None:
limit -= seek
try:
while True:
data = self.file.read(min(block_size, limit)
if limit is not None
else block_size)
if not data:
return
yield data
if limit is not None:
limit -= len(data)
if limit <= 0:
return
finally:
self.file.close()
__iter__ = app_iter_range
class DirectoryApp(object):
"""An application that serves up the files in a given directory.
This will serve index files (by default ``index.html``), or set
``index_page=None`` to disable this. If you set
``hide_index_with_redirect=True`` (it defaults to False) then
requests to, e.g., ``/index.html`` will be redirected to ``/``.
To customize `FileApp` instances creation (which is what actually
serves the responses), override the `make_fileapp` method.
"""
def __init__(self, path, index_page='index.html', hide_index_with_redirect=False,
**kw):
self.path = os.path.abspath(path)
if not self.path.endswith(os.path.sep):
self.path += os.path.sep
if not os.path.isdir(self.path):
raise IOError(
"Path does not exist or is not directory: %r" % self.path)
self.index_page = index_page
self.hide_index_with_redirect = hide_index_with_redirect
self.fileapp_kw = kw
def make_fileapp(self, path):
return FileApp(path, **self.fileapp_kw)
@wsgify
def __call__(self, req):
path = os.path.abspath(os.path.join(self.path,
req.path_info.lstrip('/')))
if os.path.isdir(path) and self.index_page:
return self.index(req, path)
if (self.index_page and self.hide_index_with_redirect
and path.endswith(os.path.sep + self.index_page)):
new_url = req.path_url.rsplit('/', 1)[0]
new_url += '/'
if req.query_string:
new_url += '?' + req.query_string
return Response(
status=301,
location=new_url)
if not os.path.isfile(path):
return exc.HTTPNotFound(comment=path)
elif not path.startswith(self.path):
return exc.HTTPForbidden()
else:
return self.make_fileapp(path)
def index(self, req, path):
index_path = os.path.join(path, self.index_page)
if not os.path.isfile(index_path):
return exc.HTTPNotFound(comment=index_path)
if not req.path_info.endswith('/'):
url = req.path_url + '/'
if req.query_string:
url += '?' + req.query_string
return Response(
status=301,
location=url)
return self.make_fileapp(index_path)
| Python |
import binascii
import cgi
import io
import os
import re
import sys
import tempfile
import mimetypes
try:
import simplejson as json
except ImportError:
import json
import warnings
from webob.acceptparse import (
AcceptLanguage,
AcceptCharset,
MIMEAccept,
MIMENilAccept,
NoAccept,
accept_property,
)
from webob.cachecontrol import (
CacheControl,
serialize_cache_control,
)
from webob.compat import (
PY3,
bytes_,
integer_types,
native_,
parse_qsl_text,
reraise,
text_type,
url_encode,
url_quote,
url_unquote,
quote_plus,
urlparse,
)
from webob.cookies import RequestCookies
from webob.descriptors import (
CHARSET_RE,
SCHEME_RE,
converter,
converter_date,
environ_getter,
environ_decoder,
parse_auth,
parse_int,
parse_int_safe,
parse_range,
serialize_auth,
serialize_if_range,
serialize_int,
serialize_range,
upath_property,
deprecated_property,
)
from webob.etag import (
IfRange,
AnyETag,
NoETag,
etag_property,
)
from webob.headers import EnvironHeaders
from webob.multidict import (
NestedMultiDict,
MultiDict,
NoVars,
GetDict,
)
from webob.util import warn_deprecation
__all__ = ['BaseRequest', 'Request', 'LegacyRequest']
class _NoDefault:
def __repr__(self):
return '(No Default)'
NoDefault = _NoDefault()
PATH_SAFE = '/:@&+$,'
http_method_probably_has_body = dict.fromkeys(
('GET', 'HEAD', 'DELETE', 'TRACE'), False)
http_method_probably_has_body.update(
dict.fromkeys(('POST', 'PUT'), True))
_LATIN_ENCODINGS = (
'ascii', 'latin-1', 'latin', 'latin_1', 'l1', 'latin1',
'iso-8859-1', 'iso8859_1', 'iso_8859_1', 'iso8859', '8859',
)
class BaseRequest(object):
## The limit after which request bodies should be stored on disk
## if they are read in (under this, and the request body is stored
## in memory):
request_body_tempfile_limit = 10*1024
_charset = None
def __init__(self, environ, charset=None, unicode_errors=None,
decode_param_names=None, **kw):
if type(environ) is not dict:
raise TypeError(
"WSGI environ must be a dict; you passed %r" % (environ,))
if unicode_errors is not None:
warnings.warn(
"You unicode_errors=%r to the Request constructor. Passing a "
"``unicode_errors`` value to the Request is no longer "
"supported in WebOb 1.2+. This value has been ignored " % (
unicode_errors,),
DeprecationWarning
)
if decode_param_names is not None:
warnings.warn(
"You passed decode_param_names=%r to the Request constructor. "
"Passing a ``decode_param_names`` value to the Request "
"is no longer supported in WebOb 1.2+. This value has "
"been ignored " % (decode_param_names,),
DeprecationWarning
)
if not _is_utf8(charset):
raise DeprecationWarning(
"You passed charset=%r to the Request constructor. As of "
"WebOb 1.2, if your application needs a non-UTF-8 request "
"charset, please construct the request without a charset or "
"with a charset of 'None', then use ``req = "
"req.decode(charset)``" % charset
)
d = self.__dict__
d['environ'] = environ
if kw:
cls = self.__class__
if 'method' in kw:
# set method first, because .body setters
# depend on it for checks
self.method = kw.pop('method')
for name, value in kw.items():
if not hasattr(cls, name):
raise TypeError(
"Unexpected keyword: %s=%r" % (name, value))
setattr(self, name, value)
if PY3: # pragma: no cover
def encget(self, key, default=NoDefault, encattr=None):
val = self.environ.get(key, default)
if val is NoDefault:
raise KeyError(key)
if val is default:
return default
if not encattr:
return val
encoding = getattr(self, encattr)
if encoding in _LATIN_ENCODINGS: # shortcut
return val
return bytes_(val, 'latin-1').decode(encoding)
else:
def encget(self, key, default=NoDefault, encattr=None):
val = self.environ.get(key, default)
if val is NoDefault:
raise KeyError(key)
if val is default:
return default
if encattr is None:
return val
encoding = getattr(self, encattr)
return val.decode(encoding)
def encset(self, key, val, encattr=None):
if encattr:
encoding = getattr(self, encattr)
else:
encoding = 'ascii'
if PY3: # pragma: no cover
self.environ[key] = bytes_(val, encoding).decode('latin-1')
else:
self.environ[key] = bytes_(val, encoding)
@property
def charset(self):
if self._charset is None:
charset = detect_charset(self._content_type_raw)
if _is_utf8(charset):
charset = 'UTF-8'
self._charset = charset
return self._charset
@charset.setter
def charset(self, charset):
if _is_utf8(charset):
charset = 'UTF-8'
if charset != self.charset:
raise DeprecationWarning("Use req = req.decode(%r)" % charset)
def decode(self, charset=None, errors='strict'):
charset = charset or self.charset
if charset == 'UTF-8':
return self
# cookies and path are always utf-8
t = Transcoder(charset, errors)
new_content_type = CHARSET_RE.sub('; charset="UTF-8"',
self._content_type_raw)
content_type = self.content_type
r = self.__class__(
self.environ.copy(),
query_string=t.transcode_query(self.query_string),
content_type=new_content_type,
)
if content_type == 'application/x-www-form-urlencoded':
r.body = bytes_(t.transcode_query(native_(r.body)))
return r
elif content_type != 'multipart/form-data':
return r
fs_environ = self.environ.copy()
fs_environ.setdefault('CONTENT_LENGTH', '0')
fs_environ['QUERY_STRING'] = ''
if PY3: # pragma: no cover
fs = cgi.FieldStorage(fp=self.body_file,
environ=fs_environ,
keep_blank_values=True,
encoding=charset,
errors=errors)
else:
fs = cgi.FieldStorage(fp=self.body_file,
environ=fs_environ,
keep_blank_values=True)
fout = t.transcode_fs(fs, r._content_type_raw)
# this order is important, because setting body_file
# resets content_length
r.body_file = fout
r.content_length = fout.tell()
fout.seek(0)
return r
# this is necessary for correct warnings depth for both
# BaseRequest and Request (due to AdhocAttrMixin.__setattr__)
_setattr_stacklevel = 2
def _body_file__get(self):
"""
Input stream of the request (wsgi.input).
Setting this property resets the content_length and seekable flag
(unlike setting req.body_file_raw).
"""
if not self.is_body_readable:
return io.BytesIO()
r = self.body_file_raw
clen = self.content_length
if not self.is_body_seekable and clen is not None:
# we need to wrap input in LimitedLengthFile
# but we have to cache the instance as well
# otherwise this would stop working
# (.remaining counter would reset between calls):
# req.body_file.read(100)
# req.body_file.read(100)
env = self.environ
wrapped, raw = env.get('webob._body_file', (0,0))
if raw is not r:
wrapped = LimitedLengthFile(r, clen)
wrapped = io.BufferedReader(wrapped)
env['webob._body_file'] = wrapped, r
r = wrapped
return r
def _body_file__set(self, value):
if isinstance(value, bytes):
warn_deprecation(
"Please use req.body = b'bytes' or req.body_file = fileobj",
'1.2',
self._setattr_stacklevel
)
self.content_length = None
self.body_file_raw = value
self.is_body_seekable = False
self.is_body_readable = True
def _body_file__del(self):
self.body = b''
body_file = property(_body_file__get,
_body_file__set,
_body_file__del,
doc=_body_file__get.__doc__)
body_file_raw = environ_getter('wsgi.input')
@property
def body_file_seekable(self):
"""
Get the body of the request (wsgi.input) as a seekable file-like
object. Middleware and routing applications should use this
attribute over .body_file.
If you access this value, CONTENT_LENGTH will also be updated.
"""
if not self.is_body_seekable:
self.make_body_seekable()
return self.body_file_raw
url_encoding = environ_getter('webob.url_encoding', 'UTF-8')
scheme = environ_getter('wsgi.url_scheme')
method = environ_getter('REQUEST_METHOD', 'GET')
http_version = environ_getter('SERVER_PROTOCOL')
content_length = converter(
environ_getter('CONTENT_LENGTH', None, '14.13'),
parse_int_safe, serialize_int, 'int')
remote_user = environ_getter('REMOTE_USER', None)
remote_addr = environ_getter('REMOTE_ADDR', None)
query_string = environ_getter('QUERY_STRING', '')
server_name = environ_getter('SERVER_NAME')
server_port = converter(
environ_getter('SERVER_PORT'),
parse_int, serialize_int, 'int')
script_name = environ_decoder('SCRIPT_NAME', '', encattr='url_encoding')
path_info = environ_decoder('PATH_INFO', encattr='url_encoding')
# bw compat
uscript_name = script_name
upath_info = path_info
_content_type_raw = environ_getter('CONTENT_TYPE', '')
def _content_type__get(self):
"""Return the content type, but leaving off any parameters (like
charset, but also things like the type in ``application/atom+xml;
type=entry``)
If you set this property, you can include parameters, or if
you don't include any parameters in the value then existing
parameters will be preserved.
"""
return self._content_type_raw.split(';', 1)[0]
def _content_type__set(self, value=None):
if value is not None:
value = str(value)
if ';' not in value:
content_type = self._content_type_raw
if ';' in content_type:
value += ';' + content_type.split(';', 1)[1]
self._content_type_raw = value
content_type = property(_content_type__get,
_content_type__set,
_content_type__set,
_content_type__get.__doc__)
_headers = None
def _headers__get(self):
"""
All the request headers as a case-insensitive dictionary-like
object.
"""
if self._headers is None:
self._headers = EnvironHeaders(self.environ)
return self._headers
def _headers__set(self, value):
self.headers.clear()
self.headers.update(value)
headers = property(_headers__get, _headers__set, doc=_headers__get.__doc__)
@property
def client_addr(self):
"""
The effective client IP address as a string. If the
``HTTP_X_FORWARDED_FOR`` header exists in the WSGI environ, this
attribute returns the client IP address present in that header
(e.g. if the header value is ``192.168.1.1, 192.168.1.2``, the value
will be ``192.168.1.1``). If no ``HTTP_X_FORWARDED_FOR`` header is
present in the environ at all, this attribute will return the value
of the ``REMOTE_ADDR`` header. If the ``REMOTE_ADDR`` header is
unset, this attribute will return the value ``None``.
.. warning::
It is possible for user agents to put someone else's IP or just
any string in ``HTTP_X_FORWARDED_FOR`` as it is a normal HTTP
header. Forward proxies can also provide incorrect values (private
IP addresses etc). You cannot "blindly" trust the result of this
method to provide you with valid data unless you're certain that
``HTTP_X_FORWARDED_FOR`` has the correct values. The WSGI server
must be behind a trusted proxy for this to be true.
"""
e = self.environ
xff = e.get('HTTP_X_FORWARDED_FOR')
if xff is not None:
addr = xff.split(',')[0].strip()
else:
addr = e.get('REMOTE_ADDR')
return addr
@property
def host_port(self):
"""
The effective server port number as a string. If the ``HTTP_HOST``
header exists in the WSGI environ, this attribute returns the port
number present in that header. If the ``HTTP_HOST`` header exists but
contains no explicit port number: if the WSGI url scheme is "https" ,
this attribute returns "443", if the WSGI url scheme is "http", this
attribute returns "80" . If no ``HTTP_HOST`` header is present in
the environ at all, this attribute will return the value of the
``SERVER_PORT`` header (which is guaranteed to be present).
"""
e = self.environ
host = e.get('HTTP_HOST')
if host is not None:
if ':' in host:
host, port = host.split(':', 1)
else:
url_scheme = e['wsgi.url_scheme']
if url_scheme == 'https':
port = '443'
else:
port = '80'
else:
port = e['SERVER_PORT']
return port
@property
def host_url(self):
"""
The URL through the host (no path)
"""
e = self.environ
scheme = e.get('wsgi.url_scheme')
url = scheme + '://'
host = e.get('HTTP_HOST')
if host is not None:
if ':' in host:
host, port = host.split(':', 1)
else:
port = None
else:
host = e.get('SERVER_NAME')
port = e.get('SERVER_PORT')
if scheme == 'https':
if port == '443':
port = None
elif scheme == 'http':
if port == '80':
port = None
url += host
if port:
url += ':%s' % port
return url
@property
def application_url(self):
"""
The URL including SCRIPT_NAME (no PATH_INFO or query string)
"""
bscript_name = bytes_(self.script_name, self.url_encoding)
return self.host_url + url_quote(bscript_name, PATH_SAFE)
@property
def path_url(self):
"""
The URL including SCRIPT_NAME and PATH_INFO, but not QUERY_STRING
"""
bpath_info = bytes_(self.path_info, self.url_encoding)
return self.application_url + url_quote(bpath_info, PATH_SAFE)
@property
def path(self):
"""
The path of the request, without host or query string
"""
bscript = bytes_(self.script_name, self.url_encoding)
bpath = bytes_(self.path_info, self.url_encoding)
return url_quote(bscript, PATH_SAFE) + url_quote(bpath, PATH_SAFE)
@property
def path_qs(self):
"""
The path of the request, without host but with query string
"""
path = self.path
qs = self.environ.get('QUERY_STRING')
if qs:
path += '?' + qs
return path
@property
def url(self):
"""
The full request URL, including QUERY_STRING
"""
url = self.path_url
qs = self.environ.get('QUERY_STRING')
if qs:
url += '?' + qs
return url
def relative_url(self, other_url, to_application=False):
"""
Resolve other_url relative to the request URL.
If ``to_application`` is True, then resolve it relative to the
URL with only SCRIPT_NAME
"""
if to_application:
url = self.application_url
if not url.endswith('/'):
url += '/'
else:
url = self.path_url
return urlparse.urljoin(url, other_url)
def path_info_pop(self, pattern=None):
"""
'Pops' off the next segment of PATH_INFO, pushing it onto
SCRIPT_NAME, and returning the popped segment. Returns None if
there is nothing left on PATH_INFO.
Does not return ``''`` when there's an empty segment (like
``/path//path``); these segments are just ignored.
Optional ``pattern`` argument is a regexp to match the return value
before returning. If there is no match, no changes are made to the
request and None is returned.
"""
path = self.path_info
if not path:
return None
slashes = ''
while path.startswith('/'):
slashes += '/'
path = path[1:]
idx = path.find('/')
if idx == -1:
idx = len(path)
r = path[:idx]
if pattern is None or re.match(pattern, r):
self.script_name += slashes + r
self.path_info = path[idx:]
return r
def path_info_peek(self):
"""
Returns the next segment on PATH_INFO, or None if there is no
next segment. Doesn't modify the environment.
"""
path = self.path_info
if not path:
return None
path = path.lstrip('/')
return path.split('/', 1)[0]
def _urlvars__get(self):
"""
Return any *named* variables matched in the URL.
Takes values from ``environ['wsgiorg.routing_args']``.
Systems like ``routes`` set this value.
"""
if 'paste.urlvars' in self.environ:
return self.environ['paste.urlvars']
elif 'wsgiorg.routing_args' in self.environ:
return self.environ['wsgiorg.routing_args'][1]
else:
result = {}
self.environ['wsgiorg.routing_args'] = ((), result)
return result
def _urlvars__set(self, value):
environ = self.environ
if 'wsgiorg.routing_args' in environ:
environ['wsgiorg.routing_args'] = (
environ['wsgiorg.routing_args'][0], value)
if 'paste.urlvars' in environ:
del environ['paste.urlvars']
elif 'paste.urlvars' in environ:
environ['paste.urlvars'] = value
else:
environ['wsgiorg.routing_args'] = ((), value)
def _urlvars__del(self):
if 'paste.urlvars' in self.environ:
del self.environ['paste.urlvars']
if 'wsgiorg.routing_args' in self.environ:
if not self.environ['wsgiorg.routing_args'][0]:
del self.environ['wsgiorg.routing_args']
else:
self.environ['wsgiorg.routing_args'] = (
self.environ['wsgiorg.routing_args'][0], {})
urlvars = property(_urlvars__get,
_urlvars__set,
_urlvars__del,
doc=_urlvars__get.__doc__)
def _urlargs__get(self):
"""
Return any *positional* variables matched in the URL.
Takes values from ``environ['wsgiorg.routing_args']``.
Systems like ``routes`` set this value.
"""
if 'wsgiorg.routing_args' in self.environ:
return self.environ['wsgiorg.routing_args'][0]
else:
# Since you can't update this value in-place, we don't need
# to set the key in the environment
return ()
def _urlargs__set(self, value):
environ = self.environ
if 'paste.urlvars' in environ:
# Some overlap between this and wsgiorg.routing_args; we need
# wsgiorg.routing_args to make this work
routing_args = (value, environ.pop('paste.urlvars'))
elif 'wsgiorg.routing_args' in environ:
routing_args = (value, environ['wsgiorg.routing_args'][1])
else:
routing_args = (value, {})
environ['wsgiorg.routing_args'] = routing_args
def _urlargs__del(self):
if 'wsgiorg.routing_args' in self.environ:
if not self.environ['wsgiorg.routing_args'][1]:
del self.environ['wsgiorg.routing_args']
else:
self.environ['wsgiorg.routing_args'] = (
(), self.environ['wsgiorg.routing_args'][1])
urlargs = property(_urlargs__get,
_urlargs__set,
_urlargs__del,
_urlargs__get.__doc__)
@property
def is_xhr(self):
"""Is X-Requested-With header present and equal to ``XMLHttpRequest``?
Note: this isn't set by every XMLHttpRequest request, it is
only set if you are using a Javascript library that sets it
(or you set the header yourself manually). Currently
Prototype and jQuery are known to set this header."""
return self.environ.get('HTTP_X_REQUESTED_WITH', '') == 'XMLHttpRequest'
def _host__get(self):
"""Host name provided in HTTP_HOST, with fall-back to SERVER_NAME"""
if 'HTTP_HOST' in self.environ:
return self.environ['HTTP_HOST']
else:
return '%(SERVER_NAME)s:%(SERVER_PORT)s' % self.environ
def _host__set(self, value):
self.environ['HTTP_HOST'] = value
def _host__del(self):
if 'HTTP_HOST' in self.environ:
del self.environ['HTTP_HOST']
host = property(_host__get, _host__set, _host__del, doc=_host__get.__doc__)
def _body__get(self):
"""
Return the content of the request body.
"""
if not self.is_body_readable:
return b''
self.make_body_seekable() # we need this to have content_length
r = self.body_file.read(self.content_length)
self.body_file_raw.seek(0)
return r
def _body__set(self, value):
if value is None:
value = b''
if not isinstance(value, bytes):
raise TypeError("You can only set Request.body to bytes (not %r)"
% type(value))
if not http_method_probably_has_body.get(self.method, True):
if not value:
self.content_length = None
self.body_file_raw = io.BytesIO()
return
self.content_length = len(value)
self.body_file_raw = io.BytesIO(value)
self.is_body_seekable = True
def _body__del(self):
self.body = b''
body = property(_body__get, _body__set, _body__del, doc=_body__get.__doc__)
def _json_body__get(self):
"""Access the body of the request as JSON"""
return json.loads(self.body.decode(self.charset))
def _json_body__set(self, value):
self.body = json.dumps(value, separators=(',', ':')).encode(self.charset)
def _json_body__del(self):
del self.body
json = json_body = property(_json_body__get, _json_body__set, _json_body__del)
def _text__get(self):
"""
Get/set the text value of the body
"""
if not self.charset:
raise AttributeError(
"You cannot access Request.text unless charset is set")
body = self.body
return body.decode(self.charset)
def _text__set(self, value):
if not self.charset:
raise AttributeError(
"You cannot access Response.text unless charset is set")
if not isinstance(value, text_type):
raise TypeError(
"You can only set Request.text to a unicode string "
"(not %s)" % type(value))
self.body = value.encode(self.charset)
def _text__del(self):
del self.body
text = property(_text__get, _text__set, _text__del, doc=_text__get.__doc__)
@property
def POST(self):
"""
Return a MultiDict containing all the variables from a form
request. Returns an empty dict-like object for non-form requests.
Form requests are typically POST requests, however PUT requests with
an appropriate Content-Type are also supported.
"""
env = self.environ
if self.method not in ('POST', 'PUT'):
return NoVars('Not a form request')
if 'webob._parsed_post_vars' in env:
vars, body_file = env['webob._parsed_post_vars']
if body_file is self.body_file_raw:
return vars
content_type = self.content_type
if ((self.method == 'PUT' and not content_type)
or content_type not in
('',
'application/x-www-form-urlencoded',
'multipart/form-data')
):
# Not an HTML form submission
return NoVars('Not an HTML form submission (Content-Type: %s)'
% content_type)
self._check_charset()
if self.is_body_seekable:
self.body_file_raw.seek(0)
fs_environ = env.copy()
# FieldStorage assumes a missing CONTENT_LENGTH, but a
# default of 0 is better:
fs_environ.setdefault('CONTENT_LENGTH', '0')
fs_environ['QUERY_STRING'] = ''
if PY3: # pragma: no cover
fs = cgi.FieldStorage(
fp=self.body_file,
environ=fs_environ,
keep_blank_values=True,
encoding='utf8')
vars = MultiDict.from_fieldstorage(fs)
else:
fs = cgi.FieldStorage(
fp=self.body_file,
environ=fs_environ,
keep_blank_values=True)
vars = MultiDict.from_fieldstorage(fs)
#ctype = self.content_type or 'application/x-www-form-urlencoded'
ctype = self._content_type_raw or 'application/x-www-form-urlencoded'
f = FakeCGIBody(vars, ctype)
self.body_file = io.BufferedReader(f)
env['webob._parsed_post_vars'] = (vars, self.body_file_raw)
return vars
@property
def GET(self):
"""
Return a MultiDict containing all the variables from the
QUERY_STRING.
"""
env = self.environ
source = env.get('QUERY_STRING', '')
if 'webob._parsed_query_vars' in env:
vars, qs = env['webob._parsed_query_vars']
if qs == source:
return vars
data = []
if source:
# this is disabled because we want to access req.GET
# for text/plain; charset=ascii uploads for example
#self._check_charset()
data = parse_qsl_text(source)
#d = lambda b: b.decode('utf8')
#data = [(d(k), d(v)) for k,v in data]
vars = GetDict(data, env)
env['webob._parsed_query_vars'] = (vars, source)
return vars
def _check_charset(self):
if self.charset != 'UTF-8':
raise DeprecationWarning(
"Requests are expected to be submitted in UTF-8, not %s. "
"You can fix this by doing req = req.decode('%s')" % (
self.charset, self.charset)
)
@property
def params(self):
"""
A dictionary-like object containing both the parameters from
the query string and request body.
"""
params = NestedMultiDict(self.GET, self.POST)
return params
@property
def cookies(self):
"""
Return a dictionary of cookies as found in the request.
"""
return RequestCookies(self.environ)
@cookies.setter
def cookies(self, val):
self.environ.pop('HTTP_COOKIE', None)
r = RequestCookies(self.environ)
r.update(val)
def copy(self):
"""
Copy the request and environment object.
This only does a shallow copy, except of wsgi.input
"""
self.make_body_seekable()
env = self.environ.copy()
new_req = self.__class__(env)
new_req.copy_body()
return new_req
def copy_get(self):
"""
Copies the request and environment object, but turning this request
into a GET along the way. If this was a POST request (or any other
verb) then it becomes GET, and the request body is thrown away.
"""
env = self.environ.copy()
return self.__class__(env, method='GET', content_type=None,
body=b'')
# webob.is_body_seekable marks input streams that are seekable
# this way we can have seekable input without testing the .seek() method
is_body_seekable = environ_getter('webob.is_body_seekable', False)
#is_body_readable = environ_getter('webob.is_body_readable', False)
def _is_body_readable__get(self):
"""
webob.is_body_readable is a flag that tells us
that we can read the input stream even though
CONTENT_LENGTH is missing. This allows FakeCGIBody
to work and can be used by servers to support
chunked encoding in requests.
For background see https://bitbucket.org/ianb/webob/issue/6
"""
if http_method_probably_has_body.get(self.method):
# known HTTP method with body
return True
elif self.content_length is not None:
# unknown HTTP method, but the Content-Length
# header is present
return True
else:
# last resort -- rely on the special flag
return self.environ.get('webob.is_body_readable', False)
def _is_body_readable__set(self, flag):
self.environ['webob.is_body_readable'] = bool(flag)
is_body_readable = property(_is_body_readable__get, _is_body_readable__set,
doc=_is_body_readable__get.__doc__
)
def make_body_seekable(self):
"""
This forces ``environ['wsgi.input']`` to be seekable.
That means that, the content is copied into a BytesIO or temporary
file and flagged as seekable, so that it will not be unnecessarily
copied again.
After calling this method the .body_file is always seeked to the
start of file and .content_length is not None.
The choice to copy to BytesIO is made from
``self.request_body_tempfile_limit``
"""
if self.is_body_seekable:
self.body_file_raw.seek(0)
else:
self.copy_body()
def copy_body(self):
"""
Copies the body, in cases where it might be shared with
another request object and that is not desired.
This copies the body in-place, either into a BytesIO object
or a temporary file.
"""
if not self.is_body_readable:
# there's no body to copy
self.body = b''
elif self.content_length is None:
# chunked body or FakeCGIBody
self.body = self.body_file_raw.read()
self._copy_body_tempfile()
else:
# try to read body into tempfile
did_copy = self._copy_body_tempfile()
if not did_copy:
# it wasn't necessary, so just read it into memory
self.body = self.body_file.read(self.content_length)
def _copy_body_tempfile(self):
"""
Copy wsgi.input to tempfile if necessary. Returns True if it did.
"""
tempfile_limit = self.request_body_tempfile_limit
todo = self.content_length
assert isinstance(todo, integer_types), todo
if not tempfile_limit or todo <= tempfile_limit:
return False
fileobj = self.make_tempfile()
input = self.body_file
while todo > 0:
data = input.read(min(todo, 65536))
if not data:
# Normally this should not happen, because LimitedLengthFile
# should have raised an exception by now.
# It can happen if the is_body_seekable flag is incorrect.
raise DisconnectionError(
"Client disconnected (%s more bytes were expected)"
% todo
)
fileobj.write(data)
todo -= len(data)
fileobj.seek(0)
self.body_file_raw = fileobj
self.is_body_seekable = True
return True
def make_tempfile(self):
"""
Create a tempfile to store big request body.
This API is not stable yet. A 'size' argument might be added.
"""
return tempfile.TemporaryFile()
def remove_conditional_headers(self,
remove_encoding=True,
remove_range=True,
remove_match=True,
remove_modified=True):
"""
Remove headers that make the request conditional.
These headers can cause the response to be 304 Not Modified,
which in some cases you may not want to be possible.
This does not remove headers like If-Match, which are used for
conflict detection.
"""
check_keys = []
if remove_range:
check_keys += ['HTTP_IF_RANGE', 'HTTP_RANGE']
if remove_match:
check_keys.append('HTTP_IF_NONE_MATCH')
if remove_modified:
check_keys.append('HTTP_IF_MODIFIED_SINCE')
if remove_encoding:
check_keys.append('HTTP_ACCEPT_ENCODING')
for key in check_keys:
if key in self.environ:
del self.environ[key]
accept = accept_property('Accept', '14.1', MIMEAccept, MIMENilAccept)
accept_charset = accept_property('Accept-Charset', '14.2', AcceptCharset)
accept_encoding = accept_property('Accept-Encoding', '14.3',
NilClass=NoAccept)
accept_language = accept_property('Accept-Language', '14.4', AcceptLanguage)
authorization = converter(
environ_getter('HTTP_AUTHORIZATION', None, '14.8'),
parse_auth, serialize_auth,
)
def _cache_control__get(self):
"""
Get/set/modify the Cache-Control header (`HTTP spec section 14.9
<http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9>`_)
"""
env = self.environ
value = env.get('HTTP_CACHE_CONTROL', '')
cache_header, cache_obj = env.get('webob._cache_control', (None, None))
if cache_obj is not None and cache_header == value:
return cache_obj
cache_obj = CacheControl.parse(value,
updates_to=self._update_cache_control,
type='request')
env['webob._cache_control'] = (value, cache_obj)
return cache_obj
def _cache_control__set(self, value):
env = self.environ
value = value or ''
if isinstance(value, dict):
value = CacheControl(value, type='request')
if isinstance(value, CacheControl):
str_value = str(value)
env['HTTP_CACHE_CONTROL'] = str_value
env['webob._cache_control'] = (str_value, value)
else:
env['HTTP_CACHE_CONTROL'] = str(value)
env['webob._cache_control'] = (None, None)
def _cache_control__del(self):
env = self.environ
if 'HTTP_CACHE_CONTROL' in env:
del env['HTTP_CACHE_CONTROL']
if 'webob._cache_control' in env:
del env['webob._cache_control']
def _update_cache_control(self, prop_dict):
self.environ['HTTP_CACHE_CONTROL'] = serialize_cache_control(prop_dict)
cache_control = property(_cache_control__get,
_cache_control__set,
_cache_control__del,
doc=_cache_control__get.__doc__)
if_match = etag_property('HTTP_IF_MATCH', AnyETag, '14.24')
if_none_match = etag_property('HTTP_IF_NONE_MATCH', NoETag, '14.26',
strong=False)
date = converter_date(environ_getter('HTTP_DATE', None, '14.8'))
if_modified_since = converter_date(
environ_getter('HTTP_IF_MODIFIED_SINCE', None, '14.25'))
if_unmodified_since = converter_date(
environ_getter('HTTP_IF_UNMODIFIED_SINCE', None, '14.28'))
if_range = converter(
environ_getter('HTTP_IF_RANGE', None, '14.27'),
IfRange.parse, serialize_if_range, 'IfRange object')
max_forwards = converter(
environ_getter('HTTP_MAX_FORWARDS', None, '14.31'),
parse_int, serialize_int, 'int')
pragma = environ_getter('HTTP_PRAGMA', None, '14.32')
range = converter(
environ_getter('HTTP_RANGE', None, '14.35'),
parse_range, serialize_range, 'Range object')
referer = environ_getter('HTTP_REFERER', None, '14.36')
referrer = referer
user_agent = environ_getter('HTTP_USER_AGENT', None, '14.43')
def __repr__(self):
try:
name = '%s %s' % (self.method, self.url)
except KeyError:
name = '(invalid WSGI environ)'
msg = '<%s at 0x%x %s>' % (
self.__class__.__name__,
abs(id(self)), name)
return msg
def as_bytes(self, skip_body=False):
"""
Return HTTP bytes representing this request.
If skip_body is True, exclude the body.
If skip_body is an integer larger than one, skip body
only if its length is bigger than that number.
"""
url = self.url
host = self.host_url
assert url.startswith(host)
url = url[len(host):]
parts = [bytes_('%s %s %s' % (self.method, url, self.http_version))]
#self.headers.setdefault('Host', self.host)
# acquire body before we handle headers so that
# content-length will be set
body = None
if self.method in ('PUT', 'POST'):
if skip_body > 1:
if len(self.body) > skip_body:
body = bytes_('<body skipped (len=%s)>' % len(self.body))
else:
skip_body = False
if not skip_body:
body = self.body
for k, v in sorted(self.headers.items()):
header = bytes_('%s: %s' % (k, v))
parts.append(header)
if body:
parts.extend([b'', body])
# HTTP clearly specifies CRLF
return b'\r\n'.join(parts)
def as_string(self, skip_body=False):
warn_deprecation(
"Please use req.as_bytes",
'1.3',
self._setattr_stacklevel
)
return self.as_bytes(skip_body=skip_body)
def as_text(self):
bytes = self.as_bytes()
return bytes.decode(self.charset)
__str__ = as_text
@classmethod
def from_bytes(cls, b):
"""
Create a request from HTTP bytes data. If the bytes contain
extra data after the request, raise a ValueError.
"""
f = io.BytesIO(b)
r = cls.from_file(f)
if f.tell() != len(b):
raise ValueError("The string contains more data than expected")
return r
@classmethod
def from_string(cls, b):
warn_deprecation(
"Please use req.from_bytes",
'1.3',
cls._setattr_stacklevel
)
return cls.from_bytes(b)
@classmethod
def from_text(cls, s):
b = bytes_(s, 'utf-8')
return cls.from_bytes(b)
@classmethod
def from_file(cls, fp):
"""Read a request from a file-like object (it must implement
``.read(size)`` and ``.readline()``).
It will read up to the end of the request, not the end of the
file (unless the request is a POST or PUT and has no
Content-Length, in that case, the entire file is read).
This reads the request as represented by ``str(req)``; it may
not read every valid HTTP request properly.
"""
start_line = fp.readline()
is_text = isinstance(start_line, text_type)
if is_text:
crlf = '\r\n'
colon = ':'
else:
crlf = b'\r\n'
colon = b':'
try:
header = start_line.rstrip(crlf)
method, resource, http_version = header.split(None, 2)
method = native_(method, 'utf-8')
resource = native_(resource, 'utf-8')
http_version = native_(http_version, 'utf-8')
except ValueError:
raise ValueError('Bad HTTP request line: %r' % start_line)
r = cls(environ_from_url(resource),
http_version=http_version,
method=method.upper()
)
del r.environ['HTTP_HOST']
while 1:
line = fp.readline()
if not line.strip():
# end of headers
break
hname, hval = line.split(colon, 1)
hname = native_(hname, 'utf-8')
hval = native_(hval, 'utf-8').strip()
if hname in r.headers:
hval = r.headers[hname] + ', ' + hval
r.headers[hname] = hval
if r.method in ('PUT', 'POST'):
clen = r.content_length
if clen is None:
body = fp.read()
else:
body = fp.read(clen)
if is_text:
body = bytes_(body, 'utf-8')
r.body = body
return r
def call_application(self, application, catch_exc_info=False):
"""
Call the given WSGI application, returning ``(status_string,
headerlist, app_iter)``
Be sure to call ``app_iter.close()`` if it's there.
If catch_exc_info is true, then returns ``(status_string,
headerlist, app_iter, exc_info)``, where the fourth item may
be None, but won't be if there was an exception. If you don't
do this and there was an exception, the exception will be
raised directly.
"""
if self.is_body_seekable:
self.body_file_raw.seek(0)
captured = []
output = []
def start_response(status, headers, exc_info=None):
if exc_info is not None and not catch_exc_info:
reraise(exc_info)
captured[:] = [status, headers, exc_info]
return output.append
app_iter = application(self.environ, start_response)
if output or not captured:
try:
output.extend(app_iter)
finally:
if hasattr(app_iter, 'close'):
app_iter.close()
app_iter = output
if catch_exc_info:
return (captured[0], captured[1], app_iter, captured[2])
else:
return (captured[0], captured[1], app_iter)
# Will be filled in later:
ResponseClass = None
def send(self, application=None, catch_exc_info=False):
"""
Like ``.call_application(application)``, except returns a
response object with ``.status``, ``.headers``, and ``.body``
attributes.
This will use ``self.ResponseClass`` to figure out the class
of the response object to return.
If ``application`` is not given, this will send the request to
``self.make_default_send_app()``
"""
if application is None:
application = self.make_default_send_app()
if catch_exc_info:
status, headers, app_iter, exc_info = self.call_application(
application, catch_exc_info=True)
del exc_info
else:
status, headers, app_iter = self.call_application(
application, catch_exc_info=False)
return self.ResponseClass(
status=status, headerlist=list(headers), app_iter=app_iter)
get_response = send
def make_default_send_app(self):
global _client
try:
client = _client
except NameError:
from webob import client
_client = client
return client.send_request_app
@classmethod
def blank(cls, path, environ=None, base_url=None,
headers=None, POST=None, **kw):
"""
Create a blank request environ (and Request wrapper) with the
given path (path should be urlencoded), and any keys from
environ.
The path will become path_info, with any query string split
off and used.
All necessary keys will be added to the environ, but the
values you pass in will take precedence. If you pass in
base_url then wsgi.url_scheme, HTTP_HOST, and SCRIPT_NAME will
be filled in from that value.
Any extra keyword will be passed to ``__init__``.
"""
env = environ_from_url(path)
if base_url:
scheme, netloc, path, query, fragment = urlparse.urlsplit(base_url)
if query or fragment:
raise ValueError(
"base_url (%r) cannot have a query or fragment"
% base_url)
if scheme:
env['wsgi.url_scheme'] = scheme
if netloc:
if ':' not in netloc:
if scheme == 'http':
netloc += ':80'
elif scheme == 'https':
netloc += ':443'
else:
raise ValueError(
"Unknown scheme: %r" % scheme)
host, port = netloc.split(':', 1)
env['SERVER_PORT'] = port
env['SERVER_NAME'] = host
env['HTTP_HOST'] = netloc
if path:
env['SCRIPT_NAME'] = url_unquote(path)
if environ:
env.update(environ)
content_type = kw.get('content_type', env.get('CONTENT_TYPE'))
if headers and 'Content-Type' in headers:
content_type = headers['Content-Type']
if content_type is not None:
kw['content_type'] = content_type
environ_add_POST(env, POST, content_type=content_type)
obj = cls(env, **kw)
if headers is not None:
obj.headers.update(headers)
return obj
class LegacyRequest(BaseRequest):
uscript_name = upath_property('SCRIPT_NAME')
upath_info = upath_property('PATH_INFO')
def encget(self, key, default=NoDefault, encattr=None):
val = self.environ.get(key, default)
if val is NoDefault:
raise KeyError(key)
if val is default:
return default
return val
class AdhocAttrMixin(object):
_setattr_stacklevel = 3
def __setattr__(self, attr, value, DEFAULT=object()):
if (getattr(self.__class__, attr, DEFAULT) is not DEFAULT or
attr.startswith('_')):
object.__setattr__(self, attr, value)
else:
self.environ.setdefault('webob.adhoc_attrs', {})[attr] = value
def __getattr__(self, attr, DEFAULT=object()):
try:
return self.environ['webob.adhoc_attrs'][attr]
except KeyError:
raise AttributeError(attr)
def __delattr__(self, attr, DEFAULT=object()):
if getattr(self.__class__, attr, DEFAULT) is not DEFAULT:
return object.__delattr__(self, attr)
try:
del self.environ['webob.adhoc_attrs'][attr]
except KeyError:
raise AttributeError(attr)
class Request(AdhocAttrMixin, BaseRequest):
""" The default request implementation """
def environ_from_url(path):
if SCHEME_RE.search(path):
scheme, netloc, path, qs, fragment = urlparse.urlsplit(path)
if fragment:
raise TypeError("Path cannot contain a fragment (%r)" % fragment)
if qs:
path += '?' + qs
if ':' not in netloc:
if scheme == 'http':
netloc += ':80'
elif scheme == 'https':
netloc += ':443'
else:
raise TypeError("Unknown scheme: %r" % scheme)
else:
scheme = 'http'
netloc = 'localhost:80'
if path and '?' in path:
path_info, query_string = path.split('?', 1)
path_info = url_unquote(path_info)
else:
path_info = url_unquote(path)
query_string = ''
env = {
'REQUEST_METHOD': 'GET',
'SCRIPT_NAME': '',
'PATH_INFO': path_info or '',
'QUERY_STRING': query_string,
'SERVER_NAME': netloc.split(':')[0],
'SERVER_PORT': netloc.split(':')[1],
'HTTP_HOST': netloc,
'SERVER_PROTOCOL': 'HTTP/1.0',
'wsgi.version': (1, 0),
'wsgi.url_scheme': scheme,
'wsgi.input': io.BytesIO(),
'wsgi.errors': sys.stderr,
'wsgi.multithread': False,
'wsgi.multiprocess': False,
'wsgi.run_once': False,
#'webob.is_body_seekable': True,
}
return env
def environ_add_POST(env, data, content_type=None):
if data is None:
return
elif isinstance(data, text_type): # pragma: no cover
data = data.encode('ascii')
if env['REQUEST_METHOD'] not in ('POST', 'PUT'):
env['REQUEST_METHOD'] = 'POST'
has_files = False
if hasattr(data, 'items'):
data = sorted(data.items())
for k, v in data:
if isinstance(v, (tuple, list)):
has_files = True
break
if content_type is None:
if has_files:
content_type = 'multipart/form-data'
else:
content_type = 'application/x-www-form-urlencoded'
if content_type.startswith('multipart/form-data'):
if not isinstance(data, bytes):
content_type, data = _encode_multipart(data, content_type)
elif content_type.startswith('application/x-www-form-urlencoded'):
if has_files:
raise ValueError('Submiting files is not allowed for'
' content type `%s`' % content_type)
if not isinstance(data, bytes):
data = url_encode(data)
else:
if not isinstance(data, bytes):
raise ValueError('Please provide `POST` data as string'
' for content type `%s`' % content_type)
data = bytes_(data, 'utf8')
env['wsgi.input'] = io.BytesIO(data)
env['webob.is_body_seekable'] = True
env['CONTENT_LENGTH'] = str(len(data))
env['CONTENT_TYPE'] = content_type
#########################
## Helper classes and monkeypatching
#########################
class DisconnectionError(IOError):
pass
class LimitedLengthFile(io.RawIOBase):
def __init__(self, file, maxlen):
self.file = file
self.maxlen = maxlen
self.remaining = maxlen
def __repr__(self):
return '<%s(%r, maxlen=%s)>' % (
self.__class__.__name__,
self.file,
self.maxlen
)
def fileno(self):
return self.file.fileno()
@staticmethod
def readable():
return True
def readinto(self, buff):
if not self.remaining:
return 0
sz0 = min(len(buff), self.remaining)
data = self.file.read(sz0)
sz = len(data)
self.remaining -= sz
#if not data:
if sz < sz0 and self.remaining:
raise DisconnectionError(
"The client disconnected while sending the POST/PUT body "
+ "(%d more bytes were expected)" % self.remaining
)
buff[:sz] = data
return sz
def _cgi_FieldStorage__repr__patch(self):
""" monkey patch for FieldStorage.__repr__
Unbelievably, the default __repr__ on FieldStorage reads
the entire file content instead of being sane about it.
This is a simple replacement that doesn't do that
"""
if self.file:
return "FieldStorage(%r, %r)" % (self.name, self.filename)
return "FieldStorage(%r, %r, %r)" % (self.name, self.filename, self.value)
cgi.FieldStorage.__repr__ = _cgi_FieldStorage__repr__patch
class FakeCGIBody(io.RawIOBase):
def __init__(self, vars, content_type):
if content_type.startswith('multipart/form-data'):
if not _get_multipart_boundary(content_type):
raise ValueError('Content-type: %r does not contain boundary'
% content_type)
self.vars = vars
self.content_type = content_type
self.file = None
def __repr__(self):
inner = repr(self.vars)
if len(inner) > 20:
inner = inner[:15] + '...' + inner[-5:]
return '<%s at 0x%x viewing %s>' % (
self.__class__.__name__,
abs(id(self)), inner)
def fileno(self):
return None
@staticmethod
def readable():
return True
def readinto(self, buff):
if self.file is None:
if self.content_type.startswith(
'application/x-www-form-urlencoded'):
data = '&'.join(
'%s=%s' % (quote_plus(bytes_(k, 'utf8')), quote_plus(bytes_(v, 'utf8')))
for k,v in self.vars.items()
)
self.file = io.BytesIO(bytes_(data))
elif self.content_type.startswith('multipart/form-data'):
self.file = _encode_multipart(
self.vars.items(),
self.content_type,
fout=io.BytesIO()
)[1]
self.file.seek(0)
else:
assert 0, ('Bad content type: %r' % self.content_type)
return self.file.readinto(buff)
def _get_multipart_boundary(ctype):
m = re.search(r'boundary=([^ ]+)', ctype, re.I)
if m:
return native_(m.group(1).strip('"'))
def _encode_multipart(vars, content_type, fout=None):
"""Encode a multipart request body into a string"""
f = fout or io.BytesIO()
w = f.write
wt = lambda t: f.write(t.encode('utf8'))
CRLF = b'\r\n'
boundary = _get_multipart_boundary(content_type)
if not boundary:
boundary = native_(binascii.hexlify(os.urandom(10)))
content_type += ('; boundary=%s' % boundary)
for name, value in vars:
w(b'--')
wt(boundary)
w(CRLF)
assert name is not None, 'Value associated with no name: %r' % value
wt('Content-Disposition: form-data; name="%s"' % name)
filename = None
if getattr(value, 'filename', None):
filename = value.filename
elif isinstance(value, (list, tuple)):
filename, value = value
if hasattr(value, 'read'):
value = value.read()
if filename is not None:
wt('; filename="%s"' % filename)
mime_type = mimetypes.guess_type(filename)[0]
else:
mime_type = None
w(CRLF)
# TODO: should handle value.disposition_options
if getattr(value, 'type', None):
wt('Content-type: %s' % value.type)
if value.type_options:
for ct_name, ct_value in sorted(value.type_options.items()):
wt('; %s="%s"' % (ct_name, ct_value))
w(CRLF)
elif mime_type:
wt('Content-type: %s' % mime_type)
w(CRLF)
w(CRLF)
if hasattr(value, 'value'):
value = value.value
if isinstance(value, bytes):
w(value)
else:
wt(value)
w(CRLF)
wt('--%s--' % boundary)
if fout:
return content_type, fout
else:
return content_type, f.getvalue()
def detect_charset(ctype):
m = CHARSET_RE.search(ctype)
if m:
return m.group(1).strip('"').strip()
def _is_utf8(charset):
if not charset:
return True
else:
return charset.lower().replace('-', '') == 'utf8'
class Transcoder(object):
def __init__(self, charset, errors='strict'):
self.charset = charset # source charset
self.errors = errors # unicode errors
self._trans = lambda b: b.decode(charset, errors).encode('utf8')
def transcode_query(self, q):
if PY3: # pragma: no cover
q_orig = q
if '=' not in q:
# this doesn't look like a form submission
return q_orig
q = list(parse_qsl_text(q, self.charset))
return url_encode(q)
else:
q_orig = q
if '=' not in q:
# this doesn't look like a form submission
return q_orig
q = urlparse.parse_qsl(q, self.charset)
t = self._trans
q = [(t(k), t(v)) for k,v in q]
return url_encode(q)
def transcode_fs(self, fs, content_type):
# transcode FieldStorage
if PY3: # pragma: no cover
decode = lambda b: b
else:
decode = lambda b: b.decode(self.charset, self.errors)
data = []
for field in fs.list or ():
field.name = decode(field.name)
if field.filename:
field.filename = decode(field.filename)
data.append((field.name, field))
else:
data.append((field.name, decode(field.value)))
# TODO: transcode big requests to temp file
content_type, fout = _encode_multipart(
data,
content_type,
fout=io.BytesIO()
)
return fout
# TODO: remove in 1.4
for _name in 'GET POST params cookies'.split():
_str_name = 'str_'+_name
_prop = deprecated_property(
None, _str_name,
"disabled starting WebOb 1.2, use %s instead" % _name, '1.2')
setattr(BaseRequest, _str_name, _prop)
| Python |
from datetime import (
date,
datetime,
)
import re
from webob.byterange import (
ContentRange,
Range,
)
from webob.compat import (
PY3,
text_type,
)
from webob.datetime_utils import (
parse_date,
serialize_date,
)
from webob.util import (
header_docstring,
warn_deprecation,
)
CHARSET_RE = re.compile(r';\s*charset=([^;]*)', re.I)
SCHEME_RE = re.compile(r'^[a-z]+:', re.I)
_not_given = object()
def environ_getter(key, default=_not_given, rfc_section=None):
if rfc_section:
doc = header_docstring(key, rfc_section)
else:
doc = "Gets and sets the ``%s`` key in the environment." % key
if default is _not_given:
def fget(req):
return req.environ[key]
def fset(req, val):
req.environ[key] = val
fdel = None
else:
def fget(req):
return req.environ.get(key, default)
def fset(req, val):
if val is None:
if key in req.environ:
del req.environ[key]
else:
req.environ[key] = val
def fdel(req):
del req.environ[key]
return property(fget, fset, fdel, doc=doc)
def environ_decoder(key, default=_not_given, rfc_section=None,
encattr=None):
if rfc_section:
doc = header_docstring(key, rfc_section)
else:
doc = "Gets and sets the ``%s`` key in the environment." % key
if default is _not_given:
def fget(req):
return req.encget(key, encattr=encattr)
def fset(req, val):
return req.encset(key, val, encattr=encattr)
fdel = None
else:
def fget(req):
return req.encget(key, default, encattr=encattr)
def fset(req, val):
if val is None:
if key in req.environ:
del req.environ[key]
else:
return req.encset(key, val, encattr=encattr)
def fdel(req):
del req.environ[key]
return property(fget, fset, fdel, doc=doc)
def upath_property(key):
if PY3: # pragma: no cover
def fget(req):
encoding = req.url_encoding
return req.environ.get(key, '').encode('latin-1').decode(encoding)
def fset(req, val):
encoding = req.url_encoding
req.environ[key] = val.encode(encoding).decode('latin-1')
else:
def fget(req):
encoding = req.url_encoding
return req.environ.get(key, '').decode(encoding)
def fset(req, val):
encoding = req.url_encoding
if isinstance(val, text_type):
val = val.encode(encoding)
req.environ[key] = val
return property(fget, fset, doc='upath_property(%r)' % key)
def deprecated_property(attr, name, text, version): # pragma: no cover
"""
Wraps a descriptor, with a deprecation warning or error
"""
def warn():
warn_deprecation('The attribute %s is deprecated: %s'
% (attr, text),
version,
3
)
def fget(self):
warn()
return attr.__get__(self, type(self))
def fset(self, val):
warn()
attr.__set__(self, val)
def fdel(self):
warn()
attr.__delete__(self)
return property(fget, fset, fdel,
'<Deprecated attribute %s>' % attr
)
def header_getter(header, rfc_section):
doc = header_docstring(header, rfc_section)
key = header.lower()
def fget(r):
for k, v in r._headerlist:
if k.lower() == key:
return v
def fset(r, value):
fdel(r)
if value is not None:
if isinstance(value, text_type) and not PY3:
value = value.encode('latin-1')
r._headerlist.append((header, value))
def fdel(r):
items = r._headerlist
for i in range(len(items)-1, -1, -1):
if items[i][0].lower() == key:
del items[i]
return property(fget, fset, fdel, doc)
def converter(prop, parse, serialize, convert_name=None):
assert isinstance(prop, property)
convert_name = convert_name or "``%s`` and ``%s``" % (parse.__name__,
serialize.__name__)
doc = prop.__doc__ or ''
doc += " Converts it using %s." % convert_name
hget, hset = prop.fget, prop.fset
def fget(r):
return parse(hget(r))
def fset(r, val):
if val is not None:
val = serialize(val)
hset(r, val)
return property(fget, fset, prop.fdel, doc)
def list_header(header, rfc_section):
prop = header_getter(header, rfc_section)
return converter(prop, parse_list, serialize_list, 'list')
def parse_list(value):
if not value:
return None
return tuple(filter(None, [v.strip() for v in value.split(',')]))
def serialize_list(value):
if isinstance(value, (text_type, bytes)):
return str(value)
else:
return ', '.join(map(str, value))
def converter_date(prop):
return converter(prop, parse_date, serialize_date, 'HTTP date')
def date_header(header, rfc_section):
return converter_date(header_getter(header, rfc_section))
########################
## Converter functions
########################
_rx_etag = re.compile(r'(?:^|\s)(W/)?"((?:\\"|.)*?)"')
def parse_etag_response(value, strong=False):
"""
Parse a response ETag.
See:
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
"""
if not value:
return None
m = _rx_etag.match(value)
if not m:
# this etag is invalid, but we'll just return it anyway
return value
elif strong and m.group(1):
# this is a weak etag and we want only strong ones
return None
else:
return m.group(2).replace('\\"', '"')
def serialize_etag_response(value): #return '"%s"' % value.replace('"', '\\"')
strong = True
if isinstance(value, tuple):
value, strong = value
elif _rx_etag.match(value):
# this is a valid etag already
return value
# let's quote the value
r = '"%s"' % value.replace('"', '\\"')
if not strong:
r = 'W/' + r
return r
def serialize_if_range(value):
if isinstance(value, (datetime, date)):
return serialize_date(value)
value = str(value)
return value or None
def parse_range(value):
if not value:
return None
# Might return None too:
return Range.parse(value)
def serialize_range(value):
if not value:
return None
elif isinstance(value, (list, tuple)):
return str(Range(*value))
else:
assert isinstance(value, str)
return value
def parse_int(value):
if value is None or value == '':
return None
return int(value)
def parse_int_safe(value):
if value is None or value == '':
return None
try:
return int(value)
except ValueError:
return None
serialize_int = str
def parse_content_range(value):
if not value or not value.strip():
return None
# May still return None
return ContentRange.parse(value)
def serialize_content_range(value):
if isinstance(value, (tuple, list)):
if len(value) not in (2, 3):
raise ValueError(
"When setting content_range to a list/tuple, it must "
"be length 2 or 3 (not %r)" % value)
if len(value) == 2:
begin, end = value
length = None
else:
begin, end, length = value
value = ContentRange(begin, end, length)
value = str(value).strip()
if not value:
return None
return value
_rx_auth_param = re.compile(r'([a-z]+)=(".*?"|[^,]*)(?:\Z|, *)')
def parse_auth_params(params):
r = {}
for k, v in _rx_auth_param.findall(params):
r[k] = v.strip('"')
return r
# see http://lists.w3.org/Archives/Public/ietf-http-wg/2009OctDec/0297.html
known_auth_schemes = ['Basic', 'Digest', 'WSSE', 'HMACDigest', 'GoogleLogin',
'Cookie', 'OpenID']
known_auth_schemes = dict.fromkeys(known_auth_schemes, None)
def parse_auth(val):
if val is not None:
authtype, params = val.split(' ', 1)
if authtype in known_auth_schemes:
if authtype == 'Basic' and '"' not in params:
# this is the "Authentication: Basic XXXXX==" case
pass
else:
params = parse_auth_params(params)
return authtype, params
return val
def serialize_auth(val):
if isinstance(val, (tuple, list)):
authtype, params = val
if isinstance(params, dict):
params = ', '.join(map('%s="%s"'.__mod__, params.items()))
assert isinstance(params, str)
return '%s %s' % (authtype, params)
return val
| Python |
"""
Decorators to wrap functions to make them WSGI applications.
The main decorator :class:`wsgify` turns a function into a WSGI
application (while also allowing normal calling of the method with an
instantiated request).
"""
from webob.compat import (
bytes_,
text_type,
)
from webob.request import Request
from webob.exc import HTTPException
__all__ = ['wsgify']
class wsgify(object):
"""Turns a request-taking, response-returning function into a WSGI
app
You can use this like::
@wsgify
def myfunc(req):
return webob.Response('hey there')
With that ``myfunc`` will be a WSGI application, callable like
``app_iter = myfunc(environ, start_response)``. You can also call
it like normal, e.g., ``resp = myfunc(req)``. (You can also wrap
methods, like ``def myfunc(self, req)``.)
If you raise exceptions from :mod:`webob.exc` they will be turned
into WSGI responses.
There are also several parameters you can use to customize the
decorator. Most notably, you can use a :class:`webob.Request`
subclass, like::
class MyRequest(webob.Request):
@property
def is_local(self):
return self.remote_addr == '127.0.0.1'
@wsgify(RequestClass=MyRequest)
def myfunc(req):
if req.is_local:
return Response('hi!')
else:
raise webob.exc.HTTPForbidden
Another customization you can add is to add `args` (positional
arguments) or `kwargs` (of course, keyword arguments). While
generally not that useful, you can use this to create multiple
WSGI apps from one function, like::
import simplejson
def serve_json(req, json_obj):
return Response(json.dumps(json_obj),
content_type='application/json')
serve_ob1 = wsgify(serve_json, args=(ob1,))
serve_ob2 = wsgify(serve_json, args=(ob2,))
You can return several things from a function:
* A :class:`webob.Response` object (or subclass)
* *Any* WSGI application
* None, and then ``req.response`` will be used (a pre-instantiated
Response object)
* A string, which will be written to ``req.response`` and then that
response will be used.
* Raise an exception from :mod:`webob.exc`
Also see :func:`wsgify.middleware` for a way to make middleware.
You can also subclass this decorator; the most useful things to do
in a subclass would be to change `RequestClass` or override
`call_func` (e.g., to add ``req.urlvars`` as keyword arguments to
the function).
"""
RequestClass = Request
def __init__(self, func=None, RequestClass=None,
args=(), kwargs=None, middleware_wraps=None):
self.func = func
if (RequestClass is not None
and RequestClass is not self.RequestClass):
self.RequestClass = RequestClass
self.args = tuple(args)
if kwargs is None:
kwargs = {}
self.kwargs = kwargs
self.middleware_wraps = middleware_wraps
def __repr__(self):
return '<%s at %s wrapping %r>' % (self.__class__.__name__,
id(self), self.func)
def __get__(self, obj, type=None):
# This handles wrapping methods
if hasattr(self.func, '__get__'):
return self.clone(self.func.__get__(obj, type))
else:
return self
def __call__(self, req, *args, **kw):
"""Call this as a WSGI application or with a request"""
func = self.func
if func is None:
if args or kw:
raise TypeError(
"Unbound %s can only be called with the function it "
"will wrap" % self.__class__.__name__)
func = req
return self.clone(func)
if isinstance(req, dict):
if len(args) != 1 or kw:
raise TypeError(
"Calling %r as a WSGI app with the wrong signature")
environ = req
start_response = args[0]
req = self.RequestClass(environ)
req.response = req.ResponseClass()
try:
args = self.args
if self.middleware_wraps:
args = (self.middleware_wraps,) + args
resp = self.call_func(req, *args, **self.kwargs)
except HTTPException as exc:
resp = exc
if resp is None:
## FIXME: I'm not sure what this should be?
resp = req.response
if isinstance(resp, text_type):
resp = bytes_(resp, req.charset)
if isinstance(resp, bytes):
body = resp
resp = req.response
resp.write(body)
if resp is not req.response:
resp = req.response.merge_cookies(resp)
return resp(environ, start_response)
else:
if self.middleware_wraps:
args = (self.middleware_wraps,) + args
return self.func(req, *args, **kw)
def get(self, url, **kw):
"""Run a GET request on this application, returning a Response.
This creates a request object using the given URL, and any
other keyword arguments are set on the request object (e.g.,
``last_modified=datetime.now()``).
::
resp = myapp.get('/article?id=10')
"""
kw.setdefault('method', 'GET')
req = self.RequestClass.blank(url, **kw)
return self(req)
def post(self, url, POST=None, **kw):
"""Run a POST request on this application, returning a Response.
The second argument (`POST`) can be the request body (a
string), or a dictionary or list of two-tuples, that give the
POST body.
::
resp = myapp.post('/article/new',
dict(title='My Day',
content='I ate a sandwich'))
"""
kw.setdefault('method', 'POST')
req = self.RequestClass.blank(url, POST=POST, **kw)
return self(req)
def request(self, url, **kw):
"""Run a request on this application, returning a Response.
This can be used for DELETE, PUT, etc requests. E.g.::
resp = myapp.request('/article/1', method='PUT', body='New article')
"""
req = self.RequestClass.blank(url, **kw)
return self(req)
def call_func(self, req, *args, **kwargs):
"""Call the wrapped function; override this in a subclass to
change how the function is called."""
return self.func(req, *args, **kwargs)
def clone(self, func=None, **kw):
"""Creates a copy/clone of this object, but with some
parameters rebound
"""
kwargs = {}
if func is not None:
kwargs['func'] = func
if self.RequestClass is not self.__class__.RequestClass:
kwargs['RequestClass'] = self.RequestClass
if self.args:
kwargs['args'] = self.args
if self.kwargs:
kwargs['kwargs'] = self.kwargs
kwargs.update(kw)
return self.__class__(**kwargs)
# To match @decorator:
@property
def undecorated(self):
return self.func
@classmethod
def middleware(cls, middle_func=None, app=None, **kw):
"""Creates middleware
Use this like::
@wsgify.middleware
def restrict_ip(app, req, ips):
if req.remote_addr not in ips:
raise webob.exc.HTTPForbidden('Bad IP: %s' % req.remote_addr)
return app
@wsgify
def app(req):
return 'hi'
wrapped = restrict_ip(app, ips=['127.0.0.1'])
Or if you want to write output-rewriting middleware::
@wsgify.middleware
def all_caps(app, req):
resp = req.get_response(app)
resp.body = resp.body.upper()
return resp
wrapped = all_caps(app)
Note that you must call ``req.get_response(app)`` to get a WebOb
response object. If you are not modifying the output, you can just
return the app.
As you can see, this method doesn't actually create an application, but
creates "middleware" that can be bound to an application, along with
"configuration" (that is, any other keyword arguments you pass when
binding the application).
"""
if middle_func is None:
return _UnboundMiddleware(cls, app, kw)
if app is None:
return _MiddlewareFactory(cls, middle_func, kw)
return cls(middle_func, middleware_wraps=app, kwargs=kw)
class _UnboundMiddleware(object):
"""A `wsgify.middleware` invocation that has not yet wrapped a
middleware function; the intermediate object when you do
something like ``@wsgify.middleware(RequestClass=Foo)``
"""
def __init__(self, wrapper_class, app, kw):
self.wrapper_class = wrapper_class
self.app = app
self.kw = kw
def __repr__(self):
return '<%s at %s wrapping %r>' % (self.__class__.__name__,
id(self), self.app)
def __call__(self, func, app=None):
if app is None:
app = self.app
return self.wrapper_class.middleware(func, app=app, **self.kw)
class _MiddlewareFactory(object):
"""A middleware that has not yet been bound to an application or
configured.
"""
def __init__(self, wrapper_class, middleware, kw):
self.wrapper_class = wrapper_class
self.middleware = middleware
self.kw = kw
def __repr__(self):
return '<%s at %s wrapping %r>' % (self.__class__.__name__, id(self),
self.middleware)
def __call__(self, app, **config):
kw = self.kw.copy()
kw.update(config)
return self.wrapper_class.middleware(self.middleware, app, **kw)
| Python |
"""
HTTP Exception
--------------
This module processes Python exceptions that relate to HTTP exceptions
by defining a set of exceptions, all subclasses of HTTPException.
Each exception, in addition to being a Python exception that can be
raised and caught, is also a WSGI application and ``webob.Response``
object.
This module defines exceptions according to RFC 2068 [1]_ : codes with
100-300 are not really errors; 400's are client errors, and 500's are
server errors. According to the WSGI specification [2]_ , the application
can call ``start_response`` more then once only under two conditions:
(a) the response has not yet been sent, or (b) if the second and
subsequent invocations of ``start_response`` have a valid ``exc_info``
argument obtained from ``sys.exc_info()``. The WSGI specification then
requires the server or gateway to handle the case where content has been
sent and then an exception was encountered.
Exception
HTTPException
HTTPOk
* 200 - HTTPOk
* 201 - HTTPCreated
* 202 - HTTPAccepted
* 203 - HTTPNonAuthoritativeInformation
* 204 - HTTPNoContent
* 205 - HTTPResetContent
* 206 - HTTPPartialContent
HTTPRedirection
* 300 - HTTPMultipleChoices
* 301 - HTTPMovedPermanently
* 302 - HTTPFound
* 303 - HTTPSeeOther
* 304 - HTTPNotModified
* 305 - HTTPUseProxy
* 306 - Unused (not implemented, obviously)
* 307 - HTTPTemporaryRedirect
HTTPError
HTTPClientError
* 400 - HTTPBadRequest
* 401 - HTTPUnauthorized
* 402 - HTTPPaymentRequired
* 403 - HTTPForbidden
* 404 - HTTPNotFound
* 405 - HTTPMethodNotAllowed
* 406 - HTTPNotAcceptable
* 407 - HTTPProxyAuthenticationRequired
* 408 - HTTPRequestTimeout
* 409 - HTTPConflict
* 410 - HTTPGone
* 411 - HTTPLengthRequired
* 412 - HTTPPreconditionFailed
* 413 - HTTPRequestEntityTooLarge
* 414 - HTTPRequestURITooLong
* 415 - HTTPUnsupportedMediaType
* 416 - HTTPRequestRangeNotSatisfiable
* 417 - HTTPExpectationFailed
* 428 - HTTPPreconditionRequired
* 429 - HTTPTooManyRequests
* 431 - HTTPRequestHeaderFieldsTooLarge
HTTPServerError
* 500 - HTTPInternalServerError
* 501 - HTTPNotImplemented
* 502 - HTTPBadGateway
* 503 - HTTPServiceUnavailable
* 504 - HTTPGatewayTimeout
* 505 - HTTPVersionNotSupported
* 511 - HTTPNetworkAuthenticationRequired
Subclass usage notes:
---------------------
The HTTPException class is complicated by 4 factors:
1. The content given to the exception may either be plain-text or
as html-text.
2. The template may want to have string-substitutions taken from
the current ``environ`` or values from incoming headers. This
is especially troublesome due to case sensitivity.
3. The final output may either be text/plain or text/html
mime-type as requested by the client application.
4. Each exception has a default explanation, but those who
raise exceptions may want to provide additional detail.
Subclass attributes and call parameters are designed to provide an easier path
through the complications.
Attributes:
``code``
the HTTP status code for the exception
``title``
remainder of the status line (stuff after the code)
``explanation``
a plain-text explanation of the error message that is
not subject to environment or header substitutions;
it is accessible in the template via %(explanation)s
``detail``
a plain-text message customization that is not subject
to environment or header substitutions; accessible in
the template via %(detail)s
``body_template``
a content fragment (in HTML) used for environment and
header substitution; the default template includes both
the explanation and further detail provided in the
message
Parameters:
``detail``
a plain-text override of the default ``detail``
``headers``
a list of (k,v) header pairs
``comment``
a plain-text additional information which is
usually stripped/hidden for end-users
``body_template``
a string.Template object containing a content fragment in HTML
that frames the explanation and further detail
To override the template (which is HTML content) or the plain-text
explanation, one must subclass the given exception; or customize it
after it has been created. This particular breakdown of a message
into explanation, detail and template allows both the creation of
plain-text and html messages for various clients as well as
error-free substitution of environment variables and headers.
The subclasses of :class:`~_HTTPMove`
(:class:`~HTTPMultipleChoices`, :class:`~HTTPMovedPermanently`,
:class:`~HTTPFound`, :class:`~HTTPSeeOther`, :class:`~HTTPUseProxy` and
:class:`~HTTPTemporaryRedirect`) are redirections that require a ``Location``
field. Reflecting this, these subclasses have two additional keyword arguments:
``location`` and ``add_slash``.
Parameters:
``location``
to set the location immediately
``add_slash``
set to True to redirect to the same URL as the request, except with a
``/`` appended
Relative URLs in the location will be resolved to absolute.
References:
.. [1] http://www.python.org/peps/pep-0333.html#error-handling
.. [2] http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5
"""
from string import Template
import re
import sys
from webob.compat import (
class_types,
text_,
text_type,
urlparse,
)
from webob.request import Request
from webob.response import Response
from webob.util import (
html_escape,
warn_deprecation,
)
tag_re = re.compile(r'<.*?>', re.S)
br_re = re.compile(r'<br.*?>', re.I|re.S)
comment_re = re.compile(r'<!--|-->')
def no_escape(value):
if value is None:
return ''
if not isinstance(value, text_type):
if hasattr(value, '__unicode__'):
value = value.__unicode__()
if isinstance(value, bytes):
value = text_(value, 'utf-8')
else:
value = text_type(value)
return value
def strip_tags(value):
value = value.replace('\n', ' ')
value = value.replace('\r', '')
value = br_re.sub('\n', value)
value = comment_re.sub('', value)
value = tag_re.sub('', value)
return value
class HTTPException(Exception):
def __init__(self, message, wsgi_response):
Exception.__init__(self, message)
self.wsgi_response = wsgi_response
def __call__(self, environ, start_response):
return self.wsgi_response(environ, start_response)
# TODO: remove in version 1.3
@property
def exception(self):
warn_deprecation(
"As of WebOb 1.2, raise the HTTPException instance directly "
"instead of raising the result of 'HTTPException.exception'",
'1.3', 2)
return self
class WSGIHTTPException(Response, HTTPException):
## You should set in subclasses:
# code = 200
# title = 'OK'
# explanation = 'why this happens'
# body_template_obj = Template('response template')
code = None
title = None
explanation = ''
body_template_obj = Template('''\
${explanation}<br /><br />
${detail}
${html_comment}
''')
plain_template_obj = Template('''\
${status}
${body}''')
html_template_obj = Template('''\
<html>
<head>
<title>${status}</title>
</head>
<body>
<h1>${status}</h1>
${body}
</body>
</html>''')
## Set this to True for responses that should have no request body
empty_body = False
def __init__(self, detail=None, headers=None, comment=None,
body_template=None, **kw):
Response.__init__(self,
status='%s %s' % (self.code, self.title),
**kw)
Exception.__init__(self, detail)
if headers:
self.headers.extend(headers)
self.detail = detail
self.comment = comment
if body_template is not None:
self.body_template = body_template
self.body_template_obj = Template(body_template)
if self.empty_body:
del self.content_type
del self.content_length
def __str__(self):
return self.detail or self.explanation
def _make_body(self, environ, escape):
args = {
'explanation': escape(self.explanation),
'detail': escape(self.detail or ''),
'comment': escape(self.comment or ''),
}
if self.comment:
args['html_comment'] = '<!-- %s -->' % escape(self.comment)
else:
args['html_comment'] = ''
if WSGIHTTPException.body_template_obj is not self.body_template_obj:
# Custom template; add headers to args
for k, v in environ.items():
args[k] = escape(v)
for k, v in self.headers.items():
args[k.lower()] = escape(v)
t_obj = self.body_template_obj
return t_obj.substitute(args)
def plain_body(self, environ):
body = self._make_body(environ, no_escape)
body = strip_tags(body)
return self.plain_template_obj.substitute(status=self.status,
title=self.title,
body=body)
def html_body(self, environ):
body = self._make_body(environ, html_escape)
return self.html_template_obj.substitute(status=self.status,
body=body)
def generate_response(self, environ, start_response):
if self.content_length is not None:
del self.content_length
headerlist = list(self.headerlist)
accept = environ.get('HTTP_ACCEPT', '')
if accept and 'html' in accept or '*/*' in accept:
content_type = 'text/html'
body = self.html_body(environ)
else:
content_type = 'text/plain'
body = self.plain_body(environ)
extra_kw = {}
if isinstance(body, text_type):
extra_kw.update(charset='utf-8')
resp = Response(body,
status=self.status,
headerlist=headerlist,
content_type=content_type,
**extra_kw
)
resp.content_type = content_type
return resp(environ, start_response)
def __call__(self, environ, start_response):
is_head = environ['REQUEST_METHOD'] == 'HEAD'
if self.body or self.empty_body or is_head:
app_iter = Response.__call__(self, environ, start_response)
else:
app_iter = self.generate_response(environ, start_response)
if is_head:
app_iter = []
return app_iter
@property
def wsgi_response(self):
return self
class HTTPError(WSGIHTTPException):
"""
base class for status codes in the 400's and 500's
This is an exception which indicates that an error has occurred,
and that any work in progress should not be committed. These are
typically results in the 400's and 500's.
"""
class HTTPRedirection(WSGIHTTPException):
"""
base class for 300's status code (redirections)
This is an abstract base class for 3xx redirection. It indicates
that further action needs to be taken by the user agent in order
to fulfill the request. It does not necessarly signal an error
condition.
"""
class HTTPOk(WSGIHTTPException):
"""
Base class for the 200's status code (successful responses)
code: 200, title: OK
"""
code = 200
title = 'OK'
############################################################
## 2xx success
############################################################
class HTTPCreated(HTTPOk):
"""
subclass of :class:`~HTTPOk`
This indicates that request has been fulfilled and resulted in a new
resource being created.
code: 201, title: Created
"""
code = 201
title = 'Created'
class HTTPAccepted(HTTPOk):
"""
subclass of :class:`~HTTPOk`
This indicates that the request has been accepted for processing, but the
processing has not been completed.
code: 202, title: Accepted
"""
code = 202
title = 'Accepted'
explanation = 'The request is accepted for processing.'
class HTTPNonAuthoritativeInformation(HTTPOk):
"""
subclass of :class:`~HTTPOk`
This indicates that the returned metainformation in the entity-header is
not the definitive set as available from the origin server, but is
gathered from a local or a third-party copy.
code: 203, title: Non-Authoritative Information
"""
code = 203
title = 'Non-Authoritative Information'
class HTTPNoContent(HTTPOk):
"""
subclass of :class:`~HTTPOk`
This indicates that the server has fulfilled the request but does
not need to return an entity-body, and might want to return updated
metainformation.
code: 204, title: No Content
"""
code = 204
title = 'No Content'
empty_body = True
class HTTPResetContent(HTTPOk):
"""
subclass of :class:`~HTTPOk`
This indicates that the the server has fulfilled the request and
the user agent SHOULD reset the document view which caused the
request to be sent.
code: 205, title: Reset Content
"""
code = 205
title = 'Reset Content'
empty_body = True
class HTTPPartialContent(HTTPOk):
"""
subclass of :class:`~HTTPOk`
This indicates that the server has fulfilled the partial GET
request for the resource.
code: 206, title: Partial Content
"""
code = 206
title = 'Partial Content'
############################################################
## 3xx redirection
############################################################
class _HTTPMove(HTTPRedirection):
"""
redirections which require a Location field
Since a 'Location' header is a required attribute of 301, 302, 303,
305 and 307 (but not 304), this base class provides the mechanics to
make this easy.
You can provide a location keyword argument to set the location
immediately. You may also give ``add_slash=True`` if you want to
redirect to the same URL as the request, except with a ``/`` added
to the end.
Relative URLs in the location will be resolved to absolute.
"""
explanation = 'The resource has been moved to'
body_template_obj = Template('''\
${explanation} <a href="${location}">${location}</a>;
you should be redirected automatically.
${detail}
${html_comment}''')
def __init__(self, detail=None, headers=None, comment=None,
body_template=None, location=None, add_slash=False):
super(_HTTPMove, self).__init__(
detail=detail, headers=headers, comment=comment,
body_template=body_template)
if location is not None:
self.location = location
if add_slash:
raise TypeError(
"You can only provide one of the arguments location "
"and add_slash")
self.add_slash = add_slash
def __call__(self, environ, start_response):
req = Request(environ)
if self.add_slash:
url = req.path_url
url += '/'
if req.environ.get('QUERY_STRING'):
url += '?' + req.environ['QUERY_STRING']
self.location = url
self.location = urlparse.urljoin(req.path_url, self.location)
return super(_HTTPMove, self).__call__(
environ, start_response)
class HTTPMultipleChoices(_HTTPMove):
"""
subclass of :class:`~_HTTPMove`
This indicates that the requested resource corresponds to any one
of a set of representations, each with its own specific location,
and agent-driven negotiation information is being provided so that
the user can select a preferred representation and redirect its
request to that location.
code: 300, title: Multiple Choices
"""
code = 300
title = 'Multiple Choices'
class HTTPMovedPermanently(_HTTPMove):
"""
subclass of :class:`~_HTTPMove`
This indicates that the requested resource has been assigned a new
permanent URI and any future references to this resource SHOULD use
one of the returned URIs.
code: 301, title: Moved Permanently
"""
code = 301
title = 'Moved Permanently'
class HTTPFound(_HTTPMove):
"""
subclass of :class:`~_HTTPMove`
This indicates that the requested resource resides temporarily under
a different URI.
code: 302, title: Found
"""
code = 302
title = 'Found'
explanation = 'The resource was found at'
# This one is safe after a POST (the redirected location will be
# retrieved with GET):
class HTTPSeeOther(_HTTPMove):
"""
subclass of :class:`~_HTTPMove`
This indicates that the response to the request can be found under
a different URI and SHOULD be retrieved using a GET method on that
resource.
code: 303, title: See Other
"""
code = 303
title = 'See Other'
class HTTPNotModified(HTTPRedirection):
"""
subclass of :class:`~HTTPRedirection`
This indicates that if the client has performed a conditional GET
request and access is allowed, but the document has not been
modified, the server SHOULD respond with this status code.
code: 304, title: Not Modified
"""
# TODO: this should include a date or etag header
code = 304
title = 'Not Modified'
empty_body = True
class HTTPUseProxy(_HTTPMove):
"""
subclass of :class:`~_HTTPMove`
This indicates that the requested resource MUST be accessed through
the proxy given by the Location field.
code: 305, title: Use Proxy
"""
# Not a move, but looks a little like one
code = 305
title = 'Use Proxy'
explanation = (
'The resource must be accessed through a proxy located at')
class HTTPTemporaryRedirect(_HTTPMove):
"""
subclass of :class:`~_HTTPMove`
This indicates that the requested resource resides temporarily
under a different URI.
code: 307, title: Temporary Redirect
"""
code = 307
title = 'Temporary Redirect'
############################################################
## 4xx client error
############################################################
class HTTPClientError(HTTPError):
"""
base class for the 400's, where the client is in error
This is an error condition in which the client is presumed to be
in-error. This is an expected problem, and thus is not considered
a bug. A server-side traceback is not warranted. Unless specialized,
this is a '400 Bad Request'
"""
code = 400
title = 'Bad Request'
explanation = ('The server could not comply with the request since\r\n'
'it is either malformed or otherwise incorrect.\r\n')
class HTTPBadRequest(HTTPClientError):
pass
class HTTPUnauthorized(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the request requires user authentication.
code: 401, title: Unauthorized
"""
code = 401
title = 'Unauthorized'
explanation = (
'This server could not verify that you are authorized to\r\n'
'access the document you requested. Either you supplied the\r\n'
'wrong credentials (e.g., bad password), or your browser\r\n'
'does not understand how to supply the credentials required.\r\n')
class HTTPPaymentRequired(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
code: 402, title: Payment Required
"""
code = 402
title = 'Payment Required'
explanation = ('Access was denied for financial reasons.')
class HTTPForbidden(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the server understood the request, but is
refusing to fulfill it.
code: 403, title: Forbidden
"""
code = 403
title = 'Forbidden'
explanation = ('Access was denied to this resource.')
class HTTPNotFound(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the server did not find anything matching the
Request-URI.
code: 404, title: Not Found
"""
code = 404
title = 'Not Found'
explanation = ('The resource could not be found.')
class HTTPMethodNotAllowed(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the method specified in the Request-Line is
not allowed for the resource identified by the Request-URI.
code: 405, title: Method Not Allowed
"""
code = 405
title = 'Method Not Allowed'
# override template since we need an environment variable
body_template_obj = Template('''\
The method ${REQUEST_METHOD} is not allowed for this resource. <br /><br />
${detail}''')
class HTTPNotAcceptable(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates the resource identified by the request is only
capable of generating response entities which have content
characteristics not acceptable according to the accept headers
sent in the request.
code: 406, title: Not Acceptable
"""
code = 406
title = 'Not Acceptable'
# override template since we need an environment variable
template = Template('''\
The resource could not be generated that was acceptable to your browser
(content of type ${HTTP_ACCEPT}. <br /><br />
${detail}''')
class HTTPProxyAuthenticationRequired(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This is similar to 401, but indicates that the client must first
authenticate itself with the proxy.
code: 407, title: Proxy Authentication Required
"""
code = 407
title = 'Proxy Authentication Required'
explanation = ('Authentication with a local proxy is needed.')
class HTTPRequestTimeout(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the client did not produce a request within
the time that the server was prepared to wait.
code: 408, title: Request Timeout
"""
code = 408
title = 'Request Timeout'
explanation = ('The server has waited too long for the request to '
'be sent by the client.')
class HTTPConflict(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the request could not be completed due to a
conflict with the current state of the resource.
code: 409, title: Conflict
"""
code = 409
title = 'Conflict'
explanation = ('There was a conflict when trying to complete '
'your request.')
class HTTPGone(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the requested resource is no longer available
at the server and no forwarding address is known.
code: 410, title: Gone
"""
code = 410
title = 'Gone'
explanation = ('This resource is no longer available. No forwarding '
'address is given.')
class HTTPLengthRequired(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the the server refuses to accept the request
without a defined Content-Length.
code: 411, title: Length Required
"""
code = 411
title = 'Length Required'
explanation = ('Content-Length header required.')
class HTTPPreconditionFailed(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the precondition given in one or more of the
request-header fields evaluated to false when it was tested on the
server.
code: 412, title: Precondition Failed
"""
code = 412
title = 'Precondition Failed'
explanation = ('Request precondition failed.')
class HTTPRequestEntityTooLarge(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the server is refusing to process a request
because the request entity is larger than the server is willing or
able to process.
code: 413, title: Request Entity Too Large
"""
code = 413
title = 'Request Entity Too Large'
explanation = ('The body of your request was too large for this server.')
class HTTPRequestURITooLong(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the server is refusing to service the request
because the Request-URI is longer than the server is willing to
interpret.
code: 414, title: Request-URI Too Long
"""
code = 414
title = 'Request-URI Too Long'
explanation = ('The request URI was too long for this server.')
class HTTPUnsupportedMediaType(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the server is refusing to service the request
because the entity of the request is in a format not supported by
the requested resource for the requested method.
code: 415, title: Unsupported Media Type
"""
code = 415
title = 'Unsupported Media Type'
# override template since we need an environment variable
template_obj = Template('''\
The request media type ${CONTENT_TYPE} is not supported by this server.
<br /><br />
${detail}''')
class HTTPRequestRangeNotSatisfiable(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
The server SHOULD return a response with this status code if a
request included a Range request-header field, and none of the
range-specifier values in this field overlap the current extent
of the selected resource, and the request did not include an
If-Range request-header field.
code: 416, title: Request Range Not Satisfiable
"""
code = 416
title = 'Request Range Not Satisfiable'
explanation = ('The Range requested is not available.')
class HTTPExpectationFailed(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indidcates that the expectation given in an Expect
request-header field could not be met by this server.
code: 417, title: Expectation Failed
"""
code = 417
title = 'Expectation Failed'
explanation = ('Expectation failed.')
class HTTPUnprocessableEntity(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the server is unable to process the contained
instructions. Only for WebDAV.
code: 422, title: Unprocessable Entity
"""
## Note: from WebDAV
code = 422
title = 'Unprocessable Entity'
explanation = 'Unable to process the contained instructions'
class HTTPLocked(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the resource is locked. Only for WebDAV
code: 423, title: Locked
"""
## Note: from WebDAV
code = 423
title = 'Locked'
explanation = ('The resource is locked')
class HTTPFailedDependency(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the method could not be performed because the
requested action depended on another action and that action failed.
Only for WebDAV.
code: 424, title: Failed Dependency
"""
## Note: from WebDAV
code = 424
title = 'Failed Dependency'
explanation = (
'The method could not be performed because the requested '
'action dependended on another action and that action failed')
class HTTPPreconditionRequired(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the origin server requires the request to be
conditional. From RFC 6585, "Additional HTTP Status Codes".
code: 428, title: Precondition Required
"""
code = 428
title = 'Precondition Required'
explanation = ('This request is required to be conditional')
class HTTPTooManyRequests(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the client has sent too many requests in a
given amount of time. Useful for rate limiting.
From RFC 6585, "Additional HTTP Status Codes".
code: 429, title: Too Many Requests
"""
code = 429
title = 'Too Many Requests'
explanation = (
'The client has sent too many requests in a given amount of time')
class HTTPRequestHeaderFieldsTooLarge(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the server is unwilling to process the request
because its header fields are too large. The request may be resubmitted
after reducing the size of the request header fields.
From RFC 6585, "Additional HTTP Status Codes".
code: 431, title: Request Header Fields Too Large
"""
code = 431
title = 'Request Header Fields Too Large'
explanation = (
'The request header fields were too large')
############################################################
## 5xx Server Error
############################################################
# Response status codes beginning with the digit "5" indicate cases in
# which the server is aware that it has erred or is incapable of
# performing the request. Except when responding to a HEAD request, the
# server SHOULD include an entity containing an explanation of the error
# situation, and whether it is a temporary or permanent condition. User
# agents SHOULD display any included entity to the user. These response
# codes are applicable to any request method.
class HTTPServerError(HTTPError):
"""
base class for the 500's, where the server is in-error
This is an error condition in which the server is presumed to be
in-error. This is usually unexpected, and thus requires a traceback;
ideally, opening a support ticket for the customer. Unless specialized,
this is a '500 Internal Server Error'
"""
code = 500
title = 'Internal Server Error'
explanation = (
'The server has either erred or is incapable of performing\r\n'
'the requested operation.\r\n')
class HTTPInternalServerError(HTTPServerError):
pass
class HTTPNotImplemented(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the server does not support the functionality
required to fulfill the request.
code: 501, title: Not Implemented
"""
code = 501
title = 'Not Implemented'
template = Template('''
The request method ${REQUEST_METHOD} is not implemented for this server. <br /><br />
${detail}''')
class HTTPBadGateway(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the server, while acting as a gateway or proxy,
received an invalid response from the upstream server it accessed
in attempting to fulfill the request.
code: 502, title: Bad Gateway
"""
code = 502
title = 'Bad Gateway'
explanation = ('Bad gateway.')
class HTTPServiceUnavailable(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the server is currently unable to handle the
request due to a temporary overloading or maintenance of the server.
code: 503, title: Service Unavailable
"""
code = 503
title = 'Service Unavailable'
explanation = ('The server is currently unavailable. '
'Please try again at a later time.')
class HTTPGatewayTimeout(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the server, while acting as a gateway or proxy,
did not receive a timely response from the upstream server specified
by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server
(e.g. DNS) it needed to access in attempting to complete the request.
code: 504, title: Gateway Timeout
"""
code = 504
title = 'Gateway Timeout'
explanation = ('The gateway has timed out.')
class HTTPVersionNotSupported(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the server does not support, or refuses to
support, the HTTP protocol version that was used in the request
message.
code: 505, title: HTTP Version Not Supported
"""
code = 505
title = 'HTTP Version Not Supported'
explanation = ('The HTTP version is not supported.')
class HTTPInsufficientStorage(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the server does not have enough space to save
the resource.
code: 507, title: Insufficient Storage
"""
code = 507
title = 'Insufficient Storage'
explanation = ('There was not enough space to save the resource')
class HTTPNetworkAuthenticationRequired(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the client needs to authenticate to gain
network access. From RFC 6585, "Additional HTTP Status Codes".
code: 511, title: Network Authentication Required
"""
code = 511
title = 'Network Authentication Required'
explanation = ('Network authentication is required')
class HTTPExceptionMiddleware(object):
"""
Middleware that catches exceptions in the sub-application. This
does not catch exceptions in the app_iter; only during the initial
calling of the application.
This should be put *very close* to applications that might raise
these exceptions. This should not be applied globally; letting
*expected* exceptions raise through the WSGI stack is dangerous.
"""
def __init__(self, application):
self.application = application
def __call__(self, environ, start_response):
try:
return self.application(environ, start_response)
except HTTPException:
parent_exc_info = sys.exc_info()
def repl_start_response(status, headers, exc_info=None):
if exc_info is None:
exc_info = parent_exc_info
return start_response(status, headers, exc_info)
return parent_exc_info[1](environ, repl_start_response)
try:
from paste import httpexceptions
except ImportError: # pragma: no cover
# Without Paste we don't need to do this fixup
pass
else: # pragma: no cover
for name in dir(httpexceptions):
obj = globals().get(name)
if (obj and isinstance(obj, type) and issubclass(obj, HTTPException)
and obj is not HTTPException
and obj is not WSGIHTTPException):
obj.__bases__ = obj.__bases__ + (getattr(httpexceptions, name),)
del name, obj, httpexceptions
__all__ = ['HTTPExceptionMiddleware', 'status_map']
status_map={}
for name, value in list(globals().items()):
if (isinstance(value, (type, class_types)) and
issubclass(value, HTTPException)
and not name.startswith('_')):
__all__.append(name)
if getattr(value, 'code', None):
status_map[value.code]=value
if hasattr(value, 'explanation'):
value.explanation = ' '.join(value.explanation.strip().split())
del name, value
| Python |
import warnings
from webob.compat import (
escape,
string_types,
text_,
text_type,
)
from webob.headers import _trans_key
def html_escape(s):
"""HTML-escape a string or object
This converts any non-string objects passed into it to strings
(actually, using ``unicode()``). All values returned are
non-unicode strings (using ``&#num;`` entities for all non-ASCII
characters).
None is treated specially, and returns the empty string.
"""
if s is None:
return ''
__html__ = getattr(s, '__html__', None)
if __html__ is not None and callable(__html__):
return s.__html__()
if not isinstance(s, string_types):
__unicode__ = getattr(s, '__unicode__', None)
if __unicode__ is not None and callable(__unicode__):
s = s.__unicode__()
else:
s = str(s)
s = escape(s, True)
if isinstance(s, text_type):
s = s.encode('ascii', 'xmlcharrefreplace')
return text_(s)
def header_docstring(header, rfc_section):
if header.isupper():
header = _trans_key(header)
major_section = rfc_section.split('.')[0]
link = 'http://www.w3.org/Protocols/rfc2616/rfc2616-sec%s.html#sec%s' % (
major_section, rfc_section)
return "Gets and sets the ``%s`` header (`HTTP spec section %s <%s>`_)." % (
header, rfc_section, link)
def warn_deprecation(text, version, stacklevel): # pragma: no cover
# version specifies when to start raising exceptions instead of warnings
if version == '1.2':
raise DeprecationWarning(text)
elif version == '1.3':
cls = DeprecationWarning
else:
cls = DeprecationWarning
warnings.warn("Unknown warn_deprecation version arg: %r" % version,
RuntimeWarning,
stacklevel=1
)
warnings.warn(text, cls, stacklevel=stacklevel+1)
status_reasons = {
# Status Codes
# Informational
100: 'Continue',
101: 'Switching Protocols',
102: 'Processing',
# Successful
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non-Authoritative Information',
204: 'No Content',
205: 'Reset Content',
206: 'Partial Content',
207: 'Multi Status',
226: 'IM Used',
# Redirection
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Found',
303: 'See Other',
304: 'Not Modified',
305: 'Use Proxy',
307: 'Temporary Redirect',
# Client Error
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Request Entity Too Large',
414: 'Request URI Too Long',
415: 'Unsupported Media Type',
416: 'Requested Range Not Satisfiable',
417: 'Expectation Failed',
418: "I'm a teapot",
422: 'Unprocessable Entity',
423: 'Locked',
424: 'Failed Dependency',
426: 'Upgrade Required',
# Server Error
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported',
507: 'Insufficient Storage',
510: 'Not Extended',
}
# generic class responses as per RFC2616
status_generic_reasons = {
1: 'Continue',
2: 'Success',
3: 'Multiple Choices',
4: 'Unknown Client Error',
5: 'Unknown Server Error',
}
| Python |
import re
__all__ = ['Range', 'ContentRange']
_rx_range = re.compile('bytes *= *(\d*) *- *(\d*)', flags=re.I)
_rx_content_range = re.compile(r'bytes (?:(\d+)-(\d+)|[*])/(?:(\d+)|[*])')
class Range(object):
"""
Represents the Range header.
"""
def __init__(self, start, end):
assert end is None or end >= 0, "Bad range end: %r" % end
self.start = start
self.end = end # non-inclusive
def range_for_length(self, length):
"""
*If* there is only one range, and *if* it is satisfiable by
the given length, then return a (start, end) non-inclusive range
of bytes to serve. Otherwise return None
"""
if length is None:
return None
start, end = self.start, self.end
if end is None:
end = length
if start < 0:
start += length
if _is_content_range_valid(start, end, length):
stop = min(end, length)
return (start, stop)
else:
return None
def content_range(self, length):
"""
Works like range_for_length; returns None or a ContentRange object
You can use it like::
response.content_range = req.range.content_range(response.content_length)
Though it's still up to you to actually serve that content range!
"""
range = self.range_for_length(length)
if range is None:
return None
return ContentRange(range[0], range[1], length)
def __str__(self):
s,e = self.start, self.end
if e is None:
r = 'bytes=%s' % s
if s >= 0:
r += '-'
return r
return 'bytes=%s-%s' % (s, e-1)
def __repr__(self):
return '%s(%r, %r)' % (
self.__class__.__name__,
self.start, self.end)
def __iter__(self):
return iter((self.start, self.end))
@classmethod
def parse(cls, header):
"""
Parse the header; may return None if header is invalid
"""
m = _rx_range.match(header or '')
if not m:
return None
start, end = m.groups()
if not start:
return cls(-int(end), None)
start = int(start)
if not end:
return cls(start, None)
end = int(end) + 1 # return val is non-inclusive
if start >= end:
return None
return cls(start, end)
class ContentRange(object):
"""
Represents the Content-Range header
This header is ``start-stop/length``, where start-stop and length
can be ``*`` (represented as None in the attributes).
"""
def __init__(self, start, stop, length):
if not _is_content_range_valid(start, stop, length):
raise ValueError(
"Bad start:stop/length: %r-%r/%r" % (start, stop, length))
self.start = start
self.stop = stop # this is python-style range end (non-inclusive)
self.length = length
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, self)
def __str__(self):
if self.length is None:
length = '*'
else:
length = self.length
if self.start is None:
assert self.stop is None
return 'bytes */%s' % length
stop = self.stop - 1 # from non-inclusive to HTTP-style
return 'bytes %s-%s/%s' % (self.start, stop, length)
def __iter__(self):
"""
Mostly so you can unpack this, like:
start, stop, length = res.content_range
"""
return iter([self.start, self.stop, self.length])
@classmethod
def parse(cls, value):
"""
Parse the header. May return None if it cannot parse.
"""
m = _rx_content_range.match(value or '')
if not m:
return None
s, e, l = m.groups()
if s:
s = int(s)
e = int(e) + 1
l = l and int(l)
if not _is_content_range_valid(s, e, l, response=True):
return None
return cls(s, e, l)
def _is_content_range_valid(start, stop, length, response=False):
if (start is None) != (stop is None):
return False
elif start is None:
return length is None or length >= 0
elif length is None:
return 0 <= start < stop
elif start >= stop:
return False
elif response and stop > length:
# "content-range: bytes 0-50/10" is invalid for a response
# "range: bytes 0-50" is valid for a request to a 10-bytes entity
return False
else:
return 0 <= start < length
| Python |
import errno
import sys
import re
try:
import httplib
except ImportError: # pragma: no cover
import http.client as httplib
from webob.compat import url_quote
import socket
from webob import exc
from webob.compat import PY3
__all__ = ['send_request_app', 'SendRequest']
class SendRequest:
"""
Sends the request, as described by the environ, over actual HTTP.
All controls about how it is sent are contained in the request
environ itself.
This connects to the server given in SERVER_NAME:SERVER_PORT, and
sends the Host header in HTTP_HOST -- they do not have to match.
You can send requests to servers despite what DNS says.
Set ``environ['webob.client.timeout'] = 10`` to set the timeout on
the request (to, for example, 10 seconds).
Does not add X-Forwarded-For or other standard headers
If you use ``send_request_app`` then simple ``httplib``
connections will be used.
"""
def __init__(self, HTTPConnection=httplib.HTTPConnection,
HTTPSConnection=httplib.HTTPSConnection):
self.HTTPConnection = HTTPConnection
self.HTTPSConnection = HTTPSConnection
def __call__(self, environ, start_response):
scheme = environ['wsgi.url_scheme']
if scheme == 'http':
ConnClass = self.HTTPConnection
elif scheme == 'https':
ConnClass = self.HTTPSConnection
else:
raise ValueError(
"Unknown scheme: %r" % scheme)
if 'SERVER_NAME' not in environ:
host = environ.get('HTTP_HOST')
if not host:
raise ValueError(
"environ contains neither SERVER_NAME nor HTTP_HOST")
if ':' in host:
host, port = host.split(':', 1)
else:
if scheme == 'http':
port = '80'
else:
port = '443'
environ['SERVER_NAME'] = host
environ['SERVER_PORT'] = port
kw = {}
if ('webob.client.timeout' in environ and
self._timeout_supported(ConnClass) ):
kw['timeout'] = environ['webob.client.timeout']
conn = ConnClass('%(SERVER_NAME)s:%(SERVER_PORT)s' % environ, **kw)
headers = {}
for key, value in environ.items():
if key.startswith('HTTP_'):
key = key[5:].replace('_', '-').title()
headers[key] = value
path = (url_quote(environ.get('SCRIPT_NAME', ''))
+ url_quote(environ.get('PATH_INFO', '')))
if environ.get('QUERY_STRING'):
path += '?' + environ['QUERY_STRING']
try:
content_length = int(environ.get('CONTENT_LENGTH', '0'))
except ValueError:
content_length = 0
## FIXME: there is no streaming of the body, and that might be useful
## in some cases
if content_length:
body = environ['wsgi.input'].read(content_length)
else:
body = ''
headers['Content-Length'] = content_length
if environ.get('CONTENT_TYPE'):
headers['Content-Type'] = environ['CONTENT_TYPE']
if not path.startswith("/"):
path = "/" + path
try:
conn.request(environ['REQUEST_METHOD'],
path, body, headers)
res = conn.getresponse()
except socket.timeout:
resp = exc.HTTPGatewayTimeout()
return resp(environ, start_response)
except (socket.error, socket.gaierror) as e:
if ((isinstance(e, socket.error) and e.args[0] == -2) or
(isinstance(e, socket.gaierror) and e.args[0] == 8)):
# Name or service not known
resp = exc.HTTPBadGateway(
"Name or service not known (bad domain name: %s)"
% environ['SERVER_NAME'])
return resp(environ, start_response)
elif e.args[0] in _e_refused: # pragma: no cover
# Connection refused
resp = exc.HTTPBadGateway("Connection refused")
return resp(environ, start_response)
raise
headers_out = self.parse_headers(res.msg)
status = '%s %s' % (res.status, res.reason)
start_response(status, headers_out)
length = res.getheader('content-length')
# FIXME: This shouldn't really read in all the content at once
if length is not None:
body = res.read(int(length))
else:
body = res.read()
conn.close()
return [body]
# Remove these headers from response (specify lower case header
# names):
filtered_headers = (
'transfer-encoding',
)
MULTILINE_RE = re.compile(r'\r?\n\s*')
def parse_headers(self, message):
"""
Turn a Message object into a list of WSGI-style headers.
"""
headers_out = []
if PY3: # pragma: no cover
headers = message._headers
else: # pragma: no cover
headers = message.headers
for full_header in headers:
if not full_header: # pragma: no cover
# Shouldn't happen, but we'll just ignore
continue
if full_header[0].isspace(): # pragma: no cover
# Continuation line, add to the last header
if not headers_out:
raise ValueError(
"First header starts with a space (%r)" % full_header)
last_header, last_value = headers_out.pop()
value = last_value + ', ' + full_header.strip()
headers_out.append((last_header, value))
continue
if isinstance(full_header, tuple): # pragma: no cover
header, value = full_header
else: # pragma: no cover
try:
header, value = full_header.split(':', 1)
except:
raise ValueError("Invalid header: %r" % (full_header,))
value = value.strip()
if '\n' in value or '\r\n' in value: # pragma: no cover
# Python 3 has multiline values for continuations, Python 2
# has two items in headers
value = self.MULTILINE_RE.sub(', ', value)
if header.lower() not in self.filtered_headers:
headers_out.append((header, value))
return headers_out
def _timeout_supported(self, ConnClass):
if sys.version_info < (2, 7) and ConnClass in (
httplib.HTTPConnection, httplib.HTTPSConnection): # pragma: no cover
return False
return True
send_request_app = SendRequest()
_e_refused = (errno.ECONNREFUSED,)
if hasattr(errno, 'ENODATA'): # pragma: no cover
_e_refused += (errno.ENODATA,)
| Python |
from webob.datetime_utils import *
from webob.request import *
from webob.response import *
from webob.util import html_escape
__all__ = [
'Request', 'LegacyRequest', 'Response', 'UTC', 'day', 'week', 'hour',
'minute', 'second', 'month', 'year', 'html_escape'
]
BaseRequest.ResponseClass = Response
__version__ = '1.2.2'
| Python |
from base64 import b64encode
from datetime import (
datetime,
timedelta,
)
from hashlib import md5
import re
import struct
import zlib
try:
import simplejson as json
except ImportError:
import json
from webob.byterange import ContentRange
from webob.cachecontrol import (
CacheControl,
serialize_cache_control,
)
from webob.compat import (
PY3,
bytes_,
native_,
text_type,
url_quote,
urlparse,
)
from webob.cookies import (
Cookie,
Morsel,
)
from webob.datetime_utils import (
parse_date_delta,
serialize_date_delta,
timedelta_to_seconds,
)
from webob.descriptors import (
CHARSET_RE,
SCHEME_RE,
converter,
date_header,
header_getter,
list_header,
parse_auth,
parse_content_range,
parse_etag_response,
parse_int,
parse_int_safe,
serialize_auth,
serialize_content_range,
serialize_etag_response,
serialize_int,
)
from webob.headers import ResponseHeaders
from webob.request import BaseRequest
from webob.util import status_reasons, status_generic_reasons
__all__ = ['Response']
_PARAM_RE = re.compile(r'([a-z0-9]+)=(?:"([^"]*)"|([a-z0-9_.-]*))', re.I)
_OK_PARAM_RE = re.compile(r'^[a-z0-9_.-]+$', re.I)
_gzip_header = b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff'
class Response(object):
"""
Represents a WSGI response
"""
default_content_type = 'text/html'
default_charset = 'UTF-8' # TODO: deprecate
unicode_errors = 'strict' # TODO: deprecate (why would response body have errors?)
default_conditional_response = False
request = None
environ = None
#
# __init__, from_file, copy
#
def __init__(self, body=None, status=None, headerlist=None, app_iter=None,
content_type=None, conditional_response=None,
**kw):
if app_iter is None and body is None and ('json_body' in kw or 'json' in kw):
if 'json_body' in kw:
json_body = kw.pop('json_body')
else:
json_body = kw.pop('json')
body = json.dumps(json_body, separators=(',', ':'))
if content_type is None:
content_type = 'application/json'
if app_iter is None:
if body is None:
body = b''
elif body is not None:
raise TypeError(
"You may only give one of the body and app_iter arguments")
if status is None:
self._status = '200 OK'
else:
self.status = status
if headerlist is None:
self._headerlist = []
else:
self._headerlist = headerlist
self._headers = None
if content_type is None:
content_type = self.default_content_type
charset = None
if 'charset' in kw:
charset = kw.pop('charset')
elif self.default_charset:
if (content_type
and 'charset=' not in content_type
and (content_type == 'text/html'
or content_type.startswith('text/')
or content_type.startswith('application/xml')
or content_type.startswith('application/json')
or (content_type.startswith('application/')
and (content_type.endswith('+xml') or content_type.endswith('+json'))))):
charset = self.default_charset
if content_type and charset:
content_type += '; charset=' + charset
elif self._headerlist and charset:
self.charset = charset
if not self._headerlist and content_type:
self._headerlist.append(('Content-Type', content_type))
if conditional_response is None:
self.conditional_response = self.default_conditional_response
else:
self.conditional_response = bool(conditional_response)
if app_iter is None:
if isinstance(body, text_type):
if charset is None:
raise TypeError(
"You cannot set the body to a text value without a "
"charset")
body = body.encode(charset)
app_iter = [body]
if headerlist is None:
self._headerlist.append(('Content-Length', str(len(body))))
else:
self.headers['Content-Length'] = str(len(body))
self._app_iter = app_iter
for name, value in kw.items():
if not hasattr(self.__class__, name):
# Not a basic attribute
raise TypeError(
"Unexpected keyword: %s=%r" % (name, value))
setattr(self, name, value)
@classmethod
def from_file(cls, fp):
"""Reads a response from a file-like object (it must implement
``.read(size)`` and ``.readline()``).
It will read up to the end of the response, not the end of the
file.
This reads the response as represented by ``str(resp)``; it
may not read every valid HTTP response properly. Responses
must have a ``Content-Length``"""
headerlist = []
status = fp.readline().strip()
is_text = isinstance(status, text_type)
if is_text:
_colon = ':'
else:
_colon = b':'
while 1:
line = fp.readline().strip()
if not line:
# end of headers
break
try:
header_name, value = line.split(_colon, 1)
except ValueError:
raise ValueError('Bad header line: %r' % line)
value = value.strip()
if not is_text:
header_name = header_name.decode('utf-8')
value = value.decode('utf-8')
headerlist.append((header_name, value))
r = cls(
status=status,
headerlist=headerlist,
app_iter=(),
)
body = fp.read(r.content_length or 0)
if is_text:
r.text = body
else:
r.body = body
return r
def copy(self):
"""Makes a copy of the response"""
# we need to do this for app_iter to be reusable
app_iter = list(self._app_iter)
iter_close(self._app_iter)
# and this to make sure app_iter instances are different
self._app_iter = list(app_iter)
return self.__class__(
content_type=False,
status=self._status,
headerlist=self._headerlist[:],
app_iter=app_iter,
conditional_response=self.conditional_response)
#
# __repr__, __str__
#
def __repr__(self):
return '<%s at 0x%x %s>' % (self.__class__.__name__, abs(id(self)),
self.status)
def __str__(self, skip_body=False):
parts = [self.status]
if not skip_body:
# Force enumeration of the body (to set content-length)
self.body
parts += map('%s: %s'.__mod__, self.headerlist)
if not skip_body and self.body:
parts += ['', self.text if PY3 else self.body]
return '\n'.join(parts)
#
# status, status_code/status_int
#
def _status__get(self):
"""
The status string
"""
return self._status
def _status__set(self, value):
if isinstance(value, int):
self.status_code = value
return
if PY3: # pragma: no cover
if isinstance(value, bytes):
value = value.decode('ascii')
elif isinstance(value, text_type):
value = value.encode('ascii')
if not isinstance(value, str):
raise TypeError(
"You must set status to a string or integer (not %s)"
% type(value))
if ' ' not in value:
try:
value += ' ' + status_reasons[int(value)]
except KeyError:
value += ' ' + status_generic_reasons[int(value) // 100]
self._status = value
status = property(_status__get, _status__set, doc=_status__get.__doc__)
def _status_code__get(self):
"""
The status as an integer
"""
return int(self._status.split()[0])
def _status_code__set(self, code):
try:
self._status = '%d %s' % (code, status_reasons[code])
except KeyError:
self._status = '%d %s' % (code, status_generic_reasons[code // 100])
status_code = status_int = property(_status_code__get, _status_code__set,
doc=_status_code__get.__doc__)
#
# headerslist, headers
#
def _headerlist__get(self):
"""
The list of response headers
"""
return self._headerlist
def _headerlist__set(self, value):
self._headers = None
if not isinstance(value, list):
if hasattr(value, 'items'):
value = value.items()
value = list(value)
self._headerlist = value
def _headerlist__del(self):
self.headerlist = []
headerlist = property(_headerlist__get, _headerlist__set,
_headerlist__del, doc=_headerlist__get.__doc__)
def _headers__get(self):
"""
The headers in a dictionary-like object
"""
if self._headers is None:
self._headers = ResponseHeaders.view_list(self.headerlist)
return self._headers
def _headers__set(self, value):
if hasattr(value, 'items'):
value = value.items()
self.headerlist = value
self._headers = None
headers = property(_headers__get, _headers__set, doc=_headers__get.__doc__)
#
# body
#
def _body__get(self):
"""
The body of the response, as a ``str``. This will read in the
entire app_iter if necessary.
"""
app_iter = self._app_iter
# try:
# if len(app_iter) == 1:
# return app_iter[0]
# except:
# pass
if isinstance(app_iter, list) and len(app_iter) == 1:
return app_iter[0]
if app_iter is None:
raise AttributeError("No body has been set")
try:
body = b''.join(app_iter)
finally:
iter_close(app_iter)
if isinstance(body, text_type):
raise _error_unicode_in_app_iter(app_iter, body)
self._app_iter = [body]
if len(body) == 0:
# if body-length is zero, we assume it's a HEAD response and
# leave content_length alone
pass # pragma: no cover (no idea why necessary, it's hit)
elif self.content_length is None:
self.content_length = len(body)
elif self.content_length != len(body):
raise AssertionError(
"Content-Length is different from actual app_iter length "
"(%r!=%r)"
% (self.content_length, len(body))
)
return body
def _body__set(self, value=b''):
if not isinstance(value, bytes):
if isinstance(value, text_type):
msg = ("You cannot set Response.body to a text object "
"(use Response.text)")
else:
msg = ("You can only set the body to a binary type (not %s)" %
type(value))
raise TypeError(msg)
if self._app_iter is not None:
self.content_md5 = None
self._app_iter = [value]
self.content_length = len(value)
# def _body__del(self):
# self.body = ''
# #self.content_length = None
body = property(_body__get, _body__set, _body__set)
def _json_body__get(self):
"""Access the body of the response as JSON"""
# Note: UTF-8 is a content-type specific default for JSON:
return json.loads(self.body.decode(self.charset or 'UTF-8'))
def _json_body__set(self, value):
self.body = json.dumps(value, separators=(',', ':')).encode(self.charset or 'UTF-8')
def _json_body__del(self):
del self.body
json = json_body = property(_json_body__get, _json_body__set, _json_body__del)
#
# text, unicode_body, ubody
#
def _text__get(self):
"""
Get/set the text value of the body (using the charset of the
Content-Type)
"""
if not self.charset:
raise AttributeError(
"You cannot access Response.text unless charset is set")
body = self.body
return body.decode(self.charset, self.unicode_errors)
def _text__set(self, value):
if not self.charset:
raise AttributeError(
"You cannot access Response.text unless charset is set")
if not isinstance(value, text_type):
raise TypeError(
"You can only set Response.text to a unicode string "
"(not %s)" % type(value))
self.body = value.encode(self.charset)
def _text__del(self):
del self.body
text = property(_text__get, _text__set, _text__del, doc=_text__get.__doc__)
unicode_body = ubody = property(_text__get, _text__set, _text__del,
"Deprecated alias for .text")
#
# body_file, write(text)
#
def _body_file__get(self):
"""
A file-like object that can be used to write to the
body. If you passed in a list app_iter, that app_iter will be
modified by writes.
"""
return ResponseBodyFile(self)
def _body_file__set(self, file):
self.app_iter = iter_file(file)
def _body_file__del(self):
del self.body
body_file = property(_body_file__get, _body_file__set, _body_file__del,
doc=_body_file__get.__doc__)
def write(self, text):
if not isinstance(text, bytes):
if not isinstance(text, text_type):
msg = "You can only write str to a Response.body_file, not %s"
raise TypeError(msg % type(text))
if not self.charset:
msg = ("You can only write text to Response if charset has "
"been set")
raise TypeError(msg)
text = text.encode(self.charset)
app_iter = self._app_iter
if not isinstance(app_iter, list):
try:
new_app_iter = self._app_iter = list(app_iter)
finally:
iter_close(app_iter)
app_iter = new_app_iter
self.content_length = sum(len(chunk) for chunk in app_iter)
app_iter.append(text)
if self.content_length is not None:
self.content_length += len(text)
#
# app_iter
#
def _app_iter__get(self):
"""
Returns the app_iter of the response.
If body was set, this will create an app_iter from that body
(a single-item list)
"""
return self._app_iter
def _app_iter__set(self, value):
if self._app_iter is not None:
# Undo the automatically-set content-length
self.content_length = None
self.content_md5 = None
self._app_iter = value
def _app_iter__del(self):
self._app_iter = []
self.content_length = None
app_iter = property(_app_iter__get, _app_iter__set, _app_iter__del,
doc=_app_iter__get.__doc__)
#
# headers attrs
#
allow = list_header('Allow', '14.7')
# TODO: (maybe) support response.vary += 'something'
# TODO: same thing for all listy headers
vary = list_header('Vary', '14.44')
content_length = converter(
header_getter('Content-Length', '14.17'),
parse_int, serialize_int, 'int')
content_encoding = header_getter('Content-Encoding', '14.11')
content_language = list_header('Content-Language', '14.12')
content_location = header_getter('Content-Location', '14.14')
content_md5 = header_getter('Content-MD5', '14.14')
content_disposition = header_getter('Content-Disposition', '19.5.1')
accept_ranges = header_getter('Accept-Ranges', '14.5')
content_range = converter(
header_getter('Content-Range', '14.16'),
parse_content_range, serialize_content_range, 'ContentRange object')
date = date_header('Date', '14.18')
expires = date_header('Expires', '14.21')
last_modified = date_header('Last-Modified', '14.29')
_etag_raw = header_getter('ETag', '14.19')
etag = converter(_etag_raw,
parse_etag_response, serialize_etag_response,
'Entity tag'
)
@property
def etag_strong(self):
return parse_etag_response(self._etag_raw, strong=True)
location = header_getter('Location', '14.30')
pragma = header_getter('Pragma', '14.32')
age = converter(
header_getter('Age', '14.6'),
parse_int_safe, serialize_int, 'int')
retry_after = converter(
header_getter('Retry-After', '14.37'),
parse_date_delta, serialize_date_delta, 'HTTP date or delta seconds')
server = header_getter('Server', '14.38')
# TODO: the standard allows this to be a list of challenges
www_authenticate = converter(
header_getter('WWW-Authenticate', '14.47'),
parse_auth, serialize_auth,
)
#
# charset
#
def _charset__get(self):
"""
Get/set the charset (in the Content-Type)
"""
header = self.headers.get('Content-Type')
if not header:
return None
match = CHARSET_RE.search(header)
if match:
return match.group(1)
return None
def _charset__set(self, charset):
if charset is None:
del self.charset
return
header = self.headers.pop('Content-Type', None)
if header is None:
raise AttributeError("You cannot set the charset when no "
"content-type is defined")
match = CHARSET_RE.search(header)
if match:
header = header[:match.start()] + header[match.end():]
header += '; charset=%s' % charset
self.headers['Content-Type'] = header
def _charset__del(self):
header = self.headers.pop('Content-Type', None)
if header is None:
# Don't need to remove anything
return
match = CHARSET_RE.search(header)
if match:
header = header[:match.start()] + header[match.end():]
self.headers['Content-Type'] = header
charset = property(_charset__get, _charset__set, _charset__del,
doc=_charset__get.__doc__)
#
# content_type
#
def _content_type__get(self):
"""
Get/set the Content-Type header (or None), *without* the
charset or any parameters.
If you include parameters (or ``;`` at all) when setting the
content_type, any existing parameters will be deleted;
otherwise they will be preserved.
"""
header = self.headers.get('Content-Type')
if not header:
return None
return header.split(';', 1)[0]
def _content_type__set(self, value):
if not value:
self._content_type__del()
return
if ';' not in value:
header = self.headers.get('Content-Type', '')
if ';' in header:
params = header.split(';', 1)[1]
value += ';' + params
self.headers['Content-Type'] = value
def _content_type__del(self):
self.headers.pop('Content-Type', None)
content_type = property(_content_type__get, _content_type__set,
_content_type__del, doc=_content_type__get.__doc__)
#
# content_type_params
#
def _content_type_params__get(self):
"""
A dictionary of all the parameters in the content type.
(This is not a view, set to change, modifications of the dict would not
be applied otherwise)
"""
params = self.headers.get('Content-Type', '')
if ';' not in params:
return {}
params = params.split(';', 1)[1]
result = {}
for match in _PARAM_RE.finditer(params):
result[match.group(1)] = match.group(2) or match.group(3) or ''
return result
def _content_type_params__set(self, value_dict):
if not value_dict:
del self.content_type_params
return
params = []
for k, v in sorted(value_dict.items()):
if not _OK_PARAM_RE.search(v):
v = '"%s"' % v.replace('"', '\\"')
params.append('; %s=%s' % (k, v))
ct = self.headers.pop('Content-Type', '').split(';', 1)[0]
ct += ''.join(params)
self.headers['Content-Type'] = ct
def _content_type_params__del(self):
self.headers['Content-Type'] = self.headers.get(
'Content-Type', '').split(';', 1)[0]
content_type_params = property(
_content_type_params__get,
_content_type_params__set,
_content_type_params__del,
_content_type_params__get.__doc__
)
#
# set_cookie, unset_cookie, delete_cookie, merge_cookies
#
def set_cookie(self, key, value='', max_age=None,
path='/', domain=None, secure=False, httponly=False,
comment=None, expires=None, overwrite=False):
"""
Set (add) a cookie for the response.
Arguments are:
``key``
The cookie name.
``value``
The cookie value, which should be a string or ``None``. If
``value`` is ``None``, it's equivalent to calling the
:meth:`webob.response.Response.unset_cookie` method for this
cookie key (it effectively deletes the cookie on the client).
``max_age``
An integer representing a number of seconds or ``None``. If this
value is an integer, it is used as the ``Max-Age`` of the
generated cookie. If ``expires`` is not passed and this value is
an integer, the ``max_age`` value will also influence the
``Expires`` value of the cookie (``Expires`` will be set to now +
max_age). If this value is ``None``, the cookie will not have a
``Max-Age`` value (unless ``expires`` is also sent).
``path``
A string representing the cookie ``Path`` value. It defaults to
``/``.
``domain``
A string representing the cookie ``Domain``, or ``None``. If
domain is ``None``, no ``Domain`` value will be sent in the
cookie.
``secure``
A boolean. If it's ``True``, the ``secure`` flag will be sent in
the cookie, if it's ``False``, the ``secure`` flag will not be
sent in the cookie.
``httponly``
A boolean. If it's ``True``, the ``HttpOnly`` flag will be sent
in the cookie, if it's ``False``, the ``HttpOnly`` flag will not
be sent in the cookie.
``comment``
A string representing the cookie ``Comment`` value, or ``None``.
If ``comment`` is ``None``, no ``Comment`` value will be sent in
the cookie.
``expires``
A ``datetime.timedelta`` object representing an amount of time or
the value ``None``. A non-``None`` value is used to generate the
``Expires`` value of the generated cookie. If ``max_age`` is not
passed, but this value is not ``None``, it will influence the
``Max-Age`` header (``Max-Age`` will be 'expires_value -
datetime.utcnow()'). If this value is ``None``, the ``Expires``
cookie value will be unset (unless ``max_age`` is also passed).
``overwrite``
If this key is ``True``, before setting the cookie, unset any
existing cookie.
"""
if overwrite:
self.unset_cookie(key, strict=False)
if value is None: # delete the cookie from the client
value = ''
max_age = 0
expires = timedelta(days=-5)
elif expires is None and max_age is not None:
if isinstance(max_age, int):
max_age = timedelta(seconds=max_age)
expires = datetime.utcnow() + max_age
elif max_age is None and expires is not None:
max_age = expires - datetime.utcnow()
value = bytes_(value, 'utf8')
key = bytes_(key, 'utf8')
m = Morsel(key, value)
m.path = bytes_(path, 'utf8')
m.domain = bytes_(domain, 'utf8')
m.comment = bytes_(comment, 'utf8')
m.expires = expires
m.max_age = max_age
m.secure = secure
m.httponly = httponly
self.headerlist.append(('Set-Cookie', m.serialize()))
def delete_cookie(self, key, path='/', domain=None):
"""
Delete a cookie from the client. Note that path and domain must match
how the cookie was originally set.
This sets the cookie to the empty string, and max_age=0 so
that it should expire immediately.
"""
self.set_cookie(key, None, path=path, domain=domain)
def unset_cookie(self, key, strict=True):
"""
Unset a cookie with the given name (remove it from the
response).
"""
existing = self.headers.getall('Set-Cookie')
if not existing and not strict:
return
cookies = Cookie()
for header in existing:
cookies.load(header)
if isinstance(key, text_type):
key = key.encode('utf8')
if key in cookies:
del cookies[key]
del self.headers['Set-Cookie']
for m in cookies.values():
self.headerlist.append(('Set-Cookie', m.serialize()))
elif strict:
raise KeyError("No cookie has been set with the name %r" % key)
def merge_cookies(self, resp):
"""Merge the cookies that were set on this response with the
given `resp` object (which can be any WSGI application).
If the `resp` is a :class:`webob.Response` object, then the
other object will be modified in-place.
"""
if not self.headers.get('Set-Cookie'):
return resp
if isinstance(resp, Response):
for header in self.headers.getall('Set-Cookie'):
resp.headers.add('Set-Cookie', header)
return resp
else:
c_headers = [h for h in self.headerlist if
h[0].lower() == 'set-cookie']
def repl_app(environ, start_response):
def repl_start_response(status, headers, exc_info=None):
return start_response(status, headers+c_headers,
exc_info=exc_info)
return resp(environ, repl_start_response)
return repl_app
#
# cache_control
#
_cache_control_obj = None
def _cache_control__get(self):
"""
Get/set/modify the Cache-Control header (`HTTP spec section 14.9
<http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9>`_)
"""
value = self.headers.get('cache-control', '')
if self._cache_control_obj is None:
self._cache_control_obj = CacheControl.parse(
value, updates_to=self._update_cache_control, type='response')
self._cache_control_obj.header_value = value
if self._cache_control_obj.header_value != value:
new_obj = CacheControl.parse(value, type='response')
self._cache_control_obj.properties.clear()
self._cache_control_obj.properties.update(new_obj.properties)
self._cache_control_obj.header_value = value
return self._cache_control_obj
def _cache_control__set(self, value):
# This actually becomes a copy
if not value:
value = ""
if isinstance(value, dict):
value = CacheControl(value, 'response')
if isinstance(value, text_type):
value = str(value)
if isinstance(value, str):
if self._cache_control_obj is None:
self.headers['Cache-Control'] = value
return
value = CacheControl.parse(value, 'response')
cache = self.cache_control
cache.properties.clear()
cache.properties.update(value.properties)
def _cache_control__del(self):
self.cache_control = {}
def _update_cache_control(self, prop_dict):
value = serialize_cache_control(prop_dict)
if not value:
if 'Cache-Control' in self.headers:
del self.headers['Cache-Control']
else:
self.headers['Cache-Control'] = value
cache_control = property(
_cache_control__get, _cache_control__set,
_cache_control__del, doc=_cache_control__get.__doc__)
#
# cache_expires
#
def _cache_expires(self, seconds=0, **kw):
"""
Set expiration on this request. This sets the response to
expire in the given seconds, and any other attributes are used
for cache_control (e.g., private=True, etc).
"""
if seconds is True:
seconds = 0
elif isinstance(seconds, timedelta):
seconds = timedelta_to_seconds(seconds)
cache_control = self.cache_control
if seconds is None:
pass
elif not seconds:
# To really expire something, you have to force a
# bunch of these cache control attributes, and IE may
# not pay attention to those still so we also set
# Expires.
cache_control.no_store = True
cache_control.no_cache = True
cache_control.must_revalidate = True
cache_control.max_age = 0
cache_control.post_check = 0
cache_control.pre_check = 0
self.expires = datetime.utcnow()
if 'last-modified' not in self.headers:
self.last_modified = datetime.utcnow()
self.pragma = 'no-cache'
else:
cache_control.properties.clear()
cache_control.max_age = seconds
self.expires = datetime.utcnow() + timedelta(seconds=seconds)
self.pragma = None
for name, value in kw.items():
setattr(cache_control, name, value)
cache_expires = property(lambda self: self._cache_expires, _cache_expires)
#
# encode_content, decode_content, md5_etag
#
def encode_content(self, encoding='gzip', lazy=False):
"""
Encode the content with the given encoding (only gzip and
identity are supported).
"""
assert encoding in ('identity', 'gzip'), \
"Unknown encoding: %r" % encoding
if encoding == 'identity':
self.decode_content()
return
if self.content_encoding == 'gzip':
return
if lazy:
self.app_iter = gzip_app_iter(self._app_iter)
self.content_length = None
else:
self.app_iter = list(gzip_app_iter(self._app_iter))
self.content_length = sum(map(len, self._app_iter))
self.content_encoding = 'gzip'
def decode_content(self):
content_encoding = self.content_encoding or 'identity'
if content_encoding == 'identity':
return
if content_encoding not in ('gzip', 'deflate'):
raise ValueError(
"I don't know how to decode the content %s" % content_encoding)
if content_encoding == 'gzip':
from gzip import GzipFile
from io import BytesIO
gzip_f = GzipFile(filename='', mode='r', fileobj=BytesIO(self.body))
self.body = gzip_f.read()
self.content_encoding = None
gzip_f.close()
else:
# Weird feature: http://bugs.python.org/issue5784
self.body = zlib.decompress(self.body, -15)
self.content_encoding = None
def md5_etag(self, body=None, set_content_md5=False):
"""
Generate an etag for the response object using an MD5 hash of
the body (the body parameter, or ``self.body`` if not given)
Sets ``self.etag``
If ``set_content_md5`` is True sets ``self.content_md5`` as well
"""
if body is None:
body = self.body
md5_digest = md5(body).digest()
md5_digest = b64encode(md5_digest)
md5_digest = md5_digest.replace(b'\n', b'')
md5_digest = native_(md5_digest)
self.etag = md5_digest.strip('=')
if set_content_md5:
self.content_md5 = md5_digest
#
# __call__, conditional_response_app
#
def __call__(self, environ, start_response):
"""
WSGI application interface
"""
if self.conditional_response:
return self.conditional_response_app(environ, start_response)
headerlist = self._abs_headerlist(environ)
start_response(self.status, headerlist)
if environ['REQUEST_METHOD'] == 'HEAD':
# Special case here...
return EmptyResponse(self._app_iter)
return self._app_iter
def _abs_headerlist(self, environ):
"""Returns a headerlist, with the Location header possibly
made absolute given the request environ.
"""
headerlist = list(self.headerlist)
for i, (name, value) in enumerate(headerlist):
if name.lower() == 'location':
if SCHEME_RE.search(value):
break
new_location = urlparse.urljoin(_request_uri(environ), value)
headerlist[i] = (name, new_location)
break
return headerlist
_safe_methods = ('GET', 'HEAD')
def conditional_response_app(self, environ, start_response):
"""
Like the normal __call__ interface, but checks conditional headers:
* If-Modified-Since (304 Not Modified; only on GET, HEAD)
* If-None-Match (304 Not Modified; only on GET, HEAD)
* Range (406 Partial Content; only on GET, HEAD)
"""
req = BaseRequest(environ)
headerlist = self._abs_headerlist(environ)
method = environ.get('REQUEST_METHOD', 'GET')
if method in self._safe_methods:
status304 = False
if req.if_none_match and self.etag:
status304 = self.etag in req.if_none_match
elif req.if_modified_since and self.last_modified:
status304 = self.last_modified <= req.if_modified_since
if status304:
start_response('304 Not Modified', filter_headers(headerlist))
return EmptyResponse(self._app_iter)
if (req.range and self in req.if_range
and self.content_range is None
and method in ('HEAD', 'GET')
and self.status_code == 200
and self.content_length is not None
):
content_range = req.range.content_range(self.content_length)
if content_range is None:
iter_close(self._app_iter)
body = bytes_("Requested range not satisfiable: %s" % req.range)
headerlist = [
('Content-Length', str(len(body))),
('Content-Range', str(ContentRange(None, None,
self.content_length))),
('Content-Type', 'text/plain'),
] + filter_headers(headerlist)
start_response('416 Requested Range Not Satisfiable',
headerlist)
if method == 'HEAD':
return ()
return [body]
else:
app_iter = self.app_iter_range(content_range.start,
content_range.stop)
if app_iter is not None:
# the following should be guaranteed by
# Range.range_for_length(length)
assert content_range.start is not None
headerlist = [
('Content-Length',
str(content_range.stop - content_range.start)),
('Content-Range', str(content_range)),
] + filter_headers(headerlist, ('content-length',))
start_response('206 Partial Content', headerlist)
if method == 'HEAD':
return EmptyResponse(app_iter)
return app_iter
start_response(self.status, headerlist)
if method == 'HEAD':
return EmptyResponse(self._app_iter)
return self._app_iter
def app_iter_range(self, start, stop):
"""
Return a new app_iter built from the response app_iter, that
serves up only the given ``start:stop`` range.
"""
app_iter = self._app_iter
if hasattr(app_iter, 'app_iter_range'):
return app_iter.app_iter_range(start, stop)
return AppIterRange(app_iter, start, stop)
def filter_headers(hlist, remove_headers=('content-length', 'content-type')):
return [h for h in hlist if (h[0].lower() not in remove_headers)]
def iter_file(file, block_size=1<<18): # 256Kb
while True:
data = file.read(block_size)
if not data:
break
yield data
class ResponseBodyFile(object):
mode = 'wb'
closed = False
def __init__(self, response):
self.response = response
self.write = response.write
def __repr__(self):
return '<body_file for %r>' % self.response
encoding = property(
lambda self: self.response.charset,
doc="The encoding of the file (inherited from response.charset)"
)
def writelines(self, seq):
for item in seq:
self.write(item)
def close(self):
raise NotImplementedError("Response bodies cannot be closed")
def flush(self):
pass
class AppIterRange(object):
"""
Wraps an app_iter, returning just a range of bytes
"""
def __init__(self, app_iter, start, stop):
assert start >= 0, "Bad start: %r" % start
assert stop is None or (stop >= 0 and stop >= start), (
"Bad stop: %r" % stop)
self.app_iter = iter(app_iter)
self._pos = 0 # position in app_iter
self.start = start
self.stop = stop
def __iter__(self):
return self
def _skip_start(self):
start, stop = self.start, self.stop
for chunk in self.app_iter:
self._pos += len(chunk)
if self._pos < start:
continue
elif self._pos == start:
return b''
else:
chunk = chunk[start-self._pos:]
if stop is not None and self._pos > stop:
chunk = chunk[:stop-self._pos]
assert len(chunk) == stop - start
return chunk
else:
raise StopIteration()
def next(self):
if self._pos < self.start:
# need to skip some leading bytes
return self._skip_start()
stop = self.stop
if stop is not None and self._pos >= stop:
raise StopIteration
chunk = next(self.app_iter)
self._pos += len(chunk)
if stop is None or self._pos <= stop:
return chunk
else:
return chunk[:stop-self._pos]
__next__ = next # py3
def close(self):
iter_close(self.app_iter)
class EmptyResponse(object):
"""An empty WSGI response.
An iterator that immediately stops. Optionally provides a close
method to close an underlying app_iter it replaces.
"""
def __init__(self, app_iter=None):
if app_iter and hasattr(app_iter, 'close'):
self.close = app_iter.close
def __iter__(self):
return self
def __len__(self):
return 0
def next(self):
raise StopIteration()
__next__ = next # py3
def _request_uri(environ):
"""Like wsgiref.url.request_uri, except eliminates :80 ports
Return the full request URI"""
url = environ['wsgi.url_scheme']+'://'
if environ.get('HTTP_HOST'):
url += environ['HTTP_HOST']
else:
url += environ['SERVER_NAME'] + ':' + environ['SERVER_PORT']
if url.endswith(':80') and environ['wsgi.url_scheme'] == 'http':
url = url[:-3]
elif url.endswith(':443') and environ['wsgi.url_scheme'] == 'https':
url = url[:-4]
if PY3: # pragma: no cover
script_name = bytes_(environ.get('SCRIPT_NAME', '/'), 'latin-1')
path_info = bytes_(environ.get('PATH_INFO', ''), 'latin-1')
else:
script_name = environ.get('SCRIPT_NAME', '/')
path_info = environ.get('PATH_INFO', '')
url += url_quote(script_name)
qpath_info = url_quote(path_info)
if not 'SCRIPT_NAME' in environ:
url += qpath_info[1:]
else:
url += qpath_info
return url
def iter_close(iter):
if hasattr(iter, 'close'):
iter.close()
def gzip_app_iter(app_iter):
size = 0
crc = zlib.crc32(b"") & 0xffffffff
compress = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS,
zlib.DEF_MEM_LEVEL, 0)
yield _gzip_header
for item in app_iter:
size += len(item)
crc = zlib.crc32(item, crc) & 0xffffffff
yield compress.compress(item)
yield compress.flush()
yield struct.pack("<2L", crc, size & 0xffffffff)
def _error_unicode_in_app_iter(app_iter, body):
app_iter_repr = repr(app_iter)
if len(app_iter_repr) > 50:
app_iter_repr = (
app_iter_repr[:30] + '...' + app_iter_repr[-10:])
raise TypeError(
'An item of the app_iter (%s) was text, causing a '
'text body: %r' % (app_iter_repr, body))
| Python |
"""
Represents the Cache-Control header
"""
import re
class UpdateDict(dict):
"""
Dict that has a callback on all updates
"""
# these are declared as class attributes so that
# we don't need to override constructor just to
# set some defaults
updated = None
updated_args = None
def _updated(self):
"""
Assign to new_dict.updated to track updates
"""
updated = self.updated
if updated is not None:
args = self.updated_args
if args is None:
args = (self,)
updated(*args)
def __setitem__(self, key, item):
dict.__setitem__(self, key, item)
self._updated()
def __delitem__(self, key):
dict.__delitem__(self, key)
self._updated()
def clear(self):
dict.clear(self)
self._updated()
def update(self, *args, **kw):
dict.update(self, *args, **kw)
self._updated()
def setdefault(self, key, value=None):
val = dict.setdefault(self, key, value)
if val is value:
self._updated()
return val
def pop(self, *args):
v = dict.pop(self, *args)
self._updated()
return v
def popitem(self):
v = dict.popitem(self)
self._updated()
return v
token_re = re.compile(
r'([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?')
need_quote_re = re.compile(r'[^a-zA-Z0-9._-]')
class exists_property(object):
"""
Represents a property that either is listed in the Cache-Control
header, or is not listed (has no value)
"""
def __init__(self, prop, type=None):
self.prop = prop
self.type = type
def __get__(self, obj, type=None):
if obj is None:
return self
return self.prop in obj.properties
def __set__(self, obj, value):
if (self.type is not None
and self.type != obj.type):
raise AttributeError(
"The property %s only applies to %s Cache-Control" % (
self.prop, self.type))
if value:
obj.properties[self.prop] = None
else:
if self.prop in obj.properties:
del obj.properties[self.prop]
def __delete__(self, obj):
self.__set__(obj, False)
class value_property(object):
"""
Represents a property that has a value in the Cache-Control header.
When no value is actually given, the value of self.none is returned.
"""
def __init__(self, prop, default=None, none=None, type=None):
self.prop = prop
self.default = default
self.none = none
self.type = type
def __get__(self, obj, type=None):
if obj is None:
return self
if self.prop in obj.properties:
value = obj.properties[self.prop]
if value is None:
return self.none
else:
return value
else:
return self.default
def __set__(self, obj, value):
if (self.type is not None
and self.type != obj.type):
raise AttributeError(
"The property %s only applies to %s Cache-Control" % (
self.prop, self.type))
if value == self.default:
if self.prop in obj.properties:
del obj.properties[self.prop]
elif value is True:
obj.properties[self.prop] = None # Empty value, but present
else:
obj.properties[self.prop] = value
def __delete__(self, obj):
if self.prop in obj.properties:
del obj.properties[self.prop]
class CacheControl(object):
"""
Represents the Cache-Control header.
By giving a type of ``'request'`` or ``'response'`` you can
control what attributes are allowed (some Cache-Control values
only apply to requests or responses).
"""
update_dict = UpdateDict
def __init__(self, properties, type):
self.properties = properties
self.type = type
@classmethod
def parse(cls, header, updates_to=None, type=None):
"""
Parse the header, returning a CacheControl object.
The object is bound to the request or response object
``updates_to``, if that is given.
"""
if updates_to:
props = cls.update_dict()
props.updated = updates_to
else:
props = {}
for match in token_re.finditer(header):
name = match.group(1)
value = match.group(2) or match.group(3) or None
if value:
try:
value = int(value)
except ValueError:
pass
props[name] = value
obj = cls(props, type=type)
if updates_to:
props.updated_args = (obj,)
return obj
def __repr__(self):
return '<CacheControl %r>' % str(self)
# Request values:
# no-cache shared (below)
# no-store shared (below)
# max-age shared (below)
max_stale = value_property('max-stale', none='*', type='request')
min_fresh = value_property('min-fresh', type='request')
# no-transform shared (below)
only_if_cached = exists_property('only-if-cached', type='request')
# Response values:
public = exists_property('public', type='response')
private = value_property('private', none='*', type='response')
no_cache = value_property('no-cache', none='*')
no_store = exists_property('no-store')
no_transform = exists_property('no-transform')
must_revalidate = exists_property('must-revalidate', type='response')
proxy_revalidate = exists_property('proxy-revalidate', type='response')
max_age = value_property('max-age', none=-1)
s_maxage = value_property('s-maxage', type='response')
s_max_age = s_maxage
def __str__(self):
return serialize_cache_control(self.properties)
def copy(self):
"""
Returns a copy of this object.
"""
return self.__class__(self.properties.copy(), type=self.type)
def serialize_cache_control(properties):
if isinstance(properties, CacheControl):
properties = properties.properties
parts = []
for name, value in sorted(properties.items()):
if value is None:
parts.append(name)
continue
value = str(value)
if need_quote_re.search(value):
value = '"%s"' % value
parts.append('%s=%s' % (name, value))
return ', '.join(parts)
| Python |
# code stolen from "six"
import sys
import types
# True if we are running on Python 3.
PY3 = sys.version_info[0] == 3
if PY3: # pragma: no cover
string_types = str,
integer_types = int,
class_types = type,
text_type = str
long = int
else:
string_types = basestring,
integer_types = (int, long)
class_types = (type, types.ClassType)
text_type = unicode
long = long
# TODO check if errors is ever used
def text_(s, encoding='latin-1', errors='strict'):
if isinstance(s, bytes):
return s.decode(encoding, errors)
return s
def bytes_(s, encoding='latin-1', errors='strict'):
if isinstance(s, text_type):
return s.encode(encoding, errors)
return s
if PY3: # pragma: no cover
def native_(s, encoding='latin-1', errors='strict'):
if isinstance(s, text_type):
return s
return str(s, encoding, errors)
else:
def native_(s, encoding='latin-1', errors='strict'):
if isinstance(s, text_type):
return s.encode(encoding, errors)
return str(s)
try:
from queue import Queue, Empty
except ImportError:
from Queue import Queue, Empty
if PY3: # pragma: no cover
from urllib import parse
urlparse = parse
from urllib.parse import quote as url_quote
from urllib.parse import urlencode as url_encode, quote_plus
from urllib.request import urlopen as url_open
else:
import urlparse
from urllib import quote_plus
from urllib import quote as url_quote
from urllib import unquote as url_unquote
from urllib import urlencode as url_encode
from urllib2 import urlopen as url_open
if PY3: # pragma: no cover
def reraise(exc_info):
etype, exc, tb = exc_info
if exc.__traceback__ is not tb:
raise exc.with_traceback(tb)
raise exc
else: # pragma: no cover
exec("def reraise(exc): raise exc[0], exc[1], exc[2]")
if PY3: # pragma: no cover
def iteritems_(d):
return d.items()
def itervalues_(d):
return d.values()
else:
def iteritems_(d):
return d.iteritems()
def itervalues_(d):
return d.itervalues()
if PY3: # pragma: no cover
def unquote(string):
if not string:
return b''
res = string.split(b'%')
if len(res) != 1:
string = res[0]
for item in res[1:]:
try:
string += bytes([int(item[:2], 16)]) + item[2:]
except ValueError:
string += b'%' + item
return string
def url_unquote(s):
return unquote(s.encode('ascii')).decode('latin-1')
def parse_qsl_text(qs, encoding='utf-8'):
qs = qs.encode('latin-1')
qs = qs.replace(b'+', b' ')
pairs = [s2 for s1 in qs.split(b'&') for s2 in s1.split(b';') if s2]
for name_value in pairs:
nv = name_value.split(b'=', 1)
if len(nv) != 2:
nv.append('')
name = unquote(nv[0])
value = unquote(nv[1])
yield (name.decode(encoding), value.decode(encoding))
else:
from urlparse import parse_qsl
def parse_qsl_text(qs, encoding='utf-8'):
qsl = parse_qsl(
qs,
keep_blank_values=True,
strict_parsing=False
)
for (x, y) in qsl:
yield (x.decode(encoding), y.decode(encoding))
if PY3: # pragma no cover
from html import escape
else:
from cgi import escape
| Python |
# (c) 2005 Ian Bicking and contributors; written for Paste
# (http://pythonpaste.org) Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license.php
"""
Gives a multi-value dictionary object (MultiDict) plus several wrappers
"""
from collections import MutableMapping
import warnings
from webob.compat import (
PY3,
iteritems_,
itervalues_,
url_encode,
)
__all__ = ['MultiDict', 'NestedMultiDict', 'NoVars', 'GetDict']
class MultiDict(MutableMapping):
"""
An ordered dictionary that can have multiple values for each key.
Adds the methods getall, getone, mixed and extend and add to the normal
dictionary interface.
"""
def __init__(self, *args, **kw):
if len(args) > 1:
raise TypeError("MultiDict can only be called with one positional "
"argument")
if args:
if hasattr(args[0], 'iteritems'):
items = list(args[0].iteritems())
elif hasattr(args[0], 'items'):
items = list(args[0].items())
else:
items = list(args[0])
self._items = items
else:
self._items = []
if kw:
self._items.extend(kw.items())
@classmethod
def view_list(cls, lst):
"""
Create a dict that is a view on the given list
"""
if not isinstance(lst, list):
raise TypeError(
"%s.view_list(obj) takes only actual list objects, not %r"
% (cls.__name__, lst))
obj = cls()
obj._items = lst
return obj
@classmethod
def from_fieldstorage(cls, fs):
"""
Create a dict from a cgi.FieldStorage instance
"""
obj = cls()
# fs.list can be None when there's nothing to parse
for field in fs.list or ():
charset = field.type_options.get('charset', 'utf8')
if PY3: # pragma: no cover
if charset == 'utf8':
decode = lambda b: b
else:
decode = lambda b: b.encode('utf8').decode(charset)
else:
decode = lambda b: b.decode(charset)
field.name = decode(field.name)
if field.filename:
field.filename = decode(field.filename)
obj.add(field.name, field)
else:
obj.add(field.name, decode(field.value))
return obj
def __getitem__(self, key):
for k, v in reversed(self._items):
if k == key:
return v
raise KeyError(key)
def __setitem__(self, key, value):
try:
del self[key]
except KeyError:
pass
self._items.append((key, value))
def add(self, key, value):
"""
Add the key and value, not overwriting any previous value.
"""
self._items.append((key, value))
def getall(self, key):
"""
Return a list of all values matching the key (may be an empty list)
"""
result = []
for k, v in self._items:
if key == k:
result.append(v)
return result
def getone(self, key):
"""
Get one value matching the key, raising a KeyError if multiple
values were found.
"""
v = self.getall(key)
if not v:
raise KeyError('Key not found: %r' % key)
if len(v) > 1:
raise KeyError('Multiple values match %r: %r' % (key, v))
return v[0]
def mixed(self):
"""
Returns a dictionary where the values are either single
values, or a list of values when a key/value appears more than
once in this dictionary. This is similar to the kind of
dictionary often used to represent the variables in a web
request.
"""
result = {}
multi = {}
for key, value in self.items():
if key in result:
# We do this to not clobber any lists that are
# *actual* values in this dictionary:
if key in multi:
result[key].append(value)
else:
result[key] = [result[key], value]
multi[key] = None
else:
result[key] = value
return result
def dict_of_lists(self):
"""
Returns a dictionary where each key is associated with a list of values.
"""
r = {}
for key, val in self.items():
r.setdefault(key, []).append(val)
return r
def __delitem__(self, key):
items = self._items
found = False
for i in range(len(items)-1, -1, -1):
if items[i][0] == key:
del items[i]
found = True
if not found:
raise KeyError(key)
def __contains__(self, key):
for k, v in self._items:
if k == key:
return True
return False
has_key = __contains__
def clear(self):
del self._items[:]
def copy(self):
return self.__class__(self)
def setdefault(self, key, default=None):
for k, v in self._items:
if key == k:
return v
self._items.append((key, default))
return default
def pop(self, key, *args):
if len(args) > 1:
raise TypeError("pop expected at most 2 arguments, got %s"
% repr(1 + len(args)))
for i in range(len(self._items)):
if self._items[i][0] == key:
v = self._items[i][1]
del self._items[i]
return v
if args:
return args[0]
else:
raise KeyError(key)
def popitem(self):
return self._items.pop()
def update(self, *args, **kw):
if args:
lst = args[0]
if len(lst) != len(dict(lst)):
# this does not catch the cases where we overwrite existing
# keys, but those would produce too many warning
msg = ("Behavior of MultiDict.update() has changed "
"and overwrites duplicate keys. Consider using .extend()"
)
warnings.warn(msg, UserWarning, stacklevel=2)
MutableMapping.update(self, *args, **kw)
def extend(self, other=None, **kwargs):
if other is None:
pass
elif hasattr(other, 'items'):
self._items.extend(other.items())
elif hasattr(other, 'keys'):
for k in other.keys():
self._items.append((k, other[k]))
else:
for k, v in other:
self._items.append((k, v))
if kwargs:
self.update(kwargs)
def __repr__(self):
items = map('(%r, %r)'.__mod__, _hide_passwd(self.items()))
return '%s([%s])' % (self.__class__.__name__, ', '.join(items))
def __len__(self):
return len(self._items)
##
## All the iteration:
##
def iterkeys(self):
for k, v in self._items:
yield k
if PY3: # pragma: no cover
keys = iterkeys
else:
def keys(self):
return [k for k, v in self._items]
__iter__ = iterkeys
def iteritems(self):
return iter(self._items)
if PY3: # pragma: no cover
items = iteritems
else:
def items(self):
return self._items[:]
def itervalues(self):
for k, v in self._items:
yield v
if PY3: # pragma: no cover
values = itervalues
else:
def values(self):
return [v for k, v in self._items]
_dummy = object()
class GetDict(MultiDict):
# def __init__(self, data, tracker, encoding, errors):
# d = lambda b: b.decode(encoding, errors)
# data = [(d(k), d(v)) for k,v in data]
def __init__(self, data, env):
self.env = env
MultiDict.__init__(self, data)
def on_change(self):
e = lambda t: t.encode('utf8')
data = [(e(k), e(v)) for k,v in self.items()]
qs = url_encode(data)
self.env['QUERY_STRING'] = qs
self.env['webob._parsed_query_vars'] = (self, qs)
def __setitem__(self, key, value):
MultiDict.__setitem__(self, key, value)
self.on_change()
def add(self, key, value):
MultiDict.add(self, key, value)
self.on_change()
def __delitem__(self, key):
MultiDict.__delitem__(self, key)
self.on_change()
def clear(self):
MultiDict.clear(self)
self.on_change()
def setdefault(self, key, default=None):
result = MultiDict.setdefault(self, key, default)
self.on_change()
return result
def pop(self, key, *args):
result = MultiDict.pop(self, key, *args)
self.on_change()
return result
def popitem(self):
result = MultiDict.popitem(self)
self.on_change()
return result
def update(self, *args, **kwargs):
MultiDict.update(self, *args, **kwargs)
self.on_change()
def __repr__(self):
items = map('(%r, %r)'.__mod__, _hide_passwd(self.items()))
# TODO: GET -> GetDict
return 'GET([%s])' % (', '.join(items))
def copy(self):
# Copies shouldn't be tracked
return MultiDict(self)
class NestedMultiDict(MultiDict):
"""
Wraps several MultiDict objects, treating it as one large MultiDict
"""
def __init__(self, *dicts):
self.dicts = dicts
def __getitem__(self, key):
for d in self.dicts:
value = d.get(key, _dummy)
if value is not _dummy:
return value
raise KeyError(key)
def _readonly(self, *args, **kw):
raise KeyError("NestedMultiDict objects are read-only")
__setitem__ = _readonly
add = _readonly
__delitem__ = _readonly
clear = _readonly
setdefault = _readonly
pop = _readonly
popitem = _readonly
update = _readonly
def getall(self, key):
result = []
for d in self.dicts:
result.extend(d.getall(key))
return result
# Inherited:
# getone
# mixed
# dict_of_lists
def copy(self):
return MultiDict(self)
def __contains__(self, key):
for d in self.dicts:
if key in d:
return True
return False
has_key = __contains__
def __len__(self):
v = 0
for d in self.dicts:
v += len(d)
return v
def __nonzero__(self):
for d in self.dicts:
if d:
return True
return False
def iteritems(self):
for d in self.dicts:
for item in iteritems_(d):
yield item
if PY3: # pragma: no cover
items = iteritems
else:
def items(self):
return list(self.iteritems())
def itervalues(self):
for d in self.dicts:
for value in itervalues_(d):
yield value
if PY3: # pragma: no cover
values = itervalues
else:
def values(self):
return list(self.itervalues())
def __iter__(self):
for d in self.dicts:
for key in d:
yield key
iterkeys = __iter__
if PY3: # pragma: no cover
keys = iterkeys
else:
def keys(self):
return list(self.iterkeys())
class NoVars(object):
"""
Represents no variables; used when no variables
are applicable.
This is read-only
"""
def __init__(self, reason=None):
self.reason = reason or 'N/A'
def __getitem__(self, key):
raise KeyError("No key %r: %s" % (key, self.reason))
def __setitem__(self, *args, **kw):
raise KeyError("Cannot add variables: %s" % self.reason)
add = __setitem__
setdefault = __setitem__
update = __setitem__
def __delitem__(self, *args, **kw):
raise KeyError("No keys to delete: %s" % self.reason)
clear = __delitem__
pop = __delitem__
popitem = __delitem__
def get(self, key, default=None):
return default
def getall(self, key):
return []
def getone(self, key):
return self[key]
def mixed(self):
return {}
dict_of_lists = mixed
def __contains__(self, key):
return False
has_key = __contains__
def copy(self):
return self
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__,
self.reason)
def __len__(self):
return 0
def __cmp__(self, other):
return cmp({}, other)
def iterkeys(self):
return iter([])
if PY3: # pragma: no cover
keys = iterkeys
items = iterkeys
values = iterkeys
else:
def keys(self):
return []
items = keys
values = keys
itervalues = iterkeys
iteritems = iterkeys
__iter__ = iterkeys
def _hide_passwd(items):
for k, v in items:
if ('password' in k
or 'passwd' in k
or 'pwd' in k
):
yield k, '******'
else:
yield k, v
| Python |
"""
Does parsing of ETag-related headers: If-None-Matches, If-Matches
Also If-Range parsing
"""
from webob.datetime_utils import (
parse_date,
serialize_date,
)
from webob.descriptors import _rx_etag
from webob.util import (
header_docstring,
warn_deprecation,
)
__all__ = ['AnyETag', 'NoETag', 'ETagMatcher', 'IfRange', 'etag_property']
def etag_property(key, default, rfc_section, strong=True):
doc = header_docstring(key, rfc_section)
doc += " Converts it as a Etag."
def fget(req):
value = req.environ.get(key)
if not value:
return default
else:
return ETagMatcher.parse(value, strong=strong)
def fset(req, val):
if val is None:
req.environ[key] = None
else:
req.environ[key] = str(val)
def fdel(req):
del req.environ[key]
return property(fget, fset, fdel, doc=doc)
def _warn_weak_match_deprecated():
warn_deprecation("weak_match is deprecated", '1.2', 3)
def _warn_if_range_match_deprecated(*args, **kw): # pragma: no cover
raise DeprecationWarning("IfRange.match[_response] API is deprecated")
class _AnyETag(object):
"""
Represents an ETag of *, or a missing ETag when matching is 'safe'
"""
def __repr__(self):
return '<ETag *>'
def __nonzero__(self):
return False
__bool__ = __nonzero__ # python 3
def __contains__(self, other):
return True
def weak_match(self, other):
_warn_weak_match_deprecated()
def __str__(self):
return '*'
AnyETag = _AnyETag()
class _NoETag(object):
"""
Represents a missing ETag when matching is unsafe
"""
def __repr__(self):
return '<No ETag>'
def __nonzero__(self):
return False
__bool__ = __nonzero__ # python 3
def __contains__(self, other):
return False
def weak_match(self, other): # pragma: no cover
_warn_weak_match_deprecated()
def __str__(self):
return ''
NoETag = _NoETag()
# TODO: convert into a simple tuple
class ETagMatcher(object):
def __init__(self, etags):
self.etags = etags
def __contains__(self, other):
return other in self.etags
def weak_match(self, other): # pragma: no cover
_warn_weak_match_deprecated()
def __repr__(self):
return '<ETag %s>' % (' or '.join(self.etags))
@classmethod
def parse(cls, value, strong=True):
"""
Parse this from a header value
"""
if value == '*':
return AnyETag
if not value:
return cls([])
matches = _rx_etag.findall(value)
if not matches:
return cls([value])
elif strong:
return cls([t for w,t in matches if not w])
else:
return cls([t for w,t in matches])
def __str__(self):
return ', '.join(map('"%s"'.__mod__, self.etags))
class IfRange(object):
def __init__(self, etag):
self.etag = etag
@classmethod
def parse(cls, value):
"""
Parse this from a header value.
"""
if not value:
return cls(AnyETag)
elif value.endswith(' GMT'):
# Must be a date
return IfRangeDate(parse_date(value))
else:
return cls(ETagMatcher.parse(value))
def __contains__(self, resp):
"""
Return True if the If-Range header matches the given etag or last_modified
"""
return resp.etag_strong in self.etag
def __nonzero__(self):
return bool(self.etag)
def __repr__(self):
return '%s(%r)' % (
self.__class__.__name__,
self.etag
)
def __str__(self):
return str(self.etag) if self.etag else ''
match = match_response = _warn_if_range_match_deprecated
__bool__ = __nonzero__ # python 3
class IfRangeDate(object):
def __init__(self, date):
self.date = date
def __contains__(self, resp):
last_modified = resp.last_modified
#if isinstance(last_modified, str):
# last_modified = parse_date(last_modified)
return last_modified and (last_modified <= self.date)
def __repr__(self):
return '%s(%r)' % (
self.__class__.__name__,
self.date
#serialize_date(self.date)
)
def __str__(self):
return serialize_date(self.date)
match = match_response = _warn_if_range_match_deprecated
| Python |
# A reaction to: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/552751
from webob import Request, Response
from webob import exc
from simplejson import loads, dumps
import traceback
import sys
class JsonRpcApp(object):
"""
Serve the given object via json-rpc (http://json-rpc.org/)
"""
def __init__(self, obj):
self.obj = obj
def __call__(self, environ, start_response):
req = Request(environ)
try:
resp = self.process(req)
except ValueError, e:
resp = exc.HTTPBadRequest(str(e))
except exc.HTTPException, e:
resp = e
return resp(environ, start_response)
def process(self, req):
if not req.method == 'POST':
raise exc.HTTPMethodNotAllowed(
"Only POST allowed",
allowed='POST').exception
try:
json = loads(req.body)
except ValueError, e:
raise ValueError('Bad JSON: %s' % e)
try:
method = json['method']
params = json['params']
id = json['id']
except KeyError, e:
raise ValueError(
"JSON body missing parameter: %s" % e)
if method.startswith('_'):
raise exc.HTTPForbidden(
"Bad method name %s: must not start with _" % method).exception
if not isinstance(params, list):
raise ValueError(
"Bad params %r: must be a list" % params)
try:
method = getattr(self.obj, method)
except AttributeError:
raise ValueError(
"No such method %s" % method)
try:
result = method(*params)
except:
text = traceback.format_exc()
exc_value = sys.exc_info()[1]
error_value = dict(
name='JSONRPCError',
code=100,
message=str(exc_value),
error=text)
return Response(
status=500,
content_type='application/json',
body=dumps(dict(result=None,
error=error_value,
id=id)))
return Response(
content_type='application/json',
body=dumps(dict(result=result,
error=None,
id=id)))
class ServerProxy(object):
"""
JSON proxy to a remote service.
"""
def __init__(self, url, proxy=None):
self._url = url
if proxy is None:
from wsgiproxy.exactproxy import proxy_exact_request
proxy = proxy_exact_request
self.proxy = proxy
def __getattr__(self, name):
if name.startswith('_'):
raise AttributeError(name)
return _Method(self, name)
def __repr__(self):
return '<%s for %s>' % (
self.__class__.__name__, self._url)
class _Method(object):
def __init__(self, parent, name):
self.parent = parent
self.name = name
def __call__(self, *args):
json = dict(method=self.name,
id=None,
params=list(args))
req = Request.blank(self.parent._url)
req.method = 'POST'
req.content_type = 'application/json'
req.body = dumps(json)
resp = req.get_response(self.parent.proxy)
if resp.status_int != 200 and not (
resp.status_int == 500
and resp.content_type == 'application/json'):
raise ProxyError(
"Error from JSON-RPC client %s: %s"
% (self.parent._url, resp.status),
resp)
json = loads(resp.body)
if json.get('error') is not None:
e = Fault(
json['error'].get('message'),
json['error'].get('code'),
json['error'].get('error'),
resp)
raise e
return json['result']
class ProxyError(Exception):
"""
Raised when a request via ServerProxy breaks
"""
def __init__(self, message, response):
Exception.__init__(self, message)
self.response = response
class Fault(Exception):
"""
Raised when there is a remote error
"""
def __init__(self, message, code, error, response):
Exception.__init__(self, message)
self.code = code
self.error = error
self.response = response
def __str__(self):
return 'Method error calling %s: %s\n%s' % (
self.response.request.url,
self.args[0],
self.error)
class DemoObject(object):
"""
Something interesting to attach to
"""
def add(self, *args):
return sum(args)
def average(self, *args):
return sum(args) / float(len(args))
def divide(self, a, b):
return a / b
def make_app(expr):
module, expression = expr.split(':', 1)
__import__(module)
module = sys.modules[module]
obj = eval(expression, module.__dict__)
return JsonRpcApp(obj)
def main(args=None):
import optparse
from wsgiref import simple_server
parser = optparse.OptionParser(
usage='%prog [OPTIONS] MODULE:EXPRESSION')
parser.add_option(
'-p', '--port', default='8080',
help='Port to serve on (default 8080)')
parser.add_option(
'-H', '--host', default='127.0.0.1',
help='Host to serve on (default localhost; 0.0.0.0 to make public)')
options, args = parser.parse_args()
if not args or len(args) > 1:
print 'You must give a single object reference'
parser.print_help()
sys.exit(2)
app = make_app(args[0])
server = simple_server.make_server(options.host, int(options.port), app)
print 'Serving on http://%s:%s' % (options.host, options.port)
server.serve_forever()
# Try python jsonrpc.py 'jsonrpc:DemoObject()'
if __name__ == '__main__':
main()
| Python |
import os
import urllib
import time
import re
from cPickle import load, dump
from webob import Request, Response, html_escape
from webob import exc
class Commenter(object):
def __init__(self, app, storage_dir):
self.app = app
self.storage_dir = storage_dir
if not os.path.exists(storage_dir):
os.makedirs(storage_dir)
def __call__(self, environ, start_response):
req = Request(environ)
if req.path_info_peek() == '.comments':
return self.process_comment(req)(environ, start_response)
# This is the base path of *this* middleware:
base_url = req.application_url
resp = req.get_response(self.app)
if resp.content_type != 'text/html' or resp.status_int != 200:
# Not an HTML response, we don't want to
# do anything to it
return resp(environ, start_response)
# Make sure the content isn't gzipped:
resp.decode_content()
comments = self.get_data(req.url)
body = resp.body
body = self.add_to_end(body, self.format_comments(comments))
body = self.add_to_end(body, self.submit_form(base_url, req))
resp.body = body
return resp(environ, start_response)
def get_data(self, url):
# Double-quoting makes the filename safe
filename = self.url_filename(url)
if not os.path.exists(filename):
return []
else:
f = open(filename, 'rb')
data = load(f)
f.close()
return data
def save_data(self, url, data):
filename = self.url_filename(url)
f = open(filename, 'wb')
dump(data, f)
f.close()
def url_filename(self, url):
return os.path.join(self.storage_dir, urllib.quote(url, ''))
_end_body_re = re.compile(r'</body.*?>', re.I|re.S)
def add_to_end(self, html, extra_html):
"""
Adds extra_html to the end of the html page (before </body>)
"""
match = self._end_body_re.search(html)
if not match:
return html + extra_html
else:
return html[:match.start()] + extra_html + html[match.start():]
def format_comments(self, comments):
if not comments:
return ''
text = []
text.append('<hr>')
text.append('<h2><a name="comment-area"></a>Comments (%s):</h2>' % len(comments))
for comment in comments:
text.append('<h3><a href="%s">%s</a> at %s:</h3>' % (
html_escape(comment['homepage']), html_escape(comment['name']),
time.strftime('%c', comment['time'])))
# Susceptible to XSS attacks!:
text.append(comment['comments'])
return ''.join(text)
def submit_form(self, base_path, req):
return '''<h2>Leave a comment:</h2>
<form action="%s/.comments" method="POST">
<input type="hidden" name="url" value="%s">
<table width="100%%">
<tr><td>Name:</td>
<td><input type="text" name="name" style="width: 100%%"></td></tr>
<tr><td>URL:</td>
<td><input type="text" name="homepage" style="width: 100%%"></td></tr>
</table>
Comments:<br>
<textarea name="comments" rows=10 style="width: 100%%"></textarea><br>
<input type="submit" value="Submit comment">
</form>
''' % (base_path, html_escape(req.url))
def process_comment(self, req):
try:
url = req.params['url']
name = req.params['name']
homepage = req.params['homepage']
comments = req.params['comments']
except KeyError, e:
resp = exc.HTTPBadRequest('Missing parameter: %s' % e)
return resp
data = self.get_data(url)
data.append(dict(
name=name,
homepage=homepage,
comments=comments,
time=time.gmtime()))
self.save_data(url, data)
resp = exc.HTTPSeeOther(location=url+'#comment-area')
return resp
if __name__ == '__main__':
import optparse
parser = optparse.OptionParser(
usage='%prog --port=PORT BASE_DIRECTORY'
)
parser.add_option(
'-p', '--port',
default='8080',
dest='port',
type='int',
help='Port to serve on (default 8080)')
parser.add_option(
'--comment-data',
default='./comments',
dest='comment_data',
help='Place to put comment data into (default ./comments/)')
options, args = parser.parse_args()
if not args:
parser.error('You must give a BASE_DIRECTORY')
base_dir = args[0]
from paste.urlparser import StaticURLParser
app = StaticURLParser(base_dir)
app = Commenter(app, options.comment_data)
from wsgiref.simple_server import make_server
httpd = make_server('localhost', options.port, app)
print 'Serving on http://localhost:%s' % options.port
try:
httpd.serve_forever()
except KeyboardInterrupt:
print '^C'
| Python |
import os
import re
from webob import Request, Response
from webob import exc
from tempita import HTMLTemplate
VIEW_TEMPLATE = HTMLTemplate("""\
<html>
<head>
<title>{{page.title}}</title>
</head>
<body>
<h1>{{page.title}}</h1>
{{if message}}
<div style="background-color: #99f">{{message}}</div>
{{endif}}
<div>{{page.content|html}}</div>
<hr>
<a href="{{req.url}}?action=edit">Edit</a>
</body>
</html>
""")
EDIT_TEMPLATE = HTMLTemplate("""\
<html>
<head>
<title>Edit: {{page.title}}</title>
</head>
<body>
{{if page.exists}}
<h1>Edit: {{page.title}}</h1>
{{else}}
<h1>Create: {{page.title}}</h1>
{{endif}}
<form action="{{req.path_url}}" method="POST">
<input type="hidden" name="mtime" value="{{page.mtime}}">
Title: <input type="text" name="title" style="width: 70%" value="{{page.title}}"><br>
Content: <input type="submit" value="Save">
<a href="{{req.path_url}}">Cancel</a>
<br>
<textarea name="content" style="width: 100%; height: 75%" rows="40">{{page.content}}</textarea>
<br>
<input type="submit" value="Save">
<a href="{{req.path_url}}">Cancel</a>
</form>
</body></html>
""")
class WikiApp(object):
view_template = VIEW_TEMPLATE
edit_template = EDIT_TEMPLATE
def __init__(self, storage_dir):
self.storage_dir = os.path.abspath(os.path.normpath(storage_dir))
def __call__(self, environ, start_response):
req = Request(environ)
action = req.params.get('action', 'view')
page = self.get_page(req.path_info)
try:
try:
meth = getattr(self, 'action_%s_%s' % (action, req.method))
except AttributeError:
raise exc.HTTPBadRequest('No such action %r' % action).exception
resp = meth(req, page)
except exc.HTTPException, e:
resp = e
return resp(environ, start_response)
def get_page(self, path):
path = path.lstrip('/')
if not path:
path = 'index'
path = os.path.join(self.storage_dir, path)
path = os.path.normpath(path)
if path.endswith('/'):
path += 'index'
if not path.startswith(self.storage_dir):
raise exc.HTTPBadRequest("Bad path").exception
path += '.html'
return Page(path)
def action_view_GET(self, req, page):
if not page.exists:
return exc.HTTPTemporaryRedirect(
location=req.url + '?action=edit')
if req.cookies.get('message'):
message = req.cookies['message']
else:
message = None
text = self.view_template.substitute(
page=page, req=req, message=message)
resp = Response(text)
if message:
resp.delete_cookie('message')
else:
resp.last_modified = page.mtime
resp.conditional_response = True
return resp
def action_view_POST(self, req, page):
submit_mtime = int(req.params.get('mtime') or '0') or None
if page.mtime != submit_mtime:
return exc.HTTPPreconditionFailed(
"The page has been updated since you started editing it")
page.set(
title=req.params['title'],
content=req.params['content'])
resp = exc.HTTPSeeOther(
location=req.path_url)
resp.set_cookie('message', 'Page updated')
return resp
def action_edit_GET(self, req, page):
text = self.edit_template.substitute(
page=page, req=req)
return Response(text)
class Page(object):
def __init__(self, filename):
self.filename = filename
@property
def exists(self):
return os.path.exists(self.filename)
@property
def title(self):
if not self.exists:
# we need to guess the title
basename = os.path.splitext(os.path.basename(self.filename))[0]
basename = re.sub(r'[_-]', ' ', basename)
return basename.capitalize()
content = self.full_content
match = re.search(r'<title>(.*?)</title>', content, re.I|re.S)
return match.group(1)
@property
def full_content(self):
f = open(self.filename, 'rb')
try:
return f.read()
finally:
f.close()
@property
def content(self):
if not self.exists:
return ''
content = self.full_content
match = re.search(r'<body[^>]*>(.*?)</body>', content, re.I|re.S)
return match.group(1)
@property
def mtime(self):
if not self.exists:
return None
else:
return os.stat(self.filename).st_mtime
def set(self, title, content):
dir = os.path.dirname(self.filename)
if not os.path.exists(dir):
os.makedirs(dir)
new_content = """<html><head><title>%s</title></head><body>%s</body></html>""" % (
title, content)
f = open(self.filename, 'wb')
f.write(new_content)
f.close()
if __name__ == '__main__':
import optparse
parser = optparse.OptionParser(
usage='%prog --port=PORT'
)
parser.add_option(
'-p', '--port',
default='8080',
dest='port',
type='int',
help='Port to serve on (default 8080)')
parser.add_option(
'--wiki-data',
default='./wiki',
dest='wiki_data',
help='Place to put wiki data into (default ./wiki/)')
options, args = parser.parse_args()
print 'Writing wiki pages to %s' % options.wiki_data
app = WikiApp(options.wiki_data)
from wsgiref.simple_server import make_server
httpd = make_server('localhost', options.port, app)
print 'Serving on http://localhost:%s' % options.port
try:
httpd.serve_forever()
except KeyboardInterrupt:
print '^C'
| Python |
import unittest
import doctest
def test_suite():
flags = doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE
return unittest.TestSuite((
doctest.DocFileSuite('test_request.txt', optionflags=flags),
doctest.DocFileSuite('test_response.txt', optionflags=flags),
doctest.DocFileSuite('test_dec.txt', optionflags=flags),
doctest.DocFileSuite('do-it-yourself.txt', optionflags=flags),
doctest.DocFileSuite('file-example.txt', optionflags=flags),
doctest.DocFileSuite('index.txt', optionflags=flags),
doctest.DocFileSuite('reference.txt', optionflags=flags),
))
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
| Python |
# -*- coding: utf-8 -*-
#
# Paste documentation build configuration file, created by
# sphinx-quickstart on Tue Apr 22 22:08:49 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
#
# All configuration values have a default value; values that are commented out
# serve to show the default value.
import sys
# If your extensions are in another directory, add it here.
#sys.path.append('some/directory')
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.txt'
# The master toctree document.
master_doc = 'index'
# General substitutions.
project = 'WebOb'
copyright = '2011, Ian Bicking and contributors'
# The default replacements for |version| and |release|, also used in various
# other places throughout the built documents.
#
# The short X.Y version.
version = '1.0'
# The full version, including alpha/beta/rc tags.
release = '1.0.8'
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
unused_docs = ['jsonrpc-example-code/test_jsonrpc']
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# Options for HTML output
# -----------------------
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
html_style = 'default.css'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Content template for the index page.
#html_index = ''
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If true, the reST sources are included in the HTML build as _sources/<name>.
#html_copy_source = True
# Output file base name for HTML help builder.
htmlhelp_basename = 'WebObdoc'
# Options for LaTeX output
# ------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
#latex_documents = []
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
| Python |
from setuptools import setup
version = '1.0.8'
setup(
name='WebOb',
version=version,
description="WSGI request and response object",
long_description="""\
WebOb provides wrappers around the WSGI request environment, and an
object to help create WSGI responses.
The objects map much of the specified behavior of HTTP, including
header parsing and accessors for other standard parts of the
environment.
You may install the `in-development version of WebOb
<http://bitbucket.org/ianb/webob/get/tip.gz#egg=WebOb-dev>`_ with
``pip install WebOb==dev`` (or ``easy_install WebOb==dev``).
* `WebOb reference <http://pythonpaste.org/webob/reference.html>`_
* `Bug tracker <https://bitbucket.org/ianb/webob/issues>`_
* `Browse source code <https://bitbucket.org/ianb/webob/src>`_
* `Mailing list <http://bit.ly/paste-users>`_
* `Release news <http://pythonpaste.org/webob/news>`_
* `Detailed changelog <https://bitbucket.org/ianb/webob/changesets>`_
""",
classifiers=[
"Development Status :: 6 - Mature",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Internet :: WWW/HTTP :: WSGI",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
"Programming Language :: Python :: 2.4",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
],
keywords='wsgi request web http',
author='Ian Bicking',
author_email='ianb@colorstudy.com',
maintainer='Sergey Schetinin',
maintainer_email='sergey@maluke.com',
url='http://pythonpaste.org/webob/',
license='MIT',
packages=['webob'],
zip_safe=True,
test_suite='nose.collector',
tests_require=['nose', 'WebTest'],
)
| Python |
#!/usr/bin/env python
import webob
def make_middleware(app):
from repoze.profile.profiler import AccumulatingProfileMiddleware
return AccumulatingProfileMiddleware(
app,
log_filename='/tmp/profile.log',
discard_first_request=True,
flush_at_shutdown=True,
path='/__profile__')
def simple_app(environ, start_response):
resp = webob.Response('Hello world!')
return resp(environ, start_response)
if __name__ == '__main__':
import sys
import os
import signal
if sys.argv[1:]:
arg = sys.argv[1]
else:
arg = None
if arg in ['open', 'run']:
import subprocess
import webbrowser
import time
os.environ['SHOW_OUTPUT'] = '0'
proc = subprocess.Popen([sys.executable, __file__])
time.sleep(1)
subprocess.call(['ab', '-n', '1000', 'http://localhost:8080/'])
if arg == 'open':
webbrowser.open('http://localhost:8080/__profile__')
print 'Hit ^C to end'
try:
while 1:
raw_input()
finally:
os.kill(proc.pid, signal.SIGKILL)
else:
from paste.httpserver import serve
if os.environ.get('SHOW_OUTPUT') != '0':
print 'Note you can also use:'
print ' %s %s open' % (sys.executable, __file__)
print 'to run ab and open a browser (or "run" to just run ab)'
print 'Now do:'
print 'ab -n 1000 http://localhost:8080/'
print 'wget -O - http://localhost:8080/__profile__'
serve(make_middleware(simple_app))
| Python |
#
| Python |
import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import pkg_resources
pkg_resources.require('WebOb')
| Python |
"""
Parses a variety of ``Accept-*`` headers.
These headers generally take the form of::
value1; q=0.5, value2; q=0
Where the ``q`` parameter is optional. In theory other parameters
exists, but this ignores them.
"""
import re
from webob.util import rfc_reference
from webob.headers import _trans_name as header_to_key
part_re = re.compile(
r',\s*([^\s;,\n]+)(?:[^,]*?;\s*q=([0-9.]*))?')
def parse_accept(value):
"""
Parses an ``Accept-*`` style header.
A list of ``[(value, quality), ...]`` is returned. ``quality``
will be 1 if it was not given.
"""
result = []
for match in part_re.finditer(','+value):
name = match.group(1)
if name == 'q':
continue
quality = match.group(2) or ''
if not quality:
quality = 1
else:
try:
quality = max(min(float(quality), 1), 0)
except ValueError:
quality = 1
result.append((name, quality))
return result
class Accept(object):
"""
Represents a generic ``Accept-*`` style header.
This object should not be modified. To add items you can use
``accept_obj + 'accept_thing'`` to get a new object
"""
def __init__(self, header_name, header_value):
self.header_name = header_name
self.header_value = header_value
self._parsed = parse_accept(header_value)
if header_name == 'Accept-Charset':
for k, v in self._parsed:
if k == '*' or k == 'iso-8859-1':
break
else:
self._parsed.append(('iso-8859-1', 1))
elif header_name == 'Accept-Language':
self._match = self._match_lang
self._parsed_nonzero = [(m,q) for (m,q) in self._parsed if q]
def __repr__(self):
return '<%s at 0x%x %s: %s>' % (
self.__class__.__name__,
abs(id(self)),
self.header_name, str(self))
def __str__(self):
result = []
for mask, quality in self._parsed:
if quality != 1:
mask = '%s;q=%0.1f' % (mask, quality)
result.append(mask)
return ', '.join(result)
# FIXME: should subtraction be allowed?
def __add__(self, other, reversed=False):
if isinstance(other, Accept):
other = other.header_value
if hasattr(other, 'items'):
other = sorted(other.items(), key=lambda item: -item[1])
if isinstance(other, (list, tuple)):
result = []
for item in other:
if isinstance(item, (list, tuple)):
name, quality = item
result.append('%s; q=%s' % (name, quality))
else:
result.append(item)
other = ', '.join(result)
other = str(other)
my_value = self.header_value
if reversed:
other, my_value = my_value, other
if not other:
new_value = my_value
elif not my_value:
new_value = other
else:
new_value = my_value + ', ' + other
return self.__class__(self.header_name, new_value)
def __radd__(self, other):
return self.__add__(other, True)
def __contains__(self, offer):
"""
Returns true if the given object is listed in the accepted
types.
"""
for mask, quality in self._parsed_nonzero:
if self._match(mask, offer):
return True
def quality(self, offer, modifier=1):
"""
Return the quality of the given offer. Returns None if there
is no match (not 0).
"""
# FIXME: this does not return best quality, just quality of the first match
for mask, quality in self._parsed:
if self._match(mask, offer):
return quality * modifier
return None
def first_match(self, offers):
"""
Returns the first allowed offered type. Ignores quality.
Returns the first offered type if nothing else matches; or if you include None
at the end of the match list then that will be returned.
"""
# FIXME: this method is a bad idea and should be deprecated
if not offers:
raise ValueError("You must pass in a non-empty list")
for offer in offers:
if offer is None:
return None
for mask, quality in self._parsed_nonzero:
if self._match(mask, offer):
return offer
return offers[0]
def best_match(self, offers, default_match=None):
"""
Returns the best match in the sequence of offered types.
The sequence can be a simple sequence, or you can have
``(match, server_quality)`` items in the sequence. If you
have these tuples then the client quality is multiplied by the
server_quality to get a total. If two matches have equal
weight, then the one that shows up first in the `offers` list
will be returned.
But among matches with the same quality the match to a more specific
requested type will be chosen. For example a match to text/* trumps */*.
default_match (default None) is returned if there is no intersection.
"""
best_quality = -1
best_offer = default_match
matched_by = '*/*'
for offer in offers:
if isinstance(offer, (tuple, list)):
offer, server_quality = offer
else:
server_quality = 1
for mask, quality in self._parsed_nonzero:
possible_quality = server_quality * quality
if possible_quality < best_quality:
continue
elif possible_quality == best_quality:
# 'text/plain' overrides 'message/*' overrides '*/*'
# (if all match w/ the same q=)
if matched_by.count('*') <= mask.count('*'):
continue
if self._match(mask, offer):
best_quality = possible_quality
best_offer = offer
matched_by = mask
return best_offer
def best_matches(self, fallback=None):
"""
Return all the matches in order of quality, with fallback (if
given) at the end.
"""
items = [i for i, q in sorted(self._parsed, key=lambda iq: -iq[1])]
if fallback:
for index, item in enumerate(items):
if self._match(item, fallback):
items[index:] = [fallback]
break
else:
items.append(fallback)
return items
def _match(self, mask, offer):
_check_offer(offer)
return mask == '*' or offer.lower() == mask.lower()
def _match_lang(self, mask, item):
return (mask == '*'
or item.lower() == mask.lower()
or item.lower().split('-')[0] == mask.lower()
)
class NilAccept(object):
"""
Represents an Accept header with no value.
"""
MasterClass = Accept
def __init__(self, header_name):
self.header_name = header_name
def __repr__(self):
return '<%s for %s: %s>' % (
self.__class__.__name__, self.header_name, self.MasterClass)
def __str__(self):
return ''
def __nonzero__(self):
return False
def __add__(self, item):
if isinstance(item, self.MasterClass):
return item
else:
return self.MasterClass(self.header_name, '') + item
def __radd__(self, item):
if isinstance(item, self.MasterClass):
return item
else:
return item + self.MasterClass(self.header_name, '')
def __contains__(self, item):
_check_offer(item)
return True
def quality(self, offer, default_quality=1):
return 0
def first_match(self, offers):
return offers[0]
def best_match(self, offers, default_match=None):
best_quality = -1
best_match = default_match
for offer in offers:
_check_offer(offer)
if isinstance(offer, (list, tuple)):
offer, quality = offer
else:
quality = 1
if quality > best_quality:
best_offer = offer
best_quality = quality
return best_offer
def best_matches(self, fallback=None):
if fallback:
return [fallback]
else:
return []
class NoAccept(NilAccept):
def __contains__(self, item):
return False
class MIMEAccept(Accept):
"""
Represents the ``Accept`` header, which is a list of mimetypes.
This class knows about mime wildcards, like ``image/*``
"""
def __init__(self, header_name, header_value):
Accept.__init__(self, header_name, header_value)
parsed = []
for mask, q in self._parsed:
try:
mask_major, mask_minor = mask.split('/')
except ValueError:
continue
if mask_major == '*' and mask_minor != '*':
continue
parsed.append((mask, q))
self._parsed = parsed
def accept_html(self):
"""
Returns true if any HTML-like type is accepted
"""
return ('text/html' in self
or 'application/xhtml+xml' in self
or 'application/xml' in self
or 'text/xml' in self)
accepts_html = property(accept_html) # note the plural
def _match(self, mask, offer):
"""
Check if the offer is covered by the mask
"""
_check_offer(offer)
if '*' not in mask:
return offer == mask
elif mask == '*/*':
return True
else:
assert mask.endswith('/*')
mask_major = mask[:-2]
offer_major = offer.split('/', 1)[0]
return offer_major == mask_major
class MIMENilAccept(NilAccept):
MasterClass = MIMEAccept
def _check_offer(offer):
if '*' in offer:
raise ValueError("The application should offer specific types, got %r" % offer)
def accept_property(header, rfc_section,
AcceptClass=Accept, NilClass=NilAccept, convert_name='accept header'
):
key = header_to_key(header)
doc = "Gets and sets the %r key in the environment." % key
doc += rfc_reference(key, rfc_section)
doc += " Converts it as a %s." % convert_name
def fget(req):
value = req.environ.get(key)
if not value:
return NilClass(header)
return AcceptClass(header, value)
def fset(req, val):
if val:
if isinstance(val, (list, tuple, dict)):
val = AcceptClass(header, '') + val
val = str(val)
req.environ[key] = val or None
def fdel(req):
del req.environ[key]
return property(fget, fset, fdel, doc)
| Python |
from webob.multidict import MultiDict
from UserDict import DictMixin
__all__ = ['ResponseHeaders', 'EnvironHeaders']
class ResponseHeaders(MultiDict):
"""
Dictionary view on the response headerlist.
Keys are normalized for case and whitespace.
"""
def __getitem__(self, key):
key = key.lower()
for k, v in reversed(self._items):
if k.lower() == key:
return v
raise KeyError(key)
def getall(self, key):
key = key.lower()
result = []
for k, v in self._items:
if k.lower() == key:
result.append(v)
return result
def mixed(self):
r = self.dict_of_lists()
for key, val in r.iteritems():
if len(val) == 1:
r[key] = val[0]
return r
def dict_of_lists(self):
r = {}
for key, val in self.iteritems():
r.setdefault(key.lower(), []).append(val)
return r
def __setitem__(self, key, value):
norm_key = key.lower()
items = self._items
for i in range(len(items)-1, -1, -1):
if items[i][0].lower() == norm_key:
del items[i]
self._items.append((key, value))
def __delitem__(self, key):
key = key.lower()
items = self._items
found = False
for i in range(len(items)-1, -1, -1):
if items[i][0].lower() == key:
del items[i]
found = True
if not found:
raise KeyError(key)
def __contains__(self, key):
key = key.lower()
for k, v in self._items:
if k.lower() == key:
return True
return False
has_key = __contains__
def setdefault(self, key, default=None):
c_key = key.lower()
for k, v in self._items:
if k.lower() == c_key:
return v
self._items.append((key, default))
return default
def pop(self, key, *args):
if len(args) > 1:
raise TypeError, "pop expected at most 2 arguments, got "\
+ repr(1 + len(args))
key = key.lower()
for i in range(len(self._items)):
if self._items[i][0].lower() == key:
v = self._items[i][1]
del self._items[i]
return v
if args:
return args[0]
else:
raise KeyError(key)
key2header = {
'CONTENT_TYPE': 'Content-Type',
'CONTENT_LENGTH': 'Content-Length',
'HTTP_CONTENT_TYPE': 'Content_Type',
'HTTP_CONTENT_LENGTH': 'Content_Length',
}
header2key = dict([(v.upper(),k) for (k,v) in key2header.items()])
def _trans_key(key):
if not isinstance(key, basestring):
return None
elif key in key2header:
return key2header[key]
elif key.startswith('HTTP_'):
return key[5:].replace('_', '-').title()
else:
return None
def _trans_name(name):
name = name.upper()
if name in header2key:
return header2key[name]
return 'HTTP_'+name.replace('-', '_')
class EnvironHeaders(DictMixin):
"""An object that represents the headers as present in a
WSGI environment.
This object is a wrapper (with no internal state) for a WSGI
request object, representing the CGI-style HTTP_* keys as a
dictionary. Because a CGI environment can only hold one value for
each key, this dictionary is single-valued (unlike outgoing
headers).
"""
def __init__(self, environ):
self.environ = environ
def __getitem__(self, hname):
return self.environ[_trans_name(hname)]
def __setitem__(self, hname, value):
self.environ[_trans_name(hname)] = value
def __delitem__(self, hname):
del self.environ[_trans_name(hname)]
def keys(self):
return filter(None, map(_trans_key, self.environ))
def __contains__(self, hname):
return _trans_name(hname) in self.environ
| Python |
import time
import calendar
from datetime import datetime, date, timedelta, tzinfo
from rfc822 import parsedate_tz, mktime_tz, formatdate
__all__ = [
'UTC', 'timedelta_to_seconds',
'year', 'month', 'week', 'day', 'hour', 'minute', 'second',
'parse_date', 'serialize_date',
'parse_date_delta', 'serialize_date_delta',
]
_now = datetime.now # hook point for unit tests
class _UTC(tzinfo):
def dst(self, dt):
return timedelta(0)
def utcoffset(self, dt):
return timedelta(0)
def tzname(self, dt):
return 'UTC'
def __repr__(self):
return 'UTC'
UTC = _UTC()
def timedelta_to_seconds(td):
"""
Converts a timedelta instance to seconds.
"""
return td.seconds + (td.days*24*60*60)
day = timedelta(days=1)
week = timedelta(weeks=1)
hour = timedelta(hours=1)
minute = timedelta(minutes=1)
second = timedelta(seconds=1)
# Estimate, I know; good enough for expirations
month = timedelta(days=30)
year = timedelta(days=365)
def parse_date(value):
if not value:
return None
try:
value = str(value)
except:
return None
t = parsedate_tz(value)
if t is None:
# Could not parse
return None
if t[-1] is None:
# No timezone given. None would mean local time, but we'll force UTC
t = t[:9] + (0,)
t = mktime_tz(t)
return datetime.fromtimestamp(t, UTC)
def serialize_date(dt):
if isinstance(dt, unicode):
dt = dt.encode('ascii')
if isinstance(dt, str):
return dt
if isinstance(dt, timedelta):
dt = _now() + dt
if isinstance(dt, (datetime, date)):
dt = dt.timetuple()
if isinstance(dt, (tuple, time.struct_time)):
dt = calendar.timegm(dt)
if not isinstance(dt, (float, int, long)):
raise ValueError(
"You must pass in a datetime, date, time tuple, or integer object, not %r" % dt)
return formatdate(dt)
def parse_date_delta(value):
"""
like parse_date, but also handle delta seconds
"""
if not value:
return None
try:
value = int(value)
except ValueError:
return parse_date(value)
else:
return _now() + timedelta(seconds=value)
def serialize_date_delta(value):
if isinstance(value, (float, int)):
return str(int(value))
else:
return serialize_date(value)
| Python |
import re, time, string
from datetime import datetime, date, timedelta
__all__ = ['Cookie']
class Cookie(dict):
def __init__(self, input=None):
if input:
self.load(input)
def load(self, data):
ckey = None
for key, val in _rx_cookie.findall(data):
if key.lower() in _c_keys:
if ckey:
self[ckey][key] = _unquote(val)
elif key[0] == '$':
# RFC2109: NAMEs that begin with $ are reserved for other uses
# and must not be used by applications.
continue
else:
self[key] = _unquote(val)
ckey = key
def __setitem__(self, key, val):
if needs_quoting(key):
return
dict.__setitem__(self, key, Morsel(key, val))
def serialize(self, full=True):
return '; '.join(m.serialize(full) for m in self.values())
def values(self):
return [m for _,m in sorted(self.items())]
__str__ = serialize
def __repr__(self):
return '<%s: [%s]>' % (self.__class__.__name__,
', '.join(map(repr, self.values())))
def cookie_property(key, serialize=lambda v: v):
def fset(self, v):
self[key] = serialize(v)
return property(lambda self: self[key], fset)
def serialize_max_age(v):
if isinstance(v, timedelta):
return str(v.seconds + v.days*24*60*60)
elif isinstance(v, int):
return str(v)
else:
return v
def serialize_cookie_date(v):
if v is None:
return None
elif isinstance(v, str):
return v
elif isinstance(v, int):
v = timedelta(seconds=v)
if isinstance(v, timedelta):
v = datetime.utcnow() + v
if isinstance(v, (datetime, date)):
v = v.timetuple()
r = time.strftime('%%s, %d-%%s-%Y %H:%M:%S GMT', v)
return r % (weekdays[v[6]], months[v[1]])
class Morsel(dict):
__slots__ = ('name', 'value')
def __init__(self, name, value):
assert name.lower() not in _c_keys
assert not needs_quoting(name)
assert isinstance(value, str)
self.name = name
# we can encode the unicode value as UTF-8 here,
# but then the decoded cookie would still be str,
# so we don't do that
self.value = value
self.update(dict.fromkeys(_c_keys, None))
path = cookie_property('path')
domain = cookie_property('domain')
comment = cookie_property('comment')
expires = cookie_property('expires', serialize_cookie_date)
max_age = cookie_property('max-age', serialize_max_age)
httponly = cookie_property('httponly', bool)
secure = cookie_property('secure', bool)
def __setitem__(self, k, v):
k = k.lower()
if k in _c_keys:
dict.__setitem__(self, k, v)
def serialize(self, full=True):
result = []
add = result.append
add("%s=%s" % (self.name, _quote(self.value)))
if full:
for k in _c_valkeys:
v = self[k]
if v:
assert isinstance(v, str), v
add("%s=%s" % (_c_renames[k], _quote(v)))
expires = self['expires']
if expires:
add("expires=%s" % expires)
if self.secure:
add('secure')
if self.httponly:
add('HttpOnly')
return '; '.join(result)
__str__ = serialize
def __repr__(self):
return '<%s: %s=%s>' % (self.__class__.__name__,
self.name, repr(self.value))
_c_renames = {
"path" : "Path",
"comment" : "Comment",
"domain" : "Domain",
"max-age" : "Max-Age",
}
_c_valkeys = sorted(_c_renames)
_c_keys = set(_c_renames)
_c_keys.update(['expires', 'secure', 'httponly'])
#
# parsing
#
_re_quoted = r'"(?:\\"|.)*?"' # any doublequoted string
_legal_special_chars = "~!@#$%^&*()_+=-`.?|:/(){}<>'"
_re_legal_char = r"[\w\d%s]" % ''.join(map(r'\%s'.__mod__,
_legal_special_chars))
_re_expires_val = r"\w{3},\s[\w\d-]{9,11}\s[\d:]{8}\sGMT"
_rx_cookie = re.compile(
# key
(r"(%s+?)" % _re_legal_char)
# =
+ r"\s*=\s*"
# val
+ r"(%s|%s|%s*)" % (_re_quoted, _re_expires_val, _re_legal_char)
)
_rx_unquote = re.compile(r'\\([0-3][0-7][0-7]|.)')
def _unquote(v):
if v and v[0] == v[-1] == '"':
v = v[1:-1]
def _ch_unquote(m):
v = m.group(1)
if v.isdigit():
return chr(int(v, 8))
return v
v = _rx_unquote.sub(_ch_unquote, v)
return v
#
# serializing
#
_trans_noop = ''.join(chr(x) for x in xrange(256))
# these chars can be in cookie value w/o causing it to be quoted
_no_escape_special_chars = "!#$%&'*+-.^_`|~/"
_no_escape_chars = string.ascii_letters + string.digits + \
_no_escape_special_chars
# these chars never need to be quoted
_escape_noop_chars = _no_escape_chars+': '
# this is a map used to escape the values
_escape_map = dict((chr(i), '\\%03o' % i) for i in xrange(256))
_escape_map.update(zip(_escape_noop_chars, _escape_noop_chars))
_escape_map['"'] = '\\"'
_escape_map['\\'] = '\\\\'
_escape_char = _escape_map.__getitem__
weekdays = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
months = (None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec')
def needs_quoting(v):
return v.translate(_trans_noop, _no_escape_chars)
def _quote(v):
if needs_quoting(v):
return '"' + ''.join(map(_escape_char, v)) + '"'
return v
| Python |
import sys, tempfile, warnings
import urllib, urlparse, cgi
if sys.version >= '2.7':
from io import BytesIO as StringIO # pragma nocover
else:
from cStringIO import StringIO # pragma nocover
from webob.headers import EnvironHeaders
from webob.acceptparse import accept_property, Accept, MIMEAccept, NilAccept, MIMENilAccept, NoAccept
from webob.multidict import TrackableMultiDict, MultiDict, UnicodeMultiDict, NestedMultiDict, NoVars
from webob.cachecontrol import CacheControl, serialize_cache_control
from webob.etag import etag_property, AnyETag, NoETag
from webob.descriptors import *
from webob.datetime_utils import *
from webob.cookies import Cookie
__all__ = ['BaseRequest', 'Request']
if sys.version >= '2.6':
parse_qsl = urlparse.parse_qsl
else:
parse_qsl = cgi.parse_qsl # pragma nocover
class _NoDefault:
def __repr__(self):
return '(No Default)'
NoDefault = _NoDefault()
PATH_SAFE = '/:@&+$,'
http_method_has_body = dict.fromkeys(('GET', 'HEAD', 'DELETE', 'TRACE'), False)
http_method_has_body.update(dict.fromkeys(('POST', 'PUT'), True))
class BaseRequest(object):
## Options:
unicode_errors = 'strict'
decode_param_names = False
## The limit after which request bodies should be stored on disk
## if they are read in (under this, and the request body is stored
## in memory):
request_body_tempfile_limit = 10*1024
def __init__(self, environ,
charset=NoDefault, unicode_errors=NoDefault, decode_param_names=NoDefault,
**kw
):
if type(environ) is not dict:
raise TypeError("WSGI environ must be a dict")
d = self.__dict__
d['environ'] = environ
if charset is not NoDefault:
self.charset = charset
cls = self.__class__
if (isinstance(getattr(cls, 'charset', None), str)
or hasattr(cls, 'default_charset')
):
raise DeprecationWarning(
"The class attr [default_]charset is deprecated")
if unicode_errors is not NoDefault:
d['unicode_errors'] = unicode_errors
if decode_param_names is not NoDefault:
d['decode_param_names'] = decode_param_names
if kw:
if 'method' in kw:
# set method first, because .body setters
# depend on it for checks
self.method = kw.pop('method')
for name, value in kw.iteritems():
if not hasattr(cls, name):
raise TypeError(
"Unexpected keyword: %s=%r" % (name, value))
setattr(self, name, value)
# this is necessary for correct warnings depth for both
# BaseRequest and Request (due to AdhocAttrMixin.__setattr__)
_setattr_stacklevel = 2
def _body_file__get(self):
"""
Input stream of the request (wsgi.input).
Setting this property resets the content_length and seekable flag
(unlike setting req.body_file_raw).
"""
if not self.is_body_readable:
return StringIO('')
return self.body_file_raw
def _body_file__set(self, value):
if isinstance(value, str):
# FIXME: change to DeprecationWarning in 1.1, raise exc in 1.2
warnings.warn(
"Please use req.body = 'str' or req.body_file = fileobj",
PendingDeprecationWarning,
stacklevel=self._setattr_stacklevel,
)
self.body = value
return
if not http_method_has_body.get(self.method, True):
raise ValueError("%s requests cannot have body" % self.method)
self.content_length = None
self.body_file_raw = value
self.is_body_seekable = False
self.is_body_readable = True
def _body_file__del(self):
self.body = ''
body_file = property(_body_file__get,
_body_file__set,
_body_file__del,
doc=_body_file__get.__doc__)
body_file_raw = environ_getter('wsgi.input')
@property
def body_file_seekable(self):
"""
Get the body of the request (wsgi.input) as a seekable file-like
object. Middleware and routing applications should use this
attribute over .body_file.
If you access this value, CONTENT_LENGTH will also be updated.
"""
if not self.is_body_seekable:
self.make_body_seekable()
return self.body_file_raw
scheme = environ_getter('wsgi.url_scheme')
method = environ_getter('REQUEST_METHOD')
http_version = environ_getter('SERVER_PROTOCOL')
script_name = environ_getter('SCRIPT_NAME', '')
path_info = environ_getter('PATH_INFO')
content_length = converter(
environ_getter('CONTENT_LENGTH', None, '14.13'),
parse_int_safe, serialize_int, 'int')
remote_user = environ_getter('REMOTE_USER', None)
remote_addr = environ_getter('REMOTE_ADDR', None)
query_string = environ_getter('QUERY_STRING', '')
server_name = environ_getter('SERVER_NAME')
server_port = converter(
environ_getter('SERVER_PORT'),
parse_int, serialize_int, 'int')
uscript_name = upath_property('SCRIPT_NAME')
upath_info = upath_property('PATH_INFO')
def _content_type__get(self):
"""Return the content type, but leaving off any parameters (like
charset, but also things like the type in ``application/atom+xml;
type=entry``)
If you set this property, you can include parameters, or if
you don't include any parameters in the value then existing
parameters will be preserved.
"""
return self.environ.get('CONTENT_TYPE', '').split(';', 1)[0]
def _content_type__set(self, value):
if value is None:
del self.content_type
return
value = str(value)
if ';' not in value:
content_type = self.environ.get('CONTENT_TYPE', '')
if ';' in content_type:
value += ';' + content_type.split(';', 1)[1]
self.environ['CONTENT_TYPE'] = value
def _content_type__del(self):
if 'CONTENT_TYPE' in self.environ:
del self.environ['CONTENT_TYPE']
content_type = property(_content_type__get,
_content_type__set,
_content_type__del,
_content_type__get.__doc__)
_charset_cache = (None, None)
def _charset__get(self):
"""Get the charset of the request.
If the request was sent with a charset parameter on the
Content-Type, that will be used. Otherwise if there is a
default charset (set during construction, or as a class
attribute) that will be returned. Otherwise None.
Setting this property after request instantiation will always
update Content-Type. Deleting the property updates the
Content-Type to remove any charset parameter (if none exists,
then deleting the property will do nothing, and there will be
no error).
"""
content_type = self.environ.get('CONTENT_TYPE', '')
cached_ctype, cached_charset = self._charset_cache
if cached_ctype == content_type:
return cached_charset
charset_match = CHARSET_RE.search(content_type)
if charset_match:
result = charset_match.group(1).strip('"').strip()
else:
result = 'UTF-8'
self._charset_cache = (content_type, result)
return result
def _charset__set(self, charset):
if charset is None or charset == '':
del self.charset
return
charset = str(charset)
content_type = self.environ.get('CONTENT_TYPE', '')
charset_match = CHARSET_RE.search(self.environ.get('CONTENT_TYPE', ''))
if charset_match:
content_type = (content_type[:charset_match.start(1)] +
charset + content_type[charset_match.end(1):])
# comma to separate params? there's nothing like that in RFCs AFAICT
#elif ';' in content_type:
# content_type += ', charset="%s"' % charset
else:
content_type += '; charset="%s"' % charset
self.environ['CONTENT_TYPE'] = content_type
def _charset__del(self):
new_content_type = CHARSET_RE.sub('', self.environ.get('CONTENT_TYPE', ''))
new_content_type = new_content_type.rstrip().rstrip(';').rstrip(',')
self.environ['CONTENT_TYPE'] = new_content_type
charset = property(_charset__get, _charset__set, _charset__del,
_charset__get.__doc__)
_headers = None
def _headers__get(self):
"""
All the request headers as a case-insensitive dictionary-like
object.
"""
if self._headers is None:
self._headers = EnvironHeaders(self.environ)
return self._headers
def _headers__set(self, value):
self.headers.clear()
self.headers.update(value)
headers = property(_headers__get, _headers__set, doc=_headers__get.__doc__)
@property
def host_url(self):
"""
The URL through the host (no path)
"""
e = self.environ
url = e['wsgi.url_scheme'] + '://'
if e.get('HTTP_HOST'):
host = e['HTTP_HOST']
if ':' in host:
host, port = host.split(':', 1)
else:
port = None
else:
host = e['SERVER_NAME']
port = e['SERVER_PORT']
if self.environ['wsgi.url_scheme'] == 'https':
if port == '443':
port = None
elif self.environ['wsgi.url_scheme'] == 'http':
if port == '80':
port = None
url += host
if port:
url += ':%s' % port
return url
@property
def application_url(self):
"""
The URL including SCRIPT_NAME (no PATH_INFO or query string)
"""
return self.host_url + urllib.quote(
self.environ.get('SCRIPT_NAME', ''), PATH_SAFE)
@property
def path_url(self):
"""
The URL including SCRIPT_NAME and PATH_INFO, but not QUERY_STRING
"""
return self.application_url + urllib.quote(
self.environ.get('PATH_INFO', ''), PATH_SAFE)
@property
def path(self):
"""
The path of the request, without host or query string
"""
return (urllib.quote(self.script_name, PATH_SAFE) +
urllib.quote(self.path_info, PATH_SAFE))
@property
def path_qs(self):
"""
The path of the request, without host but with query string
"""
path = self.path
qs = self.environ.get('QUERY_STRING')
if qs:
path += '?' + qs
return path
@property
def url(self):
"""
The full request URL, including QUERY_STRING
"""
url = self.path_url
if self.environ.get('QUERY_STRING'):
url += '?' + self.environ['QUERY_STRING']
return url
def relative_url(self, other_url, to_application=False):
"""
Resolve other_url relative to the request URL.
If ``to_application`` is True, then resolve it relative to the
URL with only SCRIPT_NAME
"""
if to_application:
url = self.application_url
if not url.endswith('/'):
url += '/'
else:
url = self.path_url
return urlparse.urljoin(url, other_url)
def path_info_pop(self, pattern=None):
"""
'Pops' off the next segment of PATH_INFO, pushing it onto
SCRIPT_NAME, and returning the popped segment. Returns None if
there is nothing left on PATH_INFO.
Does not return ``''`` when there's an empty segment (like
``/path//path``); these segments are just ignored.
Optional ``pattern`` argument is a regexp to match the return value
before returning. If there is no match, no changes are made to the
request and None is returned.
"""
path = self.path_info
if not path:
return None
slashes = ''
while path.startswith('/'):
slashes += '/'
path = path[1:]
idx = path.find('/')
if idx == -1:
idx = len(path)
r = path[:idx]
if pattern is None or re.match(pattern, r):
self.script_name += slashes + r
self.path_info = path[idx:]
return r
def path_info_peek(self):
"""
Returns the next segment on PATH_INFO, or None if there is no
next segment. Doesn't modify the environment.
"""
path = self.path_info
if not path:
return None
path = path.lstrip('/')
return path.split('/', 1)[0]
def _urlvars__get(self):
"""
Return any *named* variables matched in the URL.
Takes values from ``environ['wsgiorg.routing_args']``.
Systems like ``routes`` set this value.
"""
if 'paste.urlvars' in self.environ:
return self.environ['paste.urlvars']
elif 'wsgiorg.routing_args' in self.environ:
return self.environ['wsgiorg.routing_args'][1]
else:
result = {}
self.environ['wsgiorg.routing_args'] = ((), result)
return result
def _urlvars__set(self, value):
environ = self.environ
if 'wsgiorg.routing_args' in environ:
environ['wsgiorg.routing_args'] = (
environ['wsgiorg.routing_args'][0], value)
if 'paste.urlvars' in environ:
del environ['paste.urlvars']
elif 'paste.urlvars' in environ:
environ['paste.urlvars'] = value
else:
environ['wsgiorg.routing_args'] = ((), value)
def _urlvars__del(self):
if 'paste.urlvars' in self.environ:
del self.environ['paste.urlvars']
if 'wsgiorg.routing_args' in self.environ:
if not self.environ['wsgiorg.routing_args'][0]:
del self.environ['wsgiorg.routing_args']
else:
self.environ['wsgiorg.routing_args'] = (
self.environ['wsgiorg.routing_args'][0], {})
urlvars = property(_urlvars__get,
_urlvars__set,
_urlvars__del,
doc=_urlvars__get.__doc__)
def _urlargs__get(self):
"""
Return any *positional* variables matched in the URL.
Takes values from ``environ['wsgiorg.routing_args']``.
Systems like ``routes`` set this value.
"""
if 'wsgiorg.routing_args' in self.environ:
return self.environ['wsgiorg.routing_args'][0]
else:
# Since you can't update this value in-place, we don't need
# to set the key in the environment
return ()
def _urlargs__set(self, value):
environ = self.environ
if 'paste.urlvars' in environ:
# Some overlap between this and wsgiorg.routing_args; we need
# wsgiorg.routing_args to make this work
routing_args = (value, environ.pop('paste.urlvars'))
elif 'wsgiorg.routing_args' in environ:
routing_args = (value, environ['wsgiorg.routing_args'][1])
else:
routing_args = (value, {})
environ['wsgiorg.routing_args'] = routing_args
def _urlargs__del(self):
if 'wsgiorg.routing_args' in self.environ:
if not self.environ['wsgiorg.routing_args'][1]:
del self.environ['wsgiorg.routing_args']
else:
self.environ['wsgiorg.routing_args'] = (
(), self.environ['wsgiorg.routing_args'][1])
urlargs = property(_urlargs__get,
_urlargs__set,
_urlargs__del,
_urlargs__get.__doc__)
@property
def is_xhr(self):
"""Is X-Requested-With header present and equal to ``XMLHttpRequest``?
Note: this isn't set by every XMLHttpRequest request, it is
only set if you are using a Javascript library that sets it
(or you set the header yourself manually). Currently
Prototype and jQuery are known to set this header."""
return self.environ.get('HTTP_X_REQUESTED_WITH', ''
) == 'XMLHttpRequest'
def _host__get(self):
"""Host name provided in HTTP_HOST, with fall-back to SERVER_NAME"""
if 'HTTP_HOST' in self.environ:
return self.environ['HTTP_HOST']
else:
return '%(SERVER_NAME)s:%(SERVER_PORT)s' % self.environ
def _host__set(self, value):
self.environ['HTTP_HOST'] = value
def _host__del(self):
if 'HTTP_HOST' in self.environ:
del self.environ['HTTP_HOST']
host = property(_host__get, _host__set, _host__del, doc=_host__get.__doc__)
def _body__get(self):
"""
Return the content of the request body.
"""
if not self.is_body_readable:
return ''
self.make_body_seekable() # we need this to have content_length
r = self.body_file.read(self.content_length)
self.body_file.seek(0)
return r
def _body__set(self, value):
if value is None:
value = ''
if not isinstance(value, str):
raise TypeError("You can only set Request.body to a str (not %r)"
% type(value))
if not http_method_has_body.get(self.method, True):
if not value:
self.content_length = None
self.body_file_raw = StringIO('')
return
raise ValueError("%s requests cannot have body" % self.method)
self.content_length = len(value)
self.body_file_raw = StringIO(value)
self.is_body_seekable = True
def _body__del(self):
self.body = ''
body = property(_body__get, _body__set, _body__del, doc=_body__get.__doc__)
@property
def str_POST(self):
"""
Return a MultiDict containing all the variables from a form
request. Returns an empty dict-like object for non-form
requests.
Form requests are typically POST requests, however PUT requests
with an appropriate Content-Type are also supported.
"""
env = self.environ
if self.method not in ('POST', 'PUT'):
return NoVars('Not a form request')
if 'webob._parsed_post_vars' in env:
vars, body_file = env['webob._parsed_post_vars']
if body_file is self.body_file_raw:
return vars
content_type = self.content_type
if ((self.method == 'PUT' and not content_type)
or content_type not in
('', 'application/x-www-form-urlencoded',
'multipart/form-data')
):
# Not an HTML form submission
return NoVars('Not an HTML form submission (Content-Type: %s)'
% content_type)
if self.is_body_seekable:
self.body_file.seek(0)
fs_environ = env.copy()
# FieldStorage assumes a missing CONTENT_LENGTH, but a
# default of 0 is better:
fs_environ.setdefault('CONTENT_LENGTH', '0')
fs_environ['QUERY_STRING'] = ''
fs = cgi.FieldStorage(fp=self.body_file_raw,
environ=fs_environ,
keep_blank_values=True)
vars = MultiDict.from_fieldstorage(fs)
#ctype = self.content_type or 'application/x-www-form-urlencoded'
ctype = env.get('CONTENT_TYPE', 'application/x-www-form-urlencoded')
self.body_file = FakeCGIBody(vars, ctype)
env['webob._parsed_post_vars'] = (vars, self.body_file_raw)
return vars
@property
def POST(self):
"""
Like ``.str_POST``, but may decode values and keys
"""
vars = self.str_POST
vars = UnicodeMultiDict(vars, encoding=self.charset,
errors=self.unicode_errors,
decode_keys=self.decode_param_names)
return vars
@property
def str_GET(self):
"""
Return a MultiDict containing all the variables from the
QUERY_STRING.
"""
env = self.environ
source = env.get('QUERY_STRING', '')
if 'webob._parsed_query_vars' in env:
vars, qs = env['webob._parsed_query_vars']
if qs == source:
return vars
if not source:
vars = TrackableMultiDict(__tracker=self._update_get, __name='GET')
else:
vars = TrackableMultiDict(parse_qsl(source,
keep_blank_values=True,
strict_parsing=False),
__tracker=self._update_get, __name='GET')
env['webob._parsed_query_vars'] = (vars, source)
return vars
def _update_get(self, vars, key=None, value=None):
env = self.environ
qs = urllib.urlencode(vars.items())
env['QUERY_STRING'] = qs
env['webob._parsed_query_vars'] = (vars, qs)
@property
def GET(self):
"""
Like ``.str_GET``, but may decode values and keys
"""
vars = self.str_GET
vars = UnicodeMultiDict(vars, encoding=self.charset,
errors=self.unicode_errors,
decode_keys=self.decode_param_names)
return vars
str_postvars = deprecated_property(str_POST, 'str_postvars',
'use str_POST instead')
postvars = deprecated_property(POST, 'postvars', 'use POST instead')
str_queryvars = deprecated_property(str_GET, 'str_queryvars',
'use str_GET instead')
queryvars = deprecated_property(GET, 'queryvars', 'use GET instead')
@property
def str_params(self):
"""
A dictionary-like object containing both the parameters from
the query string and request body.
"""
return NestedMultiDict(self.str_GET, self.str_POST)
@property
def params(self):
"""
Like ``.str_params``, but may decode values and keys
"""
params = self.str_params
params = UnicodeMultiDict(params, encoding=self.charset,
errors=self.unicode_errors,
decode_keys=self.decode_param_names)
return params
@property
def str_cookies(self):
"""
Return a *plain* dictionary of cookies as found in the request.
"""
env = self.environ
source = env.get('HTTP_COOKIE', '')
if 'webob._parsed_cookies' in env:
vars, var_source = env['webob._parsed_cookies']
if var_source == source:
return vars
vars = {}
if source:
cookies = Cookie(source)
for name in cookies:
vars[name] = cookies[name].value
env['webob._parsed_cookies'] = (vars, source)
return vars
@property
def cookies(self):
"""
Like ``.str_cookies``, but may decode values and keys
"""
vars = self.str_cookies
vars = UnicodeMultiDict(vars, encoding=self.charset,
errors=self.unicode_errors,
decode_keys=self.decode_param_names)
return vars
def copy(self):
"""
Copy the request and environment object.
This only does a shallow copy, except of wsgi.input
"""
self.make_body_seekable()
env = self.environ.copy()
new_req = self.__class__(env)
new_req.copy_body()
return new_req
def copy_get(self):
"""
Copies the request and environment object, but turning this request
into a GET along the way. If this was a POST request (or any other
verb) then it becomes GET, and the request body is thrown away.
"""
env = self.environ.copy()
return self.__class__(env, method='GET', content_type=None, body='')
# webob.is_body_seekalbe marks input streams that are seekable
# this way we can have seekable input without testing the .seek() method
is_body_seekable = environ_getter('webob.is_body_seekable', False)
#is_body_readable = environ_getter('webob.is_body_readable', False)
def _is_body_readable__get(self):
"""
webob.is_body_readable is a flag that tells us
that we can read the input stream even though
CONTENT_LENGTH is missing. This allows FakeCGIBody
to work and can be used by servers to support
chunked encoding in requests.
For background see https://bitbucket.org/ianb/webob/issue/6
"""
if self.method in http_method_has_body:
# known HTTP method
return http_method_has_body[self.method]
elif self.content_length is not None:
# unknown HTTP method, but the Content-Length
# header is present
return True
else:
# last resort -- rely on the special flag
return self.environ.get('webob.is_body_readable', False)
def _is_body_readable__set(self, flag):
#@@ WARN
self.environ['webob.is_body_readable'] = bool(flag)
is_body_readable = property(_is_body_readable__get, _is_body_readable__set,
doc=_is_body_readable__get.__doc__
)
def make_body_seekable(self):
"""
This forces ``environ['wsgi.input']`` to be seekable.
That means that, the content is copied into a StringIO or temporary
file and flagged as seekable, so that it will not be unnecessarily
copied again.
After calling this method the .body_file is always seeked to the
start of file and .content_length is not None.
The choice to copy to StringIO is made from
``self.request_body_tempfile_limit``
"""
if self.is_body_seekable:
self.body_file_raw.seek(0)
else:
self.copy_body()
def copy_body(self):
"""
Copies the body, in cases where it might be shared with
another request object and that is not desired.
This copies the body in-place, either into a StringIO object
or a temporary file.
"""
if not self.is_body_readable:
# there's no body to copy
self.body = ''
elif self.content_length is None:
# chunked body or FakeCGIBody
self.body = self.body_file_raw.read()
self._copy_body_tempfile()
else:
# try to read body into tempfile
did_copy = self._copy_body_tempfile()
if not did_copy:
# it wasn't necessary, so just read it into memory
self.body = self.body_file_raw.read(self.content_length)
def _copy_body_tempfile(self):
"""
Copy wsgi.input to tempfile if necessary. Returns True if it did.
"""
tempfile_limit = self.request_body_tempfile_limit
length = self.content_length
assert isinstance(length, int)
if not tempfile_limit or length <= tempfile_limit:
return False
fileobj = self.make_tempfile()
input = self.body_file_raw
while length:
data = input.read(min(length, 65536))
fileobj.write(data)
length -= len(data)
fileobj.seek(0)
self.body_file_raw = fileobj
self.is_body_seekable = True
return True
def make_tempfile(self):
"""
Create a tempfile to store big request body.
This API is not stable yet. A 'size' argument might be added.
"""
return tempfile.TemporaryFile()
def remove_conditional_headers(self,
remove_encoding=True,
remove_range=True,
remove_match=True,
remove_modified=True):
"""
Remove headers that make the request conditional.
These headers can cause the response to be 304 Not Modified,
which in some cases you may not want to be possible.
This does not remove headers like If-Match, which are used for
conflict detection.
"""
check_keys = []
if remove_range:
check_keys += ['HTTP_IF_RANGE', 'HTTP_RANGE']
if remove_match:
check_keys.append('HTTP_IF_NONE_MATCH')
if remove_modified:
check_keys.append('HTTP_IF_MODIFIED_SINCE')
if remove_encoding:
check_keys.append('HTTP_ACCEPT_ENCODING')
for key in check_keys:
if key in self.environ:
del self.environ[key]
accept = accept_property('Accept', '14.1', MIMEAccept, MIMENilAccept, 'MIME Accept')
accept_charset = accept_property('Accept-Charset', '14.2')
accept_encoding = accept_property('Accept-Encoding', '14.3', NilClass=NoAccept)
accept_language = accept_property('Accept-Language', '14.4')
authorization = converter(
environ_getter('HTTP_AUTHORIZATION', None, '14.8'),
parse_auth, serialize_auth,
)
def _cache_control__get(self):
"""
Get/set/modify the Cache-Control header (section `14.9
<http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9>`_)
"""
env = self.environ
value = env.get('HTTP_CACHE_CONTROL', '')
cache_header, cache_obj = env.get('webob._cache_control', (None, None))
if cache_obj is not None and cache_header == value:
return cache_obj
cache_obj = CacheControl.parse(value,
updates_to=self._update_cache_control,
type='request')
env['webob._cache_control'] = (value, cache_obj)
return cache_obj
def _cache_control__set(self, value):
env = self.environ
value = value or ''
if isinstance(value, dict):
value = CacheControl(value, type='request')
if isinstance(value, CacheControl):
str_value = str(value)
env['HTTP_CACHE_CONTROL'] = str_value
env['webob._cache_control'] = (str_value, value)
else:
env['HTTP_CACHE_CONTROL'] = str(value)
env['webob._cache_control'] = (None, None)
def _cache_control__del(self):
env = self.environ
if 'HTTP_CACHE_CONTROL' in env:
del env['HTTP_CACHE_CONTROL']
if 'webob._cache_control' in env:
del env['webob._cache_control']
def _update_cache_control(self, prop_dict):
self.environ['HTTP_CACHE_CONTROL'] = serialize_cache_control(prop_dict)
cache_control = property(_cache_control__get,
_cache_control__set,
_cache_control__del,
doc=_cache_control__get.__doc__)
if_match = etag_property('HTTP_IF_MATCH', AnyETag, '14.24')
if_none_match = etag_property('HTTP_IF_NONE_MATCH', NoETag, '14.26')
date = converter_date(environ_getter('HTTP_DATE', None, '14.8'))
if_modified_since = converter_date(
environ_getter('HTTP_IF_MODIFIED_SINCE', None, '14.25'))
if_unmodified_since = converter_date(
environ_getter('HTTP_IF_UNMODIFIED_SINCE', None, '14.28'))
if_range = converter(
environ_getter('HTTP_IF_RANGE', None, '14.27'),
parse_if_range, serialize_if_range, 'IfRange object')
max_forwards = converter(
environ_getter('HTTP_MAX_FORWARDS', None, '14.31'),
parse_int, serialize_int, 'int')
pragma = environ_getter('HTTP_PRAGMA', None, '14.32')
range = converter(
environ_getter('HTTP_RANGE', None, '14.35'),
parse_range, serialize_range, 'Range object')
referer = environ_getter('HTTP_REFERER', None, '14.36')
referrer = referer
user_agent = environ_getter('HTTP_USER_AGENT', None, '14.43')
def __repr__(self):
try:
name = '%s %s' % (self.method, self.url)
except KeyError:
name = '(invalid WSGI environ)'
msg = '<%s at 0x%x %s>' % (
self.__class__.__name__,
abs(id(self)), name)
return msg
def as_string(self, skip_body=False):
"""
Return HTTP string representing this request.
If skip_body is True, exclude the body.
If skip_body is an integer larger than one, skip body
only if its length is bigger than that number.
"""
url = self.url
host = self.host_url
assert url.startswith(host)
url = url[len(host):]
parts = ['%s %s %s' % (self.method, url, self.http_version)]
#self.headers.setdefault('Host', self.host)
# acquire body before we handle headers so that
# content-length will be set
body = None
if self.method in ('PUT', 'POST'):
if skip_body > 1:
if len(self.body) > skip_body:
body = '<body skipped (len=%s)>' % len(self.body)
else:
skip_body = False
if not skip_body:
body = self.body
parts += map('%s: %s'.__mod__, sorted(self.headers.items()))
if body:
parts.extend( ['',body] )
# HTTP clearly specifies CRLF
return '\r\n'.join(parts)
__str__ = as_string
@classmethod
def from_string(cls, s):
"""
Create a request from HTTP string. If the string contains
extra data after the request, raise a ValueError.
"""
f = StringIO(s)
r = cls.from_file(f)
if f.tell() != len(s):
raise ValueError("The string contains more data than expected")
return r
@classmethod
def from_file(cls, fp):
"""Read a request from a file-like object (it must implement
``.read(size)`` and ``.readline()``).
It will read up to the end of the request, not the end of the
file (unless the request is a POST or PUT and has no
Content-Length, in that case, the entire file is read).
This reads the request as represented by ``str(req)``; it may
not read every valid HTTP request properly."""
start_line = fp.readline()
try:
method, resource, http_version = start_line.rstrip('\r\n').split(None, 2)
except ValueError:
raise ValueError('Bad HTTP request line: %r' % start_line)
r = cls(environ_from_url(resource),
http_version=http_version,
method=method.upper()
)
del r.environ['HTTP_HOST']
while 1:
line = fp.readline()
if not line.strip():
# end of headers
break
hname, hval = line.split(':', 1)
hval = hval.strip()
if hname in r.headers:
hval = r.headers[hname] + ', ' + hval
r.headers[hname] = hval
if r.method in ('PUT', 'POST'):
clen = r.content_length
if clen is None:
r.body = fp.read()
else:
r.body = fp.read(clen)
return r
def call_application(self, application, catch_exc_info=False):
"""
Call the given WSGI application, returning ``(status_string,
headerlist, app_iter)``
Be sure to call ``app_iter.close()`` if it's there.
If catch_exc_info is true, then returns ``(status_string,
headerlist, app_iter, exc_info)``, where the fourth item may
be None, but won't be if there was an exception. If you don't
do this and there was an exception, the exception will be
raised directly.
"""
if self.is_body_seekable:
self.body_file_raw.seek(0)
captured = []
output = []
def start_response(status, headers, exc_info=None):
if exc_info is not None and not catch_exc_info:
raise exc_info[0], exc_info[1], exc_info[2]
captured[:] = [status, headers, exc_info]
return output.append
app_iter = application(self.environ, start_response)
if output or not captured:
try:
output.extend(app_iter)
finally:
if hasattr(app_iter, 'close'):
app_iter.close()
app_iter = output
if catch_exc_info:
return (captured[0], captured[1], app_iter, captured[2])
else:
return (captured[0], captured[1], app_iter)
# Will be filled in later:
ResponseClass = None
def get_response(self, application, catch_exc_info=False):
"""
Like ``.call_application(application)``, except returns a
response object with ``.status``, ``.headers``, and ``.body``
attributes.
This will use ``self.ResponseClass`` to figure out the class
of the response object to return.
"""
if catch_exc_info:
status, headers, app_iter, exc_info = self.call_application(
application, catch_exc_info=True)
del exc_info
else:
status, headers, app_iter = self.call_application(
application, catch_exc_info=False)
return self.ResponseClass(
status=status, headerlist=list(headers), app_iter=app_iter,
request=self)
@classmethod
def blank(cls, path, environ=None, base_url=None,
headers=None, POST=None, **kw):
"""
Create a blank request environ (and Request wrapper) with the
given path (path should be urlencoded), and any keys from
environ.
The path will become path_info, with any query string split
off and used.
All necessary keys will be added to the environ, but the
values you pass in will take precedence. If you pass in
base_url then wsgi.url_scheme, HTTP_HOST, and SCRIPT_NAME will
be filled in from that value.
Any extra keyword will be passed to ``__init__`` (e.g.,
``decode_param_names``).
"""
env = environ_from_url(path)
environ_add_POST(env, POST)
if base_url:
scheme, netloc, path, query, fragment = urlparse.urlsplit(base_url)
if query or fragment:
raise ValueError(
"base_url (%r) cannot have a query or fragment"
% base_url)
if scheme:
env['wsgi.url_scheme'] = scheme
if netloc:
if ':' not in netloc:
if scheme == 'http':
netloc += ':80'
elif scheme == 'https':
netloc += ':443'
else:
raise ValueError(
"Unknown scheme: %r" % scheme)
host, port = netloc.split(':', 1)
env['SERVER_PORT'] = port
env['SERVER_NAME'] = host
env['HTTP_HOST'] = netloc
if path:
env['SCRIPT_NAME'] = urllib.unquote(path)
if environ:
env.update(environ)
obj = cls(env, **kw)
if headers is not None:
obj.headers.update(headers)
return obj
def environ_from_url(path):
if SCHEME_RE.search(path):
scheme, netloc, path, qs, fragment = urlparse.urlsplit(path)
if fragment:
raise TypeError("Path cannot contain a fragment (%r)" % fragment)
if qs:
path += '?' + qs
if ':' not in netloc:
if scheme == 'http':
netloc += ':80'
elif scheme == 'https':
netloc += ':443'
else:
raise TypeError("Unknown scheme: %r" % scheme)
else:
scheme = 'http'
netloc = 'localhost:80'
if path and '?' in path:
path_info, query_string = path.split('?', 1)
path_info = urllib.unquote(path_info)
else:
path_info = urllib.unquote(path)
query_string = ''
env = {
'REQUEST_METHOD': 'GET',
'SCRIPT_NAME': '',
'PATH_INFO': path_info or '',
'QUERY_STRING': query_string,
'SERVER_NAME': netloc.split(':')[0],
'SERVER_PORT': netloc.split(':')[1],
'HTTP_HOST': netloc,
'SERVER_PROTOCOL': 'HTTP/1.0',
'wsgi.version': (1, 0),
'wsgi.url_scheme': scheme,
'wsgi.input': StringIO(''),
'wsgi.errors': sys.stderr,
'wsgi.multithread': False,
'wsgi.multiprocess': False,
'wsgi.run_once': False,
#'webob.is_body_seekable': True,
}
return env
def environ_add_POST(env, data):
if data is None:
return
env['REQUEST_METHOD'] = 'POST'
if hasattr(data, 'items'):
data = data.items()
if not isinstance(data, str):
data = urllib.urlencode(data)
env['wsgi.input'] = StringIO(data)
env['webob.is_body_seekable'] = True
env['CONTENT_LENGTH'] = str(len(data))
env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
class AdhocAttrMixin(object):
_setattr_stacklevel = 3
def __setattr__(self, attr, value, DEFAULT=object()):
if (getattr(self.__class__, attr, DEFAULT) is not DEFAULT or
attr.startswith('_')):
object.__setattr__(self, attr, value)
else:
self.environ.setdefault('webob.adhoc_attrs', {})[attr] = value
def __getattr__(self, attr, DEFAULT=object()):
try:
return self.environ['webob.adhoc_attrs'][attr]
except KeyError:
raise AttributeError(attr)
def __delattr__(self, attr, DEFAULT=object()):
if getattr(self.__class__, attr, DEFAULT) is not DEFAULT:
return object.__delattr__(self, attr)
try:
del self.environ['webob.adhoc_attrs'][attr]
except KeyError:
raise AttributeError(attr)
class Request(AdhocAttrMixin, BaseRequest):
""" The default request implementation """
#########################
## Helper classes and monkeypatching
#########################
def _cgi_FieldStorage__repr__patch(self):
""" monkey patch for FieldStorage.__repr__
Unbelievably, the default __repr__ on FieldStorage reads
the entire file content instead of being sane about it.
This is a simple replacement that doesn't do that
"""
if self.file:
return "FieldStorage(%r, %r)" % (self.name, self.filename)
return "FieldStorage(%r, %r, %r)" % (self.name, self.filename, self.value)
cgi.FieldStorage.__repr__ = _cgi_FieldStorage__repr__patch
class FakeCGIBody(object):
def __init__(self, vars, content_type):
self.vars = vars
self.content_type = content_type
self._body = None
self.position = 0
def seek(self, pos, rel=0):
## FIXME: this isn't strictly necessary, but it's important
## when modifying POST parameters. I wish there was a better
## way to do this.
if rel != 0:
raise IOError
self._body = None
self.position = pos
def tell(self):
return self.position
def read(self, size=-1):
body = self._get_body()
if size < 0:
v = body[self.position:]
self.position = len(body)
return v
else:
v = body[self.position:self.position+size]
self.position = min(len(body), self.position+size)
return v
def _get_body(self):
if self._body is None:
if self.content_type.lower().startswith('application/x-www-form-urlencoded'):
self._body = urllib.urlencode(self.vars.items())
elif self.content_type.lower().startswith('multipart/form-data'):
self._body = _encode_multipart(self.vars, self.content_type)
else:
assert 0, ('Bad content type: %r' % self.content_type)
return self._body
def readline(self, size=None):
# We ignore size, but allow it to be hinted
rest = self._get_body()[self.position:]
next = rest.find('\r\n')
if next == -1:
return self.read()
self.position += next+2
return rest[:next+2]
def readlines(self, hint=None):
# Again, allow hint but ignore
body = self._get_body()
rest = body[self.position:]
self.position = len(body)
result = []
while 1:
next = rest.find('\r\n')
if next == -1:
result.append(rest)
break
result.append(rest[:next+2])
rest = rest[next+2:]
return result
def __iter__(self):
return iter(self.readlines())
def __repr__(self):
inner = repr(self.vars)
if len(inner) > 20:
inner = inner[:15] + '...' + inner[-5:]
if self.position:
inner += ' at position %s' % self.position
return '<%s at 0x%x viewing %s>' % (
self.__class__.__name__,
abs(id(self)), inner)
def _encode_multipart(vars, content_type):
"""Encode a multipart request body into a string"""
boundary_match = re.search(r'boundary=([^ ]+)', content_type, re.I)
if not boundary_match:
raise ValueError('Content-type: %r does not contain boundary'
% content_type)
boundary = boundary_match.group(1).strip('"')
lines = []
for name, value in vars.iteritems():
lines.append('--%s' % boundary)
## FIXME: encode the name like this?
assert name is not None, 'Value associated with no name: %r' % value
disp = 'Content-Disposition: form-data; name="%s"' % name
if getattr(value, 'filename', None):
disp += '; filename="%s"' % value.filename
lines.append(disp)
## FIXME: should handle value.disposition_options
if getattr(value, 'type', None):
ct = 'Content-type: %s' % value.type
if value.type_options:
ct += ''.join(['; %s="%s"' % (ct_name, ct_value)
for ct_name, ct_value in sorted(
value.type_options.items())])
lines.append(ct)
lines.append('')
if hasattr(value, 'value'):
lines.append(value.value)
else:
lines.append(value)
lines.append('--%s--' % boundary)
return '\r\n'.join(lines)
| Python |
import warnings
import re
from datetime import datetime, date
from webob.byterange import Range, ContentRange
from webob.etag import IfRange, NoIfRange
from webob.datetime_utils import parse_date, serialize_date
from webob.util import rfc_reference
CHARSET_RE = re.compile(r';\s*charset=([^;]*)', re.I)
QUOTES_RE = re.compile('"(.*)"')
SCHEME_RE = re.compile(r'^[a-z]+:', re.I)
_not_given = object()
def environ_getter(key, default=_not_given, rfc_section=None):
doc = "Gets and sets the %r key in the environment." % key
doc += rfc_reference(key, rfc_section)
if default is _not_given:
def fget(req):
return req.environ[key]
def fset(req, val):
req.environ[key] = val
fdel = None
else:
def fget(req):
return req.environ.get(key, default)
def fset(req, val):
if val is None:
if key in req.environ:
del req.environ[key]
else:
req.environ[key] = val
def fdel(req):
del req.environ[key]
return property(fget, fset, fdel, doc=doc)
def upath_property(key):
def fget(req):
return req.environ.get(key, '').decode('UTF8', req.unicode_errors)
def fset(req, val):
req.environ[key] = val.encode('UTF8', req.unicode_errors)
return property(fget, fset, doc='upath_property(%r)' % key)
def header_getter(header, rfc_section):
doc = "Gets and sets and deletes the %s header." % header
doc += rfc_reference(header, rfc_section)
key = header.lower()
def fget(r):
for k, v in r._headerlist:
if k.lower() == key:
return v
def fset(r, value):
fdel(r)
if value is not None:
if isinstance(value, unicode):
value = value.encode('ISO-8859-1') # standard encoding for headers
r._headerlist.append((header, value))
def fdel(r):
items = r._headerlist
for i in range(len(items)-1, -1, -1):
if items[i][0].lower() == key:
del items[i]
return property(fget, fset, fdel, doc)
def converter(prop, parse, serialize, convert_name=None):
assert isinstance(prop, property)
convert_name = convert_name or "%r and %r" % (parse.__name__,
serialize.__name__)
doc = prop.__doc__ or ''
doc += " Converts it using %s." % convert_name
hget, hset = prop.fget, prop.fset
def fget(r):
return parse(hget(r))
def fset(r, val):
if val is not None:
val = serialize(val)
hset(r, val)
return property(fget, fset, prop.fdel, doc)
def list_header(header, rfc_section):
prop = header_getter(header, rfc_section)
return converter(prop, parse_list, serialize_list, 'list')
def parse_list(value):
if not value:
return None
return tuple(filter(None, [v.strip() for v in value.split(',')]))
def serialize_list(value):
if isinstance(value, unicode):
return str(value)
elif isinstance(value, str):
return value
else:
return ', '.join(map(str, value))
def converter_date(prop):
return converter(prop, parse_date, serialize_date, 'HTTP date')
def date_header(header, rfc_section):
return converter_date(header_getter(header, rfc_section))
class deprecated_property(object):
"""
Wraps a descriptor, with a deprecation warning or error
"""
def __init__(self, descriptor, attr, message, warning=True):
self.descriptor = descriptor
self.attr = attr
self.message = message
self.warning = warning
def __get__(self, obj, type=None):
if obj is None:
return self
self.warn()
return self.descriptor.__get__(obj, type)
def __set__(self, obj, value):
self.warn()
self.descriptor.__set__(obj, value)
def __delete__(self, obj):
self.warn()
self.descriptor.__delete__(obj)
def __repr__(self):
return '<Deprecated attribute %s: %r>' % (
self.attr,
self.descriptor)
def warn(self):
if not self.warning:
raise DeprecationWarning(
'The attribute %s is deprecated: %s' % (self.attr, self.message))
else:
warnings.warn(
'The attribute %s is deprecated: %s' % (self.attr, self.message),
DeprecationWarning,
stacklevel=3)
########################
## Converter functions
########################
# FIXME: weak entity tags are not supported, would need special class
def parse_etag_response(value):
"""
See:
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.11
"""
if value is not None:
unquote_match = QUOTES_RE.match(value)
if unquote_match is not None:
value = unquote_match.group(1)
value = value.replace('\\"', '"')
return value
def serialize_etag_response(value):
return '"%s"' % value.replace('"', '\\"')
def parse_if_range(value):
if not value:
return NoIfRange
else:
return IfRange.parse(value)
def serialize_if_range(value):
if isinstance(value, (datetime, date)):
return serialize_date(value)
if not isinstance(value, str):
value = str(value)
return value or None
def parse_range(value):
if not value:
return None
# Might return None too:
return Range.parse(value)
def serialize_range(value):
if isinstance(value, (list, tuple)):
if len(value) != 2:
raise ValueError(
"If setting .range to a list or tuple, it must be of length 2 (not %r)"
% value)
value = Range([value])
if value is None:
return None
value = str(value)
return value or None
def parse_int(value):
if value is None or value == '':
return None
return int(value)
def parse_int_safe(value):
if value is None or value == '':
return None
try:
return int(value)
except ValueError:
return None
serialize_int = str
def parse_content_range(value):
if not value or not value.strip():
return None
# May still return None
return ContentRange.parse(value)
def serialize_content_range(value):
if isinstance(value, (tuple, list)):
if len(value) not in (2, 3):
raise ValueError(
"When setting content_range to a list/tuple, it must "
"be length 2 or 3 (not %r)" % value)
if len(value) == 2:
begin, end = value
length = None
else:
begin, end, length = value
value = ContentRange(begin, end, length)
value = str(value).strip()
if not value:
return None
return value
_rx_auth_param = re.compile(r'([a-z]+)=(".*?"|[^,]*)(?:\Z|, *)')
def parse_auth_params(params):
r = {}
for k, v in _rx_auth_param.findall(params):
r[k] = v.strip('"')
return r
# see http://lists.w3.org/Archives/Public/ietf-http-wg/2009OctDec/0297.html
known_auth_schemes = ['Basic', 'Digest', 'WSSE', 'HMACDigest', 'GoogleLogin', 'Cookie', 'OpenID']
known_auth_schemes = dict.fromkeys(known_auth_schemes, None)
def parse_auth(val):
if val is not None:
authtype, params = val.split(' ', 1)
if authtype in known_auth_schemes:
if authtype == 'Basic' and '"' not in params:
# this is the "Authentication: Basic XXXXX==" case
pass
else:
params = parse_auth_params(params)
return authtype, params
return val
def serialize_auth(val):
if isinstance(val, (tuple, list)):
authtype, params = val
if isinstance(params, dict):
params = ', '.join(map('%s="%s"'.__mod__, params.items()))
assert isinstance(params, str)
return '%s %s' % (authtype, params)
return val
| Python |
"""
Decorators to wrap functions to make them WSGI applications.
The main decorator :class:`wsgify` turns a function into a WSGI
application (while also allowing normal calling of the method with an
instantiated request).
"""
import webob
import webob.exc
from types import ClassType
__all__ = ['wsgify']
class wsgify(object):
"""Turns a request-taking, response-returning function into a WSGI
app
You can use this like::
@wsgify
def myfunc(req):
return webob.Response('hey there')
With that ``myfunc`` will be a WSGI application, callable like
``app_iter = myfunc(environ, start_response)``. You can also call
it like normal, e.g., ``resp = myfunc(req)``. (You can also wrap
methods, like ``def myfunc(self, req)``.)
If you raise exceptions from :mod:`webob.exc` they will be turned
into WSGI responses.
There are also several parameters you can use to customize the
decorator. Most notably, you can use a :class:`webob.Request`
subclass, like::
class MyRequest(webob.Request):
@property
def is_local(self):
return self.remote_addr == '127.0.0.1'
@wsgify(RequestClass=MyRequest)
def myfunc(req):
if req.is_local:
return Response('hi!')
else:
raise webob.exc.HTTPForbidden
Another customization you can add is to add `args` (positional
arguments) or `kwargs` (of course, keyword arguments). While
generally not that useful, you can use this to create multiple
WSGI apps from one function, like::
import simplejson
def serve_json(req, json_obj):
return Response(json.dumps(json_obj),
content_type='application/json')
serve_ob1 = wsgify(serve_json, args=(ob1,))
serve_ob2 = wsgify(serve_json, args=(ob2,))
You can return several things from a function:
* A :class:`webob.Response` object (or subclass)
* *Any* WSGI application
* None, and then ``req.response`` will be used (a pre-instantiated
Response object)
* A string, which will be written to ``req.response`` and then that
response will be used.
* Raise an exception from :mod:`webob.exc`
Also see :func:`wsgify.middleware` for a way to make middleware.
You can also subclass this decorator; the most useful things to do
in a subclass would be to change `RequestClass` or override
`call_func` (e.g., to add ``req.urlvars`` as keyword arguments to
the function).
"""
RequestClass = webob.Request
def __init__(self, func=None, RequestClass=None,
args=(), kwargs=None, middleware_wraps=None):
self.func = func
if (RequestClass is not None
and RequestClass is not self.RequestClass):
self.RequestClass = RequestClass
self.args = tuple(args)
if kwargs is None:
kwargs = {}
self.kwargs = kwargs
self.middleware_wraps = middleware_wraps
def __repr__(self):
if self.func is None:
args = []
else:
args = [_func_name(self.func)]
if self.RequestClass is not self.__class__.RequestClass:
args.append('RequestClass=%r' % self.RequestClass)
if self.args:
args.append('args=%r' % (self.args,))
my_name = self.__class__.__name__
if self.middleware_wraps is not None:
my_name = '%s.middleware' % my_name
else:
if self.kwargs:
args.append('kwargs=%r' % self.kwargs)
r = '%s(%s)' % (my_name, ', '.join(args))
if self.middleware_wraps is not None:
args = [repr(self.middleware_wraps)]
if self.kwargs:
args.extend(['%s=%r' % (name, value)
for name, value in sorted(self.kwargs.items())])
r += '(%s)' % ', '.join(args)
return r
def __get__(self, obj, type=None):
# This handles wrapping methods
if hasattr(self.func, '__get__'):
return self.clone(self.func.__get__(obj, type))
else:
return self
def __call__(self, req, *args, **kw):
"""Call this as a WSGI application or with a request"""
func = self.func
if func is None:
if args or kw:
raise TypeError(
"Unbound %s can only be called with the function it will wrap"
% self.__class__.__name__)
func = req
return self.clone(func)
if isinstance(req, dict):
if len(args) != 1 or kw:
raise TypeError(
"Calling %r as a WSGI app with the wrong signature")
environ = req
start_response = args[0]
req = self.RequestClass(environ)
req.response = req.ResponseClass()
req.response.request = req
try:
args = self.args
if self.middleware_wraps:
args = (self.middleware_wraps,) + args
resp = self.call_func(req, *args, **self.kwargs)
except webob.exc.HTTPException, resp:
pass
if resp is None:
## FIXME: I'm not sure what this should be?
resp = req.response
elif isinstance(resp, basestring):
body = resp
resp = req.response
resp.write(body)
if resp is not req.response:
resp = req.response.merge_cookies(resp)
return resp(environ, start_response)
else:
return self.func(req, *args, **kw)
def get(self, url, **kw):
"""Run a GET request on this application, returning a Response.
This creates a request object using the given URL, and any
other keyword arguments are set on the request object (e.g.,
``last_modified=datetime.now()``).
::
resp = myapp.get('/article?id=10')
"""
kw.setdefault('method', 'GET')
req = self.RequestClass.blank(url, **kw)
return self(req)
def post(self, url, POST=None, **kw):
"""Run a POST request on this application, returning a Response.
The second argument (`POST`) can be the request body (a
string), or a dictionary or list of two-tuples, that give the
POST body.
::
resp = myapp.post('/article/new',
dict(title='My Day',
content='I ate a sandwich'))
"""
kw.setdefault('method', 'POST')
req = self.RequestClass.blank(url, POST=POST, **kw)
return self(req)
def request(self, url, **kw):
"""Run a request on this application, returning a Response.
This can be used for DELETE, PUT, etc requests. E.g.::
resp = myapp.request('/article/1', method='PUT', body='New article')
"""
req = self.RequestClass.blank(url, **kw)
return self(req)
def call_func(self, req, *args, **kwargs):
"""Call the wrapped function; override this in a subclass to
change how the function is called."""
return self.func(req, *args, **kwargs)
def clone(self, func=None, **kw):
"""Creates a copy/clone of this object, but with some
parameters rebound
"""
kwargs = {}
if func is not None:
kwargs['func'] = func
if self.RequestClass is not self.__class__.RequestClass:
kwargs['RequestClass'] = self.RequestClass
if self.args:
kwargs['args'] = self.args
if self.kwargs:
kwargs['kwargs'] = self.kwargs
kwargs.update(kw)
return self.__class__(**kwargs)
# To match @decorator:
@property
def undecorated(self):
return self.func
@classmethod
def middleware(cls, middle_func=None, app=None, **kw):
"""Creates middleware
Use this like::
@wsgify.middleware
def restrict_ip(app, req, ips):
if req.remote_addr not in ips:
raise webob.exc.HTTPForbidden('Bad IP: %s' % req.remote_addr)
return app
@wsgify
def app(req):
return 'hi'
wrapped = restrict_ip(app, ips=['127.0.0.1'])
Or if you want to write output-rewriting middleware::
@wsgify.middleware
def all_caps(app, req):
resp = req.get_response(app)
resp.body = resp.body.upper()
return resp
wrapped = all_caps(app)
Note that you must call ``req.get_response(app)`` to get a WebOb response
object. If you are not modifying the output, you can just return the app.
As you can see, this method doesn't actually create an application, but
creates "middleware" that can be bound to an application, along with
"configuration" (that is, any other keyword arguments you pass when
binding the application).
"""
if middle_func is None:
return _UnboundMiddleware(cls, app, kw)
if app is None:
return _MiddlewareFactory(cls, middle_func, kw)
return cls(middle_func, middleware_wraps=app, kwargs=kw)
class _UnboundMiddleware(object):
"""A `wsgify.middleware` invocation that has not yet wrapped a
middleware function; the intermediate object when you do
something like ``@wsgify.middleware(RequestClass=Foo)``
"""
def __init__(self, wrapper_class, app, kw):
self.wrapper_class = wrapper_class
self.app = app
self.kw = kw
def __repr__(self):
if self.app:
args = (self.app,)
else:
args = ()
return '%s.middleware(%s)' % (
self.wrapper_class.__name__,
_format_args(args, self.kw))
def __call__(self, func, app=None):
if app is None:
app = self.app
return self.wrapper_class.middleware(func, app=app, **self.kw)
class _MiddlewareFactory(object):
"""A middleware that has not yet been bound to an application or
configured.
"""
def __init__(self, wrapper_class, middleware, kw):
self.wrapper_class = wrapper_class
self.middleware = middleware
self.kw = kw
def __repr__(self):
return '%s.middleware(%s)' % (
self.wrapper_class.__name__,
_format_args((self.middleware,), self.kw))
def __call__(self, app, **config):
kw = self.kw.copy()
kw.update(config)
return self.wrapper_class.middleware(self.middleware, app, **kw)
def _func_name(func):
"""Returns the string name of a function, or method, as best it can"""
if isinstance(func, (type, ClassType)):
name = func.__name__
if func.__module__ not in ('__main__', '__builtin__'):
name = '%s.%s' % (func.__module__, name)
return name
name = getattr(func, 'func_name', None)
if name is None:
name = repr(func)
else:
name_self = getattr(func, 'im_self', None)
if name_self is not None:
name = '%r.%s' % (name_self, name)
else:
name_class = getattr(func, 'im_class', None)
if name_class is not None:
name = '%s.%s' % (name_class.__name__, name)
module = getattr(func, 'func_globals', {}).get('__name__')
if module and module != '__main__':
name = '%s.%s' % (module, name)
return name
def _format_args(args=(), kw=None, leading_comma=False, obj=None, names=None, defaults=None):
if kw is None:
kw = {}
all = [repr(arg) for arg in args]
if names is not None:
assert obj is not None
kw = {}
if isinstance(names, basestring):
names = names.split()
for name in names:
kw[name] = getattr(obj, name)
if defaults is not None:
kw = kw.copy()
for name, value in defaults.items():
if name in kw and value == kw[name]:
del kw[name]
all.extend(['%s=%r' % (name, value) for name, value in sorted(kw.items())])
result = ', '.join(all)
if result and leading_comma:
result = ', ' + result
return result
| Python |
"""
HTTP Exception
--------------
This module processes Python exceptions that relate to HTTP exceptions
by defining a set of exceptions, all subclasses of HTTPException.
Each exception, in addition to being a Python exception that can be
raised and caught, is also a WSGI application and ``webob.Response``
object.
This module defines exceptions according to RFC 2068 [1]_ : codes with
100-300 are not really errors; 400's are client errors, and 500's are
server errors. According to the WSGI specification [2]_ , the application
can call ``start_response`` more then once only under two conditions:
(a) the response has not yet been sent, or (b) if the second and
subsequent invocations of ``start_response`` have a valid ``exc_info``
argument obtained from ``sys.exc_info()``. The WSGI specification then
requires the server or gateway to handle the case where content has been
sent and then an exception was encountered.
Exception
HTTPException
HTTPOk
* 200 - HTTPOk
* 201 - HTTPCreated
* 202 - HTTPAccepted
* 203 - HTTPNonAuthoritativeInformation
* 204 - HTTPNoContent
* 205 - HTTPResetContent
* 206 - HTTPPartialContent
HTTPRedirection
* 300 - HTTPMultipleChoices
* 301 - HTTPMovedPermanently
* 302 - HTTPFound
* 303 - HTTPSeeOther
* 304 - HTTPNotModified
* 305 - HTTPUseProxy
* 306 - Unused (not implemented, obviously)
* 307 - HTTPTemporaryRedirect
HTTPError
HTTPClientError
* 400 - HTTPBadRequest
* 401 - HTTPUnauthorized
* 402 - HTTPPaymentRequired
* 403 - HTTPForbidden
* 404 - HTTPNotFound
* 405 - HTTPMethodNotAllowed
* 406 - HTTPNotAcceptable
* 407 - HTTPProxyAuthenticationRequired
* 408 - HTTPRequestTimeout
* 409 - HTTPConflict
* 410 - HTTPGone
* 411 - HTTPLengthRequired
* 412 - HTTPPreconditionFailed
* 413 - HTTPRequestEntityTooLarge
* 414 - HTTPRequestURITooLong
* 415 - HTTPUnsupportedMediaType
* 416 - HTTPRequestRangeNotSatisfiable
* 417 - HTTPExpectationFailed
HTTPServerError
* 500 - HTTPInternalServerError
* 501 - HTTPNotImplemented
* 502 - HTTPBadGateway
* 503 - HTTPServiceUnavailable
* 504 - HTTPGatewayTimeout
* 505 - HTTPVersionNotSupported
Subclass usage notes:
---------------------
The HTTPException class is complicated by 4 factors:
1. The content given to the exception may either be plain-text or
as html-text.
2. The template may want to have string-substitutions taken from
the current ``environ`` or values from incoming headers. This
is especially troublesome due to case sensitivity.
3. The final output may either be text/plain or text/html
mime-type as requested by the client application.
4. Each exception has a default explanation, but those who
raise exceptions may want to provide additional detail.
Subclass attributes and call parameters are designed to provide an easier path
through the complications.
Attributes:
``code``
the HTTP status code for the exception
``title``
remainder of the status line (stuff after the code)
``explanation``
a plain-text explanation of the error message that is
not subject to environment or header substitutions;
it is accessible in the template via %(explanation)s
``detail``
a plain-text message customization that is not subject
to environment or header substitutions; accessible in
the template via %(detail)s
``body_template``
a content fragment (in HTML) used for environment and
header substitution; the default template includes both
the explanation and further detail provided in the
message
Parameters:
``detail``
a plain-text override of the default ``detail``
``headers``
a list of (k,v) header pairs
``comment``
a plain-text additional information which is
usually stripped/hidden for end-users
``body_template``
a string.Template object containing a content fragment in HTML
that frames the explanation and further detail
To override the template (which is HTML content) or the plain-text
explanation, one must subclass the given exception; or customize it
after it has been created. This particular breakdown of a message
into explanation, detail and template allows both the creation of
plain-text and html messages for various clients as well as
error-free substitution of environment variables and headers.
The subclasses of :class:`~_HTTPMove`
(:class:`~HTTPMultipleChoices`, :class:`~HTTPMovedPermanently`,
:class:`~HTTPFound`, :class:`~HTTPSeeOther`, :class:`~HTTPUseProxy` and
:class:`~HTTPTemporaryRedirect`) are redirections that require a ``Location``
field. Reflecting this, these subclasses have two additional keyword arguments:
``location`` and ``add_slash``.
Parameters:
``location``
to set the location immediately
``add_slash``
set to True to redirect to the same URL as the request, except with a
``/`` appended
Relative URLs in the location will be resolved to absolute.
References:
.. [1] http://www.python.org/peps/pep-0333.html#error-handling
.. [2] http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5
"""
import re
import urlparse
import sys
import types
from string import Template
from webob import Response, Request, html_escape
newstyle_exceptions = issubclass(Exception, object)
tag_re = re.compile(r'<.*?>', re.S)
br_re = re.compile(r'<br.*?>', re.I|re.S)
comment_re = re.compile(r'<!--|-->')
def no_escape(value):
if value is None:
return ''
if not isinstance(value, basestring):
if hasattr(value, '__unicode__'):
value = unicode(value)
else:
value = str(value)
return value
def strip_tags(value):
value = value.replace('\n', ' ')
value = value.replace('\r', '')
value = br_re.sub('\n', value)
value = comment_re.sub('', value)
value = tag_re.sub('', value)
return value
class HTTPException(Exception):
"""
Exception used on pre-Python-2.5, where new-style classes cannot be used as
an exception.
"""
def __init__(self, message, wsgi_response):
Exception.__init__(self, message)
self.__dict__['wsgi_response'] = wsgi_response
def __call__(self, environ, start_response):
return self.wsgi_response(environ, start_response)
def exception(self):
return self
exception = property(exception)
# for old style exceptions
if not newstyle_exceptions: #pragma NO COVERAGE
def __getattr__(self, attr):
if not attr.startswith('_'):
return getattr(self.wsgi_response, attr)
else:
raise AttributeError(attr)
def __setattr__(self, attr, value):
if attr.startswith('_') or attr in ('args',):
self.__dict__[attr] = value
else:
setattr(self.wsgi_response, attr, value)
class WSGIHTTPException(Response, HTTPException):
## You should set in subclasses:
# code = 200
# title = 'OK'
# explanation = 'why this happens'
# body_template_obj = Template('response template')
code = None
title = None
explanation = ''
body_template_obj = Template('''\
${explanation}<br /><br />
${detail}
${html_comment}
''')
plain_template_obj = Template('''\
${status}
${body}''')
html_template_obj = Template('''\
<html>
<head>
<title>${status}</title>
</head>
<body>
<h1>${status}</h1>
${body}
</body>
</html>''')
## Set this to True for responses that should have no request body
empty_body = False
def __init__(self, detail=None, headers=None, comment=None,
body_template=None, **kw):
Response.__init__(self,
status='%s %s' % (self.code, self.title),
**kw)
Exception.__init__(self, detail)
if headers:
self.headers.extend(headers)
self.detail = detail
self.comment = comment
if body_template is not None:
self.body_template = body_template
self.body_template_obj = Template(body_template)
if self.empty_body:
del self.content_type
del self.content_length
def __str__(self):
return self.detail or self.explanation
def _make_body(self, environ, escape):
args = {
'explanation': escape(self.explanation),
'detail': escape(self.detail or ''),
'comment': escape(self.comment or ''),
}
if self.comment:
args['html_comment'] = '<!-- %s -->' % escape(self.comment)
else:
args['html_comment'] = ''
body_tmpl = self.body_template_obj
if WSGIHTTPException.body_template_obj is not self.body_template_obj:
# Custom template; add headers to args
for k, v in environ.items():
args[k] = escape(v)
for k, v in self.headers.items():
args[k.lower()] = escape(v)
t_obj = self.body_template_obj
return t_obj.substitute(args)
def plain_body(self, environ):
body = self._make_body(environ, no_escape)
body = strip_tags(body)
return self.plain_template_obj.substitute(status=self.status,
title=self.title,
body=body)
def html_body(self, environ):
body = self._make_body(environ, html_escape)
return self.html_template_obj.substitute(status=self.status,
body=body)
def generate_response(self, environ, start_response):
if self.content_length is not None:
del self.content_length
headerlist = list(self.headerlist)
accept = environ.get('HTTP_ACCEPT', '')
if accept and 'html' in accept or '*/*' in accept:
content_type = 'text/html'
body = self.html_body(environ)
else:
content_type = 'text/plain'
body = self.plain_body(environ)
extra_kw = {}
if isinstance(body, unicode):
extra_kw.update(charset='utf-8')
resp = Response(body,
status=self.status,
headerlist=headerlist,
content_type=content_type,
**extra_kw
)
resp.content_type = content_type
return resp(environ, start_response)
def __call__(self, environ, start_response):
# FIXME: ensure HEAD and GET response headers are identical
if environ['REQUEST_METHOD'] == 'HEAD':
start_response(self.status, self.headerlist)
return []
if not self.body and not self.empty_body:
return self.generate_response(environ, start_response)
return Response.__call__(self, environ, start_response)
def wsgi_response(self):
return self
wsgi_response = property(wsgi_response)
def exception(self):
if newstyle_exceptions:
return self
else:
return HTTPException(self.detail, self)
exception = property(exception)
class HTTPError(WSGIHTTPException):
"""
base class for status codes in the 400's and 500's
This is an exception which indicates that an error has occurred,
and that any work in progress should not be committed. These are
typically results in the 400's and 500's.
"""
class HTTPRedirection(WSGIHTTPException):
"""
base class for 300's status code (redirections)
This is an abstract base class for 3xx redirection. It indicates
that further action needs to be taken by the user agent in order
to fulfill the request. It does not necessarly signal an error
condition.
"""
class HTTPOk(WSGIHTTPException):
"""
Base class for the 200's status code (successful responses)
code: 200, title: OK
"""
code = 200
title = 'OK'
############################################################
## 2xx success
############################################################
class HTTPCreated(HTTPOk):
"""
subclass of :class:`~HTTPOk`
This indicates that request has been fulfilled and resulted in a new
resource being created.
code: 201, title: Created
"""
code = 201
title = 'Created'
class HTTPAccepted(HTTPOk):
"""
subclass of :class:`~HTTPOk`
This indicates that the request has been accepted for processing, but the
processing has not been completed.
code: 202, title: Accepted
"""
code = 202
title = 'Accepted'
explanation = 'The request is accepted for processing.'
class HTTPNonAuthoritativeInformation(HTTPOk):
"""
subclass of :class:`~HTTPOk`
This indicates that the returned metainformation in the entity-header is
not the definitive set as available from the origin server, but is
gathered from a local or a third-party copy.
code: 203, title: Non-Authoritative Information
"""
code = 203
title = 'Non-Authoritative Information'
class HTTPNoContent(HTTPOk):
"""
subclass of :class:`~HTTPOk`
This indicates that the server has fulfilled the request but does
not need to return an entity-body, and might want to return updated
metainformation.
code: 204, title: No Content
"""
code = 204
title = 'No Content'
empty_body = True
class HTTPResetContent(HTTPOk):
"""
subclass of :class:`~HTTPOk`
This indicates that the the server has fulfilled the request and
the user agent SHOULD reset the document view which caused the
request to be sent.
code: 205, title: Reset Content
"""
code = 205
title = 'Reset Content'
empty_body = True
class HTTPPartialContent(HTTPOk):
"""
subclass of :class:`~HTTPOk`
This indicates that the server has fulfilled the partial GET
request for the resource.
code: 206, title: Partial Content
"""
code = 206
title = 'Partial Content'
## FIXME: add 207 Multi-Status (but it's complicated)
############################################################
## 3xx redirection
############################################################
class _HTTPMove(HTTPRedirection):
"""
redirections which require a Location field
Since a 'Location' header is a required attribute of 301, 302, 303,
305 and 307 (but not 304), this base class provides the mechanics to
make this easy.
You can provide a location keyword argument to set the location
immediately. You may also give ``add_slash=True`` if you want to
redirect to the same URL as the request, except with a ``/`` added
to the end.
Relative URLs in the location will be resolved to absolute.
"""
explanation = 'The resource has been moved to'
body_template_obj = Template('''\
${explanation} <a href="${location}">${location}</a>;
you should be redirected automatically.
${detail}
${html_comment}''')
def __init__(self, detail=None, headers=None, comment=None,
body_template=None, location=None, add_slash=False):
super(_HTTPMove, self).__init__(
detail=detail, headers=headers, comment=comment,
body_template=body_template)
if location is not None:
self.location = location
if add_slash:
raise TypeError(
"You can only provide one of the arguments location and add_slash")
self.add_slash = add_slash
def __call__(self, environ, start_response):
req = Request(environ)
if self.add_slash:
url = req.path_url
url += '/'
if req.environ.get('QUERY_STRING'):
url += '?' + req.environ['QUERY_STRING']
self.location = url
self.location = urlparse.urljoin(req.path_url, self.location)
return super(_HTTPMove, self).__call__(
environ, start_response)
class HTTPMultipleChoices(_HTTPMove):
"""
subclass of :class:`~_HTTPMove`
This indicates that the requested resource corresponds to any one
of a set of representations, each with its own specific location,
and agent-driven negotiation information is being provided so that
the user can select a preferred representation and redirect its
request to that location.
code: 300, title: Multiple Choices
"""
code = 300
title = 'Multiple Choices'
class HTTPMovedPermanently(_HTTPMove):
"""
subclass of :class:`~_HTTPMove`
This indicates that the requested resource has been assigned a new
permanent URI and any future references to this resource SHOULD use
one of the returned URIs.
code: 301, title: Moved Permanently
"""
code = 301
title = 'Moved Permanently'
class HTTPFound(_HTTPMove):
"""
subclass of :class:`~_HTTPMove`
This indicates that the requested resource resides temporarily under
a different URI.
code: 302, title: Found
"""
code = 302
title = 'Found'
explanation = 'The resource was found at'
# This one is safe after a POST (the redirected location will be
# retrieved with GET):
class HTTPSeeOther(_HTTPMove):
"""
subclass of :class:`~_HTTPMove`
This indicates that the response to the request can be found under
a different URI and SHOULD be retrieved using a GET method on that
resource.
code: 303, title: See Other
"""
code = 303
title = 'See Other'
class HTTPNotModified(HTTPRedirection):
"""
subclass of :class:`~HTTPRedirection`
This indicates that if the client has performed a conditional GET
request and access is allowed, but the document has not been
modified, the server SHOULD respond with this status code.
code: 304, title: Not Modified
"""
# FIXME: this should include a date or etag header
code = 304
title = 'Not Modified'
empty_body = True
class HTTPUseProxy(_HTTPMove):
"""
subclass of :class:`~_HTTPMove`
This indicates that the requested resource MUST be accessed through
the proxy given by the Location field.
code: 305, title: Use Proxy
"""
# Not a move, but looks a little like one
code = 305
title = 'Use Proxy'
explanation = (
'The resource must be accessed through a proxy located at')
class HTTPTemporaryRedirect(_HTTPMove):
"""
subclass of :class:`~_HTTPMove`
This indicates that the requested resource resides temporarily
under a different URI.
code: 307, title: Temporary Redirect
"""
code = 307
title = 'Temporary Redirect'
############################################################
## 4xx client error
############################################################
class HTTPClientError(HTTPError):
"""
base class for the 400's, where the client is in error
This is an error condition in which the client is presumed to be
in-error. This is an expected problem, and thus is not considered
a bug. A server-side traceback is not warranted. Unless specialized,
this is a '400 Bad Request'
"""
code = 400
title = 'Bad Request'
explanation = ('The server could not comply with the request since\r\n'
'it is either malformed or otherwise incorrect.\r\n')
class HTTPBadRequest(HTTPClientError):
pass
class HTTPUnauthorized(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the request requires user authentication.
code: 401, title: Unauthorized
"""
code = 401
title = 'Unauthorized'
explanation = (
'This server could not verify that you are authorized to\r\n'
'access the document you requested. Either you supplied the\r\n'
'wrong credentials (e.g., bad password), or your browser\r\n'
'does not understand how to supply the credentials required.\r\n')
class HTTPPaymentRequired(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
code: 402, title: Payment Required
"""
code = 402
title = 'Payment Required'
explanation = ('Access was denied for financial reasons.')
class HTTPForbidden(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the server understood the request, but is
refusing to fulfill it.
code: 403, title: Forbidden
"""
code = 403
title = 'Forbidden'
explanation = ('Access was denied to this resource.')
class HTTPNotFound(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the server did not find anything matching the
Request-URI.
code: 404, title: Not Found
"""
code = 404
title = 'Not Found'
explanation = ('The resource could not be found.')
class HTTPMethodNotAllowed(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the method specified in the Request-Line is
not allowed for the resource identified by the Request-URI.
code: 405, title: Method Not Allowed
"""
code = 405
title = 'Method Not Allowed'
# override template since we need an environment variable
body_template_obj = Template('''\
The method ${REQUEST_METHOD} is not allowed for this resource. <br /><br />
${detail}''')
class HTTPNotAcceptable(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates the resource identified by the request is only
capable of generating response entities which have content
characteristics not acceptable according to the accept headers
sent in the request.
code: 406, title: Not Acceptable
"""
code = 406
title = 'Not Acceptable'
# override template since we need an environment variable
template = Template('''\
The resource could not be generated that was acceptable to your browser
(content of type ${HTTP_ACCEPT}. <br /><br />
${detail}''')
class HTTPProxyAuthenticationRequired(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This is similar to 401, but indicates that the client must first
authenticate itself with the proxy.
code: 407, title: Proxy Authentication Required
"""
code = 407
title = 'Proxy Authentication Required'
explanation = ('Authentication with a local proxy is needed.')
class HTTPRequestTimeout(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the client did not produce a request within
the time that the server was prepared to wait.
code: 408, title: Request Timeout
"""
code = 408
title = 'Request Timeout'
explanation = ('The server has waited too long for the request to '
'be sent by the client.')
class HTTPConflict(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the request could not be completed due to a
conflict with the current state of the resource.
code: 409, title: Conflict
"""
code = 409
title = 'Conflict'
explanation = ('There was a conflict when trying to complete '
'your request.')
class HTTPGone(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the requested resource is no longer available
at the server and no forwarding address is known.
code: 410, title: Gone
"""
code = 410
title = 'Gone'
explanation = ('This resource is no longer available. No forwarding '
'address is given.')
class HTTPLengthRequired(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the the server refuses to accept the request
without a defined Content-Length.
code: 411, title: Length Required
"""
code = 411
title = 'Length Required'
explanation = ('Content-Length header required.')
class HTTPPreconditionFailed(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the precondition given in one or more of the
request-header fields evaluated to false when it was tested on the
server.
code: 412, title: Precondition Failed
"""
code = 412
title = 'Precondition Failed'
explanation = ('Request precondition failed.')
class HTTPRequestEntityTooLarge(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the server is refusing to process a request
because the request entity is larger than the server is willing or
able to process.
code: 413, title: Request Entity Too Large
"""
code = 413
title = 'Request Entity Too Large'
explanation = ('The body of your request was too large for this server.')
class HTTPRequestURITooLong(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the server is refusing to service the request
because the Request-URI is longer than the server is willing to
interpret.
code: 414, title: Request-URI Too Long
"""
code = 414
title = 'Request-URI Too Long'
explanation = ('The request URI was too long for this server.')
class HTTPUnsupportedMediaType(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the server is refusing to service the request
because the entity of the request is in a format not supported by
the requested resource for the requested method.
code: 415, title: Unsupported Media Type
"""
code = 415
title = 'Unsupported Media Type'
# override template since we need an environment variable
template_obj = Template('''\
The request media type ${CONTENT_TYPE} is not supported by this server.
<br /><br />
${detail}''')
class HTTPRequestRangeNotSatisfiable(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
The server SHOULD return a response with this status code if a
request included a Range request-header field, and none of the
range-specifier values in this field overlap the current extent
of the selected resource, and the request did not include an
If-Range request-header field.
code: 416, title: Request Range Not Satisfiable
"""
code = 416
title = 'Request Range Not Satisfiable'
explanation = ('The Range requested is not available.')
class HTTPExpectationFailed(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indidcates that the expectation given in an Expect
request-header field could not be met by this server.
code: 417, title: Expectation Failed
"""
code = 417
title = 'Expectation Failed'
explanation = ('Expectation failed.')
class HTTPUnprocessableEntity(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the server is unable to process the contained
instructions. Only for WebDAV.
code: 422, title: Unprocessable Entity
"""
## Note: from WebDAV
code = 422
title = 'Unprocessable Entity'
explanation = 'Unable to process the contained instructions'
class HTTPLocked(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the resource is locked. Only for WebDAV
code: 423, title: Locked
"""
## Note: from WebDAV
code = 423
title = 'Locked'
explanation = ('The resource is locked')
class HTTPFailedDependency(HTTPClientError):
"""
subclass of :class:`~HTTPClientError`
This indicates that the method could not be performed because the
requested action depended on another action and that action failed.
Only for WebDAV.
code: 424, title: Failed Dependency
"""
## Note: from WebDAV
code = 424
title = 'Failed Dependency'
explanation = ('The method could not be performed because the requested '
'action dependended on another action and that action failed')
############################################################
## 5xx Server Error
############################################################
# Response status codes beginning with the digit "5" indicate cases in
# which the server is aware that it has erred or is incapable of
# performing the request. Except when responding to a HEAD request, the
# server SHOULD include an entity containing an explanation of the error
# situation, and whether it is a temporary or permanent condition. User
# agents SHOULD display any included entity to the user. These response
# codes are applicable to any request method.
class HTTPServerError(HTTPError):
"""
base class for the 500's, where the server is in-error
This is an error condition in which the server is presumed to be
in-error. This is usually unexpected, and thus requires a traceback;
ideally, opening a support ticket for the customer. Unless specialized,
this is a '500 Internal Server Error'
"""
code = 500
title = 'Internal Server Error'
explanation = (
'The server has either erred or is incapable of performing\r\n'
'the requested operation.\r\n')
class HTTPInternalServerError(HTTPServerError):
pass
class HTTPNotImplemented(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the server does not support the functionality
required to fulfill the request.
code: 501, title: Not Implemented
"""
code = 501
title = 'Not Implemented'
template = Template('''
The request method ${REQUEST_METHOD} is not implemented for this server. <br /><br />
${detail}''')
class HTTPBadGateway(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the server, while acting as a gateway or proxy,
received an invalid response from the upstream server it accessed
in attempting to fulfill the request.
code: 502, title: Bad Gateway
"""
code = 502
title = 'Bad Gateway'
explanation = ('Bad gateway.')
class HTTPServiceUnavailable(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the server is currently unable to handle the
request due to a temporary overloading or maintenance of the server.
code: 503, title: Service Unavailable
"""
code = 503
title = 'Service Unavailable'
explanation = ('The server is currently unavailable. '
'Please try again at a later time.')
class HTTPGatewayTimeout(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the server, while acting as a gateway or proxy,
did not receive a timely response from the upstream server specified
by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server
(e.g. DNS) it needed to access in attempting to complete the request.
code: 504, title: Gateway Timeout
"""
code = 504
title = 'Gateway Timeout'
explanation = ('The gateway has timed out.')
class HTTPVersionNotSupported(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the server does not support, or refuses to
support, the HTTP protocol version that was used in the request
message.
code: 505, title: HTTP Version Not Supported
"""
code = 505
title = 'HTTP Version Not Supported'
explanation = ('The HTTP version is not supported.')
class HTTPInsufficientStorage(HTTPServerError):
"""
subclass of :class:`~HTTPServerError`
This indicates that the server does not have enough space to save
the resource.
code: 507, title: Insufficient Storage
"""
code = 507
title = 'Insufficient Storage'
explanation = ('There was not enough space to save the resource')
class HTTPExceptionMiddleware(object):
"""
Middleware that catches exceptions in the sub-application. This
does not catch exceptions in the app_iter; only during the initial
calling of the application.
This should be put *very close* to applications that might raise
these exceptions. This should not be applied globally; letting
*expected* exceptions raise through the WSGI stack is dangerous.
"""
def __init__(self, application):
self.application = application
def __call__(self, environ, start_response):
try:
return self.application(environ, start_response)
except HTTPException, exc:
parent_exc_info = sys.exc_info()
def repl_start_response(status, headers, exc_info=None):
if exc_info is None:
exc_info = parent_exc_info
return start_response(status, headers, exc_info)
return exc(environ, repl_start_response)
try:
from paste import httpexceptions
except ImportError: # pragma: no cover
# Without Paste we don't need to do this fixup
pass
else: # pragma: no cover
for name in dir(httpexceptions):
obj = globals().get(name)
if (obj and isinstance(obj, type) and issubclass(obj, HTTPException)
and obj is not HTTPException
and obj is not WSGIHTTPException):
obj.__bases__ = obj.__bases__ + (getattr(httpexceptions, name),)
del name, obj, httpexceptions
__all__ = ['HTTPExceptionMiddleware', 'status_map']
status_map={}
for name, value in globals().items():
if (isinstance(value, (type, types.ClassType)) and issubclass(value, HTTPException)
and not name.startswith('_')):
__all__.append(name)
if getattr(value, 'code', None):
status_map[value.code]=value
if hasattr(value, 'explanation'):
value.explanation = ' '.join(value.explanation.strip().split())
del name, value
| Python |
def rfc_reference(header, section):
if not section:
return ''
major_section = section.split('.')[0]
link = 'http://www.w3.org/Protocols/rfc2616/rfc2616-sec%s.html#sec%s' % (major_section, section)
if header.startswith('HTTP_'):
header = header[5:].title().replace('_', '-')
return " For more information on %s see `section %s <%s>`_." % (header, section, link)
status_reasons = {
# Status Codes
# Informational
100: 'Continue',
101: 'Switching Protocols',
102: 'Processing',
# Successful
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non Authoritative Information',
204: 'No Content',
205: 'Reset Content',
206: 'Partial Content',
207: 'Multi Status',
226: 'IM Used',
# Redirection
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Found',
303: 'See Other',
304: 'Not Modified',
305: 'Use Proxy',
307: 'Temporary Redirect',
# Client Error
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Request Entity Too Large',
414: 'Request URI Too Long',
415: 'Unsupported Media Type',
416: 'Requested Range Not Satisfiable',
417: 'Expectation Failed',
422: 'Unprocessable Entity',
423: 'Locked',
424: 'Failed Dependency',
426: 'Upgrade Required',
# Server Error
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported',
507: 'Insufficient Storage',
510: 'Not Extended',
}
| Python |
class Range(object):
"""
Represents the Range header.
This only represents ``bytes`` ranges, which are the only kind
specified in HTTP. This can represent multiple sets of ranges,
but no place else is this multi-range facility supported.
"""
def __init__(self, ranges): # expect non-inclusive
for begin, end in ranges:
assert end is None or end >= 0, "Bad ranges: %r" % ranges
self.ranges = ranges
def satisfiable(self, length):
"""
Returns true if this range can be satisfied by the resource
with the given byte length.
"""
for begin, end in self.ranges:
# FIXME: bytes=-100 request on a one-byte entity is not satifiable
# neither is bytes=100- (spec seems to be unclear on this)
if end is not None and end >= length:
return False
return True
def range_for_length(self, length):
"""
*If* there is only one range, and *if* it is satisfiable by
the given length, then return a (begin, end) non-inclusive range
of bytes to serve. Otherwise return None
"""
if length is None or len(self.ranges) != 1:
return None
start, end = self.ranges[0]
if end is None:
end = length
if start < 0:
start += length
if _is_content_range_valid(start, end, length):
stop = min(end, length)
return (start, stop)
else:
return None
def content_range(self, length):
"""
Works like range_for_length; returns None or a ContentRange object
You can use it like::
response.content_range = req.range.content_range(response.content_length)
Though it's still up to you to actually serve that content range!
"""
range = self.range_for_length(length)
if range is None:
return None
return ContentRange(range[0], range[1], length)
def __str__(self):
parts = []
for begin, end in self.ranges:
if end is None:
if begin >= 0:
parts.append('%s-' % begin)
else:
parts.append(str(begin))
else:
if begin < 0:
raise ValueError("(%r, %r) should have a non-negative first value"
% (begin, end))
if end <= 0:
raise ValueError("(%r, %r) should have a positive second value"
% (begin, end))
parts.append('%s-%s' % (begin, end-1))
return 'bytes=%s' % ','.join(parts)
def __repr__(self):
return '<%s ranges=%s>' % (
self.__class__.__name__,
', '.join(map(repr, self.ranges)))
@classmethod
def parse(cls, header):
"""
Parse the header; may return None if header is invalid
"""
bytes = cls.parse_bytes(header)
if bytes is None:
return None
units, ranges = bytes
if units != 'bytes' or ranges is None:
return None
return cls(ranges)
@staticmethod
def parse_bytes(header):
"""
Parse a Range header into (bytes, list_of_ranges).
ranges in list_of_ranges are non-inclusive (unlike the HTTP header).
Will return None if the header is invalid
"""
if not header:
raise TypeError("The header must not be empty")
ranges = []
last_end = 0
try:
(units, range) = header.split("=", 1)
units = units.strip().lower()
for item in range.split(","):
if '-' not in item:
raise ValueError()
if item.startswith('-'):
# This is a range asking for a trailing chunk.
if last_end < 0:
raise ValueError('too many end ranges')
begin = int(item)
end = None
last_end = -1
else:
(begin, end) = item.split("-", 1)
begin = int(begin)
if begin < last_end or last_end < 0:
raise ValueError('begin<last_end, or last_end<0')
if end.strip():
end = int(end) + 1 # return val is non-inclusive
if begin >= end:
raise ValueError('begin>end')
else:
end = None
last_end = end
ranges.append((begin, end))
except ValueError, e:
# In this case where the Range header is malformed,
# section 14.16 says to treat the request as if the
# Range header was not present. How do I log this?
return None
return (units, ranges)
class ContentRange(object):
"""
Represents the Content-Range header
This header is ``start-stop/length``, where start-stop and length
can be ``*`` (represented as None in the attributes).
"""
def __init__(self, start, stop, length):
if not _is_content_range_valid(start, stop, length):
raise ValueError("Bad start:stop/length: %r-%r/%r" % (start, stop, length))
self.start = start
self.stop = stop # this is python-style range end (non-inclusive)
self.length = length
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, self)
def __str__(self):
if self.length is None:
length = '*'
else:
length = self.length
if self.start is None:
assert self.stop is None
return 'bytes */%s' % length
stop = self.stop - 1 # from non-inclusive to HTTP-style
return 'bytes %s-%s/%s' % (self.start, stop, length)
def __iter__(self):
"""
Mostly so you can unpack this, like:
start, stop, length = res.content_range
"""
return iter([self.start, self.stop, self.length])
@classmethod
def parse(cls, value):
"""
Parse the header. May return None if it cannot parse.
"""
if value is None:
return None
value = value.strip()
if not value.startswith('bytes '):
# Unparseable
return None
value = value[len('bytes '):].strip()
if '/' not in value:
# Invalid, no length given
return None
range, length = value.split('/', 1)
if length == '*':
length = None
elif length.isdigit():
length = int(length)
else:
return None # invalid length
if range == '*':
return cls(None, None, length)
elif '-' not in range:
# Invalid, no range
return None
else:
start, stop = range.split('-', 1)
try:
start = int(start)
stop = int(stop)
stop += 1 # convert to non-inclusive
except ValueError:
# Parse problem
return None
if _is_content_range_valid(start, stop, length, response=True):
return cls(start, stop, length)
return None
def _is_content_range_valid(start, stop, length, response=False):
if (start is None) != (stop is None):
return False
elif start is None:
return length is None or length >= 0
elif length is None:
return 0 <= start < stop
elif start >= stop:
return False
elif response and stop > length:
# "content-range: bytes 0-50/10" is invalid for a response
# "range: bytes 0-50" is valid for a request to a 10-bytes entity
return False
else:
return 0 <= start < length
| Python |
import cgi
from webob.datetime_utils import *
from webob.request import *
from webob.response import *
# Pylons has imported UnicodeMultiDict directly from this location; so
# we're putting it here just to help them out (though it has also been
# fixed in Pylons tip on 17 Dec 2009)
from webob.multidict import UnicodeMultiDict
__all__ = [
'Request', 'Response',
'UTC', 'day', 'week', 'hour', 'minute', 'second', 'month', 'year',
'html_escape'
]
def html_escape(s):
"""HTML-escape a string or object
This converts any non-string objects passed into it to strings
(actually, using ``unicode()``). All values returned are
non-unicode strings (using ``&#num;`` entities for all non-ASCII
characters).
None is treated specially, and returns the empty string.
"""
if s is None:
return ''
if hasattr(s, '__html__'):
return s.__html__()
if not isinstance(s, basestring):
if hasattr(s, '__unicode__'):
s = unicode(s)
else:
s = str(s)
s = cgi.escape(s, True)
if isinstance(s, unicode):
s = s.encode('ascii', 'xmlcharrefreplace')
return s
BaseRequest.ResponseClass = Response
Response.RequestClass = Request
| Python |
import re, urlparse, zlib, struct
from datetime import datetime, date, timedelta
from webob.headers import ResponseHeaders
from webob.cachecontrol import CacheControl, serialize_cache_control
from webob.descriptors import *
from webob.datetime_utils import *
from webob.cookies import Cookie, Morsel
from webob.util import status_reasons
from webob.request import StringIO
__all__ = ['Response']
_PARAM_RE = re.compile(r'([a-z0-9]+)=(?:"([^"]*)"|([a-z0-9_.-]*))', re.I)
_OK_PARAM_RE = re.compile(r'^[a-z0-9_.-]+$', re.I)
_gzip_header = '\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff'
class Response(object):
"""
Represents a WSGI response
"""
default_content_type = 'text/html'
default_charset = 'UTF-8'
unicode_errors = 'strict'
default_conditional_response = False
#
# __init__, from_file, copy
#
def __init__(self, body=None, status=None, headerlist=None, app_iter=None,
request=None, content_type=None, conditional_response=None,
**kw):
if app_iter is None:
if body is None:
body = ''
elif body is not None:
raise TypeError(
"You may only give one of the body and app_iter arguments")
if status is None:
self._status = '200 OK'
else:
self.status = status
if headerlist is None:
self._headerlist = []
else:
self._headerlist = headerlist
self._headers = None
if request is not None:
if hasattr(request, 'environ'):
self._environ = request.environ
self._request = request
else:
self._environ = request
self._request = None
else:
self._environ = self._request = None
if content_type is None:
content_type = self.default_content_type
charset = None
if 'charset' in kw:
charset = kw.pop('charset')
elif self.default_charset:
if content_type and (content_type == 'text/html'
or content_type.startswith('text/')
or content_type.startswith('application/xml')
or (content_type.startswith('application/')
and content_type.endswith('+xml'))):
charset = self.default_charset
if content_type and charset:
content_type += '; charset=' + charset
elif self._headerlist and charset:
self.charset = charset
if not self._headerlist and content_type:
self._headerlist.append(('Content-Type', content_type))
if conditional_response is None:
self.conditional_response = self.default_conditional_response
else:
self.conditional_response = bool(conditional_response)
if app_iter is not None:
self._app_iter = app_iter
self._body = None
else:
if isinstance(body, unicode):
if charset is None:
raise TypeError(
"You cannot set the body to a unicode value without a charset")
body = body.encode(charset)
self._body = body
if headerlist is None:
self._headerlist.append(('Content-Length', str(len(body))))
else:
self.headers['Content-Length'] = str(len(body))
self._app_iter = None
for name, value in kw.iteritems():
if not hasattr(self.__class__, name):
# Not a basic attribute
raise TypeError(
"Unexpected keyword: %s=%r" % (name, value))
setattr(self, name, value)
@classmethod
def from_file(cls, fp):
"""Reads a response from a file-like object (it must implement
``.read(size)`` and ``.readline()``).
It will read up to the end of the response, not the end of the
file.
This reads the response as represented by ``str(resp)``; it
may not read every valid HTTP response properly. Responses
must have a ``Content-Length``"""
headerlist = []
status = fp.readline().strip()
while 1:
line = fp.readline().strip()
if not line:
# end of headers
break
try:
header_name, value = line.split(':', 1)
except ValueError:
raise ValueError('Bad header line: %r' % line)
headerlist.append((header_name, value.strip()))
r = cls(
status=status,
headerlist=headerlist,
app_iter=(),
)
r.body = fp.read(r.content_length or 0)
return r
def copy(self):
"""Makes a copy of the response"""
# we need to do this for app_iter to be reusable
app_iter = list(self.app_iter)
iter_close(self.app_iter)
# and this to make sure app_iter instances are different
self.app_iter = list(app_iter)
return self.__class__(
content_type=False,
status=self._status,
headerlist=self._headerlist[:],
app_iter=app_iter,
conditional_response=self.conditional_response)
#
# __repr__, __str__
#
def __repr__(self):
return '<%s at 0x%x %s>' % (self.__class__.__name__, abs(id(self)),
self.status)
def __str__(self, skip_body=False):
parts = [self.status]
if not skip_body:
# Force enumeration of the body (to set content-length)
self.body
parts += map('%s: %s'.__mod__, self.headerlist)
if not skip_body and self.body:
parts += ['', self.body]
return '\n'.join(parts)
#
# status, status_int
#
def _status__get(self):
"""
The status string
"""
return self._status
def _status__set(self, value):
if isinstance(value, unicode):
# Status messages have to be ASCII safe, so this is OK:
value = str(value)
if isinstance(value, int):
value = str(value)
if not isinstance(value, str):
raise TypeError(
"You must set status to a string or integer (not %s)"
% type(value))
if ' ' not in value:
# Need to add a reason:
code = int(value)
reason = status_reasons[code]
value += ' ' + reason
self._status = value
status = property(_status__get, _status__set, doc=_status__get.__doc__)
def _status_int__get(self):
"""
The status as an integer
"""
return int(self._status.split()[0])
def _status_int__set(self, code):
self._status = '%d %s' % (code, status_reasons[code])
status_int = property(_status_int__get, _status_int__set,
doc=_status_int__get.__doc__)
status_code = deprecated_property(
status_int, 'status_code', 'use .status or .status_int instead',
warning=False)
#
# headerslist, headers
#
def _headerlist__get(self):
"""
The list of response headers
"""
return self._headerlist
def _headerlist__set(self, value):
self._headers = None
if not isinstance(value, list):
if hasattr(value, 'items'):
value = value.items()
value = list(value)
self._headerlist = value
def _headerlist__del(self):
self.headerlist = []
headerlist = property(_headerlist__get, _headerlist__set,
_headerlist__del, doc=_headerlist__get.__doc__)
def _headers__get(self):
"""
The headers in a dictionary-like object
"""
if self._headers is None:
self._headers = ResponseHeaders.view_list(self.headerlist)
return self._headers
def _headers__set(self, value):
if hasattr(value, 'items'):
value = value.items()
self.headerlist = value
self._headers = None
headers = property(_headers__get, _headers__set, doc=_headers__get.__doc__)
#
# body
#
def _body__get(self):
"""
The body of the response, as a ``str``. This will read in the
entire app_iter if necessary.
"""
if self._body is None:
if self._app_iter is None:
raise AttributeError("No body has been set")
try:
body = self._body = ''.join(self._app_iter)
finally:
iter_close(self._app_iter)
if isinstance(body, unicode):
app_iter_repr = repr(self._app_iter)
if len(app_iter_repr) > 50:
app_iter_repr = (
app_iter_repr[:30] + '...' + app_iter_repr[-10:])
raise ValueError(
'An item of the app_iter (%s) was unicode, causing a '
'unicode body: %r' % (app_iter_repr, body))
self._app_iter = None
if (self._environ is not None and
self._environ['REQUEST_METHOD'] == 'HEAD'):
assert len(body) == 0, "HEAD responses must be empty"
elif len(body) == 0:
# if body-length is zero, we assume it's a HEAD response and
# leave content_length alone
pass # pragma: no cover (no idea why necessary, it's hit)
elif self.content_length is None:
self.content_length = len(body)
elif self.content_length != len(body):
raise AssertionError(
"Content-Length is different from actual app_iter length "
"(%r!=%r)"
% (self.content_length, len(body))
)
return self._body
def _body__set(self, value):
if isinstance(value, unicode):
raise TypeError(
"You cannot set Response.body to a unicode object (use "
"Response.unicode_body)")
if not isinstance(value, str):
raise TypeError(
"You can only set the body to a str (not %s)"
% type(value))
try:
if self._body or self._app_iter:
self.content_md5 = None
except AttributeError:
# if setting body early in initialization _body and _app_iter
# don't exist yet
pass
self._body = value
self.content_length = len(value)
self._app_iter = None
def _body__del(self):
self._body = None
self.content_length = None
self._app_iter = None
body = property(_body__get, _body__set, _body__del, doc=_body__get.__doc__)
#
# unicode_body
#
def _unicode_body__get(self):
"""
Get/set the unicode value of the body (using the charset of the
Content-Type)
"""
if not self.charset:
raise AttributeError(
"You cannot access Response.unicode_body unless charset is set")
body = self.body
return body.decode(self.charset, self.unicode_errors)
def _unicode_body__set(self, value):
if not self.charset:
raise AttributeError(
"You cannot access Response.unicode_body unless charset is set")
if not isinstance(value, unicode):
raise TypeError(
"You can only set Response.unicode_body to a unicode string "
"(not %s)" % type(value))
self.body = value.encode(self.charset)
def _unicode_body__del(self):
del self.body
unicode_body = property(_unicode_body__get, _unicode_body__set,
_unicode_body__del, doc=_unicode_body__get.__doc__)
ubody = property(_unicode_body__get, _unicode_body__set,
_unicode_body__del, doc="Alias for unicode_body")
#
# body_file, write(text)
#
def _body_file__get(self):
"""
A file-like object that can be used to write to the
body. If you passed in a list app_iter, that app_iter will be
modified by writes.
"""
return ResponseBodyFile(self)
def _body_file__del(self):
del self.body
body_file = property(_body_file__get, fdel=_body_file__del,
doc=_body_file__get.__doc__)
def write(self, text):
if isinstance(text, unicode):
self.unicode_body += text
else:
self.body += text
#
# app_iter
#
def _app_iter__get(self):
"""
Returns the app_iter of the response.
If body was set, this will create an app_iter from that body
(a single-item list)
"""
if self._app_iter is None:
if self._body is None:
raise AttributeError("No body or app_iter has been set")
return [self._body]
else:
return self._app_iter
def _app_iter__set(self, value):
if self._body is not None:
# Undo the automatically-set content-length
self.content_length = None
self._app_iter = value
self._body = None
def _app_iter__del(self):
self.content_length = None
self._app_iter = self._body = None
app_iter = property(_app_iter__get, _app_iter__set, _app_iter__del,
doc=_app_iter__get.__doc__)
#
# headers attrs
#
allow = list_header('Allow', '14.7')
## FIXME: I realize response.vary += 'something' won't work. It should.
## Maybe for all listy headers.
vary = list_header('Vary', '14.44')
content_length = converter(
header_getter('Content-Length', '14.17'),
parse_int, serialize_int, 'int')
content_encoding = header_getter('Content-Encoding', '14.11')
content_language = list_header('Content-Language', '14.12')
content_location = header_getter('Content-Location', '14.14')
content_md5 = header_getter('Content-MD5', '14.14')
content_disposition = header_getter('Content-Disposition', '19.5.1')
accept_ranges = header_getter('Accept-Ranges', '14.5')
content_range = converter(
header_getter('Content-Range', '14.16'),
parse_content_range, serialize_content_range, 'ContentRange object')
date = date_header('Date', '14.18')
expires = date_header('Expires', '14.21')
last_modified = date_header('Last-Modified', '14.29')
etag = converter(
header_getter('ETag', '14.19'),
parse_etag_response, serialize_etag_response, 'Entity tag')
location = header_getter('Location', '14.30')
pragma = header_getter('Pragma', '14.32')
age = converter(
header_getter('Age', '14.6'),
parse_int_safe, serialize_int, 'int')
retry_after = converter(
header_getter('Retry-After', '14.37'),
parse_date_delta, serialize_date_delta, 'HTTP date or delta seconds')
server = header_getter('Server', '14.38')
# FIXME: the standard allows this to be a list of challenges
www_authenticate = converter(
header_getter('WWW-Authenticate', '14.47'),
parse_auth, serialize_auth,
)
#
# charset
#
def _charset__get(self):
"""
Get/set the charset (in the Content-Type)
"""
header = self.headers.get('Content-Type')
if not header:
return None
match = CHARSET_RE.search(header)
if match:
return match.group(1)
return None
def _charset__set(self, charset):
if charset is None:
del self.charset
return
header = self.headers.pop('Content-Type', None)
if header is None:
raise AttributeError("You cannot set the charset when no "
"content-type is defined")
match = CHARSET_RE.search(header)
if match:
header = header[:match.start()] + header[match.end():]
header += '; charset=%s' % charset
self.headers['Content-Type'] = header
def _charset__del(self):
header = self.headers.pop('Content-Type', None)
if header is None:
# Don't need to remove anything
return
match = CHARSET_RE.search(header)
if match:
header = header[:match.start()] + header[match.end():]
self.headers['Content-Type'] = header
charset = property(_charset__get, _charset__set, _charset__del,
doc=_charset__get.__doc__)
#
# content_type
#
def _content_type__get(self):
"""
Get/set the Content-Type header (or None), *without* the
charset or any parameters.
If you include parameters (or ``;`` at all) when setting the
content_type, any existing parameters will be deleted;
otherwise they will be preserved.
"""
header = self.headers.get('Content-Type')
if not header:
return None
return header.split(';', 1)[0]
def _content_type__set(self, value):
if not value:
self._content_type__del()
return
if ';' not in value:
header = self.headers.get('Content-Type', '')
if ';' in header:
params = header.split(';', 1)[1]
value += ';' + params
self.headers['Content-Type'] = value
def _content_type__del(self):
self.headers.pop('Content-Type', None)
content_type = property(_content_type__get, _content_type__set,
_content_type__del, doc=_content_type__get.__doc__)
#
# content_type_params
#
def _content_type_params__get(self):
"""
A dictionary of all the parameters in the content type.
(This is not a view, set to change, modifications of the dict would not be
applied otherwise)
"""
params = self.headers.get('Content-Type', '')
if ';' not in params:
return {}
params = params.split(';', 1)[1]
result = {}
for match in _PARAM_RE.finditer(params):
result[match.group(1)] = match.group(2) or match.group(3) or ''
return result
def _content_type_params__set(self, value_dict):
if not value_dict:
del self.content_type_params
return
params = []
for k, v in sorted(value_dict.items()):
if not _OK_PARAM_RE.search(v):
v = '"%s"' % v.replace('"', '\\"')
params.append('; %s=%s' % (k, v))
ct = self.headers.pop('Content-Type', '').split(';', 1)[0]
ct += ''.join(params)
self.headers['Content-Type'] = ct
def _content_type_params__del(self):
self.headers['Content-Type'] = self.headers.get(
'Content-Type', '').split(';', 1)[0]
content_type_params = property(
_content_type_params__get,
_content_type_params__set,
_content_type_params__del,
_content_type_params__get.__doc__
)
#
# set_cookie, unset_cookie, delete_cookie, merge_cookies
#
def set_cookie(self, key, value='', max_age=None,
path='/', domain=None, secure=False, httponly=False,
comment=None, expires=None, overwrite=False):
"""
Set (add) a cookie for the response
"""
if overwrite:
self.unset_cookie(key, strict=False)
if value is None: # delete the cookie from the client
value = ''
max_age = 0
expires = timedelta(days=-5)
elif expires is None and max_age is not None:
if isinstance(max_age, int):
max_age = timedelta(seconds=max_age)
expires = datetime.utcnow() + max_age
elif max_age is None and expires is not None:
max_age = expires - datetime.utcnow()
if isinstance(value, unicode):
value = value.encode('utf8')
m = Morsel(key, value)
m.path = path
m.domain = domain
m.comment = comment
m.expires = expires
m.max_age = max_age
m.secure = secure
m.httponly = httponly
self.headerlist.append(('Set-Cookie', str(m)))
def delete_cookie(self, key, path='/', domain=None):
"""
Delete a cookie from the client. Note that path and domain must match
how the cookie was originally set.
This sets the cookie to the empty string, and max_age=0 so
that it should expire immediately.
"""
self.set_cookie(key, None, path=path, domain=domain)
def unset_cookie(self, key, strict=True):
"""
Unset a cookie with the given name (remove it from the
response).
"""
existing = self.headers.getall('Set-Cookie')
if not existing and not strict:
return
cookies = Cookie()
for header in existing:
cookies.load(header)
if key in cookies:
del cookies[key]
del self.headers['Set-Cookie']
for m in cookies.values():
self.headerlist.append(('Set-Cookie', str(m)))
elif strict:
raise KeyError("No cookie has been set with the name %r" % key)
def merge_cookies(self, resp):
"""Merge the cookies that were set on this response with the
given `resp` object (which can be any WSGI application).
If the `resp` is a :class:`webob.Response` object, then the
other object will be modified in-place.
"""
if not self.headers.get('Set-Cookie'):
return resp
if isinstance(resp, Response):
for header in self.headers.getall('Set-Cookie'):
resp.headers.add('Set-Cookie', header)
return resp
else:
c_headers = [h for h in self.headerlist if
h[0].lower() == 'set-cookie']
def repl_app(environ, start_response):
def repl_start_response(status, headers, exc_info=None):
return start_response(status, headers+c_headers,
exc_info=exc_info)
return resp(environ, repl_start_response)
return repl_app
#
# cache_control
#
_cache_control_obj = None
def _cache_control__get(self):
"""
Get/set/modify the Cache-Control header (section `14.9
<http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9>`_)
"""
value = self.headers.get('cache-control', '')
if self._cache_control_obj is None:
self._cache_control_obj = CacheControl.parse(
value, updates_to=self._update_cache_control, type='response')
self._cache_control_obj.header_value = value
if self._cache_control_obj.header_value != value:
new_obj = CacheControl.parse(value, type='response')
self._cache_control_obj.properties.clear()
self._cache_control_obj.properties.update(new_obj.properties)
self._cache_control_obj.header_value = value
return self._cache_control_obj
def _cache_control__set(self, value):
# This actually becomes a copy
if not value:
value = ""
if isinstance(value, dict):
value = CacheControl(value, 'response')
if isinstance(value, unicode):
value = str(value)
if isinstance(value, str):
if self._cache_control_obj is None:
self.headers['Cache-Control'] = value
return
value = CacheControl.parse(value, 'response')
cache = self.cache_control
cache.properties.clear()
cache.properties.update(value.properties)
def _cache_control__del(self):
self.cache_control = {}
def _update_cache_control(self, prop_dict):
value = serialize_cache_control(prop_dict)
if not value:
if 'Cache-Control' in self.headers:
del self.headers['Cache-Control']
else:
self.headers['Cache-Control'] = value
cache_control = property(
_cache_control__get, _cache_control__set,
_cache_control__del, doc=_cache_control__get.__doc__)
#
# cache_expires
#
def _cache_expires(self, seconds=0, **kw):
"""
Set expiration on this request. This sets the response to
expire in the given seconds, and any other attributes are used
for cache_control (e.g., private=True, etc).
"""
if seconds is True:
seconds = 0
elif isinstance(seconds, timedelta):
seconds = timedelta_to_seconds(seconds)
cache_control = self.cache_control
if seconds is None:
pass
elif not seconds:
# To really expire something, you have to force a
# bunch of these cache control attributes, and IE may
# not pay attention to those still so we also set
# Expires.
cache_control.no_store = True
cache_control.no_cache = True
cache_control.must_revalidate = True
cache_control.max_age = 0
cache_control.post_check = 0
cache_control.pre_check = 0
self.expires = datetime.utcnow()
if 'last-modified' not in self.headers:
self.last_modified = datetime.utcnow()
self.pragma = 'no-cache'
else:
cache_control.max_age = seconds
self.expires = datetime.utcnow() + timedelta(seconds=seconds)
for name, value in kw.items():
setattr(cache_control, name, value)
cache_expires = property(lambda self: self._cache_expires, _cache_expires)
#
# encode_content, decode_content, md5_etag
#
def encode_content(self, encoding='gzip', lazy=False):
"""
Encode the content with the given encoding (only gzip and
identity are supported).
"""
assert encoding in ('identity', 'gzip'), \
"Unknown encoding: %r" % encoding
if encoding == 'identity':
self.decode_content()
return
if self.content_encoding == 'gzip':
return
if lazy:
self.app_iter = gzip_app_iter(self.app_iter)
self.content_length = None
else:
self.app_iter = list(gzip_app_iter(self.app_iter))
self.content_length = sum(map(len, self.app_iter))
self.content_encoding = 'gzip'
def decode_content(self):
content_encoding = self.content_encoding or 'identity'
if content_encoding == 'identity':
return
if content_encoding not in ('gzip', 'deflate'):
raise ValueError(
"I don't know how to decode the content %s" % content_encoding)
if content_encoding == 'gzip':
from gzip import GzipFile
f = StringIO(self.body)
gzip_f = GzipFile(filename='', mode='r', fileobj=f)
self.body = gzip_f.read()
self.content_encoding = None
gzip_f.close()
f.close()
else:
# Weird feature: http://bugs.python.org/issue5784
self.body = zlib.decompress(self.body, -15)
self.content_encoding = None
def md5_etag(self, body=None, set_content_md5=False):
"""
Generate an etag for the response object using an MD5 hash of
the body (the body parameter, or ``self.body`` if not given)
Sets ``self.etag``
If ``set_content_md5`` is True sets ``self.content_md5`` as well
"""
if body is None:
body = self.body
try: # pragma: no cover
from hashlib import md5
except ImportError: # pragma: no cover
from md5 import md5
md5_digest = md5(body).digest().encode('base64').replace('\n', '')
self.etag = md5_digest.strip('=')
if set_content_md5:
self.content_md5 = md5_digest
#
# request
#
def _request__get(self):
"""
Return the request associated with this response if any.
"""
if self._request is None and self._environ is not None:
self._request = self.RequestClass(self._environ)
return self._request
def _request__set(self, value):
if value is None:
del self.request
return
if isinstance(value, dict):
self._environ = value
self._request = None
else:
self._request = value
self._environ = value.environ
def _request__del(self):
self._request = self._environ = None
request = property(_request__get, _request__set, _request__del,
doc=_request__get.__doc__)
#
# environ
#
def _environ__get(self):
"""
Get/set the request environ associated with this response, if
any.
"""
return self._environ
def _environ__set(self, value):
if value is None:
del self.environ
self._environ = value
self._request = None
def _environ__del(self):
self._request = self._environ = None
environ = property(_environ__get, _environ__set, _environ__del,
doc=_environ__get.__doc__)
#
# __call__, conditional_response_app
#
def __call__(self, environ, start_response):
"""
WSGI application interface
"""
if self.conditional_response:
return self.conditional_response_app(environ, start_response)
headerlist = self._abs_headerlist(environ)
start_response(self.status, headerlist)
if environ['REQUEST_METHOD'] == 'HEAD':
# Special case here...
return EmptyResponse(self.app_iter)
return self.app_iter
def _abs_headerlist(self, environ):
"""Returns a headerlist, with the Location header possibly
made absolute given the request environ.
"""
headerlist = self.headerlist
for name, value in headerlist:
if name.lower() == 'location':
if SCHEME_RE.search(value):
break
new_location = urlparse.urljoin(
_request_uri(environ), value)
headerlist = list(headerlist)
idx = headerlist.index((name, value))
headerlist[idx] = (name, new_location)
break
return headerlist
_safe_methods = ('GET', 'HEAD')
def conditional_response_app(self, environ, start_response):
"""
Like the normal __call__ interface, but checks conditional headers:
* If-Modified-Since (304 Not Modified; only on GET, HEAD)
* If-None-Match (304 Not Modified; only on GET, HEAD)
* Range (406 Partial Content; only on GET, HEAD)
"""
req = self.RequestClass(environ)
status304 = False
headerlist = self._abs_headerlist(environ)
if req.method in self._safe_methods:
if req.if_none_match and self.etag:
status304 = self.etag in req.if_none_match
elif req.if_modified_since and self.last_modified:
status304 = self.last_modified <= req.if_modified_since
if status304:
start_response('304 Not Modified', filter_headers(headerlist))
return EmptyResponse(self.app_iter)
if (req.range and req.if_range.match_response(self)
and self.content_range is None
and req.method in ('HEAD', 'GET')
and self.status_int == 200
and self.content_length is not None
):
content_range = req.range.content_range(self.content_length)
# FIXME: we should support If-Range
if content_range is None:
iter_close(self.app_iter)
body = "Requested range not satisfiable: %s" % req.range
headerlist = [
('Content-Length', str(len(body))),
('Content-Range', str(ContentRange(None, None, self.content_length))),
('Content-Type', 'text/plain'),
] + filter_headers(headerlist)
start_response('416 Requested Range Not Satisfiable', headerlist)
if req.method == 'HEAD':
return ()
return [body]
else:
app_iter = self.app_iter_range(content_range.start, content_range.stop)
if app_iter is not None:
# the following should be guaranteed by
# Range.range_for_length(length)
assert content_range.start is not None
headerlist = [
('Content-Length', str(content_range.stop - content_range.start)),
('Content-Range', str(content_range)),
] + filter_headers(headerlist, ('content-length',))
start_response('206 Partial Content', headerlist)
if req.method == 'HEAD':
return EmptyResponse(app_iter)
return app_iter
start_response(self.status, headerlist)
if req.method == 'HEAD':
return EmptyResponse(self.app_iter)
return self.app_iter
def app_iter_range(self, start, stop):
"""
Return a new app_iter built from the response app_iter, that
serves up only the given ``start:stop`` range.
"""
if self._app_iter is None:
return [self.body[start:stop]]
app_iter = self.app_iter
if hasattr(app_iter, 'app_iter_range'):
return app_iter.app_iter_range(start, stop)
return AppIterRange(app_iter, start, stop)
def filter_headers(hlist, remove_headers=('content-length', 'content-type')):
return [h for h in hlist if (h[0].lower() not in remove_headers)]
class ResponseBodyFile(object):
mode = 'wb'
closed = False
def __init__(self, response):
self.response = response
def __repr__(self):
return '<body_file for %r>' % self.response
encoding = property(
lambda self: self.response.charset,
doc="The encoding of the file (inherited from response.charset)"
)
def write(self, s):
if isinstance(s, unicode):
if self.response.charset is None:
raise TypeError(
"You can only write unicode to Response.body_file "
"if charset has been set"
)
s = s.encode(self.response.charset)
if not isinstance(s, str):
raise TypeError(
"You can only write str to a Response.body_file, not %s"
% type(s)
)
if not isinstance(self.response._app_iter, list):
body = self.response.body
if body:
self.response.app_iter = [body]
else:
self.response.app_iter = []
self.response.app_iter.append(s)
def writelines(self, seq):
for item in seq:
self.write(item)
def close(self):
raise NotImplementedError("Response bodies cannot be closed")
def flush(self):
pass
class AppIterRange(object):
"""
Wraps an app_iter, returning just a range of bytes
"""
def __init__(self, app_iter, start, stop):
assert start >= 0, "Bad start: %r" % start
assert stop is None or (stop >= 0 and stop >= start), (
"Bad stop: %r" % stop)
self.app_iter = iter(app_iter)
self._pos = 0 # position in app_iter
self.start = start
self.stop = stop
def __iter__(self):
return self
def _skip_start(self):
start, stop = self.start, self.stop
for chunk in self.app_iter:
self._pos += len(chunk)
if self._pos < start:
continue
elif self._pos == start:
return ''
else:
chunk = chunk[start-self._pos:]
if stop is not None and self._pos > stop:
chunk = chunk[:stop-self._pos]
assert len(chunk) == stop - start
return chunk
else:
raise StopIteration()
def next(self):
if self._pos < self.start:
# need to skip some leading bytes
return self._skip_start()
stop = self.stop
if stop is not None and self._pos >= stop:
raise StopIteration
chunk = self.app_iter.next()
self._pos += len(chunk)
if stop is None or self._pos <= stop:
return chunk
else:
return chunk[:stop-self._pos]
def close(self):
iter_close(self.app_iter)
class EmptyResponse(object):
"""An empty WSGI response.
An iterator that immediately stops. Optionally provides a close
method to close an underlying app_iter it replaces.
"""
def __init__(self, app_iter=None):
if app_iter and hasattr(app_iter, 'close'):
self.close = app_iter.close
def __iter__(self):
return self
def __len__(self):
return 0
def next(self):
raise StopIteration()
def _request_uri(environ):
"""Like wsgiref.url.request_uri, except eliminates :80 ports
Return the full request URI"""
url = environ['wsgi.url_scheme']+'://'
from urllib import quote
if environ.get('HTTP_HOST'):
url += environ['HTTP_HOST']
else:
url += environ['SERVER_NAME'] + ':' + environ['SERVER_PORT']
if url.endswith(':80') and environ['wsgi.url_scheme'] == 'http':
url = url[:-3]
elif url.endswith(':443') and environ['wsgi.url_scheme'] == 'https':
url = url[:-4]
url += quote(environ.get('SCRIPT_NAME') or '/')
from urllib import quote
path_info = quote(environ.get('PATH_INFO',''))
if not environ.get('SCRIPT_NAME'):
url += path_info[1:]
else:
url += path_info
return url
def iter_close(iter):
if hasattr(iter, 'close'):
iter.close()
def gzip_app_iter(app_iter):
size = 0
crc = zlib.crc32("") & 0xffffffffL
compress = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS,
zlib.DEF_MEM_LEVEL, 0)
yield _gzip_header
for item in app_iter:
size += len(item)
crc = zlib.crc32(item, crc) & 0xffffffffL
yield compress.compress(item)
yield compress.flush()
yield struct.pack("<2L", crc, size & 0xffffffffL)
| Python |
"""
Represents the Cache-Control header
"""
import re
class UpdateDict(dict):
"""
Dict that has a callback on all updates
"""
# these are declared as class attributes so that
# we don't need to override constructor just to
# set some defaults
updated = None
updated_args = None
def _updated(self):
"""
Assign to new_dict.updated to track updates
"""
updated = self.updated
if updated is not None:
args = self.updated_args
if args is None:
args = (self,)
updated(*args)
def __setitem__(self, key, item):
dict.__setitem__(self, key, item)
self._updated()
def __delitem__(self, key):
dict.__delitem__(self, key)
self._updated()
def clear(self):
dict.clear(self)
self._updated()
def update(self, *args, **kw):
dict.update(self, *args, **kw)
self._updated()
def setdefault(self, key, value=None):
val = dict.setdefault(self, key, value)
if val is value:
self._updated()
return val
def pop(self, *args):
v = dict.pop(self, *args)
self._updated()
return v
def popitem(self):
v = dict.popitem(self)
self._updated()
return v
token_re = re.compile(
r'([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?')
need_quote_re = re.compile(r'[^a-zA-Z0-9._-]')
class exists_property(object):
"""
Represents a property that either is listed in the Cache-Control
header, or is not listed (has no value)
"""
def __init__(self, prop, type=None):
self.prop = prop
self.type = type
def __get__(self, obj, type=None):
if obj is None:
return self
return self.prop in obj.properties
def __set__(self, obj, value):
if (self.type is not None
and self.type != obj.type):
raise AttributeError(
"The property %s only applies to %s Cache-Control" % (self.prop, self.type))
if value:
obj.properties[self.prop] = None
else:
if self.prop in obj.properties:
del obj.properties[self.prop]
def __delete__(self, obj):
self.__set__(obj, False)
class value_property(object):
"""
Represents a property that has a value in the Cache-Control header.
When no value is actually given, the value of self.none is returned.
"""
def __init__(self, prop, default=None, none=None, type=None):
self.prop = prop
self.default = default
self.none = none
self.type = type
def __get__(self, obj, type=None):
if obj is None:
return self
if self.prop in obj.properties:
value = obj.properties[self.prop]
if value is None:
return self.none
else:
return value
else:
return self.default
def __set__(self, obj, value):
if (self.type is not None
and self.type != obj.type):
raise AttributeError(
"The property %s only applies to %s Cache-Control" % (self.prop, self.type))
if value == self.default:
if self.prop in obj.properties:
del obj.properties[self.prop]
elif value is True:
obj.properties[self.prop] = None # Empty value, but present
else:
obj.properties[self.prop] = value
def __delete__(self, obj):
if self.prop in obj.properties:
del obj.properties[self.prop]
class CacheControl(object):
"""
Represents the Cache-Control header.
By giving a type of ``'request'`` or ``'response'`` you can
control what attributes are allowed (some Cache-Control values
only apply to requests or responses).
"""
update_dict = UpdateDict
def __init__(self, properties, type):
self.properties = properties
self.type = type
@classmethod
def parse(cls, header, updates_to=None, type=None):
"""
Parse the header, returning a CacheControl object.
The object is bound to the request or response object
``updates_to``, if that is given.
"""
if updates_to:
props = cls.update_dict()
props.updated = updates_to
else:
props = {}
for match in token_re.finditer(header):
name = match.group(1)
value = match.group(2) or match.group(3) or None
if value:
try:
value = int(value)
except ValueError:
pass
props[name] = value
obj = cls(props, type=type)
if updates_to:
props.updated_args = (obj,)
return obj
def __repr__(self):
return '<CacheControl %r>' % str(self)
# Request values:
# no-cache shared (below)
# no-store shared (below)
# max-age shared (below)
max_stale = value_property('max-stale', none='*', type='request')
min_fresh = value_property('min-fresh', type='request')
# no-transform shared (below)
only_if_cached = exists_property('only-if-cached', type='request')
# Response values:
public = exists_property('public', type='response')
private = value_property('private', none='*', type='response')
no_cache = value_property('no-cache', none='*')
no_store = exists_property('no-store')
no_transform = exists_property('no-transform')
must_revalidate = exists_property('must-revalidate', type='response')
proxy_revalidate = exists_property('proxy-revalidate', type='response')
max_age = value_property('max-age', none=-1)
s_maxage = value_property('s-maxage', type='response')
s_max_age = s_maxage
def __str__(self):
return serialize_cache_control(self.properties)
def copy(self):
"""
Returns a copy of this object.
"""
return self.__class__(self.properties.copy(), type=self.type)
def serialize_cache_control(properties):
if isinstance(properties, CacheControl):
properties = properties.properties
parts = []
for name, value in sorted(properties.items()):
if value is None:
parts.append(name)
continue
value = str(value)
if need_quote_re.search(value):
value = '"%s"' % value
parts.append('%s=%s' % (name, value))
return ', '.join(parts)
| Python |
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
Gives a multi-value dictionary object (MultiDict) plus several wrappers
"""
import cgi, copy, sys, warnings, urllib
from UserDict import DictMixin
__all__ = ['MultiDict', 'UnicodeMultiDict', 'NestedMultiDict', 'NoVars',
'TrackableMultiDict']
class MultiDict(DictMixin):
"""
An ordered dictionary that can have multiple values for each key.
Adds the methods getall, getone, mixed and extend and add to the normal
dictionary interface.
"""
def __init__(self, *args, **kw):
if len(args) > 1:
raise TypeError("MultiDict can only be called with one positional argument")
if args:
if hasattr(args[0], 'iteritems'):
items = list(args[0].iteritems())
elif hasattr(args[0], 'items'):
items = args[0].items()
else:
items = list(args[0])
self._items = items
else:
self._items = []
if kw:
self._items.extend(kw.iteritems())
@classmethod
def view_list(cls, lst):
"""
Create a dict that is a view on the given list
"""
if not isinstance(lst, list):
raise TypeError(
"%s.view_list(obj) takes only actual list objects, not %r"
% (cls.__name__, lst))
obj = cls()
obj._items = lst
return obj
@classmethod
def from_fieldstorage(cls, fs):
"""
Create a dict from a cgi.FieldStorage instance
"""
obj = cls()
# fs.list can be None when there's nothing to parse
for field in fs.list or ():
if field.filename:
obj.add(field.name, field)
else:
obj.add(field.name, field.value)
return obj
def __getitem__(self, key):
for k, v in reversed(self._items):
if k == key:
return v
raise KeyError(key)
def __setitem__(self, key, value):
try:
del self[key]
except KeyError:
pass
self._items.append((key, value))
def add(self, key, value):
"""
Add the key and value, not overwriting any previous value.
"""
self._items.append((key, value))
def getall(self, key):
"""
Return a list of all values matching the key (may be an empty list)
"""
result = []
for k, v in self._items:
if key == k:
result.append(v)
return result
def getone(self, key):
"""
Get one value matching the key, raising a KeyError if multiple
values were found.
"""
v = self.getall(key)
if not v:
raise KeyError('Key not found: %r' % key)
if len(v) > 1:
raise KeyError('Multiple values match %r: %r' % (key, v))
return v[0]
def mixed(self):
"""
Returns a dictionary where the values are either single
values, or a list of values when a key/value appears more than
once in this dictionary. This is similar to the kind of
dictionary often used to represent the variables in a web
request.
"""
result = {}
multi = {}
for key, value in self.iteritems():
if key in result:
# We do this to not clobber any lists that are
# *actual* values in this dictionary:
if key in multi:
result[key].append(value)
else:
result[key] = [result[key], value]
multi[key] = None
else:
result[key] = value
return result
def dict_of_lists(self):
"""
Returns a dictionary where each key is associated with a list of values.
"""
r = {}
for key, val in self.iteritems():
r.setdefault(key, []).append(val)
return r
def __delitem__(self, key):
items = self._items
found = False
for i in range(len(items)-1, -1, -1):
if items[i][0] == key:
del items[i]
found = True
if not found:
raise KeyError(key)
def __contains__(self, key):
for k, v in self._items:
if k == key:
return True
return False
has_key = __contains__
def clear(self):
self._items = []
def copy(self):
return self.__class__(self)
def setdefault(self, key, default=None):
for k, v in self._items:
if key == k:
return v
self._items.append((key, default))
return default
def pop(self, key, *args):
if len(args) > 1:
raise TypeError, "pop expected at most 2 arguments, got "\
+ repr(1 + len(args))
for i in range(len(self._items)):
if self._items[i][0] == key:
v = self._items[i][1]
del self._items[i]
return v
if args:
return args[0]
else:
raise KeyError(key)
def popitem(self):
return self._items.pop()
def update(self, *args, **kw):
if args:
lst = args[0]
if len(lst) != len(dict(lst)):
# this does not catch the cases where we overwrite existing
# keys, but those would produce too many warning
msg = ("Behavior of MultiDict.update() has changed "
"and overwrites duplicate keys. Consider using .extend()"
)
warnings.warn(msg, stacklevel=2)
DictMixin.update(self, *args, **kw)
def extend(self, other=None, **kwargs):
if other is None:
pass
elif hasattr(other, 'items'):
self._items.extend(other.items())
elif hasattr(other, 'keys'):
for k in other.keys():
self._items.append((k, other[k]))
else:
for k, v in other:
self._items.append((k, v))
if kwargs:
self.update(kwargs)
def __repr__(self):
items = map('(%r, %r)'.__mod__, _hide_passwd(self.iteritems()))
return '%s([%s])' % (self.__class__.__name__, ', '.join(items))
def __len__(self):
return len(self._items)
##
## All the iteration:
##
def keys(self):
return [k for k, v in self._items]
def iterkeys(self):
for k, v in self._items:
yield k
__iter__ = iterkeys
def items(self):
return self._items[:]
def iteritems(self):
return iter(self._items)
def values(self):
return [v for k, v in self._items]
def itervalues(self):
for k, v in self._items:
yield v
class UnicodeMultiDict(DictMixin):
"""
A MultiDict wrapper that decodes returned values to unicode on the
fly. Decoding is not applied to assigned values.
The key/value contents are assumed to be ``str``/``strs`` or
``str``/``FieldStorages`` (as is returned by the ``paste.request.parse_``
functions).
Can optionally also decode keys when the ``decode_keys`` argument is
True.
``FieldStorage`` instances are cloned, and the clone's ``filename``
variable is decoded. Its ``name`` variable is decoded when ``decode_keys``
is enabled.
"""
def __init__(self, multi, encoding=None, errors='strict',
decode_keys=False):
self.multi = multi
if encoding is None:
encoding = sys.getdefaultencoding()
self.encoding = encoding
self.errors = errors
self.decode_keys = decode_keys
def _decode_key(self, key):
if self.decode_keys:
try:
key = key.decode(self.encoding, self.errors)
except AttributeError:
pass
return key
def _encode_key(self, key):
if self.decode_keys and isinstance(key, unicode):
return key.encode(self.encoding, self.errors)
return key
def _decode_value(self, value):
"""
Decode the specified value to unicode. Assumes value is a ``str`` or
`FieldStorage`` object.
``FieldStorage`` objects are specially handled.
"""
if isinstance(value, cgi.FieldStorage):
# decode FieldStorage's field name and filename
value = copy.copy(value)
if self.decode_keys:
if not isinstance(value.name, unicode):
value.name = value.name.decode(self.encoding, self.errors)
if value.filename:
if not isinstance(value.filename, unicode):
value.filename = value.filename.decode(self.encoding,
self.errors)
elif not isinstance(value, unicode):
try:
value = value.decode(self.encoding, self.errors)
except AttributeError:
pass
return value
def _encode_value(self, value):
# FIXME: should this do the FieldStorage stuff too?
if isinstance(value, unicode):
value = value.encode(self.encoding, self.errors)
return value
def __getitem__(self, key):
return self._decode_value(self.multi.__getitem__(self._encode_key(key)))
def __setitem__(self, key, value):
self.multi.__setitem__(self._encode_key(key), self._encode_value(value))
def add(self, key, value):
"""
Add the key and value, not overwriting any previous value.
"""
self.multi.add(self._encode_key(key), self._encode_value(value))
def getall(self, key):
"""
Return a list of all values matching the key (may be an empty list)
"""
return map(self._decode_value, self.multi.getall(self._encode_key(key)))
def getone(self, key):
"""
Get one value matching the key, raising a KeyError if multiple
values were found.
"""
return self._decode_value(self.multi.getone(self._encode_key(key)))
def mixed(self):
"""
Returns a dictionary where the values are either single
values, or a list of values when a key/value appears more than
once in this dictionary. This is similar to the kind of
dictionary often used to represent the variables in a web
request.
"""
unicode_mixed = {}
for key, value in self.multi.mixed().iteritems():
if isinstance(value, list):
value = [self._decode_value(value) for value in value]
else:
value = self._decode_value(value)
unicode_mixed[self._decode_key(key)] = value
return unicode_mixed
def dict_of_lists(self):
"""
Returns a dictionary where each key is associated with a
list of values.
"""
unicode_dict = {}
for key, value in self.multi.dict_of_lists().iteritems():
value = [self._decode_value(value) for value in value]
unicode_dict[self._decode_key(key)] = value
return unicode_dict
def __delitem__(self, key):
self.multi.__delitem__(self._encode_key(key))
def __contains__(self, key):
return self.multi.__contains__(self._encode_key(key))
has_key = __contains__
def clear(self):
self.multi.clear()
def copy(self):
return UnicodeMultiDict(self.multi.copy(), self.encoding, self.errors)
def setdefault(self, key, default=None):
return self._decode_value(
self.multi.setdefault(self._encode_key(key),
self._encode_value(default)))
def pop(self, key, *args):
return self._decode_value(self.multi.pop(self._encode_key(key), *args))
def popitem(self):
k, v = self.multi.popitem()
return (self._decode_key(k), self._decode_value(v))
def __repr__(self):
items = map('(%r, %r)'.__mod__, _hide_passwd(self.iteritems()))
return '%s([%s])' % (self.__class__.__name__, ', '.join(items))
def __len__(self):
return self.multi.__len__()
##
## All the iteration:
##
def keys(self):
return [self._decode_key(k) for k in self.multi.iterkeys()]
def iterkeys(self):
for k in self.multi.iterkeys():
yield self._decode_key(k)
__iter__ = iterkeys
def items(self):
return [(self._decode_key(k), self._decode_value(v))
for k, v in self.multi.iteritems()]
def iteritems(self):
for k, v in self.multi.iteritems():
yield (self._decode_key(k), self._decode_value(v))
def values(self):
return [self._decode_value(v) for v in self.multi.itervalues()]
def itervalues(self):
for v in self.multi.itervalues():
yield self._decode_value(v)
_dummy = object()
class TrackableMultiDict(MultiDict):
tracker = None
name = None
def __init__(self, *args, **kw):
if '__tracker' in kw:
self.tracker = kw.pop('__tracker')
if '__name' in kw:
self.name = kw.pop('__name')
MultiDict.__init__(self, *args, **kw)
def __setitem__(self, key, value):
MultiDict.__setitem__(self, key, value)
self.tracker(self, key, value)
def add(self, key, value):
MultiDict.add(self, key, value)
self.tracker(self, key, value)
def __delitem__(self, key):
MultiDict.__delitem__(self, key)
self.tracker(self, key)
def clear(self):
MultiDict.clear(self)
self.tracker(self)
def setdefault(self, key, default=None):
result = MultiDict.setdefault(self, key, default)
self.tracker(self, key, result)
return result
def pop(self, key, *args):
result = MultiDict.pop(self, key, *args)
self.tracker(self, key)
return result
def popitem(self):
result = MultiDict.popitem(self)
self.tracker(self)
return result
def update(self, *args, **kwargs):
MultiDict.update(self, *args, **kwargs)
self.tracker(self)
def __repr__(self):
items = map('(%r, %r)'.__mod__, _hide_passwd(self.iteritems()))
return '%s([%s])' % (self.name or self.__class__.__name__, ', '.join(items))
def copy(self):
# Copies shouldn't be tracked
return MultiDict(self)
class NestedMultiDict(MultiDict):
"""
Wraps several MultiDict objects, treating it as one large MultiDict
"""
def __init__(self, *dicts):
self.dicts = dicts
def __getitem__(self, key):
for d in self.dicts:
value = d.get(key, _dummy)
if value is not _dummy:
return value
raise KeyError(key)
def _readonly(self, *args, **kw):
raise KeyError("NestedMultiDict objects are read-only")
__setitem__ = _readonly
add = _readonly
__delitem__ = _readonly
clear = _readonly
setdefault = _readonly
pop = _readonly
popitem = _readonly
update = _readonly
def getall(self, key):
result = []
for d in self.dicts:
result.extend(d.getall(key))
return result
# Inherited:
# getone
# mixed
# dict_of_lists
def copy(self):
return MultiDict(self)
def __contains__(self, key):
for d in self.dicts:
if key in d:
return True
return False
has_key = __contains__
def __len__(self):
v = 0
for d in self.dicts:
v += len(d)
return v
def __nonzero__(self):
for d in self.dicts:
if d:
return True
return False
def items(self):
return list(self.iteritems())
def iteritems(self):
for d in self.dicts:
for item in d.iteritems():
yield item
def values(self):
return list(self.itervalues())
def itervalues(self):
for d in self.dicts:
for value in d.itervalues():
yield value
def keys(self):
return list(self.iterkeys())
def __iter__(self):
for d in self.dicts:
for key in d:
yield key
iterkeys = __iter__
class NoVars(object):
"""
Represents no variables; used when no variables
are applicable.
This is read-only
"""
def __init__(self, reason=None):
self.reason = reason or 'N/A'
def __getitem__(self, key):
raise KeyError("No key %r: %s" % (key, self.reason))
def __setitem__(self, *args, **kw):
raise KeyError("Cannot add variables: %s" % self.reason)
add = __setitem__
setdefault = __setitem__
update = __setitem__
def __delitem__(self, *args, **kw):
raise KeyError("No keys to delete: %s" % self.reason)
clear = __delitem__
pop = __delitem__
popitem = __delitem__
def get(self, key, default=None):
return default
def getall(self, key):
return []
def getone(self, key):
return self[key]
def mixed(self):
return {}
dict_of_lists = mixed
def __contains__(self, key):
return False
has_key = __contains__
def copy(self):
return self
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__,
self.reason)
def __len__(self):
return 0
def __cmp__(self, other):
return cmp({}, other)
def keys(self):
return []
def iterkeys(self):
return iter([])
__iter__ = iterkeys
items = keys
iteritems = iterkeys
values = keys
itervalues = iterkeys
def _hide_passwd(items):
for k, v in items:
if ('password' in k
or 'passwd' in k
or 'pwd' in k
):
yield k, '******'
else:
yield k, v
| Python |
"""
Does parsing of ETag-related headers: If-None-Matches, If-Matches
Also If-Range parsing
"""
from webob.datetime_utils import *
from webob.util import rfc_reference
__all__ = ['AnyETag', 'NoETag', 'ETagMatcher', 'IfRange', 'NoIfRange', 'etag_property']
def etag_property(key, default, rfc_section):
doc = "Gets and sets the %r key in the environment." % key
doc += rfc_reference(key, rfc_section)
doc += " Converts it as a Etag."
def fget(req):
value = req.environ.get(key)
if not value:
return default
elif value == '*':
return AnyETag
else:
return ETagMatcher.parse(value)
def fset(req, val):
if val is None:
req.environ[key] = None
else:
req.environ[key] = str(val)
def fdel(req):
del req.environ[key]
return property(fget, fset, fdel, doc=doc)
class _AnyETag(object):
"""
Represents an ETag of *, or a missing ETag when matching is 'safe'
"""
def __repr__(self):
return '<ETag *>'
def __nonzero__(self):
return False
def __contains__(self, other):
return True
def weak_match(self, other):
return True
def __str__(self):
return '*'
AnyETag = _AnyETag()
class _NoETag(object):
"""
Represents a missing ETag when matching is unsafe
"""
def __repr__(self):
return '<No ETag>'
def __nonzero__(self):
return False
def __contains__(self, other):
return False
def weak_match(self, other):
return False
def __str__(self):
return ''
NoETag = _NoETag()
class ETagMatcher(object):
"""
Represents an ETag request. Supports containment to see if an
ETag matches. You can also use
``etag_matcher.weak_contains(etag)`` to allow weak ETags to match
(allowable for conditional GET requests, but not ranges or other
methods).
"""
def __init__(self, etags, weak_etags=()):
self.etags = etags
self.weak_etags = weak_etags
def __contains__(self, other):
return other in self.etags or other in self.weak_etags
def weak_match(self, other):
if other.lower().startswith('w/'):
other = other[2:]
return other in self.etags or other in self.weak_etags
def __repr__(self):
return '<ETag %s>' % (
' or '.join(self.etags))
def parse(cls, value):
"""
Parse this from a header value
"""
results = []
weak_results = []
while value:
if value.lower().startswith('w/'):
# Next item is weak
weak = True
value = value[2:]
else:
weak = False
if value.startswith('"'):
try:
etag, rest = value[1:].split('"', 1)
except ValueError:
etag = value.strip(' ",')
rest = ''
else:
rest = rest.strip(', ')
else:
if ',' in value:
etag, rest = value.split(',', 1)
rest = rest.strip()
else:
etag = value
rest = ''
if etag == '*':
return AnyETag
if etag:
if weak:
weak_results.append(etag)
else:
results.append(etag)
value = rest
return cls(results, weak_results)
parse = classmethod(parse)
def __str__(self):
# FIXME: should I quote these?
items = list(self.etags)
for weak in self.weak_etags:
items.append('W/%s' % weak)
return ', '.join(items)
class IfRange(object):
"""
Parses and represents the If-Range header, which can be
an ETag *or* a date
"""
def __init__(self, etag=None, date=None):
self.etag = etag
self.date = date
def __repr__(self):
if self.etag is None:
etag = '*'
else:
etag = str(self.etag)
if self.date is None:
date = '*'
else:
date = serialize_date(self.date)
return '<%s etag=%s, date=%s>' % (
self.__class__.__name__,
etag, date)
def __str__(self):
if self.etag is not None:
return str(self.etag)
elif self.date:
return serialize_date(self.date)
else:
return ''
def match(self, etag=None, last_modified=None):
"""
Return True if the If-Range header matches the given etag or last_modified
"""
if self.date is not None:
if last_modified is None:
# Conditional with nothing to base the condition won't work
return False
return last_modified <= self.date
elif self.etag is not None:
if not etag:
return False
return etag in self.etag
return True
def match_response(self, response):
"""
Return True if this matches the given ``webob.Response`` instance.
"""
return self.match(etag=response.etag, last_modified=response.last_modified)
@classmethod
def parse(cls, value):
"""
Parse this from a header value.
"""
date = etag = None
if not value:
etag = NoETag()
elif value and value.endswith(' GMT'):
# Must be a date
date = parse_date(value)
else:
etag = ETagMatcher.parse(value)
return cls(etag=etag, date=date)
class _NoIfRange(object):
"""
Represents a missing If-Range header
"""
def __repr__(self):
return '<Empty If-Range>'
def __str__(self):
return ''
def __nonzero__(self):
return False
def match(self, etag=None, last_modified=None):
return True
def match_response(self, response):
return True
NoIfRange = _NoIfRange()
| Python |
"""To test specific webapp issues."""
import os
import StringIO
import sys
import urllib
import unittest
gae_path = '/usr/local/google_appengine'
sys.path[0:0] = [
gae_path,
os.path.join(gae_path, 'lib', 'django_0_96'),
os.path.join(gae_path, 'lib', 'webob'),
os.path.join(gae_path, 'lib', 'yaml', 'lib'),
os.path.join(gae_path, 'lib', 'protorpc'),
]
from google.appengine.ext import webapp
def add_POST(req, data):
if data is None:
return
env = req.environ
env['REQUEST_METHOD'] = 'POST'
if hasattr(data, 'items'):
data = data.items()
if not isinstance(data, str):
data = urllib.urlencode(data)
env['wsgi.input'] = StringIO.StringIO(data)
env['webob.is_body_seekable'] = True
env['CONTENT_LENGTH'] = str(len(data))
env['CONTENT_TYPE'] = 'application/octet-stream'
class TestWebapp(unittest.TestCase):
def tearDown(self):
webapp.WSGIApplication.active_instance = None
def test_issue_3426(self):
"""When the content-type is 'application/x-www-form-urlencoded' and
POST data is empty the content-type is dropped by Google appengine.
"""
req = webapp.Request.blank('/', environ={
'REQUEST_METHOD': 'GET',
'CONTENT_TYPE': 'application/x-www-form-urlencoded',
})
self.assertEqual(req.method, 'GET')
self.assertEqual(req.content_type, 'application/x-www-form-urlencoded')
if __name__ == '__main__':
unittest.main()
| Python |
'''
Created on May 11, 2013
@author: group 2 - team pflegp, prutsm, steinb, winste
'''
import os
from libthermalraspi.sensors.lm73device import LM73Device
from libthermalraspi.sensors.ad7414 import AD7414Thermometer
from libthermalraspi.sensors.tc74 import TC74Thermometer
from libthermalraspi.sensors.hyt221 import Hyt221
from libthermalraspi.sensors.simulation import CyclicThermometer
from libthermalraspi.sensors.thermo_proxy_itmG2 import ThermoProxy_ItmG2
from libthermalraspi.sensors.thermo_proxy_itmG1 import ThermoProxy
class SensorConfigReader(object):
def __init__(self, filePath ):
self._filePath = filePath
def read(self):
return eval( file( self._filePath ).read(), { 'LM73' : LM73Device
,'AD7414' : AD7414Thermometer
,'TC74' : TC74Thermometer
,'Hyt221' : Hyt221
,'Cyclic' : CyclicThermometer
,'ProxyITMG2': ThermoProxy_ItmG2
,'ProxyITMG1': ThermoProxy
} )
| Python |
class DataStoreStdOut(object):
def get_sample(self, fromDatetime, toDatetime, maxResultCount = None, sensorIDs = None):
assert False, 'cannot get samples from stdout'
def add_sample(self, timestamp, sensorname, temperatur, status):
print timestamp, sensorname, temperatur, status
| Python |
# -*- coding: utf-8 -*-
import abc
"""Abstract base class for SampleCollector for gathering
sensor measurment data"""
class SampleCollector(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def __init__(self, store, sensorList = {}):
"""Collector mit Datenspeicher und Dictionary der abzufragender
Sensoren übergeben.
@param store: Datenbank-Connection
@param sensorList: Dictionary SensorName : SensorInstanz
"""
return
@abc.abstractmethod
def run(self, looper):
"""Messungen starten und per externem iterierbarem Objekt
(looper) Intervall der Messzyklen festlegen.
@param looper: Iterierbares Objekt/List/...
"""
return
| Python |
'''
Created on 29.04.2013
@author: Patrick Groeller
'''
from xml.dom import minidom
from libthermalraspi.database.Measurement import Measurement
class XmlMeasurementService:
def __init__(self, listOfMeasurements):
self.__listOfMeasurements = listOfMeasurements
def toXml(self):
doc = minidom.Document()
root = doc.createElement("response")
doc.appendChild(root)
root.setAttribute('id',"$(id)")
root.setAttribute('from',"$(from)")
root.setAttribute('to',"$(to)")
responseStatus = doc.createElement('status')
root.appendChild(responseStatus)
try:
sensors = doc.createElement('samples')
root.appendChild(sensors)
for measurement in self.__listOfMeasurements:
sensor = doc.createElement('sample')
sensor.setAttribute('sensorname',measurement.getSensorname())
sensor.setAttribute('temperature',str(measurement.getMeasureVal()))
sensor.setAttribute('timestamp',str(measurement.getTimestamp()))
sensor.setAttribute('status',str(measurement.getErrorCode()))
sensors.appendChild(sensor)
responseStatus.setAttribute('error','ok')
except Exception as e:
responseStatus.setAttribute('error','overflow')
#print doc.toprettyxml(encoding='utf-8')
return doc.toprettyxml(encoding='utf-8')
pass
| Python |
# coding: utf-8
from libthermalraspi.services.sampleCollector import SampleCollector
import datetime
import os
class ParallelSampleCollector(SampleCollector):
def __init__(self, store, sensorList):
self.__store = store
if type(sensorList) is dict:
self.__sensorList = sensorList
else:
print "Parameter sensorList ist kein Dictionary"
pass
def run(self, looper):
"""Messungen starten und per externem iterierbarem Objekt
(looper) Intervall der Messzyklen festlegen.
@param looper: Iterierbares Objekt/List/...
"""
for i in looper:
self.__getAllSensorTemperatures()
pass
def __getAllSensorTemperatures(self):
children = {} #dictionary { sensorName: (childPid, pipein) }
for sensorName, sensorInstance in self.__sensorList.items():
pipein, pipeout = os.pipe()
child = os.fork()
if child > 0:
# parent
children[sensorName] = ( child, pipein )
os.close(pipeout)
else:
os.close(pipein)
try:
returnValue = {'temp' : float(sensorInstance.get_temperature()), 'errorCode' : 0 }
except IOError as e:
#self.__logger.exception("Sensor IOError: %s" % e)
returnValue = {'temp' : 0, 'errorCode' : 1}
pass
os.write(pipeout, str(returnValue))
os.close(pipeout)
os._exit(0)
for sensorName, (childPid, pipein) in children.items():
os.waitpid(childPid, 0)
sensorDict = eval(os.read(pipein, 1024))
os.close(pipein)
# Persistiere Messdaten in DB
self.__store.add_sample(datetime.datetime.now(), sensorName, sensorDict['temp'], sensorDict['errorCode'])
pass
| Python |
import struct
from i2c_device import I2CDevice
class BlinkM(I2CDevice):
GO_TO_RGB = '\x6e'
FADE_TO_RGB = '\x63'
FADE_TO_HSB = '\x68'
FADE_TO_RANDOM_RGB = '\x43'
FADE_TO_RANDOM_HSB = '\x48'
PLAY_LIGHT_SCRIPT = '\x70'
STOP_SCRIPT = '\x6f'
SET_FADE_SPEED = '\x66'
SET_TIME_ADJUST = '\x74'
GET_CURRENT_RGB = '\x67'
WRITE_SCRIPT_LINE = '\x57'
READ_SCRIPT_LINE = '\x52'
SET_SCRIPT_LENGTH_AND_REPEATS = '\x4c'
SET_BLINKM_ADDRESS = '\x41'
GET_BLINKM_ADDRESS = '\x61'
GET_BLINKM_FIRMWARE_VERSION = '\x5a'
SET_STARTUP_PARAMETERS = '\x42'
def __init__(self, bus, addr):
I2CDevice.__init__(self, bus, addr)
def go_to_rgb(self, rgb):
self.write(self.GO_TO_RGB)
for color in rgb:
self.write(struct.pack('B', color))
def fade_to_rgb(self, rgb):
self.write(self.FADE_TO_RGB)
for color in rgb:
self.write(struct.pack('B', color))
def fade_to_hsb(self, hsb):
self.write(self.FADE_TO_HSB)
for color in rgb:
self.write(struct.pack('B', color))
def fade_to_random_rgb(self, rgb):
self.write(self.FADE_TO_RANDOM_RGB)
for color in rgb:
self.write(struct.pack('B', color))
def fade_to_random_hsb(self, rgb):
self.write(self.FADE_TO_RANDOM_HSB)
for color in rgb:
self.write(struct.pack('B', color))
def play_light_script(self, script_number):
self.write(self.PLAY_LIGTH_SCRIPT)
self.write(struct.pack('B', script_number))
def stop_script(self):
self.write(self.STOP_SCRIPT)
def set_fade_speed(self, speed):
self.write(self.SET_FADE_SPEED)
self.write(struct.pack('B', speed))
def set_time_adjust(self, time_adjust):
self.write(self.SET_TIME_ADJUST)
self.write(struct.pack('B', time_adjust))
def get_current_rgb(self):
self.write(self.GET_CURRENT_RGB)
return self.__readInt(3)
def set_blinkm_address(self, address):
self.write(self.SET_BLINKM_ADDRESS)
self.write(struct.pack('B'), address)
self.write('\xd0')
self.write('\x0d')
self.write(struct.pack('B'), address)
def get_blinkm_address(self):
self.write(self.GET_BLINKM_ADDRESS)
return self.__readInt(1)
def get_blinkm_firmware_version(self):
self.write(self.GET_BLINKM_FIRMWARE_VERSION)
return self.__readInt(2)
def set_startup_parameters(self, startup_mode, script_number, repeats, fade_speed, time_adjust):
self.write(self.SET_STARTUP_PARAMETERS)
self.write(struct.pack('B', startup_mode))
self.write(struct.pack('B', script_number))
self.write(struct.pack('B', repeats))
self.write(struct.pack('B', fade_speed))
self.write(struct.pack('B', time_adjust))
def __readInt(self, count):
return struct.unpack('B' * count, self.read(count))[:count]
class LightScript(object):
STARTUP = 0
RGB = 1
WHITE_FLASH = 2
RED_FLASH = 3
GREEN_FLASH = 4
BLUE_FLASH = 5
CYAN_FLASH = 6
MAGENTA_FLASH = 7
YELLOW_FLASH = 8
BLACK = 9
HUE_CYCLE = 10
MOOD_LIGHT = 11
VIRTUAL_CANDLE = 12
WATER_REFLECTIONS = 13
OLD_NEON = 14
THE_SEASONS = 15
THUNDERSTORM = 16
STOP_LIGHT = 17
MORSE_CODE = 18
| Python |
import time
import sys
import signal
class ProgramLooper:
def __init__(self, interval_seconds):
self.__interval = interval_seconds
self.__counter = 0
# to be set from signal handler
self.__stop = False
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
signal.signal(signal.SIGQUIT, self.signal_handler)
def __iter__(self):
while not self.__stop:
yield self.__counter
self.__counter += 1
time.sleep(self.__interval)
def signal_handler(self, signal, frame):
print("Shutdown application")
self.__stop = True
| Python |
'''
Created on 04.05.2013
@author: Helmut Kopf
'''
import socket
import threading
import logging
import os
import sys
import datetime
import platform
from xml.dom.minidom import parseString
from libthermalraspi.services.xml_measurement_service import XmlMeasurementService
from libthermalraspi.database import DataStoreInMemory
DEFAULT_HOST = "localhost"
DEFAULT_PORT = 1234
tempServer = None
def getDefaultLogFile():
return os.path.join(os.path.dirname(os.path.abspath( __file__ )), "TempServer.log")
class TempServer(object):
"""
Temperature server
"""
def __init__(self, host, port, datastore ,logfile, loglevel):
self.__sock = None
self.__host = host
self.__port = port
self.__store= datastore
self.__logger = TempServer.__createLogger(logfile, loglevel)
self.__logger.info("Server initialized: Host = %s, Port = %s" % (host, port))
self.__handlers = []
self.__lock = threading.Lock()
self.__disposed = False
def start(self):
try:
print("Server startet at " + str(datetime.datetime.now()) + "...")
self.__logger.info("Server startet...")
self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__sock.bind((self.__host, self.__port))
self.__sock.listen(1)
while True:
conn, _ = self.__sock.accept()
print("new connection accepted at " + str(datetime.datetime.now()) + "...")
self.__realizeResponse(conn)
except socket.error as e:
self.__logger.exception("Socket error: %s" % e)
except socket.herror as e:
self.__logger.exception("Socket address error: %s" % e)
except socket.timeout as e:
self.__logger.exception("Socket timeout error: %s" % e)
except Exception as e:
self.__logger.exception("Unexpected server error: %s" % e)
finally:
self.__closeSocket()
self.__logger.info("Server stopped...")
print("Server stopped at " + str(datetime.datetime.now()) + "...")
##
# Clean up open request handler threads for an
# organized exit:
# 1. Set disposed = True -> Prevent further response handling, all further requests should be skipped
# 2. Acquire lock
# 3. Copy handler list
# 4. Release lock
# 5. From this point the dispose flag suppress further request handling (see __realizeResponse)
# 6. Iterate over handler list copy and wait until all threads has finished
# 7. Close socket
# 8. Done
def dispose(self):
if self.__disposed == False:
# From this point the server doesn't handle response any more:
# __realizeResponse considers __disposed and skip further requests
self.__disposed = True
try:
self.__logger.info("Server handling signal termination at " + str(datetime.datetime.now()) + "...")
# Get open handlers as copy
# Since each thread removes itself by callback function, the original handlers list
# will be modified during following for-loop: Enumerate over a list that changes during
# the iterations is a bad idea...
# Since the remove handler callback acquires a lock it's not possible to lock the whole iteration in#
# dispose -> Deadlock...
# Solution: Since the handlers list can only shrink (no further requests will be handled) we can use a copy
# of current handler list.
handlers = self.__getHandlersAsCopy()
for handler in handlers:
# Wait until each thread has finished
handler.join()
self.__logger.info("Signal termination handling done")
except Exception as e:
self.__logger.exception("Server handling signal termination failed: %s" %e)
finally:
# close socket in each case
self.__closeSocket()
def __closeSocket(self):
try:
if self.__sock != None:
self.__sock.close()
self.__sock = None
except Exception as e:
self.__logger.exception("Close socket failed: %s" %e)
def __realizeResponse(self, connection):
try:
self.__lock.acquire()
# Consider dispose state:
# if intermediately called disposed -> skip response and close connection
if self.__disposed == False:
handler = ResponseHandler(connection, self.__removeHandler, self.__logger,self.__store)
self.__handlers.append(handler)
handler.start()
else:
connection.close()
except Exception as e:
self.__logger.exception("Unexpected error during realizing response: %s" % e)
finally:
self.__lock.release()
def __getHandlersAsCopy(self):
handlers = []
try:
self.__lock.acquire()
handlers = list(self.__handlers)
finally:
self.__lock.release()
return handlers
##
# Callback function, used to remove finished request handlers
# form handlers-list.
def __removeHandler(self, handler):
try:
self.__lock.acquire()
self.__handlers.remove(handler)
self.__logger.info("Handler successfully removed!")
except ValueError as e:
self.__logger.exception("Remove handler failed: %s" %e)
except Exception as e:
self.__logger.exception("Remove handler failed: %s" %e)
finally:
self.__lock.release()
@staticmethod
def __createLogger(logfile, level = logging.INFO):
logger = logging.getLogger("tempserver")
if logfile is None:
pass
else:
fhdlr = logging.FileHandler(logfile)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
fhdlr.setFormatter(formatter)
logger.addHandler(fhdlr)
logger.setLevel(level)
return logger
class ResponseHandler(threading.Thread):
def __init__(self, connection, donecallback, logger, datastore):
threading.Thread.__init__(self)
self.__connection = connection
self.__donecallback = donecallback
self.__logger = logger
self.__store = datastore
def run(self):
try:
self.__logger.info("Response requested...")
(sid, sdtf, sdtt) = self.__getDateRange()
sdtf_dt = datetime.datetime.strptime(sdtf, '%Y-%m-%d %H:%M:%S')
sdtt_dt = datetime.datetime.strptime(sdtt, '%Y-%m-%d %H:%M:%S')
measurementSamples = self.__store.get_samples(sdtf_dt,sdtt_dt)
xmlService = XmlMeasurementService(measurementSamples)
responseData = xmlService.toXml();
self.__connection.send(responseData.replace("$(id)", sid).replace("$(from)", sdtf).replace("$(to)", sdtt).encode('UTF-8'))
except Exception as e:
self.__logger.exception("Response failed by an unexpected error: %s" % e)
finally:
self.__connection.close()
self.__donecallback(self)
def __getDateRange(self):
xml = self.__getXml()
if xml != None:
xi = xml.documentElement.getAttributeNode('id')
xf = xml.documentElement.getAttributeNode('from')
xt = xml.documentElement.getAttributeNode('to')
self.__logger.info("id = " + xi.nodeValue + ", from = " + xf.nodeValue + ", to = " + xt.nodeValue)
return (str(xi.nodeValue), str(xf.nodeValue), str(xt.nodeValue))
else:
self.__logger.info("Xml is null!")
return ""
def __getXml(self):
xmlstr = self.__connection.recv(1024)
if len(xmlstr) > 0:
xml = parseString(xmlstr)
return xml
return None
##
# For linux system install a siganl handler for
# SIGINT and SIGTERM
def addSignalHandler():
if platform.system() != "Windows":
import signal
signal.signal(signal.SIGINT, terminationHandler)
signal.signal(signal.SIGTERM, terminationHandler)
print("Signal handler successfully installed")
##
# Handles termination of http-server
def terminationHandler(signal, frame):
try:
print("Server termination signal handled at " + str(datetime.datetime.now()) + "...")
if tempServer != None:
tempServer.dispose()
finally:
sys.exit(0)
if __name__ == '__main__':
host = DEFAULT_HOST = "localhost"
port = DEFAULT_PORT = 1234
store = DataStoreInMemory()
store.initSomeTestData()
if len(sys.argv) >= 2:
host = str(sys.argv[1])
if len(sys.argv) >= 3:
port = int(sys.argv[2])
if len(sys.argv) >= 4:
store = int(sys.argv[3]) != 0
addSignalHandler()
tempServer = TempServer(host, port, getDefaultLogFile(), logging.INFO, store)
tempServer.start()
| Python |
import os
import smbus
class SMBusDevice(object):
def __init__(self, busno, addr):
self.__bus = smbus.SMBus(busno)
self.__addr = addr
# todo: implement some read/write functions... | Python |
import os
import platform
# Done by HeKo, since i run the first tests for
# LM73 under windows it's necessary to load
# LM73Device successfully!
if platform.system() != "Windows":
import fcntl
class I2CDevice(object):
I2C_SLAVE = 0x0703 # from <linux/i2c-dev.h>
def __init__(self, busno, addr, testCase = False):
if testCase:
return
fd = os.open('/dev/i2c-%d' % busno, os.O_RDWR)
fcntl.ioctl(fd, self.I2C_SLAVE, addr)
self.__fd = fd
pass
def write(self, msg):
os.write(self.__fd, msg)
pass
def read(self, n):
msg = os.read(self.__fd, n)
assert len(msg) == n
return msg
pass
| Python |
#!/usr/bin/python
from thermometer import Thermometer
from libthermalraspi.i2c_device import I2CDevice
import struct
class TC74Thermometer (I2CDevice, Thermometer):
def get_temperature(self):
# "temperature register" according to datasheet (DS)
#response of TC74 is only one byte, no bits must be shifted.
self.write('\x00')
self.write('')
#Attention it doesn't works with sending a 0-Byte. You must send a empty Datapackage (Adress + no data)
tByte = self.read(1)
tRaw = struct.unpack('B', tByte)[0]
#accounting of the temperature based on the temperature table.
temp = tRaw
if(tRaw > (0,127)):
temp = ((0,255) - tRaw) * (-1)
return temp
| Python |
from thermometer import Thermometer
import socket
class ThermoProxy_ItmG2(Thermometer):
def __init__(self):
self.__host = '127.0.0.1'
self.__port = 7000
def get_temperature(self):
self.__s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__s.connect((self.__host, self.__port))
self.send_msg('get_temperature')
return self.__s.recv(1024)
def send_msg(self, msg):
return self.__s.send(msg)
| Python |
from libthermalraspi.i2c_device import I2CDevice
import time
import struct
import sys
class Stds75(I2CDevice):
def __init__(self, bus, addr):
I2CDevice.__init__(self, bus, addr)
def get_temperature(self):
# set register for next operation to 1 (CONF)
self.write('\1')
# read config
config = self.read(1)
config_ = struct.unpack('B', config)[0]
# unset bit 5 and 6 (resolution)
config_ = config_ & 0b10011111
# set bit 5 and 6 to 1 and 0
# 00 = 0.5C, 150ms
# 01 = 0.25C, 300ms
# 10 = 0.125C, 600ms
# 11 = 0.0625C, 1200ms
config_ = config_ | 0b01000000
# write config
self.write(struct.pack('BB', 1, config_))
# set register for next operation to 0 (TEMP)
self.write('\0')
# read measurement results
result = self.read(2)
b1, b2 = struct.unpack('BB', result)
# convert temperature and return it
return b1 + (b2 / 256.0)
| Python |
""" Author: Christopher Barilich - ITM11 """
import struct
from libthermalraspi.i2c_device import I2CDevice
from libthermalraspi.sensors.thermometer import Thermometer
class Stds75(I2CDevice, Thermometer):
'''
Thermal Senser STDS75
default resolution for thermometer is 9 bit (.5)
'''
def __init__(self, bus, addr):
I2CDevice.__init__(self, bus, addr)
def get_temperature(self):
"""
returns the current temperature
if polled too frequently, sensor wont update the temperature register
update cycles in ms:
9 bit: 150ms
10 bit: 300ms
11 bit: 600ms
12 bit: 1200ms
negative values not yet implemented!
"""
# get current resolution
conf = self.read_config()
mask = 0x60 # 0110 0000
res = conf & mask # extract resolution from config register
# get temperature from register
self.write('\x00')
data = self.read(2)
t_raw = struct.unpack('>h', data)
t_raw = t_raw[0]
# msb = 0b11110101
# lsb = 0b11100000
# data = struct.pack('BB', msb, lsb)
# t_raw = struct.unpack('>h', data)
# t_raw = t_raw[0]
# print t_raw
# return t_raw
# t_raw = ((msb << 8) + lsb) # convert to 2 Byte Integer
if (res == 0x00): # 9 bit resolution 0.5 degree
print "res: 0.5"
return (t_raw >> 7) * 0.5
if (res == 0x20): # 10 bit resolution 0.25 degree
print "res: 0.25"
return (t_raw >> 6) * 0.25
if (res == 0x40): # 11 bit resolution 0.125 degree
print "res: 0.125"
return (t_raw >> 5) * 0.125
if (res == 0x60): # l2 bit resolution 0.0625 degree
print "res: 0.0625"
return (t_raw >> 4) * 0.0625
def read_config(self):
'''
read config from config register
returns 1Byte integer
see Datasheet for details
'''
self.write('\x01')
data = self.read(1)
conf = struct.unpack('B', data)
return (conf[0])
def set_resolution(self, res=12):
'''
set resolution in bits: 9, 10, 11, 12 (default) and write to config register
'''
if (res < 9 or res > 12):
raise Exception('Incorrect resolution! set it to 9, 10, 11 or 12')
# reset the resolution bits to 0
oldconf = self.read_config()
reset_mask = 0x9F # 10011111
resetted_res = oldconf & reset_mask
# set the new resolution (6th and 7th bit)
if (res == 9):
new_conf = resetted_res | 0x00 # 0000 0000
if (res == 10):
new_conf = resetted_res | 0x20 # 0010 0000
if (res == 11):
new_conf = resetted_res | 0x40 # 0100 0000
if (res == 12):
new_conf = resetted_res | 0x60 # 0110 0000
self.write_config(new_conf)
def write_config (self, data):
''' write data to config register '''
self.write(struct.pack('BB', 1, data)) # first byte: register, second byte: values
# res = 0.0625 #12 bit resolution
#
# # if positive value
#
# x = t_raw = 0b0001100100010000 # 25,0625
# temp = (x >> 4) * res
#
# # if negative value
# x = t_raw = 0b1111010111100000 #-10,125
# x = ~x+1 # twos complement
# x = x>>4 # remove tailing 0s
# x = (x - 4096) *-1 * res # remove overflow and multiply with resolution
| Python |
import abc
class HumiditySensor(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def get_humidity(self):
return
| Python |
from thermometer import Thermometer
import os
# SWD11 - G2 - 2 - Pflegpeter, Prutsch, Steinbauer, Winkler
class CompositeSensor(Thermometer):
__sensors = []
def __init__(self, sensors=[]):
self.add_sensors(sensors)
def add_sensors(self, sensors):
self.__sensors.extend(sensors)
def get_temperature(self):
child_ids = dict()
pipes = dict()
for index, item in enumerate(self.__sensors):
parentRead, childWrite = os.pipe()
# fork a child process
child = os.fork()
# os.fork(): Return 0 to child process and PID of child to parent process.
if (child == 0):
# write some formatted temp stuff in the pipe
os.write(childWrite, str(item.get_temperature()).zfill(7))
os._exit(0)
else:
# save the pid of all childs
child_ids[index]=child
pipes[index]=parentRead
# close not used filedescriptor
os.close(childWrite)
temperatures = []
for _ in child_ids:
# wait for any child to return
pid, _ = os.wait()
# find child-pid in the dictionary to save corresponding temp
for index,cid in child_ids.items():
if (cid == pid):
# read exact 7 bytes from pipe
temp = os.read(pipes[index],7)
temperatures.append(float(temp))
'''print("%s with pid(%s) sent: %3.3f" % (index,cid,float(temp)))'''
return sum(temperatures) / len(temperatures)
| Python |
# StoreMock sammelt die Messungen, die der ParallelSampleCollector
# auf SensorStub durchfuehrt.
class StoreMock(object):
def __init__(self):
self.__samples = []
def add_sample(self, timestamp, sensorname, temperatur, status):
self.__samples.append((timestamp, sensorname, temperatur, status))
def __iter__(self):
for (timestamp, sensorname, temperatur, status) in self.__samples:
yield (timestamp, sensorname, temperatur, status)
| Python |
from thermometer import Thermometer
import os
class CompositeSensor(Thermometer):
__sensors = []
def __init__(self, sensors=[]):
self.add_sensors(sensors)
def add_sensors(self, sensors):
self.__sensors.extend(sensors)
def get_temperature(self):
imTheFather = True
children = []
temperatures = []
pipein, pipeout = os.pipe()
for sensor in self.__sensors:
child = os.fork()
if child:
children.append(child)
else:
imTheFather = False
os.close(pipein)
os.write(pipeout, str(sensor.get_temperature()) + "\n")
os.close(pipeout)
os._exit(0)
if imTheFather:
pipein_file = os.fdopen(pipein)
for child in children:
os.waitpid(child, 0)
temperatures.append(pipein_file.readline())
temperatures = map(float, temperatures)
return sum(temperatures) / len(temperatures)
| Python |
import abc
# Abstract base class for Thermometer objects
# get_temperature abstract interface
class Thermometer(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def get_temperature(self):
return
pass
| Python |
#SensorStub simuliert die Temperaturmessungen und erhaelt einfach eine Liste
#mit Messwerten, die als Testeingangswerte dienen.
from libthermalraspi.sensors.thermometer import Thermometer
# SensorStub erhaelt eine Liste an Messwerten, die
# in get_temperature zurueck geliefert werden.
# Dieser Test-Stub wird verwendet um im ParallelSampleCollector
# Messungen zu simulieren.
class SensorStub(Thermometer):
def __init__(self, measurements = []):
self.__measurements = measurements;
self.__index = 0
def get_temperature(self):
self.__index = self.__index + 1
if self.__index >= self.__measurements.length:
self.__index = 0
return self.__measurements[self.__index]
| Python |
from thermometer import Thermometer
import itertools
class CyclicThermometer(Thermometer):
def __init__(self, temperatures):
self.__temperatures = itertools.cycle(temperatures)
pass
def get_temperature(self):
return self.__temperatures.next()
pass
| Python |
from libthermalraspi.i2c_device import I2CDevice
from libthermalraspi.sensors.thermometer import Thermometer
from libthermalraspi.sensors.humiditysensor import HumiditySensor
import time
import struct
class Hyt221(I2CDevice, Thermometer, HumiditySensor):
def _perform_measurement(self):
# init -> trigger measurement
self.write('')
# wait until measurement is completed
status = struct.unpack('B', self.read(1))
while(status[0] & 0xC0 != 0): # check the status bits
time.sleep(0.001)
status = struct.unpack('B', self.read(1))
def get_temperature(self):
self._perform_measurement()
# read measurement results
result = self.read(4)
_, _, b2, b3 = struct.unpack('BBBB', result)
# calculating temperature -> see datasheet
b3 = b3 & 0x3F
Traw = b2 << 6 | b3
T = 165.0 * Traw / (2**14) - 40
return T
def get_humidity(self):
self._perform_measurement()
# read measurement results
result = self.read(2)
b0, b1 = struct.unpack('BB', result)
Hraw = b0 << 8 | b1
Hraw = Hraw & 0x3FFF
H = 100.0 * Hraw / (2**14)
return H
| Python |
from thermometer import Thermometer
from libthermalraspi.i2c_device import I2CDevice
import struct
class HypotheticalThermometer(I2CDevice, Thermometer):
def get_temperature(self):
# select register ("temperature register", according to
# hypothetical datasheet) for next operation
self.write('\x00')
# read 2-byte temperature register, and unpack the bytes into
# 2 8-bit integers which are then combined to form a floating
# point number (again according ot datasheet).
msb_lsb = self.read(2)
msb, lsb = struct.unpack('BB', msb_lsb)
return self.__frbozz_hardware_float(msb, lsb)
@staticmethod
def __frbozz_hardware_float(msb, lsb):
return float(((msb << 8) | lsb) >> 4)
| Python |
import os
from thermometer import Thermometer
class CompositeSensor(Thermometer):
__listSensors = []
def __init__(self, sensors = []):
self.__listSensors = sensors
def append_sensor(self, sensor):
self.__listSensors.append(sensor)
def get_temperature(self):
_listTemperatures = []
_childProcesses = []
_r, _w = os.pipe()
for listSensor in self.__listSensors:
# next sensor
newpid = os.fork()
if newpid == 0: # parent process
os.close(_r)
_w = os.fdopen(_w, 'w')
# child: writing temperature
_w.write(str(listSensor.get_temperature())+ "\n")
_w.close()
# child: closing
os._exit(0)
else:
_childProcesses.append(newpid)
os.close(_w)
_r = os.fdopen(_r) # turn r into a file object
for childProcess in _childProcesses:
os.waitpid(childProcess, 0)
temperature = _r.readline()
# parent: read temperature from child process
_listTemperatures.append(temperature)
_listTemperatures = map(float, _listTemperatures)
avgTemperature = sum(_listTemperatures) / len(_listTemperatures)
return avgTemperature | Python |
from thermometer import Thermometer
from libthermalraspi.i2c_device import I2CDevice
import struct
class DS1631SThermometer(I2CDevice, Thermometer):
def get_temperature(self):
self.write('\x4F')
msb_lsb = self.read(2)
msb, lsb = struct.unpack('BB', msb_lsb)
return self.__bitshift_to_hardware_float(msb, lsb)
@staticmethod
def __bitshift_to_hardware_float(msb, lsb):
return msb
return float((((msb << 4) | lsb) >> 8 )/4.0)
| Python |
#!/usr/bin/python
import socket
from libthermalraspi.sensors.thermometer import Thermometer
class ThermoProxy(Thermometer):
"""Connects with a server"""
def __init__(self, host="127.0.0.1", port=1024):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self._sock.connect((host, port))
self._sock.recv(1024)
except:
raise Exception("Host not found.")
def get_temperature(self):
self._sock.send("GET_TEMP")
return float(self._sock.recv(1024))
| Python |
from thermometer import Thermometer
from libthermalraspi.i2c_device import I2CDevice
import struct
class AD7414Thermometer(I2CDevice, Thermometer):
def get_temperature(self):
# "temperature register" according to datasheet (DS)
self.write('\x00')
# Read 2-byte temperature register, unpack the bytes into
# two 8-bit integers which are then combined to a floating
# point number (again according to the DS).
msb_lsb = self.read(2)
msb, lsb = struct.unpack('BB', msb_lsb)
return self.__bitshift_to_hardware_float(msb, lsb)
@staticmethod
def __bitshift_to_hardware_float(msb, lsb):
# 0000 0000 | 0000 0000
# -- msb -- | -- lsb --
# needed bits are: 0000 0000 | 00
# To avoid overwriting the msb
# (most significant byte) with the lsb
# (least significant byte), the msb
# must be bit-shifted 8 bits left and
# be combined with the lsb at the end.
# Following this, both bytes must be
# shifted to the proper position as
# outlined in the DS (cut off the
# right-most six bits) and perform
# Temp-Calculation formular.
return float((((msb << 8) | lsb) >> 6)/4.0)
| Python |
#!/usr/bin/python
from thermometer import Thermometer
from libthermalraspi.i2c_device import I2CDevice
import struct
class TC74Thermometer (I2CDevice, Thermometer):
def get_temperature(self):
# "temperature register" according to datasheet (DS)
#response of TC74 is only one byte, no bits must be shifted.
self.write('\x00')
self.write('')
#Attention it doesn't works with sending a 0-Byte. You must send a empty Datapackage (Adress + no data)
tByte = self.read(1)
tRaw = struct.unpack('B', tByte)[0]
#accounting of the temperature based on the temperature table.
temp = tRaw
if(tRaw > (0,127)):
temp = ((0,255) - tRaw) * (-1)
return temp
| Python |
#!/usr/bin/python
import socket
from libthermalraspi.sensors.thermometer import Thermometer
class ThermoProxy(Thermometer):
"""Connects with a server"""
def __init__(self, host="127.0.0.1", port=1024):
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self._sock.connect((host, port))
self._sock.recv(1024)
except:
raise Exception("Host not found.")
def get_temperature(self):
self._sock.send("GET_TEMP")
return float(self._sock.recv(1024))
| Python |
# -*- coding: utf-8 -*-
import struct
from libthermalraspi.i2c_device import I2CDevice
from libthermalraspi.sensors.thermometer import Thermometer
# Not yet tested on raspberry
# all methods successfully tested against
# datasheet specs.
class LM73Device(Thermometer, I2CDevice):
"""
Author: HeKo, PatGro
"""
def get_temperature(self):
# select Temperature register
self.write('\x00')
# read 2-byte temperature
data = self.read(2)
# Temperature register:
# D15 D14 D13 D12 D11 D10 D9 D8
# SIGN 128C 64C 32C 16C 8C 4C 2C
# D7 D6 D5 D4 D3 D2 D1 D0
# 1C 0.5C 0.25C 0.125C 0.0625C 0.03125C reserved reserved
msb, lsb = struct.unpack('BB', data)
return LM73Device.create_temperature(msb, lsb)
def set_resolution(self, resolution):
#maybe validate input first before reading,
#but atm i have to validate the input in the static method for easy-testing
# select Control/Status register
self.write('\x04')
# read 1-byte
binaryData = self.read(1)
unpackedData =struct.unpack('B', binaryData)
newData = LM73Device.getManipulatedResolution(unpackedData[0], resolution)
self.write(struct.pack('B', newData))
def get_resolution(self):
# select Control/Status register
self.write('\x04')
# read 1-byte
binaryData = self.read(1)
# Control/Status register:
# D7 D6 D5 D4 D3 D2 D1 D0
# TO_DIS RES1 RES2 reserved ALRT_STAT THI TLOW DAV
#
# as we see above: Bit 5 + 6 are responsible for resolution control
# resolution configuration:
# 00: 0.25°C/LSB, 11-bit word (10 bits plus Sign)
# 01: 0.125°C/LSB, 12-bit word (11 bits plus Sign)
# 10: 0.0625°C/LSB, 13-bit word (12 bits plus Sign)
# 11: 0.03125°C/LSB, 14-bit word (13 bits plus Sign)
data = struct.unpack('B', binaryData)
return LM73Device.resolveResolution(data)
@staticmethod
def getManipulatedResolution(data, resolution):
if resolution > 3 or resolution < 0:
raise Exception('Resolution have to be > 0 and < 4. Use the appropriate static values from ResolutionEnum!')
resetResMask = 0xCF #11001111
resetedRes =data & resetResMask
if resolution == ResolutionEnum.ZERO:
return resetedRes
elif resolution == ResolutionEnum.ONE:
return resetedRes | 0x10 # 0001 0000
elif resolution == ResolutionEnum.TWO:
return resetedRes | 0x20 # 0010 0000
elif resolution == ResolutionEnum.THREE:
return resetedRes | 0x30 # 0011 0000
@staticmethod
def resolveResolution(data):
"""
Return Values:
0 for 0.25°C/LSB, 11-bit word (10 bits plus Sign)
1 for 0.125°C/LSB, 12-bit word (11 bits plus Sign)
2 for 0.0625°C/LSB, 13-bit word (12 bits plus Sign)
3 0.03125°C/LSB, 14-bit word (13 bits plus Sign)
"""
mask=0x30 #00110000
return(data[0] & mask)>> 4
@staticmethod
def create_temperature(msb, lsb):
tmp = float(int(((msb & 0x7F) << 1) | (lsb >> 7)))
ii = 1
mask = 0x40
while ii <= 5:
if ((lsb & mask) >> (7 - ii)) != 0:
tmp = tmp + (1.0 / (2 ** ii))
mask = mask >> 1
ii = ii + 1
if (msb & 0x80) != 0:
tmp = tmp * -1
return tmp
"""
This class represents enum-like values. These values are the possible resolution values for our sensor!
@see: getManipulatedResolution
"""
class ResolutionEnum:
ZERO,ONE,TWO,THREE=range(4)
| Python |
from libthermalraspi.smbus_device import SMBusDevice
from libthermalraspi.sensors.thermometer import Thermometer
from libthermalraspi.sensors.humiditysensor import HumiditySensor
import time
class Hyt221SMBus(SMBusDevice, Thermometer, HumiditySensor):
def __init__(self, bus, addr):
SMBusDevice.__init__(self, bus, addr)
def _perform_measurement(self):
# init -> trigger measurement
self.__bus.write_quick(self.__addr)
# wait until measurement is completed
while(self.__bus.read_byte(self.__addr) & 0xC0 != 0): # check status bits
time.sleep(0.001)
def get_temperature(self):
self._perform_measurement()
# read measurement results
result = bytearray(" ")
result = self.__bus.read_i2c_block_data(self.__addr, 0)
# calculating temperature -> see datasheet
result[3] = result[3] & 0x3F
Traw = result[2] << 6 | result[3]
T = 165.0 * Traw / (2**14) - 40
return T
def get_humidity(self):
self._perform_measurement()
# read measurement results
result = bytearray(" ")
result = self.__bus.read_i2c_block_data(self.__addr, 0)
Hraw = result[0] << 8 | result[1]
Hraw = Hraw & 0x3FFF
H = 100.0 * Hraw / (2**14)
return H
| Python |
import hwtest_lm73device
import unittest
suite = unittest.TestSuite()
suite.addTest(hwtest_lm73device.suite)
if __name__ == '__main__':
unittest.TextTestRunner().run(suite)
pass
| Python |
#!/usr/bin/python
from libthermalraspi.database.Measurement import Measurement
from libthermalraspi.database.DataStoreInMemory import DataStoreInMemory
from libthermalraspi.database.DataStoreSQL import DataStoreSQL
import datetime
import unittest
import sqlite3
import os
class Datastoretest(unittest.TestCase):
def setUp_InMemory(self):
self._datastore = DataStoreInMemory()
def setUp_SQL(self):
connection = sqlite3.connect(":memory:")
self._datastore = DataStoreSQL(connection)
setupfile = open(os.path.dirname(__file__)+os.sep+"resources"+os.sep+"test_DataStore" + os.sep + "dbaccesstestsetup.sql",'r')
query = setupfile.read()
setupfile.close()
cursor = connection.cursor()
cursor.executescript(query)
connection.commit()
cursor.close()
def assertResultByFile(self,result,filename):
file = open(os.path.dirname(__file__)+os.sep+"resources"+os.sep+"test_DataStore" + os.sep + filename,'r')
expectedResult = file.read()
file.close()
self.assertEqual(expectedResult,result)
def test_add_sample_SQL(self):
self.setUp_SQL()
self.initDataForSqlStore()
measurements = self._datastore.get_samples()
result = ""
for m in measurements:
result += str(m) + "\n"
self.assertResultByFile(result,"test_addSample.txt")
def test_add_sample_InMemory(self):
self.setUp_InMemory()
self._datastore.initSomeTestData()
measurements = self._datastore.get_samples()
result = ""
for m in measurements:
result += str(m) + "\n"
self.assertResultByFile(result,"test_addSample.txt")
def test_get_samples_SQL(self):
self.setUp_SQL()
self.initDataForSqlStore()
measurements = self._datastore.get_samples(datetime.datetime.strptime("2013-01-30 23:57","%Y-%m-%d %H:%M"),datetime.datetime.strptime("2013-01-30 23:58","%Y-%m-%d %H:%M"))
result = ""
for m in measurements:
result += str(m) + "\n"
self.assertResultByFile(result,"test_get_samples.txt")
def test_get_samples_InMemory(self):
self.setUp_InMemory()
self._datastore.initSomeTestData()
measurements = self._datastore.get_samples(datetime.datetime.strptime("2013-01-30 23:57","%Y-%m-%d %H:%M"),datetime.datetime.strptime("2013-01-30 23:58","%Y-%m-%d %H:%M"))
result = ""
for m in measurements:
result += str(m) + "\n"
self.assertResultByFile(result,"test_get_samples.txt")
def initDataForSqlStore(self):
self._datastore.add_sample(datetime.datetime.strptime("2013-01-30 23:57:38","%Y-%m-%d %H:%M:%S"),"Strawberry",20.12,0)
self._datastore.add_sample(datetime.datetime.strptime("2013-01-30 23:57:37","%Y-%m-%d %H:%M:%S"),"Raspberry",30.0,0)
self._datastore.add_sample(datetime.datetime.strptime("2013-01-30 23:58:36","%Y-%m-%d %H:%M:%S"),"Banana",27.132,1)
self._datastore.add_sample(datetime.datetime.strptime("2013-01-30 23:59:35","%Y-%m-%d %H:%M:%S"),"Blackberry",27.132,0)
suite = unittest.defaultTestLoader.loadTestsFromTestCase(Datastoretest)
if __name__ == '__main__':
unittest.TextTestRunner().run(suite)
pass
| Python |
#!/usr/bin/python
from libthermalraspi.database.SensorDAO import SensorDAO
from libthermalraspi.database.MeasurementDAO import MeasurementDAO
from libthermalraspi.database.Measurement import Measurement
from libthermalraspi.database.DataStoreSQL import DataStoreSQL
import datetime
import unittest
import sqlite3
import os
class DBAccesstest(unittest.TestCase):
def setUp(self):
connection = sqlite3.connect(":memory:") #sqlite3.connect(os.path.dirname(__file__)+os.sep+"resources"+os.sep+"test_dbaccess" + os.sep + "sensordb.sqlite")
self._datastore = DataStoreSQL(connection)
setupfile = open(os.path.dirname(__file__)+os.sep+"resources"+os.sep+"test_dbaccess" + os.sep + "dbaccesstestsetup.sql",'r')
query = setupfile.read()
setupfile.close()
cursor = connection.cursor()
cursor.executescript(query)
connection.commit()
cursor.close()
def assertResultByFile(self,result,filename):
file = open(os.path.dirname(__file__)+os.sep+"resources"+os.sep+"test_dbaccess" + os.sep + filename,'r')
expectedResult = file.read()
file.close()
self.assertEqual(expectedResult,result)
def test_showSensors(self):
sensorlist = SensorDAO.readAllSensors(self._datastore.get_Database())
result = ""
for s in sensorlist:
result += s.getName() + "\n"
self.assertResultByFile(result,"test_showSensors.txt")
def test_insertSampleMeasure(self):
sensors = SensorDAO.readAllSensors(self._datastore.get_Database())
measure = MeasurementDAO(sensors[0].getName(),datetime.datetime.now(),0.0,None)
measure.insert(self._datastore.get_Database())
def test_showAllMeasurements(self):
sensorlist = SensorDAO.readMeasurements(self._datastore.get_Database())
result = ""
for s in sensorlist:
for m in s.getMeasurements():
result += str(m) + "\n"
self.assertResultByFile(result,"test_showAllMeasurements.txt")
def test_ShowMeasurementsOfSensor(self):
sensor = SensorDAO.readAllSensors(self._datastore.get_Database())[0]
sensor.readMyMeasurements(self._datastore.get_Database())
result = ""
for m in sensor.getMeasurements():
result += str(m) + "\n"
self.assertResultByFile(result,"test_ShowMeasurementsOfSensor.txt")
def test_ShowMeasurementsWithFilter(self):
sensorlist = SensorDAO.readMeasurements(self._datastore.get_Database(), \
topCount=1, \
#sensorIDs=[1,3,4], \
fromTimestamp=datetime.datetime.strptime("2013-01-01 00:00","%Y-%m-%d %H:%M"), \
toTimestamp=datetime.datetime.strptime("2013-01-01 23:58","%Y-%m-%d %H:%M"), \
)
result = ""
for s in sensorlist:
for m in s.getMeasurements():
result += str(m) + "\n"
self.assertResultByFile(result,"test_ShowMeasurementsWithFilter.txt")
def test_addSample(self):
self._datastore.add_sample(datetime.datetime.strptime("2013-01-30 23:59","%Y-%m-%d %H:%M"),"testsensor",33.33,"Mein Error")
measurements = self._datastore.get_samples()
result = ""
for m in measurements:
result += str(m) + "\n"
self.assertResultByFile(result,"test_addSample.txt")
def test_get_samples(self):
measurements = self._datastore.get_samples(datetime.datetime.strptime("2013-01-01 00:00","%Y-%m-%d %H:%M"),datetime.datetime.strptime("2013-01-01 23:58","%Y-%m-%d %H:%M"))
result = ""
for m in measurements:
result += str(m) + "\n"
self.assertResultByFile(result,"test_get_samples.txt")
suite = unittest.defaultTestLoader.loadTestsFromTestCase(DBAccesstest)
if __name__ == '__main__':
unittest.TextTestRunner().run(suite)
pass
| Python |
#!/usr/bin/python
from libthermalraspi.sensors.simulation import CyclicThermometer
from libthermalraspi.sensors.thermometer import Thermometer
import os
import sys
_listSensors = []
_listSensors.append(CyclicThermometer([5]))
_listSensors.append(CyclicThermometer([10]))
_listSensors.append(CyclicThermometer([45]))
_listTemperatures = []
_childProcesses = []
_r, _w = os.pipe()
for listSensor in _listSensors:
print("next sensor")
newpid = os.fork()
if newpid == 0: # parent process
os.close(_r)
_w = os.fdopen(_w, 'w')
print "child: writing - " + str(listSensor.get_temperature())
_w.write(str(listSensor.get_temperature())+ "\n")
_w.close()
print "child: closing"
os._exit(0)
else:
_childProcesses.append(newpid)
os.close(_w)
_r = os.fdopen(_r) # turn r into a file object
for childProcess in _childProcesses:
os.waitpid(childProcess, 0)
temperature = _r.readline()
print "parent: reading from " + str(childProcess) + " => temperature is " + temperature
_listTemperatures.append(temperature)
_listTemperatures = map(float, _listTemperatures)
avgTemperature = sum(_listTemperatures) / len(_listTemperatures)
print "****************************************"
print "Durchschnittstemperatur betraegt: " + str(avgTemperature)
print "****************************************"
| Python |
#!usr/bin/python
from libthermalraspi.sensors.stds75 import Stds75
t = Stds75(1, 0x4e)
print t.get_temperature()
| Python |
import test_simulation
import test_lm73device
import test_xmlMeasurementService
import test_compositeSensor_g2_3
import test_compositeThermometer_SWD11G2_2
#import test_SensorConfigReader
import unittest
suite = unittest.TestSuite()
suite.addTest(test_simulation.suite)
suite.addTest(test_lm73device.suite)
suite.addTest(test_xmlMeasurementService.suite)
suite.addTest(test_compositeSensor_g2_3.suite)
suite.addTest(test_compositeThermometer_SWD11G2_2.suite)
#suite.addTest(test_SensorConfigReader.suite)
if __name__ == '__main__':
unittest.TextTestRunner().run(suite)
pass
| Python |
'''
Created on 22.04.2013
@author: Helmut
'''
from libthermalraspi.sensors.lm73device import LM73Device
import unittest
class LM73DeviceHWTest(unittest.TestCase):
def test__resolution(self):
dev = LM73Device(1, 0x48)
res = dev.get_resolution()
# todo...
#dev.set_resolution(res)
# verify...
suite = unittest.defaultTestLoader.loadTestsFromTestCase(LM73DeviceHWTest)
if __name__ == '__main__':
unittest.TextTestRunner().run(suite)
pass
| Python |
import datetime
from libthermalraspi.database.DataStore import DataStore
from libthermalraspi.database.Measurement import Measurement
class DataStoreInMemory(DataStore):
def __init__(self):
self._measures = []
def get_samples(self,fromTimestamp=None,toTimestamp=None):
return sorted( \
sorted( \
(filter(lambda m: (toTimestamp==None or m.getTimestamp() <= toTimestamp) and (fromTimestamp==None or m.getTimestamp() >= fromTimestamp),self._measures)) \
,key=lambda m: m.getTimestamp(),reverse=True) \
,key=lambda m: m.getSensorname())
def add_sample(self,timestamp, sensorname, temperatur, status):
self._measures.append(Measurement(sensorname, timestamp, temperatur, status))
def initSomeTestData(self):
self.add_sample(datetime.datetime.strptime("2013-01-30 23:57:38","%Y-%m-%d %H:%M:%S"),"Strawberry",20.12,0)
self.add_sample(datetime.datetime.strptime("2013-01-30 23:57:37","%Y-%m-%d %H:%M:%S"),"Raspberry",30.0,0)
self.add_sample(datetime.datetime.strptime("2013-01-30 23:58:36","%Y-%m-%d %H:%M:%S"),"Banana",27.132,1)
self.add_sample(datetime.datetime.strptime("2013-01-30 23:59:35","%Y-%m-%d %H:%M:%S"),"Blackberry",27.132,0) | Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.