hyperlinks blocked on opening as a new tab - django - python

I have a python script (A.py) that accepts users input via form and runs another python script (B.py). B.py stores html formatted results into a folder named yyyymmdd.
The file generated by B.py is like "results_hhmmss.html", so every time B.py script is executed a new has html file is created.
As per my urls.py code below, visiting 127.0.0.1:8888 takes me to home_page. Further, once i submit form using a button in the home_page, the scripts gets executed successfully and a result file is generated.
I am not sure how to render the results as the results file name keeps varying.
Hence, i tried keeping a constant page results.html and add a hyper-link to file results_hhmmss.html within results.html.
I tried providing href= with absolute path of results_hhmmss.html file and the hyperlink can be seen when hovered pointing to
file:///Users/msh0047/tmp/welcome/20200627/results_231603.html
However, upon clicking the hyperlink, nothing happens.
When I open the hyperlink in a new tab, i see blank page with "about:blank#blocked" in the address bar.
I also tried providing href= with relative path of the results_hhmmss.html file and the hyperlink can be seen when hovered pointing to
http://127.0.0.1:8888/20200627/results_231603.html , clicking the hyperlink throws error saying Page not found(404) and The current path, 20200627/results_231603.html didn't match any of these. (these = any of the url path listed in urls.py).
However, I can open that results_hhmmss.html file by directly type/paste the absolute path into the address bar.
I am not sure what wrong i am doing here, can you please help guiding me please.
urls.py contents as below:
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home_page),
path('results/', views.generate_results_file, name='run_generate_file_script'),
]
views.py contents file as below:
def generate_results_file(request):
hhmmss = str(datetime.now().strftime("%H%M%S"))
yyyymmdd = str(datetime.now().strftime("%Y%m%d"))
results_filename = "templates/results_" + hhmmss + ".html"
ls_cmd = "pwd; ls -lart | tee " + results_filename
output = subprocess.Popen(ls_cmd, shell=True, stdout=subprocess.PIPE)
wait_for_sec = request.POST.get('seconds')
time.sleep(int(wait_for_sec))
return render(request, results_filename)
def home_page(request):
# Purpose: Just display welcome home_page.html
return render(request, 'welcome/home_page.html')
Thanks heaps in advance for taking time to read this post and willingness to help.

It is http and not https, and "about:blank#blocked" is a browser security setting. Could it be that the browser security settings need to be adjusted?

Related

Calling a function on HTML page, not found

