Flask mail api, not getting request variable properly - python

I'm trying to access a request from an HTML form, and send it as a mail, but I get a mail with a value of "None",
here is my code:
#app.route("/about", methods=['GET', 'POST'])
def send_message():
name = request.form.get('name')
msg = Message(
subject='Hello ' + str(name),
sender='kristofferlocktolboll#gmail.com',
recipients=
['kristofferlocktolboll#gmail.com'],
html=render_template("about.html"))
mail.send(msg)
confirm_msg = "Your message has been sent!"
return render_template("about.html", confirm_msg=confirm_msg)
I think it might be due to the fact, that I'm casting the object into a string, but if I don't do that, I will get an error due to making a conjunction between a String and another object
EDIT:
here is my html code, I have tried both using post and get as the method, but nothing works.
<form action="/send_message" method="post">
First name: <br>
<input type="text" name="name" size="35"><br>
Last name:<br>
<input type="text" name="lastname" size="35"><br>
Email-address: <br>
<input type="email" name="email" size="35"><br>
Phone-number: <br>
<input type="text" name="phone" size="35"><br>
Enter your message: <br>
<textarea type="text" name="message" rows="7" cols="40"></textarea><br>
</form>
EDIT 2:
When ever I try to display the confirm_msg it is displayed instantly, when I enter the site.
<p>{{confirm_msg}}</p>

Firstly you must add CSRF_TOKEN for your form:
<form method="post" action="/send_message">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
...
.....
</form>
Also can you tell us in which page you are trying to see <p>{{confirm_msg}}</p> ?

Related

How to read the HTTP POST request from a web page using the function multipart?

I have always used the Python function cgi.FieldStorage. Apparently the function cgi is deprecated since Python version 3.11. So I should start using the Python function multipart, but unfortunately it is not clear to me how to read the HTTP POST request from a web page using the function multipart. Can anyone show me a simple example of how to do that?
My current codes are as follows:
File 'Request.htm':
<h1>Form in GET method</h2>
<form action="http://localhost/PythonwebTest/getpost.py" method="get">
<label for="fname">
First name:
<input type="text" id="fnameget" name="fnameget">
</label>
<br>
<label for="lname">
Last name:
<input type="text" id="lnameget" name="lnameget">
</label>
<br />
<input type="submit" value="Submit">
</form>
<hr />
<h1>Form in POST method</h2>
<form action="http://localhost/PythonwebTest/getpost.py" method="post">
<label for="fname">
First name:
<input type="text" id="fnamepost" name="fnamepost">
</label>
<br>
<label for="lname">
Last name:
<input type="text" id="lnamepost" name="lnamepost">
</label>
<br>
<input type="submit" value="Submit">
</form>
File 'PythonwebTest/getpost.py' (at my local server):
#!C:/Program Files/Python/python.exe
print('Content-Type: text/html; charset=utf-8\n')
import os
rqsmtd = os.environ['REQUEST_METHOD']
tblrqs = {}
if rqsmtd == 'GET':
wrktbl = os.environ['QUERY_STRING'].split('&')
for wrkarg in wrktbl:
wrklst = wrkarg.split('=')
tblrqs[wrklst[0]] = wrklst[1]
print('GET request data: ' + str(tblrqs))
elif rqsmtd == 'POST':
print('...using cgi.FieldStorage:')
import cgi
wrktbl = cgi.FieldStorage()
for wrkkey in wrktbl:
if isinstance(wrktbl[wrkkey], list):
wrkvlx = wrktbl[wrkkey][0].value
else:
wrkvlx = wrktbl[wrkkey].value
tblrqs[wrkkey] = wrkvlx
print('POST request data: ' + str(tblrqs))
#-------------------------------------------------
#print('...using multipart:')
import multipart
# ...
# HOW to get HTTP POST request and
# and store them into the table 'tblrqs' here?
# ...
print('POST request data: ' + str(tblrqs))
#-------------------------------------------------
else:
print('Request method \'' + rqsmtd + '\' not supported yet')
I am currently using the pure Python with the general server interface APACHE (so not WSIG, FLASK, DJANGO or others).

Flask TypeError: The view function for '**' did not return a valid response. The function either returned None or ended without a return statement

