I'm making backend for my website and it requires flask setting cookies. When I set the cookies, it works fine, but when I try to get them with request.cookies.get('name') it returns None. I tried just returning request.cookies and all that was there was my GA cookies, not the one that I set. Am I doing something wrong? Here's my code:
#app.route("/setcookie", methods=["GET", "POST"])
def setcookie():
resp = make_response(render_template("index.html"))
resp.set_cookie("authToken", "testestestestestestes", max_age=1)
return resp
#app.route("/getcookie", methods=["GET" ,"POST"])
def getcookie():
return request.cookies
index.html form:
<form action="/setcookie" method="POST">
<button type="submit">Set</button>
</form>
<form action="/getcookie" method="POST">
<button type="submit">Get</button>
</form>
I compared the GA cookies to the cookies that I set and the only difference was the name and value so that confuses me even more. I also don't need to do anything with them on the frontend, they only need to be read by flask. Can someone help? Thanks
You set max_age to 1 second, your cookie just gets expired, try increasing max_age value
Related
I have an html form, and I would like to insure that all submissions come from my website. I think I have seen people using a key for this (I believe this happens in Django?), and might have some ideas on how to go with that. Is there any standard way to do this in Flask?
Edit:
Now I know I'm talking about CSRF token middleware. Again, is there any standard way of doing this in Flask? How can I store the key on the server side?
In flask you can do CSRF protection using Flask-SeaSurf.There are other methods also but it is straight forward.
To start Just do pip install flask-seasurf and you are ready
import Flask
from flask_seasurf import SeaSurf
app = Flask(__name__)
csrf = SeaSurf(app)
<form method="POST">
...
<input type="hidden" name="_csrf_token" value="{{ csrf_token() }}">
</form>
#csrf.exempt
#app.route('/exempt_view', methods=['POST'])
def exempt_view():
'''This view is exempted from CSRF validation.'''
return 'foobar'
For more information you can visit official website
Please mark this as answer if this solves you problem.
I am making a small project - Reminider System. I have a form which accepts values from users and inserts into the database table. The problem is occurring while fetching a value from a textbox. Below is my code and also I am giving what error am getting.
<form method="POST" action="">
<input type="hidden" name="unique" value="{{session.UID}}" disabled="true">
<button type="submit" class="btn btn-primary">Confirm</button>
</form>
This is my template
#app.route('/home/set_reminder',methods=['POST'])
#is_logged_in
def set_reminder():
if request.method=='POST' and form.validate():
uid = request.form['unique']
I am getting the error in this line uid = request.form['unique']. Not getting why it cannot fetch the value.
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'unique'
And this is the error which am getting.
Please help me out.
In your html, the uid input is disabled, so the browser will not send uid in a POST request's body. This causes the error when you try to access request.form.uid - it doesn't exist.
You could use readonly rather than disabled if the value must be returned by the browser.
See this answer for a little more information on BadRequestKeyError.
I have a Django application that generates a table of data. I have a form where you enter parameters and click one button to see the results or another to download a CSV. Seeing the results is working, but downloading the CSV is not.
I handle the response in the views.py, set the content type and disposition, and return the response. Rather than downloading the CSV, it displays the data as text. (I tried both StreamingHttpResponse and plain HttpResponse.) The same exact code works when handling a URL passing in the parameters. So, I tried a HttpResponseRedirect instead, and it does nothing. I even tried just redirecting to a plain URL, with no effect. I believe the response type is being ignored, but I don't know why.
html:
<form action="" method="post" class="form" id="form1">
{{ form.days }} {{ form.bgguserid }}
<input type="submit" value="Go!" id="button-blue"/>
<input type="submit" name="csv-button" value="CSV" id="csv-button"/>
</form>
views.py attempt 1:
def listgames(request, bgguserid, days=360):
if 'csv-button' in request.POST:
# create CSV in variable wb
response = StreamingHttpResponse(wb, content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="collectionvalue.csv"'
return response
attempt 2, the same but with:
response = HttpResponseRedirect ('/collection/{0}/csv/{1}/'.format(bgguserid,days))
I'm open to other solutions like a client-side redirect to the functioning URL, but I don't want to lose the form validation, and my HTML/javascript skills are weak.
I figured out the problem.
The code in views.py (which I partly copied from somewhere) was creating a new HttpRequest object from the return value of the form handling method.
def indexform(request):
if request.method == 'POST':
form = IndexForm(request.POST)
# Check if the form is valid:
if form.is_valid():
# process the data in form.cleaned_data as required
response = listgames(request, bgguserid=form.cleaned_data['bgguserid'], days=form.cleaned_data['days'])
# redirect to a new URL:
return HttpRequest(response)
By changing that last line to just return response, it works as intended. Sorry for wasting anyone's time.
So I'm trying to send data from an html form to my python flask framework.
Here's the example of the html code I'm using
<form method=post action=/test>
<input name=Name value=Austin type=hidden><input type=submit value="Add Notification">
and here's the python flask I'm working with
#app.route('/test', methods=('GET', 'POST')
def test_page():
v = request.values.get('Name')
return v
I've tried many different request methods and can't seem to get it to work and I get a 405 error. I'm not very familiar with the flask web development or using post requests. If anyone could point me in the correct direction then that'd be great!
You're POSTing to your endpoint, but app.route by default only enables GET. Change app.route('/test') to app.route('/test', methods=('GET', 'POST')), and you'll be able to access your endpoint.
That 405 response you're getting is Method Not Allowed.
(Unrelated issue, request.values.get['Name'] should be request.values.get('Name').)
After reading many similar sounding problems and the relevant Flask docs, I cannot seem to figure out what is generating the following error upon submitting a form:
400 Bad Request
The browser (or proxy) sent a request that this server could not understand.
While the form always displays properly, the bad request happens when I submit an HTML form that ties to either of these functions:
#app.route('/app/business', methods=['GET', 'POST'])
def apply_business():
if request.method == 'POST':
new_account = Business(name=request.form['name_field'], email=request.form['email_field'], account_type="business",
q1=request.form['q1_field'], q2=request.form['q2_field'], q3=request.form['q3_field'], q4=request.form['q4_field'],
q5=request.form['q5_field'], q6=request.form['q6_field'], q7=request.form['q7_field'],
account_status="pending", time=datetime.datetime.utcnow())
db.session.add(new_account)
db.session.commit()
session['name'] = request.form['name_field']
return redirect(url_for('success'))
return render_template('application.html', accounttype="business")
#app.route('/app/student', methods=['GET', 'POST'])
def apply_student():
if request.method == 'POST':
new_account = Student(name=request.form['name_field'], email=request.form['email_field'], account_type="student",
q1=request.form['q1_field'], q2=request.form['q2_field'], q3=request.form['q3_field'], q4=request.form['q4_field'],
q5=request.form['q5_field'], q6=request.form['q6_field'], q7=request.form['q7_field'], q8=request.form['q8_field'],
q9=request.form['q9_field'], q10=request.form['q10_field'],
account_status="pending", time=datetime.datetime.utcnow())
db.session.add(new_account)
db.session.commit()
session['name'] = request.form['name_field']
return redirect(url_for('success'))
return render_template('application.html', accounttype="student")
The relevant part of HTML is
<html>
<head>
<title>apply</title>
</head>
<body>
{% if accounttype=="business" %}
<form action="{{ url_for('apply_business') }}" method=post class="application_form">
{% elif accounttype=="student" %}
<form action="{{ url_for('apply_student') }}" method=post class="application_form">
{% endif %}
<p>Full Name:</p>
<input name="name_field" placeholder="First and Last">
<p>Email Address:</p>
<input name="email_field" placeholder="your#email.com">
...
The problem for most people was not calling GET or POST, but I am doing just that in both functions, and I double checked to make sure I imported everything necessary, such as from flask import request. I also queried the database and confirmed that the additions from the form weren't added.
In the Flask app, I was requesting form fields that were labeled slightly different in the HTML form. Keeping the names consistent is a must. More can be read at this question Form sending error, Flask
The solution was simple and uncovered in the comments. As addressed in this question, Form sending error, Flask, and pointed out by Sean Vieira,
...the issue is that Flask raises an HTTP error when it fails to find a
key in the args and form dictionaries. What Flask assumes by default
is that if you are asking for a particular key and it's not there then
something got left out of the request and the entire request is
invalid.
In other words, if only one form element that you request in Python cannot be found in HTML, then the POST request is not valid and the error appears, in my case without any irregularities in the traceback. For me, it was a lack of consistency with spelling: in the HTML, I labeled various form inputs
<input name="question1_field" placeholder="question one">
while in Python, when there was a POST called, I grab a nonexistent form with
request.form['question1']
whereas, to be consistent with my HTML form names, it needed to be
request.form['question1_field']