Calling a function on HTML page, not found - python

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.

Related

hyperlinks blocked on opening as a new tab - django

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?

Testing the html elements in flask routing templates unittest

I have a login page for a flask app with cloud database, I want to test the results after logging in, specifically, I want to test the HTML elements after logging in. I have seen people test return status code or using assertIn to check if data exist.
Is there a way for me to target a specific HTML tag, like <h1 id="userTitle"> </h1> from rendered templates after POST username, password to the route function login()
def test_users_login(self):
result = self.app.post('/login', data=dict(username='Nicole', password='abc123'), follow_redirects=True)
# I want to check the HTML tag's text value data after logging in
self.assertEqual(result.data.getTag("h1", b"Nicole") #What I imagined using <h1>
self.assertEqual(result.data.getId("user", b"Nicole") #What I imagined using id
#This returns true which is okay, because 'Nicole' exists in the whole page
self.assertIn(b'Nicole', result.data)
In my rendered jinja2 template I have this which is after logging in.
<h1 id="userTitle">{{ session['username'] }},Welcome!</h1>
I guess assertIn works well, but I just want to know how to test an HTML tag without running a browser test.
Although I didn't get a correct answer from here, but I just managed to do the unit-test with just assertIn, by checking the contents of the page.
Thanks everyone

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

Reading and writing files from html in Google App Engine

I am working with GAE and Python, I know python, but I don't know HTML, which seems to be what I need right now. I want to take in a text file write something in it then return it for download. I am using other people's examples, but far all I have is:
class MainPage(webapp.RequestHandler):
#http://bukhantsov.org/2011/12/python-google-app-engine-calculator/
def get(self):
self.response.out.write("""<html>
<body>
<form action='/' method='get' autocomplete='off'>
<input type='file' name='file'/><br/>
</form>
</body>
</html>""")
I imagine there is something I need to put in the file line so I can access what the user feeds it, but I don't know what or how to access it from the python code. So what should I do here?
If I understand your question correctly, you are trying to grab the text data being sent by the user via the GET call that is defined by the form action HTML line.
Concisely, you are looking for this call:
file = self.request.get('file')
This may also be useful:
filename = self.request.GET['file'].filename
These can be used in the same location and in conjunction with your "self.response.out".
More information can be found here:
https://developers.google.com/appengine/docs/python/tools/webapp/requestclass#Request_get
Alternatively, the BlobStore APIs may be easier.
https://developers.google.com/appengine/docs/python/blobstore/overview
Possibly related:
Upload files in Google App Engine,
Get original filename google app engine
Hope that helps!
Jess

How to run a Python script in a web page

I'm very new to Python. I just know what Python is.
I have created the below code (in Python IDLE):
print "Hi Welcome to Python test page\n";
print "Now it will show a calculation";
print "30+2=";
print 30+2;
Then I saved this page in my localhost as index.py
I run the script using
http://localhost/index.py
But it does not show the executed Python script. Instead, it showed the above code as HTML. Where is the problem? How can I run a Python file in a web page?
In order for your code to show, you need several things:
Firstly, there needs to be a server that handles HTTP requests. At the moment you are just opening a file with Firefox on your local hard drive. A server like Apache or something similar is required.
Secondly, presuming that you now have a server that serves the files, you will also need something that interprets the code as Python code for the server. For Python users the go to solution is nowadays mod_wsgi. But for simpler cases you could stick with CGI (more info here), but if you want to produce web pages easily, you should go with a existing Python web framework like Django.
Setting this up can be quite the hassle, so be prepared.
As others have pointed out, there are many web frameworks for Python.
But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:
Rename your script to index.cgi. You also need to execute chmod +x index.cgi to give it execution privileges.
Add these 2 lines in the beginning of the file:
#!/usr/bin/python
print('Content-type: text/html\r\n\r')
After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.
Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python might work instead.
Using the Flask library in Python, you can achieve that.
Remember to store your HTML page to a folder named "templates" inside where you are running your Python script.
So your folder would look like
templates (folder which would contain your HTML file)
your Python script
This is a small example of your Python script. This simply checks for plagiarism.
from flask import Flask
from flask import request
from flask import render_template
import stringComparison
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template("my-form.html") # This should be the name of your HTML file
#app.route('/', methods=['POST'])
def my_form_post():
text1 = request.form['text1']
text2 = request.form['text2']
plagiarismPercent = stringComparison.extremelySimplePlagiarismChecker(text1,text2)
if plagiarismPercent > 50 :
return "<h1>Plagiarism Detected !</h1>"
else :
return "<h1>No Plagiarism Detected !</h1>"
if __name__ == '__main__':
app.run()
This a small template of HTML file that is used:
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Enter the texts to be compared</h1>
<form action="." method="POST">
<input type="text" name="text1">
<input type="text" name="text2">
<input type="submit" name="my-form" value="Check !">
</form>
</body>
</html>
This is a small little way through which you can achieve a simple task of comparing two strings and which can be easily changed to suit your requirements.
If you are using your own computer, install a software called XAMPP (or WAMP either works). This is basically a website server that only runs on your computer. Then, once it is installed, go to the xampp folder and double click the htdocs folder. Now you
need to create an HTML file (I'm going to call it runpython.html). (Remember to move the Python file to htdocs as well.)
Add in this to your HTML body (and inputs as necessary).
<form action = "file_name.py" method = "POST">
<input type = "submit" value = "Run the Program!!!">
</form>
Now, in the Python file, we are basically going to be printing out HTML code.
# We will need a comment here depending on your server. It is basically telling the server where your python.exe is in order to interpret the language. The server is too lazy to do it itself.
import cgitb
import cgi
cgitb.enable() # This will show any errors on your webpage
inputs = cgi.FieldStorage() # REMEMBER: We do not have inputs, simply a button to run the program. In order to get inputs, give each one a name and call it by inputs['insert_name']
print "Content-type: text/html" # We are using HTML, so we need to tell the server
print # Just do it because it is in the tutorial :P
print "<title> MyPythonWebpage </title>"
print "Whatever you would like to print goes here, preferably in between tags to make it look nice"
Well, the OP didn't say server or client side, so I will just leave this here in case someone like me is looking for client side:
Skulpt is a implementation of Python to run at client side. Very interesting, no plugin required, just simple JavaScript code.
With your current requirement, this would work:
def start_html():
return '<html>'
def end_html():
return '</html>'
def print_html(text):
text = str(text)
text = text.replace('\n', '<br>')
return '<p>' + str(text) + '</p>'
if __name__ == '__main__':
webpage_data = start_html()
webpage_data += print_html("Hi Welcome to Python test page\n")
webpage_data += fd.write(print_html("Now it will show a calculation"))
webpage_data += print_html("30+2=")
webpage_data += print_html(30+2)
webpage_data += end_html()
with open('index.html', 'w') as fd: fd.write(webpage_data)
Open the index.html file, and you will see what you want.

Categories

Resources