I am learning Flask and i started my first project using this framework. At the moment I want to save the user input to the database but I am getting a
TypeError: The view function for 'bookingPage' did not return a valid response.
The function either returned None or ended without a return statement. I checked my function and the return statement must return the booking page in case if it is a GET request and redirect to the main page in case if it is a POST request.
I also checked other posts here regarding such error, but there are answers like "you need to add the return statement". In my case the return statement is present
Here is the code of my function:
#app.route('/booking', methods=['POST', 'GET'])
def bookingPage():
if request.method == 'POST':
firstname = request.form['firstname']
lastname = request.form['lastname']
phone = request.form['phone']
email = request.form['email']
birthdate = request.form['birthdate']
booking_date = request.form['booking_date']
booking_time = request.form['booking_time']
guests_nr = request.form['guests_nr']
notes = request.form['notes']
reservation = Booking(CustomerFname=firstname, CustomerLname=lastname, CustomerPhone=phone, CustomerEmail=email,
CustomerBirthdate=birthdate, ReservationDate=booking_date, ReservationTime=booking_time,
NumberOfGuests=guests_nr, CustomerNotes=notes)
try:
db.session.add(reservation)
db.session.commit()
return redirect('/')
except:
return "An error has been occurred. Please, try again later"
else:
return render_template('booking.html')
Also here is the code of the html
<div class="booking-container">
<form method="post">
<input type="text" name="firstname" id="firstname" class="form-control" placeholder="First Name" required>
<input type="text" name="lastname" id="lastname" class="form-control" placeholder="Last Name" required>
<input type="text" name="email" id="email" class="form-control" placeholder="Email" required>
<input type="text" name="phone" id="phone" class="form-control" placeholder="Phone Number" required>
<input type="text" name="birthdate" id="birthdate" class="form-control" placeholder="Date of Birth" required>
<input type="text" name="booking_date" id="booking_date" class="form-control" placeholder="Reservation Date" required>
<input type="text" name="booking_time" id="booking_time" class="form-control" placeholder="Reservation Time" required>
<input type="text" name="guests_nr" id="guests_nr" class="form-control" placeholder="Number of Guests" required>
<textarea name="notes" id="notes" class="form-control" placeholder="Notes"></textarea>
<input type="submit" class="btn-submit" value="Sent">
</form>
</div>
the issue is solved. I made a stupid mistake there:
In
def booking():
if request.method == 'POST':
must be ['POST'] instead of 'POST'

pyFlask is putting my inputs in my url browser

Briefly, python Flask is the workbench of web hosting I use, and I am trying to create an input form that doesn't appear in your history.
This is my form html:
<form name="ViewWindow" action="/home/ViewWindow/ViewWindowResult/">
<input name="url" type="url" required="required" placeholder="URL Here">
<input type="submit" value="Go">
</form>
And this is the python code working with the input url:
#web_site.route('/home/ViewWindow/ViewWindowResult/', methods=('GET', 'POST'))
def ViewWindowResult():
urlboi = request.values.get('url')
response = urllibrequest.urlopen(url) # import urllib.request as urllibrequest
htmlBytes = response.read()
htmlstr = htmlBytes.decode("utf8")
return html("ViewWindowResult.html", value=htmlstr)
My goal is to get here; /home/ViewWindow/ViewWindow/ViewWindowResult/,
but I end up getting here when I input "https://www.w3schools.com/tags/"; /home/ViewWindow/ViewWindowResult/?url=https%3A%2F%2Fwww.w3schools.com%2Ftags%2F
Why does Flask put my inputs in the url string? I do not intend to do this anywhere.
Edit: You can check this out by going to https://sm--supermechm500.repl.co/home/ViewWindow/
Try specifying the form method like so:
<form name="ViewWindow" action="/home/ViewWindow/ViewWindowResult/" method="post">
<input name="url" type="url" required="required" placeholder="URL Here">
<input type="submit" value="Go">
</form>
use post method like
<form name="ViewWindow" action="/home/ViewWindow/ViewWindowResult/" method="post">
<input name="url" type="url" required="required" placeholder="URL Here">
<input type="submit" value="Go">
</form
and then you python code is
#web_site.route('/home/ViewWindow/ViewWindowResult/', methods=('GET', 'POST'))
def ViewWindowResult():
input=request.form['url']
#write your code here
return(input)
its working for me it will print the url which same you entered

