示例#1
0
文件: app.py 项目: vthunder/cc.engine
    def __call__(self, environ, start_response):
        request = Request(environ)
        path_info = request.path_info
        route_match = routing.mapping.match(path_info)

        if route_match is None:
            # If there's an equivalent URL that ends with /, redirect
            # to that.
            if not path_info.endswith('/') \
                    and request.method == 'GET' \
                    and routing.mapping.match(path_info + '/'):
                new_path_info = path_info + '/'
                if request.GET:
                    new_path_info = '%s?%s' % (new_path_info,
                                               urllib.urlencode(request.GET))
                redirect = exc.HTTPFound(location=new_path_info)
                return request.get_response(redirect)(environ, start_response)

            # Return a 404
            response = util.generate_404_response(request, routing, environ,
                                                  self.staticdirector)
            return response(environ, start_response)

        controller = load_controller(route_match['controller'])
        request.start_response = start_response

        request.matchdict = route_match
        request.urlgen = routes.URLGenerator(routing.mapping, environ)
        request.staticdirect = self.staticdirector

        return controller(request)(environ, start_response)
示例#2
0
 def __init__(self, core, runtime, method, group):
   Framework.CoreObject.__init__(self, core)
   self._method = method
   self._route_lock = runtime.lock()
   self._route_controllers = {}
   self._route_mapper = routes.Mapper()
   self._route_generator = routes.URLGenerator(self._route_mapper, {})
   self._route_group = group
   self._arg_types = {}
示例#3
0
def generate_404_response(request, routing, environ, staticdirector):
    """
    Create a 'nice looking' 404 response.
    """
    request.matchdict = {}
    request.urlgen = routes.URLGenerator(routing.mapping, environ)
    request.staticdirect = staticdirector

    target_lang = get_target_lang_from_request(request)

    context = {'page_style': 'bare'}
    context.update(rtl_context_stuff(target_lang))

    return Response(render_template(request, target_lang,
                                    'catalog_pages/404.html', context),
                    status=404)
示例#4
0
 def __call__(self, req):
     '''
     Glue.  A WSGI app is a callable; thus in order to make this object an application, 
     we define __call__ to make it callable.  We then ask our Mapper to do some routing,
     and dispatch to the appropriate method.  That method must return a webob.Response.
     '''
     results = self.map.routematch(environ=req.environ)
     if not results:
         return webob.exc.HTTPNotFound()
     match, route = results
     link = routes.URLGenerator(self.map, req.environ)
     req.urlvars = ((), match)
     kwargs = match.copy()
     method = kwargs.pop('method')
     req.link = link
     return getattr(self, method)(req, **kwargs)
示例#5
0
 def __call__(self, req):
     results = self.map.routematch(environ=req.environ)
     if not results:
         oReply = {'responseCode': 404}
         return json.dumps(oReply)
     try:
         match, route = results
         link = routes.URLGenerator(self.map, req.environ)
         req.urlvars = ((), match)
         kwargs = match.copy()
         method = kwargs.pop('method')
         req.link = link
         return getattr(self, method)(req, **kwargs)
     except Exception as e:
         oReply = {'responseCode': 500, 'message': str(e)}
         return json.dumps(oReply)
示例#6
0
    def __call__(self, environ, start_response):
        request = Request(environ)
        path_info = request.path_info

        ## Routing / controller loading stuff
        route_match = self.routing.match(path_info)

        # No matching page?
        if route_match is None:
            # Try to do see if we have a match with a trailing slash
            # added and if so, redirect
            if not path_info.endswith('/') \
                    and request.method == 'GET' \
                    and self.routing.match(path_info + '/'):
                new_path_info = path_info + '/'
                if request.GET:
                    new_path_info = '%s?%s' % (new_path_info,
                                               urllib.urlencode(request.GET))
                redirect = exc.HTTPFound(location=new_path_info)
                return request.get_response(redirect)(environ, start_response)

            # Okay, no matches.  404 time!
            return exc.HTTPNotFound()(environ, start_response)

        controller = util.import_component(route_match['controller'])
        request.start_response = start_response

        ## Attach utilities to the request object
        request.matchdict = route_match
        request.urlgen = routes.URLGenerator(self.routing, environ)
        # Do we really want to load this via middleware?  Maybe?
        request.session = request.environ['beaker.session']
        # Attach self as request.app
        # Also attach a few utilities from request.app for convenience?
        request.app = self
        request.locale = util.get_locale_from_request(request)

        request.template_env = util.get_jinja_env(self.template_loader,
                                                  request.locale)
        request.db = self.db
        request.staticdirect = self.staticdirector

        util.setup_user_in_request(request)

        return controller(request)(environ, start_response)
