I am working with python web.py framework,i had an anchor tag with html code as below for example
<p><a href = "/edit.py?tr=%d"%1>Edit</a></p>
So when i click this link it goes to edit.py file in my project directory, but as you observe i am passing some values after edit.py like /edit.py?tr=%d"%1. Actually i will pass these values dynamically in further process.
Here after redirecting to edit.py, how to access the values after ? from the py file?
because my intention is to edit the record after saving in to database.
You can get them using web.input, e.g.
def GET(self):
data = web.input()
tr = data.tr
Documentation is avaliable here: http://webpy.org/cookbook/input
Related
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.
I am using a django template to generate pdf via feeding it a context object from the function but not the view, it works fine in case of view, but I am not able to load the local static images on the template from the function. but this is possible in view because there I can tell which base path to use. But I not able to do the same in the function.
As you can see I can how I am getting the base url from the view. Here I can get because I have requests object but in function I do not have any requests object. So images are not loading.
html = HTML(string=html_string, base_url=request.build_absolute_uri('/'))
This is how I am trying to do in the function:
html_string = render_to_string('experiences/voucher.html', data)
html = HTML(string=html_string, base_url=settings.STATIC_ROOT)
result = html.write_pdf("file_new.pdf", stylesheets=[css],optimize_images=True)
I would like to know how can I tell, where are my images so that images can be rendered on the pdf.
It was not working because base_url had not way to know where the images are located especially on the running server, so I had to explicitly define the path to the local resources so I did something like this:
first I added an envoirnment variable in my .env file:
like HOST=http://localhost:8000 and then I get this url in my actuall code like this:
path = os.environ["HOST"]+"/static/"
and at the end i pass this path to base_url parameter in HTML()
html = HTML(string=html_string, base_url=path)
and after all this it worked like a charm.
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
This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Get the data received in a Flask request
(23 answers)
Closed 2 years ago.
So here's what i'm trying to do:
Static Website in HTML(just a simple table) Screenshot Here
Admin Page to update text's on that website by html for (I'm not sure if it's good idea) Another Screenshot
I was trying in Python Flask, but I have no idea how to storage data from HTML Form into Python variables. All I did is to use {{ }} in my index.html(first ss) and then I can edit content straight from Python Code, but it's not what I want.
What i want?
I want to make a form or smth like that which allows user to easy update text on index(first ss).
User has to choose which cell he wants to update and write a new content, then submit and that's all.
Is it Python Flask good idea to do it? (I'm pretty new in Python)
At the moment I'm using Wordpress+PostGrid plugin to do something like that, but editing the grid(first ss) is there so hard.
I'm stubborn that's why I want to do it on my self.
Any advises about method which I should use or language will be very helpful.
Thanks!
Since you do NOT want to render a template of your table website, but change the HTML file itself, I have the following proposition for you:
Set up a Flask application to receive your request, e.g. on an update route (/update).
Have your admin website use a form that posts to your update route. Make sure to give your select and input tags the name attribute. For example:
<form action="{{url_for('update')}}" method="post">
<select name="element">
<option value="imptitle">imptitle</option>
<option value="zaktitle">zaktitle</option>
</select>
<input type="text" name="new_value">
<input type="submit" value="Update">
</form>
In your Flask app you can extract the information from the request by using request.form, using the same names that you specified in your select and input tags, e.g.:
#app.route('/update', methods=['POST'])
def update():
element = request.form['element']
new_value = request.form['new_value']
Then replace the element's value within your table HTML: open your table HTML file, read its content, search the element and replace its value using regular expression (you can read up on how to do that here), overwrite the contents of the file with updated content. For example:
with open('index.html', 'r') as f:
content = f.read()
# new_content = ... (do your search and replace here)
with open('index.html', 'w') as f:
f.write(new_content)
can anyone help me with "extracting" stuff from site using Python? Here is the info :
I have folder name with set of numbers (they are ID of item) and i have to use that ID for entering page and then "scrap" info from page to my notepad... It's like this : http://www.somesite.com/pic.mhtml?id=[ID]... I need to exctract picture link (picture link always have ID.jpg at the end of the file)from it and write it in notepad and then replace that txt name with name of the picture... Picture is always in title tags... Thanks in advance...
What you need is a data scraper - http://www.crummy.com/software/BeautifulSoup/ will help you pull data off of websites. You can then load that data into a variable, write it to a file, or do anything you normally do with data.
You could try parsing the html source for images.
Try something similar:
class Parser(object):
__rx = r'(url|src)="(http://www\.page\.com/path/?ID=\d*\.(jpeg|jpg|gif|png)'
def __crawl(self, url):
images = []
code = urllib.urlopen(url).read()
for line in code.split('\n'):
imagesearch = re.search(self.__rx, line)
if imagesearch:
image = '%s.%s' % (imagesearch.group(2), imagesearch.group(4))
images.append(image)
return images
it's untestet, you may want to check the regex