I have a problem accessing the value from a Form input in HTML. I'm using Tornado.
It gives me the error: WARNING:tornado.access:404 GET /Python_Tornado_IV.py?input1=pedro (127.0.0.1) 0.00ms
These are the files:
File "Python_Tornado_IV.py":
import tornado.web
import tornado.ioloop
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html")
if self.get_argument("input1") is not None:
valor = self.get_argument("input1")
print("Valor introduzido:", valor)
else:
print("Não foi introduzido nenhum valor!")
app = tornado.web.Application([(r"/", MainHandler)])
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
File "index.html":
<!Doctype html>
<html>
<body>
<form name="form1" action="Python_Tornado_IV.py" method="get">
<input type="text" name="input1">
<input type="submit" value="Submit">
</form>
</body>
</html>
Both files are in the same directory.
In Tornado, you don't make requests to a file. Rather, you make requests to the registered urls of a handler.
As you've set the path for your MainHandler as r"/", so this is where you're supposed to make the requests to.
Change the action of your form to this:
action="/"
Related
Attempting to upload a document through Dropbox's API through a Submit button on Flask application. The HTML loads on localhost, but whenever I upload the document and hit Sumbit, there is a 404 error and the document does not post to the Dropbox API. Any ideas on where I'm going wrong?
Python
from flask import Flask, render_template, request
import dropbox
# Function Definition
def uploader(token, file):
target = '/temp'
targetFile = target + 'test.docx'
connection = dropbox.Dropbox(token)
meta = connection.files_upload(file, targetFile, mode=dropbox.files.WriteMode("overwrite"))
# Flask App
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def upload_document():
if request.method == "POST":
uploader(token, request.files['file'])
return render_template('index.html')
if __name__ == "__main__":
app.run()
HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method = "post" action = "/home" enctype = "multipart/form-data">
<p>
<input type="file" name="file" autocomplete="off" required>
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
</body>
</html>
It looks like the issue stemmed from the script not reading the file when being passed through the function via the Dropbox connection. When using this, add file.read() within the connection.
# Function Definition
def uploader(token, file):
target = '/temp'
targetFile = target + 'test.docx'
connection = dropbox.Dropbox(token)
meta = connection.files_upload(file.read(), targetFile, mode=dropbox.files.WriteMode("overwrite"))
I am getting error 400 when i load my website, i have check everything and nothing seems off.
Thanks
Error:
Bad Request
The browser (or proxy) sent a request that this server could not understand.
What the code does:
It takes a input from a user, that is then saved in a file for use of tracking what a user orders from my drinks machine
import flask
from flask import request
#app.route('/Half1File', methods=['POST'])
def Half1File():
print(request.form['projectFilepath'])
Name = request.form['projectFilepath']
print(Name)
file = open("Tab.txt", "a")
file.write('\n'+Name + ", Drink1Half")
return
print (Name)
#app.route("/Half1Tab")
def Half1Tab():
return """<html>
<form action="/Half1File" method="post">
Project file path: <input type="text" name="Name"><br>
<input type="submit" value="Submit">
</form>
</html>"""
You have to fix the name of the value passed to request in your form, and provide a view in the return statement (i made it easy).
import flask
from flask import request
app = flask.Flask(__name__)
#app.route('/Half1File', methods=['POST'])
def Half1File():
print(request.form)
print(request.form['Name'])
Name = request.form['Name']
print(Name)
file = open("Tab.txt", "a")
file.write('\n'+Name + ", Drink1Half")
return """<html><div>OK : {} </div></html>""".format(Name)
#app.route("/Half1Tab")
def Half1Tab():
return """<html>
<form action="/Half1File" method="post">
Project file path: <input type="text" name="Name"><br>
<input type="submit" value="Submit">
</form>
</html>"""
Edited to include the first answers input:
My HTML form looks like this:
<!DOCTYPE html>
<html>
<body>
<form action="http://localhost:5000/upload_candidates" method='POST' enctype="multipart/form-data">
<input type="file" name="csv_file" accept="*">
<input type="submit">
</form>
</body>
</html>
the Flask endpoint looks like this:
#app.route('/upload_candidates', methods=['POST'])
def upload_candidates():
print('this worked')
file = request.files['file']
print('did this work?')
x = file.read()
print(x)
if __name__ == "__main__":
app.run(threaded=True, debug=True)
I'm getting an error: The browser (or proxy) sent a request that this server could not understand.
In the terminal:
* Detected change in '..../hello.py', reloading
* Restarting with stat
* Debugger is active!
* Debugger pin code: 238-076-488
this worked
In the network console:
Request URL:http://localhost:5000/upload_candidates
Request Method:POST
Status Code:400 BAD REQUEST
Remote Address:127.0.0.1:5000
It seems like it doesn't like the file = request.files['file'] line.
What am I doing wrong?
Your <form> is missing an enctype attribute:
<form action="http://localhost:5000/upload_candidates"
method="POST"
enctype="multipart/form-data">
Also, it appears that you are referencing a request.files member by the wrong name. Try this:
file = request.files['csv_file']
I have the following scenario:
<form class=*** method="post" action=("main.py" ???)>
<input class=*** type="email" name="email">
<input class=*** type="submit" value=***>
</form>
This form is in a .html file, evidently in a different file from the python code. I wish know which ways do I have to get the information from the form and send to the python file to finally work on it (I guess is something about the action field but not sure).
OBS: I must use the webapp2 (I'm using the google server so django and other stuff do not work on it)
You can see Handling Forms with webapp2 from the Google App Engine wepapp2 tutorial.
import cgi
from google.appengine.api import users
import webapp2
MAIN_PAGE_HTML = """\
<html>
<body>
<form action="/sign" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</form>
</body>
</html>
"""
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.write(MAIN_PAGE_HTML)
class Guestbook(webapp2.RequestHandler):
def post(self):
self.response.write('<html><body>You wrote:<pre>')
self.response.write(cgi.escape(self.request.get('content')))
self.response.write('</pre></body></html>')
application = webapp2.WSGIApplication([
('/', MainPage),
('/sign', Guestbook),
], debug=True)
And read through the entire tutorial for more information about Datastore and template
Using template allow you to put code html code in another file.
from flask import *
from twilio import twiml
from twilio.rest import TwilioRestClient
from flask import render_template
import os
#Pull in configuration from system environment variables
TWILIO_ACCOUNT_SID = os.environ.get('Axxxxxx')
TWILIO_AUTH_TOKEN = os.environ.get('Sxxxxxxxxx')
TWILIO_NUMBER = os.environ.get('xxxxxxx')
# create an authenticated client that can make requests to Twilio for your
# account.
#client = TwilioRestClient(account='Axxxxx', token'sxxxxxxxx')
#create a flask web app
app = Flask(__name__)
client = TwilioRestClient(account='Axxxxx', token='Sxxxxx')
#app.route('/')
def homepage():
return render_template('index.html')
#Handling a post request to send text messages.
#app.route('/message', methods=['POST', 'GET'])
def message():
# Send a text message to the number provided
if request.method == 'POST':
message = client.sms.messages.create(to=request.form['Phone_number'],
from_=TWILIO_NUMBER,
body=request.form['body'])
return render_template('message.html')
if __name__ == '__main__':
# Note that in production, you would want to disable debugging
app.run(debug=True)
I am using flask. When i input the number and the text message it gives me this error
Method Not Allowed
The method is not allowed for the requested URL.
You're posting to the wrong endpoint. Your form should look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Send an SMS</title>
</head>
<body>
<form action="/message" method="POST">
Cell phone number: <input name="phone_number" type="text" />
Text in here: <input name="body" type="text" />
<button type="submit">Send Text</button>
</form>
</script>
</body>
</html>
(Above, action was changed from / to /message.)
Note: if this is a template run through flask.render_template, you should change
<form action="/message" method="POST">
to
<form action="{{ url_for('message') }}" method="POST">
This is a more sustainable way to use urls in flask, and it will reduce your overhead if you ever need to change the value.