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
Related
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.
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> ?
I'm working on a simple UI to start and stop games by ID. The basic HTML I have written is as follows (game_id is populated by JS):
<div align="center" class="top">
<div align="left" class="game-id-input">
Game ID: <input type="text" name="game_id" id="game_id">
</div>
<div align="right" class="buttons">
<form action="{{ url_for('start_game', game_id=game_id) }}" method="get">
<input type="submit" name="start" value="Start game" class="btn btn-success"></input>
</form>
<form action="{{ url_for('end_game', game_id=game_id) }}" method="get">
<input type="submit" name="end" value="End game" class="btn btn-danger"></input>
</form>
</div>
</div>
which looks like
I also have Flask route functions defined for each of the forms:
#app.route("/start_game/<game_id>")
def start_game(game_id):
# ...
#app.route("/end_game/<game_id>")
def end_game(game_id):
# ...
In my forms, how can I make game_id correspond to the game_id from #game_id?
Currently when I submit start and end games, I get a File Not Found error because it's just appending the literal <game_id> to the route.
I'm new to web development. This should be trivial, but I don't know what to search for. Sorry in advance for such a simple question.
You are trying to generate a url based on user input, but user input isn't available when Jinja is rendering the template on the server side, it's only available on the client side. So if you wanted to post to URLs with the game id as a URL parameter, you would have to build that URL on the client side with JavaScript.
For what you're trying to do, that's not really necessary. You can get the submitted value of a named input with request.form['name']. Buttons are just like any other input, so you can name them to find out what action was taken.
#app.route('/manage_game', methods=['POST'])
def manage_game():
start = request.form['action'] == 'Start'
game_id = request.form['game_id']
if start:
start_game(game_id)
else:
stop_game(game_id)
return redirect(url_for('index'))
<form method="POST" action="{{ url_for('manage_game') }}">
<input type="text" name="game_id"/>
<input type="submit" name="action" value="Start"/>
<input type="submit" name="action" value="Stop"/>
</form>
Even that's more verbose than you need. Given that you'd know if a game was already in progress, just toggle the current status instead of picking an action. It would never make sense to start a game that's already started, only stop it.
I cannot comment, but I would like to correct davidism's code.
I believe that you need action within your form element with a value which corresponds to the function within the server python code for this to work. Minor, but an important correction. So it would be like this:
In your server.py:
#app.route('/manage_game', methods=['POST'])
def manage_game():
start = request.form['action'] == 'Start'
game_id = request.form['game_id']
if start:
start_game(game_id)
else:
stop_game(game_id)
return redirect(url_for('index'))
In your HTML:
<form method="POST" action=/manage_game>
<input type="text" name="game_id"/>
<input type="submit" name="action" value="Start"/>
<input type="submit" name="action" value="Stop"/>
</form>
<form action="/fileupload" enctype="multipart/form-data" method="post">
<label>Title<input name="name"></label>
<label>Author<input name="author"></label>
<label>Year <input name="year"></label>
<label>Link <input name="link"></label>
<input type="file" name="file">
<input type="submit">
</form>
The question is why self.get_uploads() returns nothing,when self.request.get('file') works (or I suggest it works)
class FileUploadHandler(H.Handler,blobstore_handlers.BlobstoreUploadHandler):
def post(self):
name=self.request.get('name')
if name:
logging.error(name)
author=self.request.get('author')
if author:
logging.error(author)
year =self.request.get('year')
if year and year.isdigit():
year=int(year)
f =self.get_uploads('file')#FILE NOT FOUND
#f=self.request.get('file') # WORKS FINE
if not f:
logging.error("FILE NOT FOUND")
self.redirect("/files")
I looked at the sample app but they also use self.request.get('file')
The answer is that you should create upload url for blob.
You need get_uploads()[0] or name.
Simple example on the uploads handler (Compare and make appropriate changes in your code):
<form name="myform" action="{{ upload_url }}" method="post" enctype="multipart/form-data">
<h1>Select an Image</h1>
<input name="file" type="file"><br>
<input type="submit" value="Upload">
</form>
Handler:
class UploadBlobsHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
try:
upload = self.get_uploads()[0]
logging.info(upload)
url = images.get_serving_url(upload)
# Do something with it.
except:
self.redirect('/uploadform/?error', abort=True)
self.redirect('/uploadform/?success&image_url=' + url)
Example on how to use uploads with blobstorrhandlers: gae-image-upload-example
This is a full solution to my problem:
<form action="{{upload_url}}" enctype="multipart/form-data" method="post">
<label>Title<input name="name"></label>
<label>Author<input name="author"></label>
<label>Year <input name="year"></label>
<label>Link <input name="link"></label>
<input type="file" name="file">
<input type="submit">
</form>
where upload_url =blobstore.create_upload_url('/fileupload',max_bytes_per_blob=10*1000*1000)
and the code to process the request is next:
upload=self.get_uploads('file')[0]
I have the following template form, containing several variables.
<form action="https://me.s3.amazonaws.com/" method="post" enctype='multipart/form-data' class="upload-form">
<input type="hidden" name="key" value="videos/{{filename}}">
<input type="hidden" name="AWSAccessKeyId" value="{{access_key}}">
<input type="hidden" name="acl" value="public-read">
<input type="hidden" name="policy" value="{{policy}}">
<input type="hidden" name="signature" value="{{signature}}">
<input type="hidden" name="Content-Type" value="{{content_type}}">
<input name="file" type="file">
<input type="submit" value="Upload" name="upload">
</form>
However, as soon as the submit button is hit, the form is sent to amazon, and I'm not able to pass it variables. This is what I've been trying to do, unsuccessfully --
if 'upload' in request.POST:
policy = base64.b64encode(...)
signature = base64.b64encode(
hmac.new('secret_key', policy, sha).digest())
file = request.POST['files']
filename=file.name
content_type=mimetypes.guess_type(filename)[0]
What do I need to do to pass the variables to the form after the POST request but BEFORE amazon processes the form? Thank you.
You should change your form's action to your django view and in your view you can re-post to https://me.s3.amazonaws.com/:
In your template
<form action="http://mywebsite/upload" method="post" ...
In your view.py:
def upload(request):
# Your treatment here.
# Post the data to amazon S3.
urllib2.urlopen("https://me.s3.amazonaws.com/", your_data)
...
You could change the form to POST to one of your own views, then do your post-processing in your view, and then within your view code, issue a POST to Amazon with the correct values using, say, urllib2 or similar.