def icon_url(self): if isdir(self.path): return static_url('weboot:static/folder_32.png', self.request) if exists(self.path) and isfile(self.path): if self.name.endswith(".root"): return static_url('weboot:static/folder_chart_32.png', self.request) return static_url('weboot:static/close_32.png', self.request)
def icon_url(self): p = self.vfs.get(self.path) if p.isdir(): if p.isvfile(): return static_url('weboot:static/folder_chart_32.png', self.request) else: return static_url('weboot:static/folder_32.png', self.request) elif p.isobject(): raise RuntimeError("Should not be a VFSTraverser!") return static_url('weboot:static/close_32.png', self.request)
def static_url(self, path, **kw): """ Generates a fully qualified URL for a static :term:`asset`. The asset must live within a location defined via the :meth:`pyramid.config.Configurator.add_static_view` :term:`configuration declaration` directive (see :ref:`static_assets_section`). This is a convenience method. The result of calling :meth:`pyramid.request.Request.static_url` is the same as calling :func:`pyramid.url.static_url` with an explicit ``request`` parameter. The :meth:`pyramid.request.Request.static_url` method calls the :func:`pyramid.url.static_url` function using the Request object as the ``request`` argument. The ``*kw`` arguments passed to :meth:`pyramid.request.Request.static_url` are passed through to :func:`pyramid.url.static_url` unchanged and its result is returned. This call to :meth:`pyramid.request.Request.static_url`:: request.static_url('mypackage:static/foo.css') Is completely equivalent to calling :func:`pyramid.url.static_url` like this:: from pyramid.url import static_url static_url('mypackage:static/foo.css', request) See :func:`pyramid.url.static_url` for more information """ return static_url(path, self, **kw)
def cover(request): sbid = request.matchdict['sbid'] response_headers = {'content_type': 'image/jpeg',} try: monograph = request.db.get(sbid) if 'thumbnail' in request.path: img = request.db.fetch_attachment(monograph,monograph['cover_thumbnail']['filename'], stream=True) else: img = request.db.fetch_attachment(monograph,monograph['cover']['filename'], stream=True) response_headers['expires'] = datetime_rfc822(365) except (couchdbkit.ResourceNotFound, KeyError): img = urllib2.urlopen(static_url('scielobooks:static/images/fakecover.jpg', request)) response = Response(**response_headers) response.app_iter = img try: response.etag = str(hash(img)) except TypeError: #cannot generate a hash for the object, return it without the ETag pass return response
def test_it_with_name(self): from jslibs import includeme request = testing.DummyRequest() self.config.registry.settings['jslibs.static_view_name'] = 'aname' includeme(self.config) url = static_url(u'jslibs:resources/', request) self.assertEqual(url, u'http://example.com/aname/')
def add_globals(event): '''Add *context_url* and *static_url* functions to the template renderer global namespace for easy generation of url's within templates. ''' request = event['request'] def context_url(s, context=None, request=request): if context is None: context = request.context url = resource_url(context, request) if not url.endswith('/'): url += '/' return url + s def gen_url(route_name=None, request=request, **kw): if not route_name: local_request = get_current_request() route_name = local_request.matched_route.name url = route_url(route_name, request, **kw) return url event['gen_url'] = gen_url event['context_url'] = context_url event['static_url'] = lambda x: static_url(x, request)
def static_url(self, path, **kw): """ Generates a fully qualified URL for a static :term:`asset`. The asset must live within a location defined via the :meth:`pyramid.config.Configurator.add_static_view` :term:`configuration declaration` or the ``<static>`` ZCML directive (see :ref:`static_assets_section`). This is a convenience method. The result of calling :meth:`pyramid.request.Request.static_url` is the same as calling :func:`pyramid.url.static_url` with an explicit ``request`` parameter. The :meth:`pyramid.request.Request.static_url` method calls the :func:`pyramid.url.static_url` function using the Request object as the ``request`` argument. The ``*kw`` arguments passed to :meth:`pyramid.request.Request.static_url` are passed through to :func:`pyramid.url.static_url` unchanged and its result is returned. This call to :meth:`pyramid.request.Request.static_url`:: request.static_url('mypackage:static/foo.css') Is completely equivalent to calling :func:`pyramid.url.static_url` like this:: from pyramid.url import static_url static_url('mypackage:static/foo.css', request) See :func:`pyramid.url.static_url` for more information """ return static_url(path, self, **kw)
def cover(request): sbid = request.matchdict['sbid'] response_headers = { 'content_type': 'image/jpeg', } try: monograph = request.db.get(sbid) if 'thumbnail' in request.path: img = request.db.fetch_attachment( monograph, monograph['cover_thumbnail']['filename'], stream=True) else: img = request.db.fetch_attachment(monograph, monograph['cover']['filename'], stream=True) response_headers['expires'] = datetime_rfc822(365) except (couchdbkit.ResourceNotFound, KeyError): img = urllib2.urlopen( static_url('scielobooks:static/images/fakecover.jpg', request)) response = Response(**response_headers) response.app_iter = img return response
def home_view(request, input_filepath, output_basename_generator): settings = request.registry.settings converted_path = settings['convertit.converted_path'] input_mimetype = get_input_mimetype(request, input_filepath) output_mimetype = request.GET.get('to', 'application/pdf') output_basename = output_basename_generator(request, output_mimetype) output_filepath = os.path.join(converted_path, output_basename) remove_old_files(request) convert = get_converter(request, input_mimetype, output_mimetype) try: convert(input_filepath, output_filepath) except Exception as e: message = "Sorry, there was an error converting the document. Reason: %s" log.error(message % str(e)) return HTTPInternalServerError(body=message % str(e), content_type='text/plain') return HTTPFound(static_url(output_filepath, request), content_disposition='attachement; filename=%s' % output_basename)
def book_details(request): main = get_renderer(BASE_TEMPLATE).implementation() sbid = request.matchdict['sbid'] try: monograph = Monograph.get(request.db, sbid) except couchdbkit.ResourceNotFound: raise exceptions.NotFound() book_attachments = [] if getattr(monograph, 'toc', None): toc_url = static_url('scielobooks:database/%s/%s', request) % (monograph._id, monograph.toc['filename']) book_attachments.append({'url':toc_url, 'text':_('Table of Contents')}) if getattr(monograph, 'editorial_decision', None): editorial_decision_url = static_url('scielobooks:database/%s/%s', request) % (monograph._id, monograph.editorial_decision['filename']) book_attachments.append({'url':editorial_decision_url, 'text':_('Parecer da Editora')}) if getattr(monograph, 'pdf_file', None): pdf_file_url = static_url('scielobooks:database/%s/%s', request) % (monograph._id, monograph.pdf_file['filename']) book_attachments.append({'url':pdf_file_url, 'text':_('Book in PDF')}) if getattr(monograph, 'epub_file', None): epub_file_url = static_url('scielobooks:database/%s/%s', request) % (monograph._id, monograph.epub_file['filename']) book_attachments.append({'url':epub_file_url, 'text':_('Book in epub')}) evaluation = request.rel_db_session.query(rel_models.Evaluation).filter_by(monograph_sbid=monograph._id).one() parts = catalog_views.get_book_parts(monograph._id, request) return {'document':monograph, 'document_parts':parts, 'evaluation':evaluation, 'book_attachments':book_attachments, 'main':main, 'user':get_logged_user(request), 'cover_full_url': request.route_url('catalog.cover', sbid=monograph._id), 'cover_thumb_url': request.route_url('catalog.cover_thumbnail', sbid=monograph._id), 'add_part_url': request.route_url('staff.new_part', sbid=monograph._id), 'general_stuff': {'breadcrumb': [ (_('Dashboard'), request.route_url('staff.panel')), (monograph.title, None), ] } }
def static_url(self): """ provides the base of the static URL .. code-block:: xml <link rel="shortcut" href="${url.static_url}images/icon.png" /> """ return static_url('atemplate:static/', self.request)
def view_entry(request): doc = request.db.get(request.matchdict['id']) img_url = static_url('pyramidattachs:attachments/%s/%s', request) % (doc['_id'], doc['attachment']['filename']) return render_to_response('templates/view.pt', {'title':doc['title'], 'attach':img_url, 'about':doc['description'], '_id': doc['_id']}, request=request)
def static_url_filter(ctx, path, **kw): """A filter from ``path`` to a string representing the absolute URL. This filter calls :py:func:`pyramid.url.static_url`. Example:: <link rel="stylesheet" href="{{'yourapp:static/css/style.css'|static_url}}" /> """ request = ctx.get('request') or get_current_request() return static_url(path, request, **kw)
def view_entry(request): doc = request.db.get(request.matchdict['id']) img_url = static_url('pyramidattachs:attachments/%s/%s', request) % (doc['_id'], doc['attachment']['filename']) return render_to_response('templates/view.pt', { 'title': doc['title'], 'attach': img_url, 'about': doc['description'], '_id': doc['_id'] }, request=request)
def view_root_object_render(context, request): """ Only called if the object doesn't inherit from Renderable """ if request.params.get("render", "") == "xml": o = context.obj xmlfile = R.TXMLFile("test.xml", "recreate") o.Write() xmlfile.Close() with open("test.xml") as fd: content = fd.read() return Response(content, content_type="text/plain") return HTTPFound(location=static_url('weboot:static/close_32.png', request))
def cover(request): sbid = request.matchdict['sbid'] try: monograph = request.db.get(sbid) if 'thumbnail' in request.path: img = request.db.fetch_attachment(monograph,monograph['cover_thumbnail']['filename'], stream=True) else: img = request.db.fetch_attachment(monograph,monograph['cover']['filename'], stream=True) except (couchdbkit.ResourceNotFound, KeyError): img = urllib2.urlopen(static_url('scielobooks:static/images/fakecover.jpg', request)) response = Response(content_type='image/jpeg') response.app_iter = img return response
def cover(request): sbid = request.matchdict["sbid"] try: monograph = request.db.get(sbid) if "thumbnail" in request.path: img = request.db.fetch_attachment(monograph, monograph["cover_thumbnail"]["filename"], stream=True) else: img = request.db.fetch_attachment(monograph, monograph["cover"]["filename"], stream=True) except (couchdbkit.ResourceNotFound, KeyError): img = urllib2.urlopen(static_url("scielobooks:static/images/fakecover.jpg", request)) response = Response(content_type="image/jpeg") response.app_iter = img return response
def StaticUrl(self, file): """ Generates the url for a static file. *file* is the filename to look the url up for. E.g. for the default static directory use :: <link tal:attributes="href view.StaticUrl('layout2.css')" rel="stylesheet" type="text/css" media="all" /> to reference a file in a different directory you must include the python module like :: <link tal:attributes="href view.StaticUrl('my_app.design:static/layout2.css')" rel="stylesheet" type="text/css" media="all" /> returns url """ if not u":" in file and self.viewModule and self.viewModule.static: file = u"%s/%s" % (self.viewModule.static, file) return static_url(file, self.request)
def template_globals(event): """Adds stuff we use all the time to template context. There is no need to add *request* since it is already there. """ request = event["request"] settings = request.registry.settings # A nicer "route_url": no need to pass it the request object. event["url"] = lambda name, *a, **kw: route_url(name, request, *a, **kw) event["base_path"] = settings.get("base_path", "/") event["static_url"] = lambda s: static_url(s, request) event["appname"] = settings.get("app.name", "Application") localizer = get_localizer(request) translate = localizer.translate pluralize = localizer.pluralize event["_"] = lambda text, mapping=None: translate(text, domain=package_name, mapping=mapping) event["plur"] = lambda singular, plural, n, mapping=None: pluralize( singular, plural, n, domain=package_name, mapping=mapping )
def StaticUrl(self, file): """ Generates the url for a static file. *file* is the filename to look the url up for. E.g. for the default static directory use :: <link tal:attributes="href view.StaticUrl('layout2.css')" rel="stylesheet" type="text/css" media="all" /> to reference a file in a different directory you must include the python module like :: <link tal:attributes="href view.StaticUrl('nive.cms.design:static/layout2.css')" rel="stylesheet" type="text/css" media="all" /> returns url """ if not u":" in file and self.viewModule and self.viewModule.static: file = u"%s/%s" % (self.viewModule.static, file) return static_url(file, self.request)
def template_globals(event): '''Adds stuff we use all the time to template context. There is no need to add *request* since it is already there. ''' request = event['request'] settings = request.registry.settings # A nicer "route_url": no need to pass it the request object. event['url'] = lambda name, *a, **kw: \ route_url(name, request, *a, **kw) event['base_path'] = settings.get('base_path', '/') event['static_url'] = lambda s: static_url(s, request) event['appname'] = settings.get('app.name', 'Application') localizer = get_localizer(request) translate = localizer.translate pluralize = localizer.pluralize event['_'] = lambda text, mapping=None: \ translate(text, domain=package_name, mapping=mapping) event['plur'] = lambda singular, plural, n, mapping=None: \ pluralize(singular, plural, n, domain=package_name, mapping=mapping)
def add_globals(event): '''Add *context_url* and *static_url* functions to the template renderer global namespace for easy generation of url's within templates. ''' request = event['request'] def context_url(s, context=None,request=request): if context is None: context = request.context url = resource_url(context,request) if not url.endswith('/'): url += '/' return url + s def gen_url(route_name=None, request=request, **kw): if not route_name: local_request = get_current_request() route_name = local_request.matched_route.name url = route_url(route_name, request, **kw) return url event['gen_url'] = gen_url event['context_url'] = context_url event['static_url'] = lambda x: static_url(x, request)
def template_globals(event): '''Adds stuff we use all the time to template context. There is no need to add *request* since it is already there. ''' request = event['request'] settings = request.registry.settings # A nicer "route_url": no need to pass it the request object. event['url'] = lambda name, *a, **kw: \ route_url(name, request, *a, **kw) event['base_path'] = settings.get('base_path', '/') event['static_url'] = lambda s: static_url(s, request) event['locale_name'] = get_locale_name(request) # to set xml:lang event['enabled_locales'] = settings['enabled_locales'] event['appname'] = settings.get('app.name', 'Application') # http://docs.pylonsproject.org/projects/pyramid_cookbook/dev/i18n.html localizer = get_localizer(request) translate = localizer.translate pluralize = localizer.pluralize event['_'] = lambda text, mapping=None: \ translate(text, domain=package_name, mapping=mapping) event['plur'] = lambda singular, plural, n, mapping=None: \ pluralize(singular, plural, n, domain=package_name, mapping=mapping)
def home_view(request, input_filepath, output_basename_generator): settings = request.registry.settings converted_path = settings['convertit.converted_path'] input_mimetype = get_input_mimetype(request, input_filepath) output_mimetype = request.GET.get('to', 'application/pdf') output_basename = output_basename_generator(request, output_mimetype) output_filepath = os.path.join(converted_path, output_basename) remove_old_files(request) convert = get_converter(request, input_mimetype, output_mimetype) try: convert(input_filepath, output_filepath) except Exception as e: message = "Sorry, there was an error fetching the document. Reason: %s" return HTTPBadRequest(message % str(e)) return HTTPFound(static_url(output_filepath, request), content_disposition='attachement; filename=%s' % output_basename)
def StaticUrl(self, file): """ Generates the url for a static file. *file* is the filename to look the url up for. E.g. for the default static directory use :: <link tal:attributes="href view.StaticUrl('layout2.css')" rel="stylesheet" type="text/css" media="all" > to reference a file in a different directory you must include the python module like :: <link tal:attributes="href view.StaticUrl('my_app.design:static/layout2.css')" rel="stylesheet" type="text/css" media="all" > absolute http urls can also be used based on the url prefix http, https and / :: <link tal:attributes="href view.StaticUrl('/assets/layout2.css')" rel="stylesheet" type="text/css" media="all" > <link tal:attributes="href view.StaticUrl('http://myserver.com/assets/layout2.css')" rel="stylesheet" type="text/css" media="all" > <link tal:attributes="href view.StaticUrl('https://myserver.com/assets/layout2.css')" rel="stylesheet" type="text/css" media="all" > returns url """ if file is None: return u"" if file.startswith((u"http://",u"https://",u"/")): return file if not u":" in file and self.viewModule and self.viewModule.static: if self.viewModule.static.endswith((u"/",u":")): file = self.viewModule.static + file else: file = u"%s/%s" % (self.viewModule.static, file) if file.startswith((u"http://",u"https://",u"/")): return file return static_url(file, self.request)
def upload(request): logged_in = authenticated_userid(request) if not logged_in: return HTTPFound(location=route_url("signup", request)) form = Form(request, schema=schemas.Upload) if request.POST and form.validate(): if not validate_csrf(request): return HTTPUnauthorized("Not authorized") pic_form = request.POST["pic_form"] target_form = request.POST["target_form"] picfile = request.POST["picture.upload"] if not picfile: permanent_file_path = os.path.join(permanent_store, picfile.filename.lstrip(os.sep)) permanent_file = open(permanent_file_path, "w") shutil.copyfileobj(picfile.file, permanent_file) picfile.file.close() permanent_file.close() pic_url = static_url("carvewithus:uploads/" + picfile.filename.lstrip(os.sep), request) return dict(pic_url=pic_url, pic_form=pic_form, target_form=target_form) return {}
def home_view(request, input_filepath, output_basename_generator): settings = request.registry.settings converted_path = settings["convertit.converted_path"] input_mimetype = get_input_mimetype(request, input_filepath) output_mimetype = request.GET.get("to", "application/pdf") output_basename = output_basename_generator(request, output_mimetype) output_filepath = os.path.join(converted_path, output_basename) remove_old_files(request) convert = get_converter(request, input_mimetype, output_mimetype) try: convert(input_filepath, output_filepath) except Exception as e: message = "Sorry, there was an error converting the document. Reason: %s" log.error(message % str(e)) return HTTPInternalServerError(body=message % str(e), content_type="text/plain") return HTTPFound( static_url(output_filepath, request), content_disposition="attachement; filename=%s" % output_basename )
def _callFUT(self, *arg, **kw): from pyramid.url import static_url return static_url(*arg, **kw)
def static_url_filter(path, **kw): """A filter from ``path`` to a string representing the absolute URL. This filter calls `pyramid.url.static_url`. """ request = get_current_request() return static_url(path, request, **kw)
def pdf_file(request): sbid = request.matchdict['sbid'] req_part = request.matchdict['part'].split('-') monograph = Monograph.get(request.db, sbid) if len(req_part) == 2: if req_part[1] != getattr(monograph, 'isbn', None) and req_part[1] != getattr( monograph, 'eisbn', None): raise exceptions.NotFound() try: url = static_url( 'scielobooks:fileserver/{0}/pdf/{1}.pdf'.format( sbid, request.matchdict['part']), request) u = urllib2.urlopen(url) return HTTPFound(location=url) except (urllib2.HTTPError, urllib2.URLError): #cannot find in static file server, fetch from db try: pdf_file = request.db.fetch_attachment( monograph._id, monograph.pdf_file['filename'], stream=True) except (couchdbkit.ResourceNotFound, AttributeError): raise exceptions.NotFound() else: if asbool( request.registry.settings.get('fileserver_sync_enable', False)): if req_part[1] == getattr(monograph, 'eisbn', None) and getattr( monograph, 'isbn', None): #when the eisbn is registered at an already published book. The eisbn takes #precedence when generating the shortname. source_filename = '-'.join([ monograph.shortname.split('-')[0], monograph.isbn ]) try: url = static_url( 'scielobooks:fileserver/{0}/pdf/{1}.pdf'. format(sbid, source_filename), request) u = urllib2.urlopen(url) except (urllib2.HTTPError, urllib2.URLError): # there are no static files available for this book. fresh_pdf_file = request.db.fetch_attachment( monograph._id, monograph.pdf_file['filename'], stream=True) functions.transfer_static_file( request, fresh_pdf_file, monograph._id, monograph.shortname, 'pdf', request.registry. settings['fileserver_remotebase']) else: dest_filename = monograph.shortname functions.symlink_static_file( request, monograph._id, source_filename, dest_filename, 'pdf', request.registry. settings['fileserver_remotebase']) else: fresh_pdf_file = request.db.fetch_attachment( monograph._id, monograph.pdf_file['filename'], stream=True) functions.transfer_static_file( request, fresh_pdf_file, monograph._id, monograph.shortname, 'pdf', request.registry.settings['fileserver_remotebase']) else: parts = get_book_parts(monograph._id, request) try: selected_part = parts[int(req_part[2])] except (IndexError, ValueError): raise exceptions.NotFound() part = Part.get(request.db, selected_part['part_sbid']) try: pdf_file = request.db.fetch_attachment(part._id, part.pdf_file['filename'], stream=True) except (couchdbkit.ResourceNotFound, AttributeError): raise exceptions.NotFound() response = Response(content_type='application/pdf', expires=datetime_rfc822(365)) response.app_iter = pdf_file try: response.etag = str(hash(pdf_file)) except TypeError: #cannot generate a hash for the object, return it without the ETag pass return response
def icon_url(self): return static_url('weboot:static/close_32.png', self.request)
def _callFUT(self, path, request, **kw): from pyramid.url import static_url return static_url(path, request, **kw)
def icon_url(self): return static_url('weboot:static/folder_chart_32.png', self.request)
def user_session_handler(event): s = event['request'].session r = event['request'] e = event if 'message' in s: e['message'] = s['message'] else: e['message'] = None e['template_filters'] = template_filters # this could be accessed by the request object, request.static_url() # should fixup the first here at least to be normal e['static_base'] = static_url("{0}/".format(r.registry.settings['template_static_asset']), r) e['static_url'] = static_url e['site_name'] = r.registry.settings['site.site_name'] # export date fuzzing function to templates e['fuzzify_date'] = users.fuzzify_date e['new_message_num'] = None e['karma'] = None e['u'] = None e['logged_in_admin'] = None e['logged_in'] = False s['logged_in_admin'] = False e['followed_users'] = [] if 'recent_comments.num' in r.registry.settings: e['recent_comments'] = submission.get_recent_comments(r.registry.settings['recent_comments.num']) else: # use ten as default if server parameter is missing e['recent_comments'] = submission.get_recent_comments(10) if 'sort' in r.params: e['sort'] = r.params['sort'] else: e['sort'] = 'new' if 'logged_in' in s: #@TODO: implement caching/rate limiting so we don't perform this on every single request anymore num = epistle_queries.get_new_message_num(s['users.id']) if num == 0: s['new_message_num'] = None e['new_message_num'] = None else: s['new_message_num'] = num e['new_message_num'] = num #@TODO: another calculation that would benefit from caching #if 'karma' in s: # e['karma'] = s['karma'] # print 'AAAAAAAAAA' + str(s['karma']) #else: #not caching right now, commenting conditional karma = users.get_user_by_id(s['users.id']).update_karma() s['karma'] = karma e['karma'] = karma if 'followed_users' in s and len(s['followed_users']) > 0: e['followed_users'] = s['followed_users'] else: s['followed_users'] = users.get_followed_users(s['users.id']) e['followed_users'] = s['followed_users'] u = users.get_user_by_id(s['users.id']) e['logged_in_admin'] = u.is_user_admin() s['logged_in_admin'] = e['logged_in_admin'] e['u'] = u e['logged_in'] = True elif 'logged_in' not in s and r.registry.settings['user.generate_anon_accounts'] == 'true': # do not create a new user if we are on the login page # this simplifies anon -> permanent transfer if r.url.find('login') != -1: return # create a temporary user if this is a new session # all activity will be associated with this user until conversion to real account is performed u = User("{0}".format(uuid.UUID(bytes=os.urandom(16))), str(os.urandom(8)), real_name = "Unregistered User", temporary = True) dbsession.add(u) dbsession.flush() s['users.id'] = str(u.id) s['users.display_name'] = u.display_name() s['logged_in'] = True e['logged_in'] = True
def icon_path(self): """ Default Icon """ return static_url('weboot:static/folder_32.png', self.request)
def icon_url(self): return static_url('weboot:static/tree.png', self.request)
def pdf_file(request): sbid = request.matchdict['sbid'] req_part = request.matchdict['part'].split('-') monograph = Monograph.get(request.db, sbid) if len(req_part) == 2: if req_part[1] != getattr(monograph, 'isbn', None) and req_part[1] != getattr(monograph, 'eisbn', None): raise exceptions.NotFound() try: url = static_url('scielobooks:fileserver/{0}/pdf/{1}.pdf'.format(sbid, request.matchdict['part']), request) u = urllib2.urlopen(url) return HTTPFound(location=url) except (urllib2.HTTPError, urllib2.URLError): #cannot find in static file server, fetch from db try: pdf_file = request.db.fetch_attachment(monograph._id, monograph.pdf_file['filename'], stream=True) except (couchdbkit.ResourceNotFound, AttributeError): raise exceptions.NotFound() else: if asbool(request.registry.settings.get('fileserver_sync_enable', False)): if req_part[1] == getattr(monograph, 'eisbn', None) and getattr(monograph, 'isbn', None): #when the eisbn is registered at an already published book. The eisbn takes #precedence when generating the shortname. source_filename = '-'.join([monograph.shortname.split('-')[0], monograph.isbn]) try: url = static_url('scielobooks:fileserver/{0}/pdf/{1}.pdf'.format(sbid, source_filename), request) u = urllib2.urlopen(url) except (urllib2.HTTPError, urllib2.URLError): # there are no static files available for this book. fresh_pdf_file = request.db.fetch_attachment(monograph._id, monograph.pdf_file['filename'], stream=True) functions.transfer_static_file(request, fresh_pdf_file, monograph._id, monograph.shortname, 'pdf', request.registry.settings['fileserver_remotebase']) else: dest_filename = monograph.shortname functions.symlink_static_file(request, monograph._id, source_filename, dest_filename, 'pdf', request.registry.settings['fileserver_remotebase']) else: fresh_pdf_file = request.db.fetch_attachment(monograph._id, monograph.pdf_file['filename'], stream=True) functions.transfer_static_file(request, fresh_pdf_file, monograph._id, monograph.shortname, 'pdf', request.registry.settings['fileserver_remotebase']) else: parts = get_book_parts(monograph._id, request) try: selected_part = parts[int(req_part[2])] except (IndexError, ValueError): raise exceptions.NotFound() part = Part.get(request.db, selected_part['part_sbid']) try: pdf_file = request.db.fetch_attachment(part._id, part.pdf_file['filename'], stream=True) except (couchdbkit.ResourceNotFound, AttributeError): raise exceptions.NotFound() response = Response(content_type='application/pdf', expires=datetime_rfc822(365)) response.app_iter = pdf_file try: response.etag = str(hash(pdf_file)) except TypeError: #cannot generate a hash for the object, return it without the ETag pass return response
def test_it_default(self): from jslibs import includeme request = testing.DummyRequest() includeme(self.config) url = static_url(u'jslibs:resources/', request) self.assertEqual(url, u'http://example.com/jslibs_static/')