示例#7
0
    def __init__(self, **kwargs):
        """ Initialize session from cherrypy config. """

        config = cherrypy.config
        prefix = self.name_prefix

        host = config['file_host']
        urlgen = routes.URLGenerator(cherrypy.routes_mapper, {
            'HTTP_HOST': host,
            'HTTPS': 1
        })

        client_id = config[prefix + '_client_id']
        redirect_uri = urlgen(prefix + '_callback', host=host)

        super(CloudOAuth2Session, self).__init__(client_id=client_id,
                                                 scope=self.oauth2_scope,
                                                 redirect_uri=redirect_uri,
                                                 **kwargs)
        self.client_secret = config[prefix + '_client_secret']
        self.ebook = None

        self.mount("http://", http_adapter)
        self.mount("https://", https_adapter)
示例#8
0
from i18n_tool import ugettext as _
import BaseSearcher

# pylint: disable=R0921

http_adapter  = requests.adapters.HTTPAdapter ()
https_adapter = requests.adapters.HTTPAdapter ()

# Google Drive `bug´ see:
# https://github.com/idan/oauthlib/commit/ca4811b3087f9d34754d3debf839e247593b8a39
os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1'

config = cherrypy.config

urlgen = routes.URLGenerator (cherrypy.routes_mapper, {
    'HTTP_HOST': config['file_host'],
    'HTTPS': config['host_https']
})

def log (msg):
    """ Log an informational  message. """
    cherrypy.log (msg, context = 'CLOUDSTORAGE', severity = logging.INFO)


def error_log (msg):
    """ Log an error message. """
    cherrypy.log ('Error: ' + msg, context = 'CLOUDSTORAGE', severity = logging.ERROR)


class CloudOAuth2Session (requests_oauthlib.OAuth2Session): # pylint: disable=R0904
    """ An OAuth2 session. """
