本文整理汇总了Python中indico.web.flask.util.ResponseUtil类的典型用法代码示例。如果您正苦于以下问题:Python ResponseUtil类的具体用法?Python ResponseUtil怎么用?Python ResponseUtil使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ResponseUtil类的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self):
self._responseUtil = ResponseUtil()
self._requestStarted = False
self._aw = AccessWrapper() # Fill in the aw instance with the current information
self._target = None
self._reqParams = {}
self._startTime = None
self._endTime = None
self._tempFilesToDelete = []
self._redisPipeline = None
self._doProcess = True # Flag which indicates whether the RH process
示例2: __init__
def __init__(self, req=None):
"""Constructor. Initialises the rh setting up basic attributes so it is
able to process the request.
Parameters:
req - OBSOLETE, MUST BE NONE
"""
RequestHandlerBase.__init__(self, req)
self._responseUtil = ResponseUtil()
self._requestStarted = False
self._aw = AccessWrapper() #Fill in the aw instance with the current information
self._target = None
self._reqParams = {}
self._startTime = None
self._endTime = None
self._tempFilesToDelete = []
self._redisPipeline = None
self._doProcess = True #Flag which indicates whether the RH process
示例3: RH
class RH(RequestHandlerBase):
"""This class is the base for request handlers of the application. A request
handler will be instantiated when a web request arrives to mod_python;
the mp layer will forward the request to the corresponding request
handler which will know which action has to be performed (displaying a
web page or performing some operation and redirecting to another page).
Request handlers will be responsible for parsing the parameters coming
from a mod_python request, handle the errors which occurred during the
action to perform, managing the sessions, checking security for each
operation (thus they implement the access control system of the web
interface).
It is important to encapsulate all this here as in case of changing
the web application framework we'll just need to adapt this layer (the
rest of the system wouldn't need any change).
Attributes:
_uh - (URLHandler) Associated URLHandler which points to the
current rh.
_req - UNUSED/OBSOLETE, always None
_requestStarted - (bool) Flag which tells whether a DB transaction
has been started or not.
_aw - (AccessWrapper) Current access information for the rh.
_target - (Locable) Reference to an object which is the destination
of the operations needed to carry out the rh. If set it must
provide (through the standard Locable interface) the methods
to get the url parameters in order to reproduce the access to
the rh.
_reqParams - (dict) Dictionary containing the received HTTP
parameters (independently of the method) transformed into
python data types. The key is the parameter name while the
value should be the received paramter value (or values).
"""
_tohttps = False # set this value to True for the RH that must be HTTPS when there is a BaseSecureURL
_doNotSanitizeFields = []
_isMobile = True # this value means that the generated web page can be mobile
HTTP_VERBS = frozenset(('GET', 'POST', 'PUT', 'DELETE'))
def __init__(self):
self._responseUtil = ResponseUtil()
self._requestStarted = False
self._aw = AccessWrapper() # Fill in the aw instance with the current information
self._target = None
self._reqParams = {}
self._startTime = None
self._endTime = None
self._tempFilesToDelete = []
self._redisPipeline = None
self._doProcess = True # Flag which indicates whether the RH process
# must be carried out; this is useful for
# the checkProtection methods when they
# detect that an immediate redirection is
# needed
# Methods =============================================================
def getTarget(self):
return self._target
def isMobile(self):
return self._isMobile
def _setSessionUser(self):
self._aw.setUser(session.user)
@property
def csrf_token(self):
return session.csrf_token
def _getRequestParams(self):
return self._reqParams
def getRequestParams(self):
return self._getRequestParams()
def _disableCaching(self):
"""Disables caching"""
# IE doesn't seem to like 'no-cache' Cache-Control headers...
if request.user_agent.browser == 'msie':
# actually, the only way to safely disable caching seems to be this one
self._responseUtil.headers["Cache-Control"] = "private"
self._responseUtil.headers["Expires"] = "-1"
else:
self._responseUtil.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
self._responseUtil.headers["Pragma"] = "no-cache"
def _redirect(self, targetURL, status=303):
targetURL = str(targetURL)
if "\r" in targetURL or "\n" in targetURL:
raise MaKaCError(_("http header CRLF injection detected"))
self._responseUtil.redirect = (targetURL, status)
def _changeRH(self, rh, params):
"""Calls the specified RH after processing this one"""
self._responseUtil.call = lambda: rh().process(params)
def _checkHttpsRedirect(self):
"""If HTTPS must be used but it is not, redirect!"""
if self.use_https() and not request.is_secure:
#.........这里部分代码省略.........
示例4: handler
def handler(prefix, path):
path = posixpath.join('/', prefix, path)
ContextManager.destroy()
clearCache() # init fossil cache
logger = Logger.get('httpapi')
if request.method == 'POST':
# Convert POST data to a query string
queryParams = dict((key, value.encode('utf-8')) for key, value in request.form.iteritems())
query = urllib.urlencode(queryParams)
else:
# Parse the actual query string
queryParams = dict((key, value.encode('utf-8')) for key, value in request.args.iteritems())
query = request.query_string
dbi = DBMgr.getInstance()
dbi.startRequest()
minfo = HelperMaKaCInfo.getMaKaCInfoInstance()
if minfo.getRoomBookingModuleActive():
Factory.getDALManager().connect()
apiKey = get_query_parameter(queryParams, ['ak', 'apikey'], None)
cookieAuth = get_query_parameter(queryParams, ['ca', 'cookieauth'], 'no') == 'yes'
signature = get_query_parameter(queryParams, ['signature'])
timestamp = get_query_parameter(queryParams, ['timestamp'], 0, integer=True)
noCache = get_query_parameter(queryParams, ['nc', 'nocache'], 'no') == 'yes'
pretty = get_query_parameter(queryParams, ['p', 'pretty'], 'no') == 'yes'
onlyPublic = get_query_parameter(queryParams, ['op', 'onlypublic'], 'no') == 'yes'
onlyAuthed = get_query_parameter(queryParams, ['oa', 'onlyauthed'], 'no') == 'yes'
oauthToken = 'oauth_token' in queryParams
# Get our handler function and its argument and response type
hook, dformat = HTTPAPIHook.parseRequest(path, queryParams)
if hook is None or dformat is None:
raise NotFound
# Disable caching if we are not just retrieving data (or the hook requires it)
if request.method == 'POST' or hook.NO_CACHE:
noCache = True
ak = error = result = None
ts = int(time.time())
typeMap = {}
responseUtil = ResponseUtil()
try:
used_session = None
if cookieAuth:
used_session = session
if not used_session.user: # ignore guest sessions
used_session = None
if apiKey or oauthToken or not used_session:
if not oauthToken:
# Validate the API key (and its signature)
ak, enforceOnlyPublic = checkAK(apiKey, signature, timestamp, path, query)
if enforceOnlyPublic:
onlyPublic = True
# Create an access wrapper for the API key's user
aw = buildAW(ak, onlyPublic)
else: # Access Token (OAuth)
at = OAuthUtils.OAuthCheckAccessResource()
aw = buildAW(at, onlyPublic)
# Get rid of API key in cache key if we did not impersonate a user
if ak and aw.getUser() is None:
cacheKey = normalizeQuery(path, query,
remove=('_', 'ak', 'apiKey', 'signature', 'timestamp', 'nc', 'nocache',
'oa', 'onlyauthed'))
else:
cacheKey = normalizeQuery(path, query,
remove=('_', 'signature', 'timestamp', 'nc', 'nocache', 'oa', 'onlyauthed'))
if signature:
# in case the request was signed, store the result under a different key
cacheKey = 'signed_' + cacheKey
else:
# We authenticated using a session cookie.
if Config.getInstance().getCSRFLevel() >= 2:
token = request.headers.get('X-CSRF-Token', get_query_parameter(queryParams, ['csrftoken']))
if used_session.csrf_protected and used_session.csrf_token != token:
raise HTTPAPIError('Invalid CSRF token', 403)
aw = AccessWrapper()
if not onlyPublic:
aw.setUser(used_session.user)
userPrefix = 'user-' + used_session.user.getId() + '_'
cacheKey = userPrefix + normalizeQuery(path, query,
remove=('_', 'nc', 'nocache', 'ca', 'cookieauth', 'oa', 'onlyauthed',
'csrftoken'))
# Bail out if the user requires authentication but is not authenticated
if onlyAuthed and not aw.getUser():
raise HTTPAPIError('Not authenticated', 403)
addToCache = not hook.NO_CACHE
cache = GenericCache('HTTPAPI')
cacheKey = RE_REMOVE_EXTENSION.sub('', cacheKey)
if not noCache:
obj = cache.get(cacheKey)
if obj is not None:
result, extra, ts, complete, typeMap = obj
addToCache = False
if result is None:
# Perform the actual exporting
#.........这里部分代码省略.........
示例5: handler
def handler(prefix, path):
path = posixpath.join('/', prefix, path)
ContextManager.destroy()
clearCache() # init fossil cache
logger = Logger.get('httpapi')
if request.method == 'POST':
# Convert POST data to a query string
queryParams = dict((key, value.encode('utf-8')) for key, value in request.form.iteritems())
query = urllib.urlencode(queryParams)
else:
# Parse the actual query string
queryParams = dict((key, value.encode('utf-8')) for key, value in request.args.iteritems())
query = request.query_string
dbi = DBMgr.getInstance()
dbi.startRequest()
apiKey = get_query_parameter(queryParams, ['ak', 'apikey'], None)
cookieAuth = get_query_parameter(queryParams, ['ca', 'cookieauth'], 'no') == 'yes'
signature = get_query_parameter(queryParams, ['signature'])
timestamp = get_query_parameter(queryParams, ['timestamp'], 0, integer=True)
noCache = get_query_parameter(queryParams, ['nc', 'nocache'], 'no') == 'yes'
pretty = get_query_parameter(queryParams, ['p', 'pretty'], 'no') == 'yes'
onlyPublic = get_query_parameter(queryParams, ['op', 'onlypublic'], 'no') == 'yes'
onlyAuthed = get_query_parameter(queryParams, ['oa', 'onlyauthed'], 'no') == 'yes'
scope = 'read:legacy_api' if request.method == 'GET' else 'write:legacy_api'
try:
oauth_valid, oauth_request = oauth.verify_request([scope])
if not oauth_valid and oauth_request and oauth_request.error_message != 'Bearer token not found.':
raise BadRequest('OAuth error: {}'.format(oauth_request.error_message))
elif g.get('received_oauth_token') and oauth_request.error_message == 'Bearer token not found.':
raise BadRequest('OAuth error: Invalid token')
except ValueError:
# XXX: Dirty hack to workaround a bug in flask-oauthlib that causes it
# not to properly urlencode request query strings
# Related issue (https://github.com/lepture/flask-oauthlib/issues/213)
oauth_valid = False
# Get our handler function and its argument and response type
hook, dformat = HTTPAPIHook.parseRequest(path, queryParams)
if hook is None or dformat is None:
raise NotFound
# Disable caching if we are not just retrieving data (or the hook requires it)
if request.method == 'POST' or hook.NO_CACHE:
noCache = True
ak = error = result = None
ts = int(time.time())
typeMap = {}
responseUtil = ResponseUtil()
try:
used_session = None
if cookieAuth:
used_session = session
if not used_session.user: # ignore guest sessions
used_session = None
if apiKey or oauth_valid or not used_session:
if not oauth_valid:
# Validate the API key (and its signature)
ak, enforceOnlyPublic = checkAK(apiKey, signature, timestamp, path, query)
if enforceOnlyPublic:
onlyPublic = True
# Create an access wrapper for the API key's user
aw = buildAW(ak, onlyPublic)
else: # Access Token (OAuth)
at = load_token(oauth_request.access_token.access_token)
aw = buildAW(at, onlyPublic)
# Get rid of API key in cache key if we did not impersonate a user
if ak and aw.getUser() is None:
cacheKey = normalizeQuery(path, query,
remove=('_', 'ak', 'apiKey', 'signature', 'timestamp', 'nc', 'nocache',
'oa', 'onlyauthed'))
else:
cacheKey = normalizeQuery(path, query,
remove=('_', 'signature', 'timestamp', 'nc', 'nocache', 'oa', 'onlyauthed'))
if signature:
# in case the request was signed, store the result under a different key
cacheKey = 'signed_' + cacheKey
else:
# We authenticated using a session cookie.
if Config.getInstance().getCSRFLevel() >= 2:
token = request.headers.get('X-CSRF-Token', get_query_parameter(queryParams, ['csrftoken']))
if used_session.csrf_protected and used_session.csrf_token != token:
raise HTTPAPIError('Invalid CSRF token', 403)
aw = AccessWrapper()
if not onlyPublic:
aw.setUser(used_session.avatar)
userPrefix = 'user-{}_'.format(used_session.user.id)
cacheKey = userPrefix + normalizeQuery(path, query,
remove=('_', 'nc', 'nocache', 'ca', 'cookieauth', 'oa', 'onlyauthed',
'csrftoken'))
# Bail out if the user requires authentication but is not authenticated
if onlyAuthed and not aw.getUser():
raise HTTPAPIError('Not authenticated', 403)
addToCache = not hook.NO_CACHE
cache = GenericCache('HTTPAPI')
#.........这里部分代码省略.........
示例6: RH
class RH(RequestHandlerBase):
"""This class is the base for request handlers of the application. A request
handler will be instantiated when a web request arrives to mod_python;
the mp layer will forward the request to the corresponding request
handler which will know which action has to be performed (displaying a
web page or performing some operation and redirecting to another page).
Request handlers will be responsible for parsing the parameters coming
from a mod_python request, handle the errors which occurred during the
action to perform, managing the sessions, checking security for each
operation (thus they implement the access control system of the web
interface).
It is important to encapsulate all this here as in case of changing
the web application framework we'll just need to adapt this layer (the
rest of the system wouldn't need any change).
Attributes:
_uh - (URLHandler) Associated URLHandler which points to the
current rh.
_req - UNUSED/OBSOLETE, always None
_requestStarted - (bool) Flag which tells whether a DB transaction
has been started or not.
_aw - (AccessWrapper) Current access information for the rh.
_target - (Locable) Reference to an object which is the destination
of the operations needed to carry out the rh. If set it must
provide (through the standard Locable interface) the methods
to get the url parameters in order to reproduce the access to
the rh.
_reqParams - (dict) Dictionary containing the received HTTP
parameters (independently of the method) transformed into
python data types. The key is the parameter name while the
value should be the received paramter value (or values).
"""
_tohttps = False # set this value to True for the RH that must be HTTPS when there is a BaseSecureURL
_doNotSanitizeFields = []
_isMobile = True # this value means that the generated web page can be mobile
HTTP_VERBS = frozenset(('GET', 'POST', 'PUT', 'DELETE'))
def __init__(self, req=None):
"""Constructor. Initialises the rh setting up basic attributes so it is
able to process the request.
Parameters:
req - OBSOLETE, MUST BE NONE
"""
RequestHandlerBase.__init__(self, req)
self._responseUtil = ResponseUtil()
self._requestStarted = False
self._aw = AccessWrapper() #Fill in the aw instance with the current information
self._target = None
self._reqParams = {}
self._startTime = None
self._endTime = None
self._tempFilesToDelete = []
self._redisPipeline = None
self._doProcess = True #Flag which indicates whether the RH process
# must be carried out; this is useful for
# the checkProtection methods when they
# detect that an inmediate redirection is
# needed
# Methods =============================================================
def getTarget(self):
return self._target
def isMobile(self):
return self._isMobile
def _setSessionUser(self):
self._aw.setUser(session.user)
@property
def csrf_token(self):
return session.csrf_token
def _getRequestParams(self):
return self._reqParams
def getRequestParams(self):
return self._getRequestParams()
def _disableCaching(self):
"""Disables caching"""
# IE doesn't seem to like 'no-cache' Cache-Control headers...
if request.user_agent.browser == 'msie':
# actually, the only way to safely disable caching seems to be this one
self._responseUtil.headers["Cache-Control"] = "private"
self._responseUtil.headers["Expires"] = "-1"
else:
self._responseUtil.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
self._responseUtil.headers["Pragma"] = "no-cache"
def _redirect(self, targetURL, status=303):
targetURL = str(targetURL)
if "\r" in targetURL or "\n" in targetURL:
raise MaKaCError(_("http header CRLF injection detected"))
self._responseUtil.redirect = (targetURL, status)
#.........这里部分代码省略.........
示例7: __init__
def __init__(self):
self.commit = True
self._responseUtil = ResponseUtil()
示例8: RH
class RH(object):
NOT_SANITIZED_FIELDS = frozenset()
CSRF_ENABLED = True # require a csrf_token when accessing the RH with anything but GET
EVENT_FEATURE = None # require a certain event feature when accessing the RH. See `EventFeature` for details
DENY_FRAMES = False # whether to send an X-Frame-Options:DENY header
CHECK_HTML = False # whether to run the legacy HTML sanitizer
#: A dict specifying how the url should be normalized.
#: `args` is a dictionary mapping view args keys to callables
#: used to retrieve the expected value for those arguments if they
#: are present in the request's view args.
#: `locators` is a set of callables returning objects with locators.
#: `preserved_args` is a set of view arg names which will always
#: be copied from the current request if present.
#: The callables are always invoked with a single `self` argument
#: containing the RH instance.
#: `endpoint` may be used to specify the endpoint used to build
#: the URL in case of a redirect. Usually this should not be used
#: in favor of ``request.endpoint`` being used if no custom endpoint
#: is set.
#: Arguments specified in the `defaults` of any rule matching the
#: current endpoint are always excluded when checking if the args
#: match or when building a new URL.
#: If the view args built from the returned objects do not match
#: the request's view args, a redirect is issued automatically.
#: If the request is not using GET/HEAD, a 404 error is raised
#: instead of a redirect since such requests cannot be redirected
#: but executing them on the wrong URL may pose a security risk in
#: case and of the non-relevant URL segments is used for access
#: checks.
normalize_url_spec = {
'args': {},
'locators': set(),
'preserved_args': set(),
'endpoint': None
}
def __init__(self):
self.commit = True
self._responseUtil = ResponseUtil()
# Methods =============================================================
def validate_json(self, schema, json=None):
"""Validates the request's JSON payload using a JSON schema.
:param schema: The JSON schema used for validation.
:param json: The JSON object (defaults to ``request.json``)
:raises BadRequest: if the JSON validation failed
"""
if json is None:
json = request.json
try:
jsonschema.validate(json, schema)
except jsonschema.ValidationError as e:
raise BadRequest('Invalid JSON payload: {}'.format(e.message))
@property
def csrf_token(self):
return session.csrf_token if session.csrf_protected else ''
def normalize_url(self):
"""Performs URL normalization.
This uses the :attr:`normalize_url_spec` to check if the URL
params are what they should be and redirects or fails depending
on the HTTP method used if it's not the case.
:return: ``None`` or a redirect response
"""
if current_app.debug and self.normalize_url_spec is RH.normalize_url_spec:
# in case of ``class SomeRH(RH, MixinWithNormalization)``
# the default value from `RH` overwrites the normalization
# rule from ``MixinWithNormalization``. this is never what
# the developer wants so we fail if it happens. the proper
# solution is ``class SomeRH(MixinWithNormalization, RH)``
cls = next((x
for x in inspect.getmro(self.__class__)
if (x is not RH and x is not self.__class__ and hasattr(x, 'normalize_url_spec') and
getattr(x, 'normalize_url_spec', None) is not RH.normalize_url_spec)),
None)
if cls is not None:
raise Exception('Normalization rule of {} in {} is overwritten by base RH. Put mixins with class-level '
'attributes on the left of the base class'.format(cls, self.__class__))
if not self.normalize_url_spec or not any(self.normalize_url_spec.itervalues()):
return
spec = {
'args': self.normalize_url_spec.get('args', {}),
'locators': self.normalize_url_spec.get('locators', set()),
'preserved_args': self.normalize_url_spec.get('preserved_args', set()),
'endpoint': self.normalize_url_spec.get('endpoint', None)
}
# Initialize the new view args with preserved arguments (since those would be lost otherwise)
new_view_args = {k: v for k, v in request.view_args.iteritems() if k in spec['preserved_args']}
# Retrieve the expected values for all simple arguments (if they are currently present)
for key, getter in spec['args'].iteritems():
if key in request.view_args:
new_view_args[key] = getter(self)
# Retrieve the expected values from locators
prev_locator_args = {}
#.........这里部分代码省略.........