diff --git a/microhttp_restful/base_model.py b/microhttp_restful/base_model.py index 533aebc..b3e5a65 100644 --- a/microhttp_restful/base_model.py +++ b/microhttp_restful/base_model.py @@ -9,7 +9,7 @@ from webtest_docgen import FormParam -from nanohttp import context, HttpNotFound +from nanohttp import context, HTTPNotFound from microhttp_restful import MetadataField, Field from microhttp_restful.validation import validate_form @@ -119,7 +119,7 @@ def expose(cls, func): def wrapper(*args, **kwargs): result = super(BaseModel, cls).expose(func)(*args, **kwargs) if result is None: - raise HttpNotFound + raise HTTPNotFound return result diff --git a/microhttp_restful/field.py b/microhttp_restful/field.py index 84b6d74..5d9ebb6 100644 --- a/microhttp_restful/field.py +++ b/microhttp_restful/field.py @@ -1,7 +1,7 @@ import re from sqlalchemy import Unicode, String from sqlalchemy_dict import Field as SADictField -from nanohttp import HttpBadRequest +from nanohttp import HTTPBadRequest # noinspection PyAbstractClass @@ -64,7 +64,7 @@ def _validate_pattern(self, value): if value is None: return if not re.match(self.info['pattern'], value): - raise HttpBadRequest('Cannot match field: %s with value "%s" by acceptable pattern' % (self.name, value)) + raise HTTPBadRequest('Cannot match field: %s with value "%s" by acceptable pattern' % (self.name, value)) return value def _validate_length(self, value, min_length, max_length): @@ -72,16 +72,16 @@ def _validate_length(self, value, min_length, max_length): return if not isinstance(value, str): - raise HttpBadRequest('Invalid type: %s for field: %s' % (type(value), self.name)) + raise HTTPBadRequest('Invalid type: %s for field: %s' % (type(value), self.name)) value_length = len(value) if min_length is not None: if value_length < min_length: - raise HttpBadRequest('Please enter at least %d characters for field: %s.' % (min_length, self.name)) + raise HTTPBadRequest('Please enter at least %d characters for field: %s.' % (min_length, self.name)) if max_length is not None: if value_length > max_length: - raise HttpBadRequest('Cannot enter more than: %d in field: %s.' % (max_length, self.name)) + raise HTTPBadRequest('Cannot enter more than: %d in field: %s.' % (max_length, self.name)) def validate(self, value): if 'pattern' in self.info: diff --git a/microhttp_restful/mixins/filtering.py b/microhttp_restful/mixins/filtering.py index 4652fbe..7766cea 100644 --- a/microhttp_restful/mixins/filtering.py +++ b/microhttp_restful/mixins/filtering.py @@ -1,6 +1,6 @@ from sqlalchemy import between -from nanohttp import context, HttpBadRequest +from nanohttp import context, HTTPBadRequest class FilteringMixin: @@ -13,8 +13,8 @@ def filter_by_request(cls, query=None): for c in cls.iter_dict_columns(): # noinspection PyUnresolvedReferences json_name = cls.get_dict_key(c) - if json_name in context.query_string: - value = context.query_string[json_name] + if json_name in context.query: + value = context.query[json_name] query = cls._filter_by_column_value(query, c, value) return query @@ -23,7 +23,7 @@ def filter_by_request(cls, query=None): def _filter_by_column_value(cls, query, column, value): import_value = getattr(cls, 'import_value') if not isinstance(value, str): - raise HttpBadRequest() + raise HTTPBadRequest() if value.startswith('^') or value.startswith('!^'): value = value.split(',') @@ -32,7 +32,7 @@ def _filter_by_column_value(cls, query, column, value): items = [first_item] + value[1:] items = [i for i in items if i.strip()] if not len(items): - raise HttpBadRequest('Invalid query string: %s' % value) + raise HTTPBadRequest('Invalid query string: %s' % value) expression = column.in_([import_value(column, j) for j in items]) if not_: expression = ~expression diff --git a/microhttp_restful/mixins/ordering.py b/microhttp_restful/mixins/ordering.py index 07d3de8..1556f9c 100644 --- a/microhttp_restful/mixins/ordering.py +++ b/microhttp_restful/mixins/ordering.py @@ -22,7 +22,7 @@ def sort_by_request(cls, query=None): # noinspection PyUnresolvedReferences query = query or cls.query - sort_exp = context.query_string.get('sort', '').strip() + sort_exp = context.query.get('sort', '').strip() if not sort_exp: return query diff --git a/microhttp_restful/mixins/pagination.py b/microhttp_restful/mixins/pagination.py index 106222a..174bf00 100644 --- a/microhttp_restful/mixins/pagination.py +++ b/microhttp_restful/mixins/pagination.py @@ -1,4 +1,4 @@ -from nanohttp import context, HttpBadRequest +from nanohttp import context, HTTPBadRequest class PaginationMixin: @@ -13,17 +13,17 @@ def paginate_by_request(cls, query=None): try: take = int( - context.query_string.get('take') or context.environ.get(cls.__take_header_key__) or cls.__max_take__) + context.query.get('take') or context.environ.get(cls.__take_header_key__) or cls.__max_take__) except ValueError: take = cls.__max_take__ try: - skip = int(context.query_string.get('skip') or context.environ.get(cls.__skip_header_key__) or 0) + skip = int(context.query.get('skip') or context.environ.get(cls.__skip_header_key__) or 0) except ValueError: skip = 0 if take > cls.__max_take__: - raise HttpBadRequest() + raise HTTPBadRequest() context.response_headers.add_header('X-Pagination-Take', str(take)) context.response_headers.add_header('X-Pagination-Skip', str(skip)) diff --git a/microhttp_restful/mixins/soft_delete.py b/microhttp_restful/mixins/soft_delete.py index 6160529..c66eb12 100644 --- a/microhttp_restful/mixins/soft_delete.py +++ b/microhttp_restful/mixins/soft_delete.py @@ -3,7 +3,7 @@ from sqlalchemy import DateTime from sqlalchemy.events import event -from nanohttp import HttpConflict +from nanohttp import HTTPConflict from microhttp_restful import Field @@ -35,7 +35,7 @@ def soft_undelete(self, ignore_errors=False): @staticmethod def before_delete(mapper, connection, target): - raise HttpConflict('Cannot remove this object: %s' % target) + raise HTTPConflict('Cannot remove this object: %s' % target) @classmethod def __declare_last__(cls): diff --git a/microhttp_restful/tests/test_filtering_mixin.py b/microhttp_restful/tests/test_filtering_mixin.py index 5acf8e0..d95be0e 100644 --- a/microhttp_restful/tests/test_filtering_mixin.py +++ b/microhttp_restful/tests/test_filtering_mixin.py @@ -2,7 +2,7 @@ from sqlalchemy import Integer, Unicode -from nanohttp import HttpBadRequest +from nanohttp import HTTPBadRequest from nanohttp.contexts import Context from microhttp.ext import db @@ -32,8 +32,8 @@ def test_filtering_mixin(self): # Bad Value with Context({'QUERY_STRING': 'id=1'}, self.application) as context: - context.query_string['id'] = 1 - self.assertRaises(HttpBadRequest, FilteringObject.filter_by_request) + context.query['id'] = 1 + self.assertRaises(HTTPBadRequest, FilteringObject.filter_by_request) # IN with Context({'QUERY_STRING': 'id=^1,2,3'}, self.application): @@ -45,7 +45,7 @@ def test_filtering_mixin(self): # IN (error) with Context({'QUERY_STRING': 'id=^'}, self.application): - self.assertRaises(HttpBadRequest, FilteringObject.filter_by_request) + self.assertRaises(HTTPBadRequest, FilteringObject.filter_by_request) # Between with Context({'QUERY_STRING': 'id=~1,3'}, self.application): diff --git a/microhttp_restful/tests/test_orm.py b/microhttp_restful/tests/test_orm.py index 3d17c88..93c3392 100644 --- a/microhttp_restful/tests/test_orm.py +++ b/microhttp_restful/tests/test_orm.py @@ -4,7 +4,7 @@ from sqlalchemy import Integer, Unicode, ForeignKey, Boolean, Table, Date, Time, Float from sqlalchemy.orm import synonym -from nanohttp import HttpBadRequest +from nanohttp import HTTPBadRequest from microhttp.ext import db from microhttp_restful import ModifiedMixin, Field, composite, relationship @@ -132,20 +132,20 @@ def test_orm(self): self.assertEqual(post1.id, 1) # Validation, Type - with self.assertRaises(HttpBadRequest): + with self.assertRaises(HTTPBadRequest): Author(title=234) # Validation, Pattern - with self.assertRaises(HttpBadRequest): + with self.assertRaises(HTTPBadRequest): Author(email='invalidEmailAddress') # Validation, Min length - with self.assertRaises(HttpBadRequest): + with self.assertRaises(HTTPBadRequest): Author(title='1') # Validation, Max length # Validation, Max length - with self.assertRaises(HttpBadRequest): + with self.assertRaises(HTTPBadRequest): Author(phone='12321321321312321312312') # Metadata diff --git a/microhttp_restful/tests/test_pagination_mixin.py b/microhttp_restful/tests/test_pagination_mixin.py index 439c0ea..f2fe4d4 100644 --- a/microhttp_restful/tests/test_pagination_mixin.py +++ b/microhttp_restful/tests/test_pagination_mixin.py @@ -2,7 +2,7 @@ from sqlalchemy import Integer, Unicode -from nanohttp import HttpBadRequest +from nanohttp import HTTPBadRequest from nanohttp.contexts import Context from microhttp.ext import db @@ -41,7 +41,7 @@ def test_pagination_mixin(self): self.assertEqual(PagingObject.paginate_by_request().count(), 4) with Context({'QUERY_STRING': 'take=5'}, self.application): - self.assertRaises(HttpBadRequest, PagingObject.paginate_by_request) + self.assertRaises(HTTPBadRequest, PagingObject.paginate_by_request) if __name__ == '__main__': # pragma: no cover diff --git a/microhttp_restful/tests/test_soft_delete_mixin.py b/microhttp_restful/tests/test_soft_delete_mixin.py index 20a2ce3..804c5e3 100644 --- a/microhttp_restful/tests/test_soft_delete_mixin.py +++ b/microhttp_restful/tests/test_soft_delete_mixin.py @@ -2,7 +2,7 @@ from sqlalchemy import Unicode -from nanohttp import HttpConflict +from nanohttp import HTTPConflict from microhttp.ext import db from microhttp_restful import SoftDeleteMixin, Field @@ -48,7 +48,7 @@ def test_soft_delete_mixin(self): self.assertEqual(SoftDeleteCheckingModel.exclude_deleted().count(), 1) db_session.delete(instance) - self.assertRaises(HttpConflict, db_session.commit) + self.assertRaises(HTTPConflict, db_session.commit) if __name__ == '__main__': # pragma: no cover diff --git a/microhttp_restful/tests/test_validation_blacklist.py b/microhttp_restful/tests/test_validation_blacklist.py index 5c9ec72..fa4ee6c 100644 --- a/microhttp_restful/tests/test_validation_blacklist.py +++ b/microhttp_restful/tests/test_validation_blacklist.py @@ -17,7 +17,7 @@ class ValidationBlackListController(RestController): admin={'blacklist': ['blacklistParamForAdmin']}) def post(self): result = copy.deepcopy(context.form) - result.update(context.query_string) + result.update(context.query) return result diff --git a/microhttp_restful/tests/test_validation_exact.py b/microhttp_restful/tests/test_validation_exact.py index 4368f0f..d9a23d6 100644 --- a/microhttp_restful/tests/test_validation_exact.py +++ b/microhttp_restful/tests/test_validation_exact.py @@ -18,7 +18,7 @@ class ValidationController(RestController): admin={'exact': ['exactParamForAdmin']}) def post(self): result = copy.deepcopy(context.form) - result.update(context.query_string) + result.update(context.query) return result diff --git a/microhttp_restful/tests/test_validation_exclude.py b/microhttp_restful/tests/test_validation_exclude.py index eee81fc..274848a 100644 --- a/microhttp_restful/tests/test_validation_exclude.py +++ b/microhttp_restful/tests/test_validation_exclude.py @@ -18,7 +18,7 @@ class ValidationExcludeController(RestController): admin={'exclude': ['excludedParamForAdmin']}) def post(self): result = copy.deepcopy(context.form) - result.update(context.query_string) + result.update(context.query) return result diff --git a/microhttp_restful/tests/test_validation_filter.py b/microhttp_restful/tests/test_validation_filter.py index c97c7d9..3ac3c08 100644 --- a/microhttp_restful/tests/test_validation_filter.py +++ b/microhttp_restful/tests/test_validation_filter.py @@ -20,7 +20,7 @@ class ValidationFilterController(RestController): ) def post(self): result = copy.deepcopy(context.form) - result.update(context.query_string) + result.update(context.query) return result diff --git a/microhttp_restful/tests/test_validation_pattern.py b/microhttp_restful/tests/test_validation_pattern.py index d8d8203..c87fa6b 100644 --- a/microhttp_restful/tests/test_validation_pattern.py +++ b/microhttp_restful/tests/test_validation_pattern.py @@ -35,7 +35,7 @@ class ValidationPatternController(RestController): ) def post(self): result = copy.deepcopy(context.form) - result.update(context.query_string) + result.update(context.query) return result diff --git a/microhttp_restful/tests/test_validation_requires.py b/microhttp_restful/tests/test_validation_requires.py index 2d5c9ec..1318ddc 100644 --- a/microhttp_restful/tests/test_validation_requires.py +++ b/microhttp_restful/tests/test_validation_requires.py @@ -18,7 +18,7 @@ class ValidationRequiresController(RestController): admin={'requires': ['requiresParamForAdmin']}) def post(self): result = copy.deepcopy(context.form) - result.update(context.query_string) + result.update(context.query) return result diff --git a/microhttp_restful/tests/test_validation_types.py b/microhttp_restful/tests/test_validation_types.py index 17b8741..6a998e0 100644 --- a/microhttp_restful/tests/test_validation_types.py +++ b/microhttp_restful/tests/test_validation_types.py @@ -34,7 +34,7 @@ class ValidationTypesController(RestController): ) def post(self): result = copy.deepcopy(context.form) - result.update(context.query_string) + result.update(context.query) return result diff --git a/microhttp_restful/tests/test_validation_whitelist.py b/microhttp_restful/tests/test_validation_whitelist.py index bbca8c2..9a8d7e2 100644 --- a/microhttp_restful/tests/test_validation_whitelist.py +++ b/microhttp_restful/tests/test_validation_whitelist.py @@ -18,7 +18,7 @@ class ValidationWhitelistController(RestController): admin={'whitelist': ['whitelistParamForAdmin']}) def post(self): result = copy.deepcopy(context.form) - result.update(context.query_string) + result.update(context.query) return result diff --git a/microhttp_restful/validation.py b/microhttp_restful/validation.py index d623b14..9422ae8 100644 --- a/microhttp_restful/validation.py +++ b/microhttp_restful/validation.py @@ -2,7 +2,7 @@ import functools from itertools import chain -from nanohttp import context, HttpBadRequest +from nanohttp import context, HTTPBadRequest class FormValidator: @@ -61,7 +61,7 @@ def extract_rules_pair(self, rule_name, user_rules) -> dict: return result def __call__(self, *args, **kwargs): - input_collections = [context.form, context.query_string] + input_collections = [context.form, context.query] all_input_fields = set(chain(*input_collections)) user_rules = [v for k, v in self._rules_per_role.items() if k in context.identity.roles] \ if hasattr(context, 'identity') and context.identity else [] @@ -69,7 +69,7 @@ def __call__(self, *args, **kwargs): denied_fields = self.extract_rules_odd('blacklist', user_rules) if denied_fields: if all_input_fields & denied_fields: - raise HttpBadRequest('These fields are denied: [%s]' % ', '.join(denied_fields)) + raise HTTPBadRequest('These fields are denied: [%s]' % ', '.join(denied_fields)) excluded_fields = self.extract_rules_odd('exclude', user_rules) if excluded_fields: @@ -86,19 +86,19 @@ def __call__(self, *args, **kwargs): whitelist_fields = self.extract_rules_odd('whitelist', user_rules) if whitelist_fields: if all_input_fields - whitelist_fields: - raise HttpBadRequest( + raise HTTPBadRequest( 'These fields are not allowed: [%s]' % ', '.join(all_input_fields - whitelist_fields) ) required_fields = self.extract_rules_odd('requires', user_rules) if required_fields: if required_fields - all_input_fields: - raise HttpBadRequest('These fields are required: [%s]' % ', '.join(required_fields - all_input_fields)) + raise HTTPBadRequest('These fields are required: [%s]' % ', '.join(required_fields - all_input_fields)) exact_fields = self.extract_rules_odd('exact', user_rules) if exact_fields: if exact_fields != all_input_fields: - raise HttpBadRequest('Exactly these fields are allowed: [%s]' % ', '.join(exact_fields)) + raise HTTPBadRequest('Exactly these fields are allowed: [%s]' % ', '.join(exact_fields)) type_pairs = self.extract_rules_pair('types', user_rules) if type_pairs: @@ -109,7 +109,7 @@ def __call__(self, *args, **kwargs): try: collection[field] = desired_type(collection[field]) except ValueError: - raise HttpBadRequest('The field: %s must be %s' % (field, desired_type)) + raise HTTPBadRequest('The field: %s must be %s' % (field, desired_type)) pattern_pairs = self.extract_rules_pair('pattern', user_rules) if pattern_pairs: @@ -119,7 +119,7 @@ def __call__(self, *args, **kwargs): desired_pattern = pattern_pairs[field] pattern = re.compile(desired_pattern) if isinstance(desired_pattern, str) else desired_pattern if pattern.match(collection[field]) is None: - raise HttpBadRequest( + raise HTTPBadRequest( 'The field %s: %s must be matched with %s pattern' % (field, collection[field], pattern.pattern) ) @@ -130,19 +130,19 @@ def validate_form(blacklist=None, exclude=None, filter_=None, whitelist=None, re pattern=None, **rules_per_role): """Creates a validation decorator based on given rules: - :param blacklist: A list fields to raise :class:`nanohttp.exceptions.HttpBadRequest` if exists in request. + :param blacklist: A list fields to raise :class:`nanohttp.exceptions.HTTPBadRequest` if exists in request. :param exclude: A list of fields to remove from the request payload if exists. :param filter_: A list of fields to filter the request payload. - :param whitelist: A list of fields to raise :class:`nanohttp.exceptions.HttpBadRequest` if anythings else found in + :param whitelist: A list of fields to raise :class:`nanohttp.exceptions.HTTPBadRequest` if anythings else found in the request payload. - :param requires: A list of fields to raise :class:`nanohttp.exceptions.HttpBadRequest` if the given fields are not + :param requires: A list of fields to raise :class:`nanohttp.exceptions.HTTPBadRequest` if the given fields are not in the request payload. - :param exact: A list of fields to raise :class:`nanohttp.exceptions.HttpBadRequest` if the given fields are not + :param exact: A list of fields to raise :class:`nanohttp.exceptions.HTTPBadRequest` if the given fields are not exact match. :param types: A dictionary of fields and their expected types. Fields will be casted to expected types if possible. - Otherwise :class:`nanohttp.exceptions.HttpBadRequest` will be raised. + Otherwise :class:`nanohttp.exceptions.HTTPBadRequest` will be raised. :param pattern: A dictionary of fields and their expected regex patterns. Fields will be matched by expected pattern - if possible. Otherwise :class:`nanohttp.exceptions.HttpBadRequest` will be raised. + if possible. Otherwise :class:`nanohttp.exceptions.HTTPBadRequest` will be raised. :param rules_per_role: A dictionary ``{ role: { ... } }``, which you can apply above rules to single role. @@ -166,8 +166,8 @@ def wrapper(*args, **kwargs): def prevent_form(func): @functools.wraps(func) def wrapper(*args, **kwargs): - if context.form or context.query_string: - raise HttpBadRequest('No input allowed.') + if context.form or context.query: + raise HTTPBadRequest('No input allowed.') return func(*args, **kwargs) return wrapper diff --git a/setup.py b/setup.py index 61a8a57..437a24a 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ dependencies = [ 'pytz', - 'microhttp', + 'microhttp ~= 0.13.0', 'sqlalchemy_dict >= 0.3.3', 'webtest_docgen' ]