示例#9
0
    def __init__(self):
        self.format = None
        self.page = None
        self.template = None
        self.query = None
        self.id = None
        self.sort_order = None
        self.search_terms = None
        self.start_index = 1
        self.items_per_page = 1
        self.total_results = -1
        self.page_mode = 'screen'
        self.user_dialog = ('', '')
        self.opensearch_support = 0  # 0 = none, 1 = full, 2 = fake(Stanza, Aldiko, ...)
        self.books_in_archive = babel.numbers.format_number(
            books_in_archive, locale=str(cherrypy.response.i18n.locale))
        self.breadcrumbs = [
            (_('Project Gutenberg'), _('Go to the Main page.'), '/'),
            (__('1 free ebook', '{count} free ebooks',
                books_in_archive).format(count=self.books_in_archive),
             _('Start a new search.'), '/ebooks/'),
        ]

        # default output formatting functions
        self.f_format_title = self.format_title
        self.f_format_subtitle = self.format_author
        self.f_format_extra = self.format_none  # depends on sort order, set in fix_sortorder ()
        self.f_format_url = self.format_bibrec_url
        self.f_format_thumb_url = self.format_thumb_url
        self.f_format_icon = self.format_icon  # icon class

        self.user_agent = cherrypy.request.headers.get('User-Agent', '')

        cherrypy.request.os = self
        s = cherrypy.session
        k = cherrypy.request.params

        host = cherrypy.request.headers.get('X-Forwarded-Host',
                                            cherrypy.config['host'])
        self.host = host.split(',')[-1].strip()  # keep only the last hub
        # turns out X-Forwarded-Protocol (X-Forwarded-Proto is the defacto standaard)
        # is not a thing and has to be set in HAProxy
        self.protocol = cherrypy.request.headers.get('X-Forwarded-Protocol',
                                                     'https')

        # sanity check
        if self.host not in (cherrypy.config['all_hosts']):
            self.host = cherrypy.config['host']
        if self.protocol not in VALID_PROTOCOLS:
            self.protocol = 'https'

        self.urlgen = routes.URLGenerator(cherrypy.routes_mapper,
                                          {'HTTP_HOST': self.host})

        self.set_format(k.get('format'))

        # query: this param is set when an actual query is requested

        self.query = ''
        if 'query' in k:
            self.query = SQLStatement.preprocess_query(k['query'])

        # search_terms: this is used to carry the last query
        # to display in the search input box

        self.search_terms = self.query or s.get('search_terms', '')

        self.sort_order = k.get('sort_order') or s.get(
            'sort_order') or USER_SORT_ORDERS[0]
        if self.sort_order not in USER_SORT_ORDERS:
            raise cherrypy.HTTPError(400, 'Bad Request. Unknown sort order.')
        s['sort_order'] = self.sort_order

        try:
            self.id = int(k.get('id') or '0')
            self.start_index = int(k.get('start_index') or '1')
            self.items_per_page = min(100,
                                      int(k.get('items_per_page') or '25'))
        except ValueError as what:
            raise cherrypy.HTTPError(400, 'Bad Request. ' + str(what))

        self.file_host = cherrypy.config['file_host']
        self.now = datetime.datetime.utcnow().replace(
            microsecond=0).isoformat() + 'Z'
        self.do_animations = 'Kindle/' not in self.user_agent  # no animations on e-ink
        self.ip = cherrypy.request.remote.ip
        self.type_opds = 'application/atom+xml;profile=opds-catalog'

        self.base_url = None
        self.canonical_url = None
        self.entries = []

        # NOTE: For page titles etc.
        self.pg = self.title = _('Project Gutenberg')
        # NOTE: The tagline at the top of every page.
        self.tagline = _(
            'Project Gutenberg offers {count} free ebooks to download.'
        ).format(count=self.books_in_archive)
        # NOTE: The site's description in the html meta tags.
        self.description = _(
            'Project Gutenberg offers {count} free ebooks for '
            'Kindle, iPad, Nook, Android, and iPhone.').format(
                count=self.books_in_archive)
        # NOTE: The placeholder inside an empty search box.
        self.placeholder = _('Search Project Gutenberg.')

        # these need to be here because they have to be localized
        # NOTE: Msg to user indicating the order of the search results.
        self.sorted_msgs = {
            'downloads': _("sorted by popularity"),
            'release_date': _("sorted by release date"),
            'quantity': _("sorted by quantity of books"),
            'title': _("sorted alphabetically"),
            'alpha': _("sorted alphabetically by title"),
            'author': _("sorted alphabetically by author"),
            'nentry': _("sorted by relevance"),
            'random': _("in random order"),
        }

        self.snippet_image_url = self.url('/pics/logo-144x144.png',
                                          host=self.file_host)
        self.og_type = 'website'
        self.class_ = ClassAttr()
        self.title_icon = None
        self.icon = None
        self.sort_orders = []
        self.alternate_sort_orders = []

        lang = self.lang = s.get('_lang_', 'en_US')
        if len(lang) == 2:
            lang = self.lang_to_default_locale.get(lang, 'en_US')
        lang2 = self.lang[:2]

        self.paypal_lang = lang if lang in PAYPAL_LANGS else 'en_US'
        self.flattr_lang = lang if lang in FLATTR_LANGS else 'en_US'

        lang = lang.replace('_', '-')

        self.google_lang = lang if lang in GOOGLE_LANGS else (
            lang2 if lang2 in GOOGLE_LANGS else 'en-US')
        lang = lang.lower()
        self.twitter_lang = lang if lang in TWITTER_LANGS else (
            lang2 if lang2 in TWITTER_LANGS else 'en')

        self.viewport = "width=device-width"  # , initial-scale=1.0"
        self.touch_icon = '/gutenberg/apple-icon.png'
        self.touch_icon_precomposed = None  # not yet used

        if 'user_dialog' in s:
            self.user_dialog = s['user_dialog']
            del s['user_dialog']

        msg = k.get('msg')
        if msg is not None:
            if msg == 'welcome_stranger':
                self.user_dialog = (_(
                    "Welcome to Project Gutenberg. "
                    "You'll find here {count} ebooks completely free of charge."
                ).format(count=self.books_in_archive), _('Welcome'))
