flask.request.form Cached Data - python

I've written an app that contains an html text input:
<form method="POST" action="" enctype="multipart/form-data">
<input class="ocsp_override_box_input" type="text" id="ocsp_override" name="ocsp_override" placeholder="Override the AIA field with a URL here..." value="">
</form>
In the flask app, I access the data with the following:
ocsp_override = request.form.get('ocsp_override')
It works as expected and the rest of my code is able to use this string value and do things with it. So far, so good. The way the code works is that this field should be optional. If it is blank, then it is ignored. If data is filled in it, it runs some checks and then uses this override string later on.
The issue I'm finding is that if I complete the text form using flask dev, it works as expected, but when I reload the page and leave it blank, it appears to be caching the previous entry.
For instance, if I enter in http://example.com in the text field, the code will use that string. If I reload the page (not using F5, by reloading the get page so I can post again), and I leave the field blank, the code appears to be trying to use http://example.com again. What's weird is that if I try to print(request.form.get('ocsp_override')) then it shows nothing.
If I wait a length of time (I want to say 10 mins), and then try again, everything works as expected with the field blank.
Is there some kind of caching happening here and how can I force it to reload and be fresh every time?

You might try disabling autocomplete:
e.g.
<input class="ocsp_override_box_input" ... autocomplete="off">
And if that does not work, you can try adding a cache control header to the response to prevent the browser from caching the page:
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
See this answer describing Cache-Control vs Pragma headers.

Related

Call Django url namespace inside window.open

Good day, all.
Currently, I want to try if the user clicks the update button on the web and then shows a popup window for updating their data. Before I have line code for updates like this:
<a class = "btn btn-outline-primary" href="{% url 'help:update show.id %}">Update</a>
then I added the URL inside the window.open with an id parameter like this:
onclick="window.open('update',show.id, 'newwindow', 'width=400, height=250'); return false;"
the page is open but in the same tab not in the new window as I expected in the pop-up. Is there any way to do like I expected? Thank you :)
This is the Syntax for window.open()
window.open(URL, name, specs, replace);
To open the target url in a new window, the second parameter 'name' must be either '_blank' or left blank.
Also from running a couple of tests it seems necessary to include something not blank in the third parameter as well. so,
so,
window.open('','',"width=200,height=100");
seems to work as expected. or even :
window.open("", "", "popup");

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

Storage data from HTML Form as a variable and print it in the html table (Python Flask?) [duplicate]

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)

How to update session object

With two <a>:
<a id="100" onclick="createTriggered(this.id)"<i></i> Click Link </a>
<a id="200" onclick="createTriggered(this.id)"<i></i> Click Link </a>
both linked to the same onClick javascript function:
<script type=text/javascript>
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
function onClick(id){
var data = $.getJSON($SCRIPT_ROOT + '/triggered', {a:id} );
window.alert({{ "session.keys()" }});
}
</script>
This javascript function takes the clicked <a> id and sends it to flask function:
#app.route('/onClick')
def onClick():
session['a_id'] = request.args.get('a')
return ('ok')
After Flask function gets id it updates session object creating a new key session['a_id'].
Finally javascript window.alert is used to check if the session object has the new 'a_id' key which should be already set by Flask function. When window.alert pops up it shows that the new key is missing. Refreshing the page and re-clicking the <a> link will pop up the window.alert() again but this time showing the new session['a_id'] key is there. It looks like the update of the session object is lagging behind. I have to refresh the page in order for the browser to pick up the change made by Flask function. Is there a way to assure that the update made by the Flask function to the session object is reflected immediately?
Finally, since I am updating the session object which is global to the entire session I really don't want to return any template or to redirect to another link. All I want is Flask function to set the session variables so it could be used somewhere down the logic. Would it be ok to return a dummy string from Flask function in this case?
It looks like the update of the session object is lagging behind.
It is not lagging. The issue is that originally you don't have anything in your session, thus your HTML page and your javascript is equivalent to
window.alert().
After you update your session, re-render the page update the javascript code to window.alert('a_id').
Is there a way to assure that the update made by the Flask function to the session object is reflected immediately?
You can examine your javascript callback to check the cookie return. The cookie is encrypted, so you won't see the value unless you know how to decrypt it. It is not recommended to do that. However, at the very least you can see the value of the cookie is changed.

How to get url string params in Web2Py?

Really stupid question here... but I can't seem to figure it out. In PHP when passing url params for say: www.mysit.com/index?name=steve I would use:
$_GET["name"]
In web2py I know you can get stuff via request.vars.someNameAttribute for stuff like what text is within a box. But how do I get params straight from the url string? Specifically I have form like this:
<form action="add_comment?idnum=5">
<input type="text" name="comment_text"/>
<input type="submit"/>
</form>
In the controller def add_comment(), how do I get that the idnum is 5??? I've been trying request.vars.idnum but this doesn't return anything. Am I not calling it right? Or is there some issue with the way I'm passing it in the "action" attribute?
Nvm, figured it out.
request.vars.idnum is indeed the way to go... it just wasn't working because the method attribute of was not set to "post".

Categories

Resources