Python Flask/JSON Error: Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)

guys.
So my problem is as follows.
I created a linear model and saved it as .pkl in Python 3.7.
Then, I created an app.py file with the code shown below (html template file is also created).
import pickle
from flask import Flask, request, render_template, jsonify
#creating instance of the class
app=Flask(__name__)
#loading the model
model = pickle.load(open("model.pkl", "rb"))
#loading the index template and the main page
#app.route('/')
def index():
return render_template('index.html')
#inputs from the user
#app.route('/result', methods=['POST'])
def result():
features = request.get_json(force=True)['Input1', 'Input2', 'Input3',
'Input4', 'Input5', 'Input6',
'Input7', 'Input8', 'Input9']
#creating a response object
#storing the model's prediction in the object
response = {}
response['predictions'] = model.predict([features]).tolist()
#returning the response object as json
return flask.jsonify(response)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000, debug=True)
The problem is that, when I run app.py file, I get this error: "Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)". I tried modifying my code multiple times, even trying to find another solution to write it, but no luck so far, it just always raises an error.
Is there any mistake in my code that may raise this error? I should note (if it may be important) that all my variables are float type except one which is an integer.
The html script is included here as follows:
<html>
<body>
<h3>Prediction_form</h3>
<div>
<form action="{{ url_for('result') }}" method="POST">
<label for="Input1">Input1</label>
<input type="text" id="Input1" name="Input1">
<br>
<label for="Input2">Input2</label>
<input type="text" id="Input2" name="Input2">
<br>
<label for="Input3">Input3</label>
<input type="text" id="Input3" name="Input3">
<br>
<label for="Input4">Input4</label>
<input type="text" id="Input4" name="Input4">
<br>
<label for="Input5">Input5</label>
<input type="text" id="Input5" name="Input5">
<br>
<label for="Input6">Input6</label>
<input type="text" id="Input6" name="Input6">
<br>
<label for="Input7">Input7</label>
<input type="text" id="Input7" name="Input7">
<br>
<label for="Input8">Input8</label>
<input type="text" id="Input8" name="Input8">
<br>
<label for="Input9">Input9</label>
<input type="text" id="Input9" name="Input9">
<br>
<input type="submit" value="Submit">
<br>
<br>
{{ prediction_text }}
</form>
</div>
</body>
</html>
I am new to Python, so I may be missing something important.
Any help is appreciated.
Many thanks.
The form post uses the default encoding of application/x-www-form-urlencoded. That's not compatible with using get_json() to retrieve the posted form. Setting up your data for prediction will require something like this
form_fields = ['Field1', 'Field2' ... and so on ]
features = [request.form[field] for field in form_fields]
instead.

Python - How to send private message form using requests? (vBulletin forum)

I'm trying to send a PM on a forum that I use, but it's not sending - no error code received.
This is the HTML that I think is causing the issue :
<div style="margin-top:6px">
<input type="hidden" name="s" value="">
<input type="hidden" name="securitytoken" value="1515973553-20dc0500315dc868c0bad3384f0d0adb6b85fdd6">
<input type="hidden" name="do" value="insertpm">
<input type="hidden" name="pmid" value="">
<input type="hidden" name="forward" value="">
<input type="submit" class="button" name="sbutton" id="vB_Editor_001_save" value="Submit Message" accesskey="s" tabindex="1">
<input type="submit" class="button" value="Preview Message" accesskey="r" name="preview" tabindex="1">
</div>
In any case, here's the page: http://forum.toribash.com/private.php?do=newpm
But you'd need an account on the forum to access that page, by default.
Here's my payload, using requests:
msg_data = {
'title': "Discord registration request",
'message': "TEST",
'securitytoken': auth_final,
'do': "insertpm",
}
r = session_requests.post(url, data=msg_data)
result = session_requests.get(url,headers = dict(referer = url))
tree_pm_send = html.fromstring(result.content)
I'm 100% sure that security token variable I entered is correct, but nothing appears in my sent inbox after that.

Categories