Flask MethodView No request object in def Post(self) - python

I am trying to send a html5 form to flask using the class based MethodView. From what I understand, the def post(self): should contain a request object with the form attributes. However, when I try the below code I get "NameError: global name 'request' is not defined"
flask:
from app import app
from flask.views import MethodView
from app import app
from flask.views import MethodView
from flask import url_for
#app.route('/')
def index():
return app.send_static_file('index.html')
class ImageShareForm(MethodView):
def get(self):
pass
def post(self):
print (request)
app.add_url_rule('/imageshareform/', view_func=ImageShareForm.as_view('imageshareform'))
html:
<form method="POST">
<div class="form-group btn-group-ls well col-md-5">
<legend>Region</legend>
<input class="form-inline" type="radio" name="regions" id="IAD" value="IAD" checked>
<label for="IAD" class="btn btn-default region">Virginia</label>
<input class="form-inline" type="radio" name="regions" id="ORD" value="ORD">
<label for="ORD" class="btn btn-default region">Chicago</label>
<input class="form-inline" type="radio" name="regions" id="DFW" value="DFW">
<label for="DFW" class="btn btn-default region">Dallas</label>
<input type="radio" id="HKG" name="regions" value="HKG">
<label for="HKG" class="btn btn-default region">Hong Kong</label>
</div>
<div class="form-group well col-md-5">
<label for="producerUsername">Producer Username</label>
<input type="text" class="form-control" id="producerUsername" placeholder="Enter producer's username" >
<label for="producerApiKey">Producer Api Key</label>
<input type="text" class="form-control" id="producerApiKey" placeholder="Enter producer's api key" >
</div>
<div class="form-group well col-md-5">
<label for="consumerUsername">Consumer Username</label>
<input type="text" class="form-control" id="consumerUsername" placeholder="Enter consumer's username" >
<label for="consumerApiKey">Consumer Api Key</label>
<input type="text" class="form-control" id="consumerApiKey" placeholder="Enter consumer's api key" >
</div>
<div class="form-group well col-md-5">
<label for="imageUuid">Image UUID</label>
<input type="text" class="form-control" id="imageUuid" placeholder="Enter images's image Uuid" >
</div>
<div class="col-md-5">
<input type="submit" value="Submit" class="btn btn-primary" formenctype="multipart/form-data" formaction="/imageshareform">
</div>
</form>

Found out I needed to import request that comes with Flask

Related

Unable to resolve 'Method Not Allowed - The method is not allowed for the requested URL.' error

