PageRenderTime 41ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/cola/core/urls.py

https://github.com/Flowerowl/cola
Python | 71 lines | 66 code | 0 blank | 5 comment | 0 complexity | 8fb4c0bae00aa6053b25cdf4bf033e9d MD5 | raw file
Possible License(s): Apache-2.0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. '''
  4. Copyright (c) 2013 Qin Xuye <qin@qinxuye.me>
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. Created on 2013-5-21
  15. @author: Chine
  16. '''
  17. import re
  18. class Url(object):
  19. def __init__(self, url_re, name, parser, **kw):
  20. self.url_re = re.compile(url_re, re.IGNORECASE)
  21. self.name = name
  22. self.parser = parser
  23. self.options = kw
  24. def match(self, url):
  25. return self.url_re.match(url) is not None
  26. class UrlPatterns(object):
  27. def __init__(self, *urls):
  28. for url in urls:
  29. if not isinstance(url, Url):
  30. raise ValueError('urls must be Url instances')
  31. self.url_patterns = list(urls)
  32. def __add__(self, url_obj):
  33. if not isinstance(url_obj, Url):
  34. raise ValueError('url_obj must be an instance of Url')
  35. self.url_patterns.append(url_obj)
  36. return self
  37. def matches(self, urls, pattern_names=None):
  38. for url in urls:
  39. if isinstance(url, basestring):
  40. url_str = url
  41. else:
  42. url_str = str(url)
  43. for pattern in self.url_patterns:
  44. if pattern_names is not None and \
  45. pattern.name not in pattern_names:
  46. continue
  47. if pattern.match(url_str):
  48. yield url
  49. break
  50. def get_parser(self, url, pattern_names=None, options=False):
  51. for pattern in self.url_patterns:
  52. if pattern.match(str(url)):
  53. if pattern_names is not None and \
  54. pattern.name not in pattern_names:
  55. continue
  56. if options is True:
  57. return pattern.parser, pattern.options
  58. return pattern.parser