def handle(request): path = request.path[1:] if path == "favicon.ico" or path.endswith(".png"): return serve(request, path) if path.startswith("static"): return serve(request, request.path[len("/static/"):]) if path.startswith("theme"): return serve(request, request.path[len("/theme/"):]) if path == "" or path.endswith("/"): path = path + "index.html" if os.path.exists(dotslash(path)) and os.path.isfile(dotslash(path)): return path ajax = read_yaml_file(dotslash("ajax.yaml")) if ajax: if request.GET: path = request.path + "?" + request.META["QUERY_STRING"] # TODO: make it immune to order of GET params if path in ajax: return JSONResponse(ajax[path]) if request.path in ajax: return JSONResponse(ajax[request.path]) if not request.path.endswith("/"): return d.HttpResponseRedirect(request.path + "/") raise d.Http404("File not found.")
def getImage(request, author_guid, image_name): # Find the file, read it, and send it as an # HTTPResponse object try: imagePath = author_guid + "/" + image_name image = Image.objects.get(file=imagePath) content_type = mimetypes.guess_type(image.file.path) except Image.DoesNotExist: return views.serve(request, 'images/not_found.png') if request.user.is_authenticated(): author = Author.objects.get(user=request.user) if image.isAllowedToViewImage(author): with open(image.file.path, 'rb') as f: return HttpResponse(f.read(), content_type=content_type) else: return views.serve(request, 'images/not_allowed.png') else: if image.visibility == Image.PUBLIC: with open(image.file.path, 'rb') as f: return HttpResponse(f.read(), content_type=content_type) else: return views.serve(request, 'images/not_allowed.png')
def process_response(self, request, response): if response is d.Http404: return response path = request.path[1:] if path == "favicon.ico" or path.endswith(".png"): return serve(request, path) if path.startswith("theme"): return serve(request, request.path[len("/theme/"):]) if path == "" or path.endswith("/"): path = path + "index.html" if os.path.exists(dotslash(path)) and os.path.isfile(dotslash(path)): return d.render_to_response( path, {}, d.RequestContext(request) ) ajax = read_yaml_file(dotslash("ajax.yaml")) if ajax: if request.GET: path = request.path + "?" + request.META["QUERY_STRING"] # TODO: make it immune to order of GET params if path in ajax: return JSONResponse(ajax[path]) if request.path in ajax: return JSONResponse(ajax[request.path]) if not request.path.endswith("/"): return d.HttpResponseRedirect(request.path + "/") return response
def process_response(self, request, response): if response is d.Http404: return response path = request.path[1:] if path == "favicon.ico" or path.endswith(".png"): return serve(request, path) if path.startswith("theme"): return serve(request, request.path[len("/theme/"):]) if path == "" or path.endswith("/"): path = path + "index.html" if os.path.exists(dotslash(path)) and os.path.isfile(dotslash(path)): return d.render_to_response(path, {}, d.RequestContext(request)) ajax = read_yaml_file(dotslash("ajax.yaml")) if ajax: if request.GET: path = request.path + "?" + request.META["QUERY_STRING"] # TODO: make it immune to order of GET params if path in ajax: return JSONResponse(ajax[path]) if request.path in ajax: return JSONResponse(ajax[request.path]) if not request.path.endswith("/"): return d.HttpResponseRedirect(request.path + "/") return response
def serve_dev_assets(request): """Serving compiled JS assets during development During development, Django collects the static files so we can serve them via this view. """ if request.path == '/': return serve(request, 'index.html') return serve(request, request.path)
def doxygen(request, path=None): """ Hack to serve doxygen files """ if not path: return static_server.serve(request, "doxygen/html/index.html") # Super hacky ... for some reason index.html doesn't work ?? elif path == "index.html/": return redirect("/doxygen/") else: return static_server.serve(request, "doxygen/html/%s" % path)
def static_media(request, **kwargs): """ Serve static files below a given point in the directory structure. """ from django.contrib.staticfiles.views import serve module = kwargs.get('module') path = kwargs.get('path', '') version = kwargs.get('version') if module: path = '%s/%s' % (module, path) response = serve(request, path, insecure=True) # We need CORS for font files if path.endswith( ('.js', '.ttf', '.ttc', '.otf', '.eot', '.woff', '.woff2')): response['Access-Control-Allow-Origin'] = '*' # If we have a version, we can cache it FOREVER if version is not None: response['Cache-Control'] = 'max-age=315360000' return response
def student_example_file(request): if not request.user.is_authenticated() or request.user.type != 'admin': return redirect('login') else: filepath = "/static/example_student_list.xlsx" return serve(request, os.path.basename(filepath), os.path.dirname(filepath))
def static_app_view(request, event_slug): event = settings.INFOKALA_GET_EVENT_OR_404(slug=event_slug) if not is_user_allowed_to_access(request.user, event): return render(request, 'infokala_tracon_forbidden.html', status=403) return serve(request, path='infokala/infokala.html', insecure=True)
def list(self, request, *args, **kwargs): # Switch between static experiments JSON or dynamic API data based on # waffle flag static_experiments_json if waffle.flag_is_active(request, 'static_experiments_json'): return serve(request, path='api/experiments.json') return super(ExperimentViewSet, self).list(request, *args, **kwargs)
def serve_with_Expires(request, path, cache_timeout=365 * 24 * 60 * 60): """ This view can be used in the development server to add the Expires header on the static files protected by the modtime change detection in the freshstatic template tag (see there). The browsers will stop asking for the file again and again during the normal browsing. Example in your urls.py:: urlpatterns += static.static(settings.STATIC_URL, serve_with_Expires) By adding a cache_timeout parameter to the above call with the number of seconds you will change the deafult expiration of 1 year. """ from django.utils.http import http_date from django.contrib.staticfiles.views import serve response = serve(request, path) if not response.has_header('Expires'): response['Expires'] = http_date(time.time() + cache_timeout) return response
def process_request(self, request): if request.path.startswith(settings.STATIC_URL): static_path = request.path[len(settings.STATIC_URL):] return views.serve(request, static_path) else: if request.method == 'POST': template_str = request.POST.get('template', 'no template provided') template = Template(template_str) if 'context' in request.POST: context = json.loads(request.POST['context']) magic_context = {} for citem in context: if "." not in context: cvalue = context[citem] magic_context[citem] = \ OverAccomodatingContextItem(context, cvalue, citem) c = Context(magic_context) return HttpResponse(template.render(c)) else: c = get_context(template) return HttpResponse(json.dumps(c)) else: return HttpResponse(""" <form action="." method="post"> Template: <input type="text" name="template"><br/> Data: <textarea name="context"></textarea><br/> <input type="submit"> </form> """)
def serve_static_content(request, path): if not settings.DEBUG: raise Http404('static content files not served when not in DEBUG mode') path = rewrite_package_path(path) response = static_views.serve(request, path) response['Content-Cache'] = 'no-store' return response
def static_media(request, **kwargs): """ Serve static files below a given point in the directory structure. """ from django.contrib.staticfiles.views import serve module = kwargs.get('module') path = kwargs.get('path', '') version = kwargs.get('version') if module: path = '%s/%s' % (module, path) response = serve(request, path, insecure=True) # We need CORS for font files if path.endswith(('.js', '.ttf', '.ttc', '.otf', '.eot', '.woff', '.woff2')): response['Access-Control-Allow-Origin'] = '*' # If we have a version and not DEBUG, we can cache it FOREVER if version is not None and not settings.DEBUG: response['Cache-Control'] = FOREVER_CACHE else: # Otherwise, we explicitly don't want to cache at all response['Cache-Control'] = NEVER_CACHE return response
def serve(self, request, path): from django.contrib.staticfiles import finders absolute_path = finders.find(path) if not absolute_path: raise Http404('%r could not be matched to a static file.' % path) absolute_path, filename = os.path.split(absolute_path) return serve(request, path=filename, document_root=absolute_path)
def serve_with_Expires(request, path, cache_timeout=365 * 24 * 60 * 60): """ This view can be used in the development server to add the Expires header on the static files protected by the modtime change detection in the freshstatic template tag (see there). The browsers will stop asking for the file again and again during the normal browsing. Example in your urls.py:: urlpatterns += static.static(settings.STATIC_URL, serve_with_Expires) By adding a cache_timeout parameter to the above call with the number of seconds you will change the deafult expiration of 1 year. """ from django.utils.http import http_date from django.contrib.staticfiles.views import serve response = serve(request, path) if not response.has_header('Expires'): response['Expires'] = http_date(time.time() + cache_timeout) return response
def process_request(self, request): if request.path.startswith(settings.STATIC_URL): static_path = request.path[len(settings.STATIC_URL):] return views.serve(request, static_path) else: if request.method == 'POST': template_str = request.POST.get('template', 'no template provided') template = Template(template_str) if 'context' in request.POST: context = json.loads(request.POST['context']) magic_context = {} for citem in context: if "." not in context: cvalue = context[citem] magic_context[citem] = \ OverAccomodatingContextItem(context, cvalue, citem) c = Context(magic_context) return HttpResponse(template.render(c)) else: c = get_context(template) return HttpResponse(json.dumps(c)) else: return HttpResponse( """ <form action="." method="post"> Template: <input type="text" name="template"><br/> Data: <textarea name="context"></textarea><br/> <input type="submit"> </form> """)
def test(request): #stock = json.loads(request.body) #query1 = querybuild(['AAPL','GOOG','YHOO','MSFT']) #data = requests.get(query1) #add_to_stock(data.text) #add_to_symbols(stock['stocks']) #dic = {"response":data.text} return serve(request,"abc.zip")
def serve_html(request, file_name): if not file_name: file_name = 'index' file_path = '{}.html'.format(file_name) # Use Django staticfiles's serve view. return serve(request, file_path,)
def serve_problem_asset(request, path): ''' a wrapper function around django.contrib.staticfiles.views.serve() to serve problem assets to superusers only ''' if request.user.is_superuser: return views.serve(request, path, show_indexes=True) else: return HttpResponseForbidden("Don't do that.")
def serve_problem_asset(request, path): ''' a wrapper function around django.contrib.staticfiles.views.serve() to serve problem assets to superusers only ''' if request.user.is_superuser: return views.serve(request, path, show_indexes=True) else: return HttpResponseForbidden("Don't do that.")
def show(request, tipo, url): dato = getDoc(tipo, url, request.session) if dato == None: try: return serve(request, 'content_iesgn' + "/" + tipo + "/" + url) except: raise Http404 info = {"dato": dato, "tipo": tipo} return render(request, "mostrardoc.html", info)
def _serve_with_headers_fixed(request, path, insecure=False, **kwargs): response = serve(request, path, insecure=insecure, **kwargs) # Allow loading of github-btn.html in an <iframe> if path.startswith("3rdparty/github-buttons-") and path.endswith( "/docs/github-btn.html"): response["X-Frame-Options"] = "sameorigin" return response
def serve_docs(request, path=''): docs_path = os.path.join(settings.DOCS_DIR, path) if os.path.isdir(docs_path): path = os.path.join(path, 'index.html') path = os.path.join(settings.DOCS_STATIC_NAMESPACE, path) return serve(request, path, insecure=True)
def _serve_with_headers_fixed(request, path, insecure=False, **kwargs): response = serve(request, path, insecure=insecure, **kwargs) # Allow loading of github-btn.html in an <iframe> if (path.startswith('3rdparty/github-buttons-') and path.endswith('/docs/github-btn.html')): response['X-Frame-Options'] = 'sameorigin' return response
def serve(self, request): try: resp = super(ScssMediaHandler, self).serve(request) except Http404: path = request.path[len(settings.STATIC_URL):] resp = serve(request, path[:-4] + '.scss') resp.content = Scss().compile(resp.content) resp['Content-Length'] = len(resp.content) resp['Content-Type'] = 'text/css' return resp
def get(self, request, path, **kwargs) -> HttpResponse: """ Tries to serve the requested file. If it is not found or a directory is requested, the index.html is delivered. """ try: response = serve(request, path, **kwargs) except Http404: response = static.serve(request, self.index_path, document_root=self.index_document_root, **kwargs) return response
def widget(request, name): """ Return widget template Only for development environment. In production, add the following line into virtualhost configuration:: AliasMatch ^/views/(.*).html /var/www/seaboard/static/widgets/$1/$1.html :param name: widget name. """ return serve(request, 'widgets/' + name + '/' + name + '.html')
def serve_docs(request, path): docs_path = os.path.join(settings.DOCS_DIR, path) # /docs/<path>/ に`index.html`を追加する if os.path.isdir(docs_path): path = os.path.join(path, 'index.html') # /docs/<path>/index.html はそのまま返す path = os.path.join(settings.DOCS_STATIC_NAMESPACE, path) return serve(request, path, insecure=True)
def serve_dev_assets(request): """Serving compiled JS assets during development During development, Django collects the static files so we can serve them via this view. """ try: return serve(request, request.path) except Http404: # If we failed to find a static file, instead of raising a 404 error, # we serve the index template and let the frontend to render the 404 page. return index(request)
def direct_serv(request,requested_file): start_time = datetime.now() utils.debug_print('Requested key from user: '******'flow') msg = "%s\,%s\,%s\,%s\,%s\,%s"%(start_time.strftime("%H:%M:%S"),\ str(datetime.now() - start_time),\ "Unknown",\ requested_file,\ str(psutil.cpu_percent()),\ str(psutil.virtual_memory()[2])) utils.print_performance(msg) return serve(request,consts.PWD_MEDIA_FILES+requested_file)
def retrieve(self, request, *args, **kwargs): """Use the deep serializer for individual retrieval, which includes ExperimentDetail items""" # Switch between static experiments JSON or dynamic API data based on # waffle flag static_experiments_json if waffle.flag_is_active(request, 'static_experiments_json'): return serve(request, path='api/experiments/%s.json' % kwargs['pk']) instance = self.get_object() serializer = ExperimentSerializer( instance, context=self.get_serializer_context()) return Response(serializer.data)
def download(request): keys = request.path.split('/') print keys key = int(keys[-2]) dat = Data.objects.filter(id=key).first() if(dat.follow_user==True): fname = dat.file print "received" if(keys[-3]=='ajax'): return HttpResponseRedirect('/download/15/') return serve(request,fname.name) else: return render(request,"failed.html",{})
def static_media(request, **kwargs): """ Serve static files below a given point in the directory structure. """ from django.contrib.staticfiles.views import serve module = kwargs.get('module') path = kwargs.get('path', '') if module: path = '%s/%s' % (module, path) return serve(request, path, insecure=True)
def static_media(request, **kwargs): """ Serve static files below a given point in the directory structure. """ from django.contrib.staticfiles.views import serve module = kwargs.get('module') path = kwargs.get('path', '') if module: path = '%s/%s' % (module, path) return serve(request, path, insecure=True)
def get(self, request, path, **kwargs) -> HttpResponse: """ Tries to serve the requested file. If it is not found or a directory is requested, the index.html is delivered. """ try: response = serve(request, path, insecure=True, **kwargs) except Http404: response = static.serve( request, self.index_path, document_root=self.index_document_root, **kwargs, ) return response
def inst_logo(request, inst_type): # Return institution logo # given institution type try: inst = plaid_client.institution_search(institution_id=inst_type).json() if inst == [] or not inst['logo']: raise ValueError except ValueError: return serve(request, 'img/umbrella.png') inst_image = inst['logo'] inst_image_bin = base64.b64decode(inst_image) return HttpResponse(inst_image_bin, content_type='image/jpeg')
def media(self, request, module, path): """ Serve static files below a given point in the directory structure. """ if conf.USE_STATICFILES and serve: return serve(request, path='%s/%s' % (module, path)) if module == 'nexus': document_root = os.path.join(NEXUS_ROOT, 'static') else: document_root = self.get_module(module).media_root path = posixpath.normpath(urllib.unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not part: # Strip empty path components. continue drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): # Strip '.' and '..' in path. continue newpath = os.path.join(newpath, part).replace('\\', '/') if newpath and path != newpath: return HttpResponseRedirect(newpath) fullpath = os.path.join(document_root, newpath) if os.path.isdir(fullpath): raise Http404("Directory indexes are not allowed here.") if not os.path.exists(fullpath): raise Http404('"%s" does not exist' % fullpath) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) mimetype = mimetypes.guess_type( fullpath)[0] or 'application/octet-stream' if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): return HttpResponseNotModified(mimetype=mimetype) contents = open(fullpath, 'rb').read() response = HttpResponse(contents, mimetype=mimetype) response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) response["Content-Length"] = len(contents) return response
def static_media(request, **kwargs): """ Serve static files below a given point in the directory structure. """ from django.contrib.staticfiles.views import serve module = kwargs.get('module') path = kwargs.get('path', '') if module: path = '%s/%s' % (module, path) response = serve(request, path, insecure=True) # We need CORS for font files if path.endswith(('.eot', '.ttf', '.woff', '.js')): response['Access-Control-Allow-Origin'] = '*' return response
def static_media(request, **kwargs): """ Serve static files below a given point in the directory structure. """ from django.contrib.staticfiles.views import serve module = kwargs.get('module') path = kwargs.get('path', '') if module: path = '%s/%s' % (module, path) response = serve(request, path, insecure=True) # We need CORS for font files if path.endswith(('.eot', '.ttf', '.woff')): response['Access-Control-Allow-Origin'] = '*' return response
def media(self, request, module, path): """ Serve static files below a given point in the directory structure. """ if conf.USE_STATICFILES and serve: return serve(request, path='%s/%s' % (module, path)) if module == 'nexus': document_root = os.path.join(NEXUS_ROOT, 'static') else: document_root = self.get_module(module).media_root path = posixpath.normpath(urllib.unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not part: # Strip empty path components. continue drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): # Strip '.' and '..' in path. continue newpath = os.path.join(newpath, part).replace('\\', '/') if newpath and path != newpath: return HttpResponseRedirect(newpath) fullpath = os.path.join(document_root, newpath) if os.path.isdir(fullpath): raise Http404("Directory indexes are not allowed here.") if not os.path.exists(fullpath): raise Http404('"%s" does not exist' % fullpath) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) mimetype = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream' if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): return HttpResponseNotModified(mimetype=mimetype) contents = open(fullpath, 'rb').read() response = HttpResponse(contents, mimetype=mimetype) response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) response["Content-Length"] = len(contents) return response
def dispatch(self, request, path): dir_path = os.path.dirname(os.path.realpath(__file__)) static_path = os.path.join(dir_path, 'static/mkdocs_build') docs_path = os.path.join(static_path, path) if os.path.isdir(docs_path): path = os.path.join(path, 'index.html') path = os.path.join('mkdocs_build', path) file_response = serve(request, path, insecure=True) response = HttpResponse( file_response.streaming_content, content_type=file_response.get('Content-type') + ';charset=utf-8') context_data = self.get_context_data() diazo = DiazoTransformer(request, response) response = diazo.transform(self.diazo_rules, self.diazo_theme_template, self.html5, context_data) return response
def get(self, path, requirejsFallback=None, **kwargs): class request(object): # mockup META = {'HTTP_IF_MODIFIED_SINCE': None} try: return super(StaticsStorage, self).get(path, requirejsFallback, **kwargs) except self.PathNotFound: from django.contrib.staticfiles.views import serve from django.utils.six.moves.urllib.request import url2pathname from django.http import Http404 if requirejsFallback: if os.path.exists(os.path.join(self.root, requirejsFallback)): path = requirejsFallback try: return serve(request, path, insecure=True) except Http404: pass raise self.PathNotFound(path=path, root=self.root, storage=self, **kwargs)
def static_serve_dev(request, path): """Proxy missing static files to the webpack server. This view replaces django's static files serve view. When a file is missing from django's paths, then we make a proxy request to the webpack server to see if it's a front-end file. Note that to enable this view, you need to run your django with the nostatic option, like this:: $ ./manage.py runserver --nostatic """ try: # First try to load the file with django's regular serve view. return serve(request, path, insecure=True) except Http404: # If the file couldn't be found in django's static files, then we # try to proxy it to the webpack server. return catchall_dev(request)
def static_serve_dev(request, path, insecure=False, **kwargs): """Proxy missing static files to the webpack server. This view replaces django's static files serve view. When a file is missing from django's paths, then we make a proxy request to the webpack server to see if it's a front-end file. Note that to enable this view, you need to run your django with the nostatic option, like this:: $ ./manage.py runserver --nostatic """ try: # First try to load the file with django's regular serve view. return serve(request, path, insecure=False, **kwargs) except Http404: # If the file couldn't be found in django's static files, then we # try to proxy it to the webpack server. return catchall_dev(request)
async def application(scope, receive, send): assert scope["type"] == "http" while (await receive())["more_body"]: pass meta = {} headers = dict(scope["headers"]) if b"if-modified-since" in headers: meta["HTTP_IF_MODIFIED_SINCE"] = headers[b"if-modified-since"].decode( "latin-1") request = OurHttpRequest(meta) try: django_response = views.serve(request, scope["path"]) except Http404 as err: django_response = HttpResponseNotFound() await send({ "type": "http.response.start", "status": django_response.status_code, "headers": [ (b"Access-Control-Allow-Origin", b"*"), *((k.encode("latin-1"), v.encode("latin-1")) for k, v in django_response.items()), ], }) if django_response.streaming: # success for chunk in django_response: await send({ "type": "http.response.body", "body": chunk, "more_body": True }) await send({"type": "http.response.body"}) else: await send({ "type": "http.response.body", "body": django_response.content })
def serve(self, request): """ Actually serves the request path. """ # serve static content as usually response = serve(request, self.file_path(request.path), insecure=True) # resource is using the template system? if isinstance(response, FileResponse) and re.match(r'.{1,}\.(template|templating)\..{1,}$', request.path): # load content from file response and run it through the template # system. The result is then packed into a new http response with # the last-modified timestamp based on the current date and time # and content type of the original response. content = ''.join([chunk for chunk in response.streaming_content]) rendered_response = HttpResponse( serve_static_with_context(content), content_type=response['Content-Type'] ) rendered_response['Content-Length'] = len(rendered_response.content) rendered_response['Last-Modified'] = http_date() response = rendered_response return response
def static_media(request, **kwargs): """ Serve static files below a given point in the directory structure. """ from django.contrib.staticfiles.views import serve module = kwargs.get('module') path = kwargs.get('path', '') version = kwargs.get('version') if module: path = '%s/%s' % (module, path) response = serve(request, path, insecure=True) # We need CORS for font files if path.endswith(('.js', '.ttf', '.ttc', '.otf', '.eot', '.woff', '.woff2')): response['Access-Control-Allow-Origin'] = '*' # If we have a version, we can cache it FOREVER if version is not None: response['Cache-Control'] = 'max-age=315360000' return response
def return_static(request, path, insecure=True, **kwargs): return serve(request, path, insecure, **kwargs)
def ui_serve(request, path): return views.serve(request, '/ui/'+path)
def serve(self, request): """ Actually serves the request path. """ return serve(request, self.file_path(request.path), insecure=True)
def hello( req, path, *args, **kwargs): print path return serve(req, path, *args, **kwargs)
def staticfiles_handler_serve(self, request): import time resp = serve(request, self.file_path(request.path), insecure=True) if resp.status_code == 200: resp["Expires"] = http_date(time.time() + 24 * 3600) return resp
def protected_serve(request, path, insecure=False, **kwargs): return serve(request, path, insecure, **kwargs)
def index(request): return static.serve(request, 'index.html', insecure=True)
def serve(self, request): document_root, path = os.path.split(self.file_path(request.path)) return static.serve(request, path, document_root=document_root, insecure=True)