I am receiving a 'Method Not Allowed - The method is not allowed for the request URL.' error when I click on the 'Logout' button on the Main page. I expect it to go to the index page but I keep receiving an error. I have tried updating the methods for Main and dropsession but neither works. Thanks!
Updated method of '/dropsession' from 'GET' to 'POST'. Still getting same error.
Updated - Fixed by removing methods from '/dropsession' and removing tag from HTML.
main program:
from flask import Flask, request, render_template, redirect, url_for, session, g
import os
app = Flask(__name__)
app.secret_key = os.urandom(24)
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
session.pop('user', None)
if request.form['password'] == 'admin' and request.form['username'] == 'admin':
session['user'] = request.form['username']
return redirect(url_for('main'))
return render_template('index.html')
#app.route('/main')
def main():
if g.user:
return render_template('main.html', user=session['user'])
return redirect(url_for('index'))
#app.before_request
def before_request():
g.user = None
if 'user' in session:
g.user = session['user']
#app.route('/dropsession', methods=['POST'])
def dropsession():
session.pop('user', None)
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
Html:
<link rel="stylesheet" href="/static/style.css" type="text/css">
<form action="main" method="POST">
<div class="main">
<div class="main-screen">
<div class="main-title">
<h1><center>Patient Hypothyroidism Probability</center></h1>
<h4>This application is designed to assist medical professional.
By using machine learning, the application will determine if the patient has
hypothyroidism.</h4>
<h4>Please enter patient information below:</h4>
<label for="age">Age: </label><input type="number" id="age" name="age" class="entryfield">
<br>
<p>On Thyroxine:</p>
<div>
<input type="radio" id="thyroxine_yes" name="thyroxine" value="1"><label>Yes</label>
<input type="radio" id="thyroxine_no" name="thyroxine" value="0"><label>No</label>
</div>
<p>On Antithyroid medication:</p>
<div>
<input type="radio" id="antithyroid_yes" name="antithyroid" value="1"><label>Yes</label>
<input type="radio" id="antithyroid_no" name="antithyroid" value="0"><label>No</label>
</div>
<p>Thyroid Surgery:</p>
<div>
<input type="radio" id="thyroid_surgery_yes" name="thyroid_surgery" value="1"><label>Yes</label>
<input type="radio" id="thyroid_surgery_no" name="thyroid_surgery" value="0"><label>No</label>
</div>
<p>Pregnant:</p>
<div>
<input type="radio" id="pregnant_yes" name="pregnant" value="1"><label>Yes</label>
<input type="radio" id="pregnant_no" name="pregnant" value="0"><label>No</label>
</div>
<p>Sick:</p>
<div>
<input type="radio" id="sick_yes" name="sick" value="1"><label>Yes</label>
<input type="radio" id="sick_no" name="sick" value="0"><label>No</label>
</div>
<p>Tumor:</p>
<div>
<input type="radio" id="tumor_yes" name="tumor" value="1"><label>Yes</label>
<input type="radio" id="tumor_no" name="tumor" value="0"><label>No</label>
</div>
<p>On Lithium:</p>
<div>
<input type="radio" id="lithium_yes" name="lithium" value="1"><label>Yes</label>
<input type="radio" id="lithium_no" name="lithium" value="0"><label>No</label>
</div>
<p>Goitre:</p>
<div>
<input type="radio" id="goitre_yes" name="goitre" value="1"><label>Yes</label>
<input type="radio" id="goitre_no" name="goitre" value="0"><label>No</label>
</div>
<br>
<p>TSH Measured:</p>
<div>
<input type="radio" id="tsh_measured_yes" name="tsh_measured" value="1"><label>Yes</label>
<input type="radio" id="tsh_measured_no" name="tsh_measured" value="0"><label>No</label>
</div>
<label for="age">TSH (if measured): </label><input type="number" id="tsh" name="tsh" class="entryfield" step="0.1">
<br>
<p>T3 Measured:</p>
<div>
<input type="radio" id="t3_measured_yes" name="t3_measured" value="1"><label>Yes</label>
<input type="radio" id="t3_measured_no" name="t3_measured" value="0"><label>No</label>
</div>
<label for="age">T3 (if measured): </label><input type="number" id="t3" name="t3" class="entryfield" step="0.1">
<br>
<p>Total T4 Measured:</p>
<div>
<input type="radio" id="tt4_measured_yes" name="tt4_measured" value="1"><label>Yes</label>
<input type="radio" id="tt4_measured_no" name="tt4_measured" value="0"><label>No</label>
</div>
<label for="age">Total T4 (if measured): </label><input type="number" id="tt4" name="tt4" class="entryfield" step="0.1">
<br>
<p>Free T4 Measured:</p>
<div>
<input type="radio" id="t4u_measured_yes" name="t4u_measured" value="1"><label>Yes</label>
<input type="radio" id="t4u_measured_no" name="t4u_measured" value="0"><label>No</label>
</div>
<label for="age">Free T4 (if measured): </label><input type="number" id="t4u" name="t4u" class="entryfield" step="0.01">
<br>
<p>Free Thyroxine Index Measured:</p>
<div>
<input type="radio" id="fti_measured_yes" name="fti_measured" value="1"><label>Yes</label>
<input type="radio" id="fti_measured_no" name="fti_measured" value="0"><label>No</label>
</div>
<label for="age">Free Thyroxine Index (if measured): </label><input type="number" id="fti" name="fti" class="entryfield" step="0.1">
</div>
<button onclick="window.location = 'http://localhost:5000/dropsession'" type="submit">Logout</button>
</div>
</div>
</div>
</form>

405 Method Not Allowed Error in post request while creating user

