本文整理汇总了Python中pyramid.compat.ascii_native_函数的典型用法代码示例。如果您正苦于以下问题:Python ascii_native_函数的具体用法?Python ascii_native_怎么用?Python ascii_native_使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ascii_native_函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_conceptscheme_concepts
def get_conceptscheme_concepts(self):
scheme_id = self.request.matchdict['scheme_id']
provider = self.skos_registry.get_provider(scheme_id)
if not provider:
return HTTPNotFound()
query = {}
mode = self.request.params.get('mode', 'default')
sort = self.request.params.get('sort', None)
label = self.request.params.get('label', None)
postprocess = False
if mode == 'dijitFilteringSelect' and label == '':
concepts = []
else:
if label not in [None, '*', '']:
if mode == 'dijitFilteringSelect' and '*' in label:
postprocess = True
query['label'] = label.replace('*', '')
else:
query['label'] = label
type = self.request.params.get('type', None)
if type in ['concept', 'collection']:
query['type'] = type
coll = self.request.params.get('collection', None)
if coll is not None:
query['collection'] = {'id': coll, 'depth': 'all'}
concepts = provider.find(query)
# We need to refine results further
if postprocess:
if label.startswith('*') and label.endswith('*'):
concepts = [c for c in concepts if label[1:-1] in c['label']]
elif label.endswith('*'):
concepts = [c for c in concepts if c['label'].startswith(label[0:-1])]
elif label.startswith('*'):
concepts = [c for c in concepts if c['label'].endswith(label[1:])]
#Result sorting
if sort:
sort_desc = (sort[0:1] == '-')
sort = sort[1:] if sort[0:1] in ['-', '+'] else sort
sort = sort.strip() # dojo store does not encode '+'
if (len(concepts) > 0) and (sort in concepts[0]):
concepts.sort(key=lambda concept: concept[sort], reverse=sort_desc)
# Result paging
paging_data = False
if 'Range' in self.request.headers:
paging_data = parse_range_header(self.request.headers['Range'])
count = len(concepts)
if not paging_data:
paging_data = {
'start': 0,
'finish': count - 1 if count > 0 else 0,
'number': count
}
cslice = concepts[paging_data['start']:paging_data['finish']+1]
self.request.response.headers[ascii_native_('Content-Range')] = \
ascii_native_('items %d-%d/%d' % (
paging_data['start'], paging_data['finish'], count
))
return cslice
示例2: test_get_uri_no_uri
def test_get_uri_no_uri(self):
res = self.testapp.get(
'/uris',
{},
{ascii_native_('Accept'): ascii_native_('application/json')},
status=400
)
self.assertEqual('400 Bad Request', res.status)
示例3: test_get_conceptschemes_json
def test_get_conceptschemes_json(self):
res = self.testapp.get(
'/conceptschemes',
{},
{ascii_native_('Accept'): ascii_native_('application/json')})
self.assertEqual('200 OK', res.status)
self.assertIn('application/json', res.headers['Content-Type'])
data = json.loads(res.body.decode('utf-8'))
self.assertIsInstance(data, list)
self.assertEqual(len(data), 1)
示例4: test_get_conceptscheme_concepts_search_dfs_all
def test_get_conceptscheme_concepts_search_dfs_all(self):
res = self.testapp.get(
'/conceptschemes/TREES/c',
{'mode': 'dijitFilteringSelect', 'label': '*'},
{ascii_native_('Accept'): ascii_native_('application/json')}
)
self.assertEqual('200 OK', res.status)
self.assertIn('application/json', res.headers['Content-Type'])
data = json.loads(res.body.decode('utf-8'))
self.assertIsInstance(data, list)
self.assertEqual(3, len(data))
示例5: test_get_uri_deprecated_way
def test_get_uri_deprecated_way(self):
res1 = self.testapp.get(
'/uris?uri=http://python.com/trees',
{},
{ascii_native_('Accept'): ascii_native_('application/json')}
)
res2 = self.testapp.get(
'/uris/http://python.com/trees',
{},
{ascii_native_('Accept'): ascii_native_('application/json')}
)
self.assertEqual(res1.body, res2.body)
示例6: test_get_conceptschemes_trees_cs_json
def test_get_conceptschemes_trees_cs_json(self):
res = self.testapp.get(
'/conceptschemes/TREES/c',
{},
{ascii_native_('Accept'): ascii_native_('application/json')}
)
self.assertEqual('200 OK', res.status)
self.assertIn('application/json', res.headers['Content-Type'])
self.assertIsInstance(res.headers['Content-Range'], string_types)
self.assertEqual('items 0-2/3', res.headers['Content-Range'])
data = json.loads(res.body.decode('utf-8'))
self.assertIsInstance(data, list)
self.assertEqual(len(data), 3)
示例7: test_get_uri_cs_json
def test_get_uri_cs_json(self):
res = self.testapp.get(
'/uris?uri=http://python.com/trees',
{},
{ascii_native_('Accept'): ascii_native_('application/json')}
)
self.assertEqual('200 OK', res.status)
self.assertIn('application/json', res.headers['Content-Type'])
data = json.loads(res.body.decode('utf-8'))
self.assertIsInstance(data, dict)
self.assertIn('uri', data)
self.assertIn('id', data)
self.assertIn('type', data)
示例8: test_get_top_concepts
def test_get_top_concepts(self):
res = self.testapp.get(
'/conceptschemes/TREES/topconcepts',
{ascii_native_('Accept'): ascii_native_('application/json')}
)
self.assertEqual('200 OK', res.status)
self.assertIn('application/json', res.headers['Content-Type'])
data = json.loads(res.body.decode('utf-8'))
self.assertIsInstance(data, list)
self.assertEqual(2, len(data))
for c in data:
self.assertIn('id', c)
self.assertIn('uri', c)
self.assertIn('label', c)
self.assertEqual('concept', c['type'])
示例9: test_json_basic_auth
def test_json_basic_auth(anonhtmltestapp):
from base64 import b64encode
from pyramid.compat import ascii_native_
url = '/'
value = "Authorization: Basic %s" % ascii_native_(b64encode(b'nobody:pass'))
res = anonhtmltestapp.get(url, headers={'Authorization': value}, status=401)
assert res.content_type == 'application/json'
示例10: find_resource
def find_resource(resource, path):
""" Given a resource object and a string or tuple representing a path
(such as the return value of :func:`pyramid.traversal.resource_path` or
:func:`pyramid.traversal.resource_path_tuple`), return a resource in this
application's resource tree at the specified path. The resource passed
in *must* be :term:`location`-aware. If the path cannot be resolved (if
the respective node in the resource tree does not exist), a
:exc:`KeyError` will be raised.
This function is the logical inverse of
:func:`pyramid.traversal.resource_path` and
:func:`pyramid.traversal.resource_path_tuple`; it can resolve any
path string or tuple generated by either of those functions.
Rules for passing a *string* as the ``path`` argument: if the
first character in the path string is the ``/``
character, the path is considered absolute and the resource tree
traversal will start at the root resource. If the first character
of the path string is *not* the ``/`` character, the path is
considered relative and resource tree traversal will begin at the resource
object supplied to the function as the ``resource`` argument. If an
empty string is passed as ``path``, the ``resource`` passed in will
be returned. Resource path strings must be escaped in the following
manner: each Unicode path segment must be encoded as UTF-8 and as
each path segment must escaped via Python's :mod:`urllib.quote`.
For example, ``/path/to%20the/La%20Pe%C3%B1a`` (absolute) or
``to%20the/La%20Pe%C3%B1a`` (relative). The
:func:`pyramid.traversal.resource_path` function generates strings
which follow these rules (albeit only absolute ones).
Rules for passing *text* (Unicode) as the ``path`` argument are the same
as those for a string. In particular, the text may not have any nonascii
characters in it.
Rules for passing a *tuple* as the ``path`` argument: if the first
element in the path tuple is the empty string (for example ``('',
'a', 'b', 'c')``, the path is considered absolute and the resource tree
traversal will start at the resource tree root object. If the first
element in the path tuple is not the empty string (for example
``('a', 'b', 'c')``), the path is considered relative and resource tree
traversal will begin at the resource object supplied to the function
as the ``resource`` argument. If an empty sequence is passed as
``path``, the ``resource`` passed in itself will be returned. No
URL-quoting or UTF-8-encoding of individual path segments within
the tuple is required (each segment may be any string or unicode
object representing a resource name). Resource path tuples generated by
:func:`pyramid.traversal.resource_path_tuple` can always be
resolved by ``find_resource``.
"""
if isinstance(path, text_type):
path = ascii_native_(path)
D = traverse(resource, path)
view_name = D['view_name']
context = D['context']
if view_name:
raise KeyError('%r has no subelement %s' % (context, view_name))
return context
示例11: test_get_conceptscheme_json
def test_get_conceptscheme_json(self):
res = self.testapp.get(
'/conceptschemes/TREES',
{},
{ascii_native_('Accept'): ascii_native_('application/json')})
self.assertEqual('200 OK', res.status)
self.assertIn('application/json', res.headers['Content-Type'])
data = json.loads(res.body.decode('utf-8'))
self.assertIsInstance(data, dict)
self.assertIn('id', data)
self.assertIn('uri', data)
self.assertIn('subject', data)
self.assertIn('label', data)
self.assertIn('labels', data)
self.assertEqual(len(data['labels']), 2)
for l in data['labels']:
self.assertIsInstance(l, dict)
self.assertIn('notes', data)
示例12: test_get_conceptschemes_trees_larch_json
def test_get_conceptschemes_trees_larch_json(self):
res = self.testapp.get(
'/conceptschemes/TREES/c/1',
{},
{ascii_native_('Accept'): ascii_native_('application/json')}
)
self.assertEqual('200 OK', res.status)
self.assertIn('application/json', res.headers['Content-Type'])
data = json.loads(res.body.decode('utf-8'))
self.assertIsInstance(data, dict)
self.assertIn('id', data)
self.assertIn('label', data)
self.assertIn('labels', data)
self.assertIn('notes', data)
self.assertEqual('concept', data['type'])
self.assertIn('narrower', data)
self.assertIn('broader', data)
self.assertIn('related', data)
示例13: _page_results
def _page_results(self, concepts):
# Result paging
paging_data = False
if 'Range' in self.request.headers:
paging_data = parse_range_header(self.request.headers['Range'])
count = len(concepts)
if not paging_data:
paging_data = {
'start': 0,
'finish': count - 1 if count > 0 else 0,
'number': count
}
cslice = concepts[paging_data['start']:paging_data['finish']+1]
self.request.response.headers[ascii_native_('Content-Range')] = \
ascii_native_('items %d-%d/%d' % (
paging_data['start'], paging_data['finish'], count
))
return cslice
示例14: _get_tag_label
def _get_tag_label(self, column_index):
"""
Convenience method returning a tag label. All tag labels are strings.
Returns *None* if the tag label is an empty string.
Overwrite this method to address special formats (e.g. keyword
conversion, case-sensitivity, whitespaces, etc.).
:returns: Tag label.
:rtype: :class:`str`
"""
tag_label = self._get_cell_value(self._current_row, column_index)
if tag_label is None:
result = None
else:
result = ascii_native_(tag_label)
return result
示例15: get_cell_value
def get_cell_value(self, sheet, row_index, column_index):
"""
Returns the value of the specified in the given sheet.
Converts the passed cell value either into
a ascii string (if basestring) or a number (if non_string).
"""
cell_value = sheet.cell_value(row_index, column_index)
cell_name = '%s%i' % (label_from_number(column_index + 1),
row_index + 1)
sheet_name = self.get_sheet_name(sheet)
conv_value = None
if isinstance(cell_value, string_types):
try:
conv_value = ascii_native_(cell_value)
except UnicodeEncodeError:
msg = 'Unknown character in cell %s (sheet "%s"). Remove ' \
'or replace the character, please.' \
% (cell_name, sheet_name)
self.add_error(msg)
else:
if conv_value == '':
conv_value = None
else:
# Try to convert to an int or float.
try:
conv_value = int(conv_value)
except ValueError:
try:
conv_value = float(conv_value)
except ValueError:
pass
elif isinstance(cell_value, (float, int)):
if is_valid_number(value=cell_value, is_integer=True):
conv_value = int(cell_value)
else:
conv_value = cell_value
else:
msg = 'There is some unknown content in cell %s (sheet %s).' \
% (cell_name, sheet_name)
self.add_error(msg)
return conv_value