I am writing a tool to record and monitor downtime on a range of equipment.
I have my file structure as below:
File Structure
Sites is just a subfolder containing individual HTMLS for where the equipment is located.
Currently, flask runs webapp.py which contains:
>from . import app
>#app = (__init__.app)
>from . import views
>from . import ReportingTool
views.py has all of my #app.route's in it, up until the [site].html files. From there, on the [site].html file I ask for input from the user. I haven't started writing code to record the user input in any meaningful way, just want to get the data to a python script and commit them to variables. To this end, in the html file I have
<body>
<div class="menu">
<form method="post" enctype="multipart\form-data" action="{{ url_for('downTime') }}">
<fieldset class="datafieldset">
This then requests different data from the user in the form of multiple field sets as seen here: fieldsets
as you see in the code snippet above I set the action to be url_for('downTime'), downTime is a function in my python file ReportingTool.py. this throws out an error, "werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'downTime'. Did you mean 'supportguide' instead?" traceback
Is there something I need to add or specify on the html document to enable this page (and the other [site].html pages to call functions from the ReportingTool.py file? the #app.route that calls the [site].html file is this and that is called with a redirected from here I've only got it setup like that becuase I wanted the name for the site to appear in the address bar.
Thanks in advance.
I am not sure on steps to fix as I am kind of throwing myself in the deep end to learn basic coding by creating an application for my workplace to replace an excel spreadsheet I created.
You are not reaching the downTime function in the ReportingTool.py file. I suggest trying add_url_rule in your views.py by adding the /reported endpoint referencing the downTime function in ReportingTool.py. Something like this;
app.add_url_rule('/reported', 'ReportingTool.downTime', view_func=ReportingTool.downTime, methods=METHODS)
This answer is based on the responds for this question. You are trying to reach a function in a different file from your main view file. Assuming you are calling the page with the form from a function in the views.py file.
Solved with info from Kakedis' input, and the links they provided.
I added:
app.add_url_rule('/reported', 'ReportingTool.downTime', view_func=ReportingTool.downTime, methods=METHODS)
to webbapp.py, then:
#app.route('/reported')
def downTime():
try:
DTref = request.form['refDT']
except:
DTref = "No Reference"
print(DTref)
print("reported")
return(render_template("/UserRip.html"))
to ReportingTool.py
This now prints the above to console to confirm it's pulling the correct func and brings the user back to the starting page.

Unable to serve static file from flask server

I have a index.html file, which has the absolute path 'c:\project\web\frontend\index.html'
I am trying to return it using the following function
#webserver.route('/')
def home()
return webserver.send_static_file(path)
I have verified that the path is correct by accessing it directly in the browser.
I have tried to replace '\' with '/' without any luck.
It is running on a windows machine.
If you look at flask's documentation for send_static_file. You'll see that it says that it's used internally by flask framework to send a file to the browser. If you want to render an html, it's common to use render_template. You need to make sure that your index.html is in a folder called templates first.
So I would do the following:
#webserver.route('/')
def home()
return flask.render_template('index.html')
I had to define the path to be the static_folder, when creating the flask object. Once I defined the folder to be static, the html page was served.

Wagtail render any path in index page

I need to enable some pages to write an arbitrary URL that does not depend on the structure of the site.
For example I have structure:
/
/blog
/blog/blogpost1
/blog/blogpost2
But, for example, I need change url from /blog/blbogpost2 to /some/blogpost/url1
For this, I decided to give the opportunity to handle any URL of the main page of the site.
class IndexPage(RoutablePageMixin, Page):
...
#route(r'^(?P<path>.*)/$')
def render_page_with_special_path(self, request, path, *args, **kwargs):
pages = Page.objects.not_exact_type(IndexPage).specific()
for page in pages:
if hasattr(page, 'full_path'):
if page.full_path == path:
return page.serve(request)
# some logic
But now, if this path is not found, but I need to return this request to the standard handler. How can I do it?
This isn't possible with RoutablePageMixin; Wagtail treats URL routing and page serving as two distinct steps, and once it's identified the function responsible for serving the page (which, for RoutablePageMixin, is done by checking the URL route given in #route), there's no way to go back to the URL routing step.
However, it can be done by overriding the page's route() method, which is the low-level mechanism used by RoutablePageMixin. Your version would look something like this:
from wagtail.core.url_routing import RouteResult
class IndexPage(Page):
def route(self, request, path_components):
# reconstruct the original URL path from the list of path components
path = '/'
if path_components:
path += '/'.join(path_components) + '/'
pages = Page.objects.not_exact_type(IndexPage).specific()
for page in pages:
if hasattr(page, 'full_path'):
if page.full_path == path:
return RouteResult(page)
# no match found, so revert to the default routing mechanism
return super().route(request, path_components)

my hyperlink generated in django doesn't work

So I have the following environment; django 1.8. apache on ubuntu 14 with mod_wsgi and mod x-sendfile enabled.
I have a very simple view to server the files as follows:
def foo(request, filename):
response = HttpResponse()
response['Content-Disposition'] = 'attachment; filename={0}'.format(filename)
response['X-Sendfile'] = "/home/amir/DjV/Files/{0}".format(filename)
return response
and here's my urlconf regarding the view:
url(r'^foo/(.+)/$', foo)
I've written a snippet that generate absolute path to files to be presented in a download list. The generated paths work fine if I enter them in the browser; but if I use them as hyperlinks, when clicked it goes to blank page. For examlple here is one the urls that is generated by the snippet I mentioned:
http://192.168.43.6:8000/foo/uuid.txt
it works fine and I get to download the uuid.txt, but when I put it into django template as follows, it doesn't work:
192.168.43.6:8000/foo/uuid.txt
My question being: why my link works fine when entered manually but not when used as a hyperlink? Could it be because of being a local address? How can I fix it?
You need to specify a protocol inside your template when doing such things:
192.168.43.6:8000/foo/uuid.txt
However, you should not hard code urls in this way in special not if they are handled inside your Django application. Check {% url %} templating whether it could be a benefit for you

Displaying image in template with Flask?

So I am hosting some user-uploaded images on my site. I want to have an html page that displays the image inline, and some data about it on the side, etc. I've set up my app with two handlers, one that displays the image on the page that uses a url_for to get the url for the raw image(e.g. i.mysite.com/image.jpg). It displays on the page fine, but takes forever to load. When I remove this function and just generate a URL for the image alone without the page, it loads instantly. Is this just a flask thing that will be remedied in a production environment with a real webserver, or is there another way I should be doing this? The images are not in the /static folder, they are in their own folder. I get the url for the raw image link in the handler for the function that displays the page with the image on it, and pass that as a path to the template.
#app.route('/<filename>', subdomain='i')
def uploaded_image(filename):
return send_from_directory(app.config['IMAGE_FOLDER'], filename)
#app.route('/<tag>/', subdomain='i', methods=['GET'])
def display_image(tag):
file = Storedfile.query.filter_by(routing_id=tag).first()
filename = file.name
return render_template("image-page.html", source=url_for('uploaded_image', filename=filename))
Like I said it displays the image fine, but takes forever to load, and when I inspect the image on the page with FF's dev tools, instead of seeing an actual URL, I see something like
<img src="/pyhE4eJ.jpg"></img>
For the other links, I get actual URLS that are made from functions, like
Shouldn't the source for the image be looking like this too?

Categories

Resources