I'm making a user registration form in which I have made a post request to get the user input data in a print out form but 405 Method Not allowed error causing the problem. I'm a newbie so that's why I couldn't figure out what's going wrong.
CONTROLLER CLASS:
import web
from Models import RegisterModel
urls = (
"/", "Home",
"/register", "Register",
"/post", "PostRegistration",
)
render = web.template.render("Views/Templates", base="MainLayout")
app = web.application(urls, globals())
# Classes/routes
class Home:
def GET(self):
return render.Home()
class Register:
def GET(self):
return render.Register()
class PostRegistration:
def POST(self):
data = web.input()
reg_model = RegisterModel.RegisterModelCls()
reg_model.insert_user(data)
return data.username
if __name__ == "__main__":
app.run()
Registration form:
<div class="container">
<h2>Register Account</h2>
<br /><br />
<form>
<div class="form-group label-static is-empty">
<label for="username" class="control-label">Username</label>
<input id="username" name="username" class="form-control"
type="text" placeholder="Choose a username" />
</div>
<div class="form-group label-static is-empty">
<label for="display_name" class="control-label">Full Name</label>
<input id="display_name" name="name" class="form-control"
type="text" placeholder="Enter your full name" />
</div>
<div class="form-group label-static is-empty">
<label for="email" class="control-label">Email Address</label>
<input id="email" name="email" class="form-control" type="email"
placeholder="Enter your Email" />
</div>
<div class="form-group label-static is-empty">
<label for="password" class="control-label">Password</label>
<input id="password" name="password" class="form-control"
type="password" placeholder="Make a password" />
</div>
<a type="submit" href="/post" class="btn btn-info waves-effect"
>Submit <div class="ripple-container"></div></a>
</form>
</div>
RegistrationModel.py class (which suppose to print the user input)
import pymongo
from pymongo import MongoClient
class RegisterModelCls:
def insert_user(self, data):
print("data is: " + data)
Error:
http://0.0.0.0:8080/
127.0.0.1:64395 - - [06/Sep/2019 00:19:16] "HTTP/1.1 GET /post" - 405
Method Not Allowed
You're mixing GET and POST.
The Error indicates you're doing a "GET" operation, on the url '/post'.
web.py takes the URL and looks it up in the urls list, and identifies the url '/post' is handled by the class "PostRegistration".
So, web.py calls the GET method on class PostRegistration, which doesn't exist, or, as web.py says "Method Not Allowed".
To get past that, either use a POST operation (as #Barmar suggests) or, rename PostRegistration.POST(self) to PostRegistration.GET(self).

Problem in getting data from form in flask

I am basically creating a flask web app which takes username from user and gets his /her codeforces data I am having a problem in extracting the email-id
from the form. I am getting the username but not the email-id.They are both in one form tag in the html file.
Error in browser:
werkzeug.exceptions.HTTPException.wrap..newcls: 400 Bad Request: KeyError: 'email-id'
<form method="POST">
<div class="field">
<label class="label">Username:</label>
<div class="control">
<input class="input" type="text" placeholder="Enter Codeforces username" name="username" value="{{user.handle}}"></input>
</div>
</div>
<div class="has-text-centered">
<input class="button is-link" name="get-info" type="submit" value="Get Info">
</div>
<div class="field">
<label class="label">EMail id:</label>
<div class="control">
<input class="input" type="text" placeholder="Enter mail id" name="email-id" value="">
</div>
</div>
<div class="has-text-centered">
<input class="button is-link" name="get-mail" type="submit" value="Get Mail">
</div>
</form>
#app.route('/',methods=['GET','POST'])
def index():
if request.method == 'POST':
username = request.form['username']
email_id = request.form['email-id']
print(email_id)
print(username)

Redirect after form submission cgi script

I wrote a simple email script in python that takes the data from a form and emails it using boto. What I need to do now is redirect the user to another page "thankyou.html" without showing any cgi output.
HTML FORM:
<form method="post" action="/cgi-bin/iemail.py">
<div class="row uniform 50%">
<div class="6u 12u$(xsmall)">
<input type="text" name="name" id="name" value="" placeholder="Name" required="required"/>
</div>
<div class="6u 12u$(xsmall)">
<input type="text" name="company" id="company" value="" placeholder="Company Name" required="required"/>
</div>
<div class="6u 12u$(xsmall)">
<input type="text" name="phone" id="phone" value="" placeholder="Phone Number" required="required"/>
</div>
<div class="6u$ 12u$(xsmall)">
<input type="email" name="email" id="email" value="" placeholder="Email" required="required"/>
</div>
<div class="12u$">
<div class="select-wrapper">
<select name="category" id="category">
<option value="">- Category -</option>
<option value="Additional Information">Additional Information</option>
<option value="Services Request">Services Request</option>
<option value="Consulting Request">Consulting Request</option>
<option value="Development Request">Development Request</option>
<option value='Support Request'>Support Request</option>
</select>
</div>
</div>
<div class="4u 12u$(small)">
<input type="radio" id="priority-low" name="priority" checked>
<label for="priority-low">Low</label>
</div>
<div class="4u 12u$(small)">
<input type="radio" id="priority-normal" name="priority">
<label for="priority-normal">Normal</label>
</div>
<div class="4u$ 12u$(small)">
<input type="radio" id="priority-high" name="priority">
<label for="priority-high">High</label>
</div>
<div class="12u$">
<textarea name="message" id="message" placeholder="Enter your message" rows="6" required="required"></textarea>
</div>
<div class="6u 12u$(small)">
<!--<input type="checkbox" id="demo-copy" name="demo-copy">
<label for="demo-copy">Email me a copy</label>
</div>-->
<div class="6u$ 12u$(small)">
<input type="checkbox" id="human" name="human" required="required">
<label for="human">Not a robot</label>
</div>
<div class="12u$">
<ul class="actions">
<li><input type="submit" value="Send Message" class="special" /></li>
<input type="hidden" name="redirect" value="index.html" />
<li><input type="reset" value="Reset" /></li>
</ul>
</div>
</div>
</form>
Python Script:
#!/usr/bin/python2.7
import cgi
import html
import boto.ses
import cgitb; cgitb.enable() #for troubleshooting
print("Content-Type: text/html")
print
def getdata():
form = cgi.FieldStorage()
name = form["name"].value
company = form["company"].value
phone = form["phone"].value
email = form["email"].value
category = form["category"].value
message = form["message"].value
return name, company, phone, email, category, message
#main Program
if __name__=="__main__":
try:
name, company, phone, email, category, message = getdata()
conn = boto.ses.connect_to_region('us-west-2')
conn.send_email(
'admin#gmail.com',
category,
'%r, %r, %r, %r %r' % (email, name, company,
phone, message),
to_addresses = 'admin#gmail.com'
)
except:
cgi.print_exception()
I only can get redirected to the output for the cgi script, I need to send customers to thankyou.html

How to post data via form HTML?

I want to post the data to the server via form. How can I do this?
<div class="panel-body">
<form role="form" action="{% url 'login' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="sender-email" class="control-label">Username:</label>
<div class="input-icon"> <i class="icon-user fa"></i>
<input id="sender-email" type="text" placeholder="Username" class="form-control email">
</div>
</div>
<div class="form-group">
<label for="user-pass" class="control-label">Password:</label>
<div class="input-icon"> <i class="icon-lock fa"></i>
<input type="password" class="form-control" placeholder="Password" id="user-pass">
</div>
</div>
<div class="form-group">
<input class="btn btn-primary btn-block" id="authenticate_user" type="submit" value="Submit">
</div>
</form>
</div>
My views.py
#csrf_exempt
def signin(request):
if request.method == 'POST':
print request.POST.get('sender-email') #prints None
username = request.POST['username'] # throws error, username not available.
password = request.POST['password']
How do I post the data without using jquery? I know of a way of posting through AJAX jquery, but dont wanna do that.
The 'name' attribute of input tags is set as keys of request.GET and request.POST.
Add name attribute to all your input tags.
<input name="username" id="sender-email" type="text" placeholder="Username" class="form-control email">
<input name="password" type="password" class="form-control" placeholder="Password" id="user-pass" >
POST data are populated using the name attribute of your input elements. Change your id attributes or add a name one accordingly. E.g:
<input type="password" class="form-control" placeholder="Password" name="user-pass">
You should also consider using a form to handle your data more easily.

Categories