示例#10
0
文件: routing.py 项目: Julian/Minion
 def __init__(self, mapper=None):
     if mapper is None:
         mapper = routes.Mapper()
     self._generator = routes.URLGenerator(mapper, {})  # XXX: environ
     self._mapper = mapper
            content = self.get_history_dataset_association(
                trans,
                history,
                content_id,
                check_ownership=True,
                check_accessible=True)
        except Exception, e:
            return str(e)
        try:
            item = content.get_api_value(view='element')
            if trans.user_is_admin() or trans.app.config.expose_dataset_path:
                item['file_name'] = content.file_name
            if not item['deleted']:
                # Problem: Method url_for cannot use the dataset controller
                # Get the environment from DefaultWebTransaction and use default webapp mapper instead of webapp API mapper
                url = routes.URLGenerator(trans.webapp.mapper, trans.environ)
                # http://routes.groovie.org/generating.html
                # url_for is being phased out, so new applications should use url
                item['download_url'] = url(controller='dataset',
                                           action='display',
                                           dataset_id=trans.security.encode_id(
                                               content.id),
                                           to_ext=content.ext)
                item = self.encode_all_ids(trans, item)
        except Exception, e:
            item = "Error in history API at listing dataset"
            log.error(item + ": %s" % str(e))
            trans.response.status = 500
        return item

    @web.expose_api
示例#12
0
 def __init__(self):
     super().__init__()
     self.host = cherrypy.config['host']
     self.urlgen = routes.URLGenerator(cherrypy.routes_mapper, {'HTTP_HOST': self.host})
     self.formatter = formatters['html']
示例#13
0
import routes
import PMS

routemap = routes.Mapper()
routegen = routes.URLGenerator(routemap, {})
controllers = {}

def ConnectRoute(path, action="__NONE__", **kwargs):
  def ConnectRoute_inner(f):
    if f.__name__ not in controllers:
      controllers[f.__name__] = f
    routemap.connect(None, path, controller=f.__name__, action=action, **kwargs)
    PMS.Log("(Framework) Created a new route: %s => %s" % (path, f.__name__))
    return f
  return ConnectRoute_inner
  
def GenerateRoute(f, action='__NONE__', **kwargs):
  return PMS.Plugin.CurrentPrefix() + routegen(controller=f.__name__, action=action, **kwargs)

def MatchRoute(path):
  try:
    d = routemap.match(path)
    if not d:
      raise
    else:
      f = controllers[d["controller"]]
      del d["controller"]
      if d["action"] == "__NONE__": del d["action"]
      return f, d
  except:
    return None, None
示例#14
0
                new_path_info = path_info + '/'
                if request.GET:
                    new_path_info = '%s?%s' % (
                        new_path_info, urllib.urlencode(request.GET))
                redirect = exc.HTTPFound(location=new_path_info)
                return request.get_response(redirect)(environ, start_response)
            # Return a 404
            response = util.generate_404_response(
                request, routing, environ, self.staticdirector)
            return response(environ, start_response)

        controller = load_controller(route_match['controller'])
        request.start_response = start_response

        request.matchdict = route_match
        request.urlgen = routes.URLGenerator(routing.mapping, environ)
        request.staticdirect = self.staticdirector

        return controller(request)(environ, start_response)


def ccengine_app_factory(global_config, **kw):
    if kw.has_key('direct_remote_path'):
        staticdirector = staticdirect.RemoteStaticDirect(
            kw['direct_remote_path'].strip())
    elif kw.has_key('direct_remote_paths'):
        staticdirector = staticdirect.MultiRemoteStaticDirect(
            dict([line.strip().split(' ', 1)
                  for line in kw['direct_remote_paths'].strip().splitlines()]))
    else:
        raise ImproperlyConfigured(
示例#15
0
 def __init__(self):
     self.host = cherrypy.config['host']
     self.urlgen = routes.URLGenerator(cherrypy.routes_mapper,
                                       {'HTTP_HOST': self.host})