def image(request, filename): # Return the file if it is in the images directory if os.path.exists(os.path.join(settings.MEDIA_ROOT, 'images', filename)): return serve(request, filename, document_root=os.path.join(settings.MEDIA_ROOT, 'images')) # If not then look for it in the cache directory path = os.path.join(settings.MEDIA_ROOT, 'images', 'cache', filename) if os.path.exists(path): return serve(request, filename, document_root=os.path.join(settings.MEDIA_ROOT, 'images', 'cache')) # If it isn't there, then make the image # look for an image that is the same without size info m = re.search('-(\d+)x(\d+)', filename) if not m: raise Http404 origname = re.sub('-\d+x\d+', '', filename) origpath = os.path.join(settings.MEDIA_ROOT, 'images', origname) if not os.path.exists(origpath): raise Http404 orig = PILImage.open(origpath) format = orig.format (basewidth, baseheight) = (int(m.group(1)), int(m.group(2))) wpercent = (basewidth/float(orig.size[0])) hsize = int((float(orig.size[1])*float(wpercent))) img = orig.convert('RGB').resize((basewidth, hsize), PILImage.ANTIALIAS) img.save(path, format) response = HttpResponse(mimetype="image/%s"%(format)) img.save(response, format) return response
def process_request(self, request): """ Determines the templates and static files from the individual Blog theme. Templates are loaded using a custom template loader where the theme_dirs can be set during the request. Static files are served (in debug-mode) via the Django view for static files using the theme directory. """ # theme_dir is the path to all the theme files. # /templates and /static should be in this directory. theme_dir = os.path.join(settings.THEME_DIR, request.blog.theme) custom_path = request.blog.theme_path if custom_path: if os.path.exists(custom_path): theme_dir = custom_path else: print 'Using default theme since the theme path is not valid: %s' % request.blog.theme_path # templates from blog import templateloader templateloader.theme_template_dirs = (os.path.join(theme_dir, "templates"),) # static files if settings.DEBUG and request.path.find('/static/') == 0: # return view for serving static files from django.views.static import serve try: return serve(request, request.path, document_root=theme_dir) except Http404: return serve(request, request.path, document_root=settings.MEDIA_ROOT) return None
def getPDF(request, user, pdfid=None, texid=None, default=''): """Liefert die URL einer Datei per GET Request. :param request: Anfrage des Clients, wird unverändert zurückgesendet :param user: User Objekt (eingeloggter Benutzer) :param pdfid: Id der PDF Datei, welche angefordert wurde :param texid: Id der tex Datei von welcher die PDF Datei angefordert wurde :return: URL der Datei """ if (pdfid): # PDF Objekt pdfobj = PDF.objects.get(id=pdfid) # Pfad zur PDF Datei filepath = pdfobj.getTempPath() return serve(request, os.path.basename(filepath), os.path.dirname(filepath)) elif (texid): #Tex Objekt texobj = TexFile.objects.get(id=texid) # PDF Objekt, welches zur Tex Datei gehört pdfobj = PDF.objects.filter(folder=texobj.folder, name=texobj.name[:-3] + 'pdf') if pdfobj.exists(): # Pfad zur PDF Datei filepath = pdfobj[0].getTempPath() return serve(request, os.path.basename(filepath), os.path.dirname(filepath)) else: return serve(request, os.path.basename(default), os.path.dirname(default))
def serve_img(req, res, scale, id_source): #print "img request of page %s of file %s at res %s and scale %s w/ invite_key=%s and req=%s" % (req.GET["page"], id_file, res, scale, req.GET["invite_key"], req ) #TODO: check permissions. uid = UR.getUserId(req); if not auth.canReadFile(uid, id_source): return HttpResponse("Error: You don't have credentials to see this file %s " % (id_source,)) page = int(req.GET["page"])-1 page_str = settings.IMG_FMT_STRING % (page,) filename = req.META["PATH_INFO"].rstrip('/') filename = "%s_%s.png" % (filename, page_str) response = None try: response = serve(req, filename,settings.HTTPD_MEDIA_CACHE) return response except Http404: #let's generate on demand try: pdf_dir = "%s/%s" % (settings.HTTPD_MEDIA,settings.REPOSITORY_DIR) img_dir = "%s/%s" % (settings.HTTPD_MEDIA_CACHE,settings.CACHE_DIR) process_page(id_source, page, res, scale, pdf_dir, img_dir, settings.IMG_FMT_STRING) response = serve(req, filename,settings.HTTPD_MEDIA_CACHE) return response except Http404: basedir = dirname(dirname(dirname(abspath(__file__)))) #TODO: would be better to do a redirect to the not_available page f = open("%s/content/data/icons/png/not_available.png" % basedir) s = f.read() f.close() return HttpResponse(s)
def baobab_serve(request, path, document_root=None, show_indexes=False): if not settings.INFINITE_CACHE: return serve(request, path, document_root, show_indexes) else: if _serve_gzip(request): resp = serve(request, path + '.gz', document_root, show_indexes) resp['Content-Encoding'] = 'gzip' else: resp = serve(request, path, document_root, show_indexes) resp['Cache-Control'] = 'public, max-age=%d' % (3600 * 24 * 365) resp['Vary'] = 'Accept-Encoding' return resp
def servephoto(request,path): iml = schoolim.objects.filter(name=str(path)) if len(iml)==1: im = schoolim.objects.get(name=str(path)) if im.vistoall == False: if request.user.is_authenticated() and request.user.is_active: return serve(request,path,settings.MEDIA_ROOT+'/snaps') else: raise Http404 else: return serve(request,path,settings.MEDIA_ROOT+'/snaps') else: raise Http404
def serve_with_theme(request, path): """ Mimics ``django.views.static.serve`` for serving files from ``MEDIA_ROOT`` during development, first checking for the file in the theme defined by the ``THEME`` setting if specified. """ theme = getattr(settings, "THEME") if theme: theme_root = os.path.join(path_for_import(theme), "media") try: return serve(request, path, document_root=theme_root) except Http404: pass return serve(request, path, document_root=settings.MEDIA_ROOT)
def serve_from_apps(request, path, document_root=None): """Wrapper around django.views.static.serve that tries the generic view first and then falls back to the various media directories in any installed applications before giving up.""" if document_root is not None and document_root != '': try: return serve(request, path, document_root=document_root) except Http404: pass # Try from an app instead for app_root in get_app_roots(): try: return serve(request, path, document_root=app_root) except Http404: pass # Try the next app raise Http404, '"%s" does not exist' % path
def get(self, request, *args, **kwargs): def surogate_encode(filename): ''' On apache, using wsgi, LANG is not set, so that sys.getfilesystemencoding() returns ascii. This leads to os.path.exists('é') to crash. The way around is to use 'surrogateescape' that maps unencoded chars into unicode private range U+DCxx. ''' name_bytes = bytes(filename, encoding=settings.FILE_CHARSET) return str( name_bytes, encoding=sys.getfilesystemencoding(), errors='surrogateescape') def simple_quote(txt): ''' This is a simple urlquote fonction whose only purpose is to make sure unquote won't do nasty stuff, like double unquoting '../..' ''' return txt.replace('%', '%25') cg = self.contactgroup filename = self.kwargs['filename'] fullfilename = cg.get_fullfilename(filename) if os.path.isdir(surogate_encode(fullfilename)): return HttpResponseRedirect( cg.get_absolute_url() + 'files/' + filename + '/') return static.serve( request, simple_quote(surogate_encode(filename)), cg.static_folder(), show_indexes=False)
def serve(request, path, document_root=None, insecure=False, **kwargs): """ Serve static files below a given point in the directory structure or from locations inferred from the staticfiles finders. To use, put a URL pattern such as:: (r'^(?P<path>.*)$', 'django.contrib.staticfiles.views.serve') in your URLconf. It uses the django.views.static view to serve the found files. """ if not settings.DEBUG and not insecure: raise ImproperlyConfigured("The staticfiles view can only be used in " "debug mode or if the --insecure " "option of 'runserver' is used") normalized_path = posixpath.normpath(unquote(path)).lstrip('/') absolute_path = finders.find(normalized_path) if not absolute_path: if path.endswith('/') or path == '': raise Http404("Directory indexes are not allowed here.") raise Http404("'%s' could not be found" % path) document_root, path = os.path.split(absolute_path) return static.serve(request, path, document_root=document_root, **kwargs)
def blog_post_by_alias(request, alias): if alias.startswith("static/"): # This only really happens when there's no Nginx at play. # For example, when the mincss post process thing runs, it's # forced to download the 'localhost:8000/static/main.©e9fc100fa.css' # file. return static.serve( request, alias.replace("static/", ""), document_root=settings.STATIC_ROOT ) if alias.startswith("q/") and alias.count("/") == 1: # E.g. www.peterbe.com/q/have%20to%20learn url = "https://songsear.ch/" + alias return http.HttpResponsePermanentRedirect(url) lower_endings = (".asp", ".aspx", ".xml", ".php", ".jpg/view") if any(alias.lower().endswith(x) for x in lower_endings): return http.HttpResponse("Not found", status=404) if alias == "...": return redirect("/") if alias.startswith("podcasttime/podcasts/"): return redirect( "https://podcasttime.io/{}".format(alias.replace("podcasttime/", "")) ) if alias.startswith("cdn-2916.kxcdn.com/"): return redirect("https://" + alias) try: blogitem = BlogItem.objects.get(alias__iexact=alias) url = reverse("blog_post", args=[blogitem.oid]) return http.HttpResponsePermanentRedirect(url) except BlogItem.DoesNotExist: print("UNDEALTH WITH ALIAS:", repr(alias)) # Use http.HttpResponse(..., status=404) if you don't want to wake up # Rollbar. Or configure Rollbar to not trigger on Http404 exceptions. # return http.HttpResponse(alias, status=404) raise http.Http404(alias)
def books(request, path): if path is None or path == '': documents_file = open(os.path.join( settings.BASE_DIR + '/books/', 'books.yml'), 'r') data = yaml.load(documents_file) books = [] if data.get("documents") and data.get("documents") != None: if request.user.is_authenticated(): books = [ book for position, book in sorted( data['documents'].iteritems())] else: books = [ book for position, book in sorted( data['documents'].iteritems() ) if book.get("visibilty").lower() == "public"] return render(request, "site/books.html", {"books": books}) # return render(request, 'html/index.html') else: # if path.endswith('html'): # return render(request, 'html/' + path) # else: return serve( request, path, document_root=settings.BASE_DIR + '/books/templates/html/')
def serve_cors(*args, **kwargs): """A wrapper around django.views.static.serve that adds CORS headers.""" if not settings.DEBUG: raise RuntimeError("Don't use kitsune.sumo.views.serve_cors " "in production.") from django.views.static import serve return serve(*args, **kwargs)
def render_to_response(self, context, **response_kwargs): """ Override render_to_response to serve the book cover static image """ return static.serve( self.request, self.object.cover.name, settings.MEDIA_ROOT)
def chart(request, **kwargs): from django.views.static import serve chart = kwargs['chart'] if 'chart' in kwargs else None if 'maintainer_id' in kwargs: kwargs['maintainer'] = get_object_or_404( Maintainer, id=kwargs['maintainer_id'] ) if 'herd' in kwargs: kwargs['herd'] = get_object_or_404(Herd, herd=kwargs['herd']) for kw in ('-small', '-weekly', '-monthly', '-yearly'): if chart.endswith(kw): if kw in ('-weekly', '-monthly', '-yearly'): kwargs['period'] = kw kwargs[kw] = True chart = chart[:-len(kw)] if chart == 'pie-packages': path = charts.pie_packages(**kwargs) elif chart == 'pie-versions': path = charts.pie_versions(**kwargs) elif chart == 'packages': path = charts.packages(**kwargs) elif chart == 'versions': path = charts.versions(**kwargs) else: raise Http404() return serve(request, path, document_root=charts.CHARTS_ROOT)
def get(self, request, *args, **kwargs): user = get_user(self) assign = get_object_or_404(AssignSubmission, id=int(args[0])) if assign.task.course.teacher != user: raise PermissionDenied('user is not teacher') filename = assign.data.name return serve(request, filename, document_root=settings.MEDIA_ROOT)
def static_serve(request, path, client): """ Given a request for a media asset, this view does the necessary wrangling to get the correct thing delivered to the user. This can also emulate the combo behavior seen when SERVE_REMOTE == False and EMULATE_COMBO == True. """ if msettings["SERVE_REMOTE"]: # We're serving from S3, redirect there. url = client.remote_media_url().strip("/") + "/%(path)s" return redirect_to(request, url, path=path) if not msettings["SERVE_REMOTE"] and msettings["EMULATE_COMBO"]: # Combo emulation is on and we're serving media locally. Try to see if # the given path matches a combo file defined in the JOINED dict in # the MEDIASYNC settings dict. combo_match = _find_combo_match(path) if combo_match: # We found a combo file match. Combine it and serve the result. return combo_serve(request, combo_match, client) # No combo file, but we're serving locally. Use the standard (inefficient) # Django static serve view. resp = serve(request, path, document_root=client.media_root) resp.content = client.process(resp.content, resp["Content-Type"], path) return resp
def getGeoview(request, geo_uid): token_key = get_token_key(request) data = DataOperator(token_key) if request.method == 'GET': if not data.has_geoview_permissions(geo_uid, Role.VIEWER): return HttpResponse(json_error('No viewing permissions for this GeoView.')) file = False if request.GET.get('file'): filepath = data.get_geoview(geo_uid, file) return serve(request, os.path.basename(filepath), os.path.dirname(filepath)) else: geoview = data.get_geoview(geo_uid) geoview.include_layers = geoview.include_geom = True geoview.token_key = token_key myjson = to_json(geoview) geoview.include_layers = geoview.include_geom = False return HttpResponse(myjson, content_type='application/json') if request.method == 'DELETE': if not data.has_geoview_permissions(geo_uid, Role.EDITOR): return HttpResponse(json_error('No editing permissions for this GeoView.')) data.delete_geoview(geo_uid) message = "Deleted GeoView with uid " + str(geo_uid) return HttpResponse(json_error(message)) return HttpResponse(json_error('ERROR: must GET or DELETE GeoViews'))
def staticattachment(request, bookid, attachment, version=None, chapter = None): """ Django View. Returns content of an attachment. @todo: It is wrong in so many different levels to serve attachments this way. @type request: C{django.http.HttpRequest} @param request: Client Request object @type bookid: C{string} @param bookid: Unique Book ID @type attachment: C{string} @param attachment: Name of the attachment @type version: C{string} @param version: Version of the book """ from django.views import static try: book = models.Book.objects.get(url_title__iexact=bookid) except models.Book.DoesNotExist: return pages.ErrorPage(request, "errors/book_does_not_exist.html", {"book_name": bookid}) book_version = getVersion(book, version) path = '%s/%s' % (book_version.getVersion(), attachment) document_root = '%s/books/%s/' % (settings.DATA_ROOT, bookid) return static.serve(request, path, document_root)
def get_download(r, hashtag, filename): """ Download XPI (it has to be ready) """ if not validator.is_valid('alphanum', hashtag): log.warning('[security] Wrong hashtag provided') return HttpResponseForbidden("{'error': 'Wrong hashtag'}") path = os.path.join(settings.XPI_TARGETDIR, '%s.xpi' % hashtag) log.info('[xpi:%s] Downloading Addon from %s' % (filename, path)) tend = time.time() tkey = xpi_utils.get_queued_cache_key(hashtag, r) tqueued = cache.get(tkey) if tqueued: ttotal = (tend - tqueued) * 1000 statsd.timing('xpi.build.total', ttotal) total = '%dms' % ttotal else: total = 'n/a' log.info('[xpi:%s] Downloading Add-on (%s)' % (hashtag, total)) response = serve(r, path, '/', show_indexes=False) response['Content-Disposition'] = ('attachment; ' 'filename="%s.xpi"' % filename) return response
def serve(request, path, document_root=None, insecure=False, **kwargs): """ Serve static files below a given point in the directory structure or from locations inferred from the staticfiles finders. To use, put a URL pattern such as:: (r'^(?P<path>.*)$', 'assetfiles.views.serve') in your URLconf. It uses the django.views.static view to serve the found files. """ if not settings.DEBUG and not insecure: raise ImproperlyConfigured('The staticfiles view can only be used in ' 'debug mode or if the the --insecure ' "option of 'runserver' is used") normalized_path = posixpath.normpath(unquote(path)).lstrip('/') static_path = finders.find(normalized_path) if static_path: document_root, path = os.path.split(static_path) return static.serve(request, path, document_root=document_root, **kwargs) asset_path, filter = assets.find(normalized_path) if asset_path: content = filter.filter(asset_path) mimetype, encoding = mimetypes.guess_type(normalized_path) return HttpResponse(content, content_type=mimetype) if path.endswith('/') or path == '': raise Http404('Directory indexes are not allowed here.') raise Http404("'%s' could not be found" % path)
def export_file_analysis(request): params = {} from_date = request.GET.get('date', '').strip() if from_date and is_valid_date(from_date): real_date = from_date else: real_date = org_datetime.date.today() params['start_date'] = str(real_date) params['end_date'] = str(real_date) list_type = request.GET.get('list_type', '').strip() list_detail = request.GET.get('list_detail', '').strip() action = request.GET.get('action', '').strip() params['list_type'] = list_type params['list_detail'] = list_detail params['action'] = action row_header = [] if list_type == 'search': ret_data = get_basic_search(params) row_header = ['id', 'name', 'total_times'] else: ret_data = get_basic_download(params) if ret_data: unique_id = hashlib.md5(str(real_date) + str(list_type) + str(list_detail)).hexdigest() filename = 'data%s.xls' % unique_id if row_header: export_special_excel(filename, ret_data, names=row_header) else: export_simple_excel(filename, ret_data) return serve(request, filename, export_filepath) else: return HttpResponse('Sorry, Fail to get detail.')
def protected_download(request, path): """Check for a signed download agreement before delivering the asset.""" settings.use_editable() agreement = Agreement.objects.filter(user=request.user, version=settings.DOWNLOAD_AGREEMENT_VERSION) if not agreement.exists(): params = {'next': request.path} previous = request.META.get('HTTP_REFERER', None) or None if previous is not None: params['next'] = previous request.session['waiting_download'] = request.path agreement_url = '%s?%s' % ( reverse('page', kwargs={'slug': 'download-agreement'}), urllib.urlencode(params)) return redirect(agreement_url) if settings.DEBUG: response = serve(request, path, document_root=os.path.join(settings.MEDIA_ROOT, FILEBROWSER_DIRECTORY, 'protected')) else: response = HttpResponse() response['X-Accel-Redirect'] = '/__protected__/%s' % path response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(path) if request.path == request.session.get('waiting_download'): del request.session['waiting_download'] if request.path == request.session.get('ready_download'): del request.session['ready_download'] return response
def serve(request, path, insecure=False, **kwargs): """ Serve static files below a given point in the directory structure or from locations inferred from the staticfiles finders. To use, put a URL pattern such as:: from django.contrib.staticfiles import views path('<path:path>', views.serve) in your URLconf. It uses the django.views.static.serve() view to serve the found files. """ if not settings.DEBUG and not insecure: raise Http404 normalized_path = posixpath.normpath(path).lstrip('/') absolute_path = finders.find(normalized_path) if not absolute_path: if path.endswith('/') or path == '': raise Http404("Directory indexes are not allowed here.") raise Http404("'%s' could not be found" % path) document_root, path = os.path.split(absolute_path) return static.serve(request, path, document_root=document_root, **kwargs)
def serve_static(request, path, insecure=False, **kwargs): """Collect and serve static files. This view serves up static files, much like Django's :py:func:`~django.views.static.serve` view, with the addition that it collects static files first (if enabled). This allows images, fonts, and other assets to be served up without first loading a page using the ``{% javascript %}`` or ``{% stylesheet %}`` template tags. You can use this view by adding the following to any :file:`urls.py`:: urlpatterns += static('static/', view='pipeline.views.serve_static') """ # Follow the same logic Django uses for determining access to the # static-serving view. if not django_settings.DEBUG and not insecure: raise ImproperlyConfigured("The staticfiles view can only be used in " "debug mode or if the --insecure " "option of 'runserver' is used") if not settings.PIPELINE_ENABLED and settings.PIPELINE_COLLECTOR_ENABLED: # Collect only the requested file, in order to serve the result as # fast as possible. This won't interfere with the template tags in any # way, as those will still cause Django to collect all media. default_collector.collect(request, files=[path]) return serve(request, path, document_root=django_settings.STATIC_ROOT, **kwargs)
def serve_docs(request, lang_slug, version_slug, filename, project_slug=None): if not project_slug: project_slug = request.slug proj = get_object_or_404(Project, slug=project_slug) # Redirects if not version_slug or not lang_slug: version_slug = proj.get_default_version() url = reverse(serve_docs, kwargs={ 'project_slug': project_slug, 'version_slug': version_slug, 'lang_slug': proj.language, 'filename': filename }) return HttpResponseRedirect(url) ver = get_object_or_404(Version, project__slug=project_slug, slug=version_slug) # Auth checks if ver not in proj.versions.public(request.user, proj): res = HttpResponse("You don't have access to this version.") res.status_code = 401 return res # Normal handling if not filename: filename = "index.html" #This is required because we're forming the filenames outselves instead of letting the web server do it. elif proj.documentation_type == 'sphinx_htmldir' and "_static" not in filename and "_images" not in filename and "html" not in filename and not "inv" in filename: filename += "index.html" else: filename = filename.rstrip('/') # Use the old paths if we're on our old location. # Otherwise use the new language symlinks. # This can be removed once we have 'en' symlinks for every project. if lang_slug == proj.language: basepath = proj.rtd_build_path(version_slug) else: basepath = proj.translations_path(lang_slug) basepath = os.path.join(basepath, version_slug) log.info('Serving %s for %s' % (filename, proj)) if not settings.DEBUG: fullpath = os.path.join(basepath, filename) mimetype, encoding = mimetypes.guess_type(fullpath) mimetype = mimetype or 'application/octet-stream' response = HttpResponse(mimetype=mimetype) if encoding: response["Content-Encoding"] = encoding try: response['X-Accel-Redirect'] = os.path.join('/user_builds', proj.slug, 'rtd-builds', version_slug, filename) except UnicodeEncodeError: raise Http404 return response else: return serve(request, filename, basepath)
def serve_static(request, path, insecure=False, **kwargs): """ Serve static files below a given point in the directory structure or from locations inferred from the staticfiles finders. To use, put a URL pattern such as: (r'^static/(?P<path>.*)$', 'annalist.views.statichack.serve_static') in your `annalist_root/urls.py` URL configuration file. It uses the django.views.static.serve() view to serve the found files. """ # log.info("serve_static %s"%(path)) try: normalized_path = posixpath.normpath(unquote(path)).lstrip('/') absolute_path = finders.find(normalized_path) if not absolute_path: if path.endswith('/') or path == '': raise Http404("Directory indexes are not allowed here.") raise Http404("'%s' could not be found" % path) document_root, path = os.path.split(absolute_path) # log.info("document_root %s, path %s"%(document_root, path)) except Exception as e: log.info(str(e)) raise return static.serve(request, path, document_root=document_root, **kwargs)
def serve_docs(request, username, project_slug, filename): """ The way that we're serving the documentation. This is coming out of Django so that we can do simple page counting, and because later we can use Django auth to protect views. This could probably be refactored to serve out of nginx if we have more time. """ proj = Project.objects.get(slug=project_slug, user__username=username) if not filename: filename = "index.html" filename = filename.rstrip('/') if 'html' in filename: try: proj.full_html_path except AttributeError: return render_to_response('404.html', {'project': proj}, context_instance=RequestContext(request)) pageview, created = PageView.objects.get_or_create(project=proj, url=filename) if not created: pageview.count = F('count') + 1 pageview.save() return serve(request, filename, proj.full_html_path)
def download(request, package_name, file_name): pkg = get_object_or_404(Pkg, name=package_name) release_url = get_object_or_404(ReleaseUrl, filename=file_name, release__pkg=pkg) filepath = get_binary_path(release_url) return serve(request, filepath, '/')
def serve_pages(request, coll_id, page_ref, insecure=False, **kwargs): """ Serve static files below a given point in the directory structure or from locations inferred from the staticfiles finders. To use, put a URL pattern such as: url(r'^c/(?P<coll_id>\w{1,128})/p/(?P<page_ref>[\w/.-]{1,250})$', 'annalist.views.statichack.serve_pages`), in your `annalist_root/annalist/urls.py` URL configuration file. It uses the django.views.static.serve() view to serve the found files. """ # log.info("serve_pages %s"%(path)) try: page_path = settings.BASE_SITE_DIR+"/c/"+coll_id+"/p/"+page_ref log.info("statichack.serve_pages %s"%(page_path,)) normalized_path = posixpath.normpath(unquote(page_path)) if not os.path.exists(normalized_path): if page_path.endswith('/') or page_path == '': raise Http404("Directory indexes are not allowed here.") raise Http404("'%s' could not be found" % page_path) document_root, path = os.path.split(normalized_path) # log.info("document_root %s, path %s"%(document_root, path)) except Exception as e: log.info(str(e)) raise return static.serve(request, path, document_root=document_root, **kwargs)
def mediaserver(request, path): return serve(request, path, settings.MEDIA_ROOT)
def serve_variation_dev(request, path, document_root=None, show_indexes=False): try: return serve(request, path, document_root, show_indexes) except Http404: return serve_variation(request, path)
def get_file(request, file_name): filepath = os.path.join(settings.BASE_DIR, '.well-known/acme-challenge', file_name) return serve(request, os.path.basename(filepath), os.path.dirname(filepath))
def serve(self, request): relative_url = request.path[len(self.base_url[2]):] return serve(request, relative_url, document_root=self.get_base_dir())
def sphinx_static(request, lang, version, path, subpath=None): """ Serve Sphinx static assets from a subdir of the build location. """ document_root = str(get_doc_root_or_404(lang, version).joinpath(subpath)) return static.serve(request, document_root=document_root, path=path)
def loader_validation(request): """ Used for loader.io validation only. """ from django.views.static import serve filepath = './loaderio-9810f09c6dab96eb6166d196409169e0.txt' return serve(request, os.path.basename(filepath), os.path.dirname(filepath))
def serve_from_media_root(request, path): """ A convenience view for serving files from the media root directory. """ return serve(request, path, document_root=settings.MEDIA_ROOT)
def protected_serve(request, path, document_root=None, show_indexes=False): return serve(request, path, document_root, show_indexes)
def favicon(request): path = 'favicon.ico' document_root = settings.STATIC_ROOT fullpath = os.path.join(document_root, path) #debug() return serve(request, path=path, document_root=settings.STATIC_ROOT)
def onesignal_sdk_updater_worker(request): return serve(request, 'js/spp/OneSignalSDUpdaterKWorker.js', document_root=os.path.join(settings.BASE_DIR, 'pythonpro', 'core', 'static'))
def get(self, request, *args, **kwargs): print(self.kwargs[self.lookup_field]) file_path = settings.MEDIA_ROOT return serve(request, path=self.kwargs[self.lookup_field], document_root=file_path)
def protected_serve(request, path, document_root=None, show_indexes=False): """ Serve static files from ``MEDIA_ROOT`` for authenticated requests. """ return serve(request, path, document_root, show_indexes)
# 项目配置信息(项目路径),在 setting 文件里的写法是: PROJECT_DIR = os.path.dirname(__file__) from xyt.settings import PROJECT_DIR # 写出文件 news_file = codecs.open('%s/test.html' % os.path.abspath(PROJECT_DIR), 'wb', 'utf-8') try: t = get_template('news/newsContent.html') html = t.render(Context(locals())) news_file.write(html) except IOError, ioe: raise RpcError(ioe.message) finally: news_file.close() # 返回静态文件 return serve(request, document_root=PROJECT_DIR, path="test.html") 5.获取参数 def index(request, other_ars=False): # 判断请求类型 if request.method == 'POST': # 判断发送方式 print 'POST...' # 获取请求参数 code = request.POST.get('code', '') # 获取post过来的值 iacs = request.GET.get('iacs') # 获取get的值 name = request.REQUEST.get('name','') # 获取请求的值 # 获取请求 url scheme = request.META.get('wsgi.url_scheme', 'http') # http / https absolute_uri = request.build_absolute_uri() # 带域名的完整请求地址,如“http://127.0.0.1:8080/api/info/?a=1&b=2” full_url = request.get_full_path() # 获取带参数URL,如“/api/info/?a=1&b=2”
def serve_file(request, path): """ Serve a file directly from the filesystem """ document_root = os.path.dirname(path) filename = os.path.basename(path) return static.serve(request, filename, document_root=document_root)
def objects_inventory(request, lang, version): response = static.serve(request, document_root=get_doc_root_or_404(lang, version), path="objects.inv") response['Content-Type'] = "text/plain" return response
def get_detail_report(request, path): if request.user.is_authenticated(): return serve(request, path, settings.GALEN_REPORT_DIR) else: return redirect('/admin/login/?next=/automate/')
def pokedex(request): objectpath = 'projects/static/pokedex.pdf' return serve(request, os.path.basename(objectpath), os.path.dirname(objectpath))
def dnc_pipeline(request): objectpath = 'projects/static/dnc_pipeline.pdf' return serve(request, os.path.basename(objectpath), os.path.dirname(objectpath))
def activelearning(request): objectpath = 'projects/static/activelearning.pdf' return serve(request, os.path.basename(objectpath), os.path.dirname(objectpath))
def nmt(request): objectpath = 'projects/static/nmt.pdf' return serve(request, os.path.basename(objectpath), os.path.dirname(objectpath))
def DownloadResume(request): filepath = 'templates/RESUME.pdf' return serve(request, os.path.basename(filepath), os.path.dirname(filepath))
def symcnn(request): objectpath = 'projects/static/assistedmodeling.pdf' return serve(request, os.path.basename(objectpath), os.path.dirname(objectpath))
def GetDB(request): filepath = '../anime.db' return serve(request, os.path.basename(filepath), os.path.dirname(filepath))
def getthumbnail( request, path ): return serve( request, path, settings.THUMBNAIL_ROOT, False )
def index(request): cov.html_report() return serve(request, os.path.basename(filepath + '/index.html'), os.path.dirname(filepath))
def serve(request, path, insecure=False, **kwargs): """ Serve static files below a given point in the directory structure or from locations inferred from the staticfiles finders. To use, put a URL pattern such as:: from django.contrib.staticfiles import views url(r'^(?P<path>.*)$', views.serve) in your URLconf. It uses the django.views.static.serve() view to serve the found files. """ if not settings.DEBUG and not insecure: raise Http404 <<<<<<< HEAD normalized_path = posixpath.normpath(unquote(path)).lstrip('/') ======= normalized_path = posixpath.normpath(path).lstrip('/') >>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435 absolute_path = finders.find(normalized_path) if not absolute_path: if path.endswith('/') or path == '': raise Http404("Directory indexes are not allowed here.") raise Http404("'%s' could not be found" % path) document_root, path = os.path.split(absolute_path) return static.serve(request, path, document_root=document_root, **kwargs)
def contribute_view(request): """Generate a contribute.json""" return serve(request, 'contribute.json', document_root=settings.ROOT)
def contribute_json(request): return static.serve(request, "contribute.json", document_root=settings.ROOT)
def pot_file(request, pot_name): version = DocumentRelease.objects.current().version doc_root = str(get_doc_root_or_404('en', version, subroot='gettext')) return static.serve(request, document_root=doc_root, path=pot_name)
def documentation(request, path): if not path or path.endswith('/'): path += 'index.html' return serve(request, path, docs.DOCS_HTML_PATH)