Can't use PUT method with flask [duplicate] - python

This question already has answers here:
Using PUT method in HTML form
(10 answers)
Closed 6 years ago.
I wrote this easy program:
#app.route('/puttest/', methods=['GET', 'PUT'])
def upload_file():
if request.method == 'PUT':
return 'Hello, {}!'.format(request.form['name'])
else:
return '''
<title>Does it work ?</title>
<h1>PUT test</h1>
<form action=http://localhost:8887/puttest/ method=put>
<input type=text name=name>
<input type=submit value=try>
</form>
'''
if __name__ == '__main__':
app.run('0.0.0.0', 8887)
It works perfectly for GET method, but it doesn't work with PUT. Trying to send put message, I can see this error at a browser:
Method Not Allowed
The method is not allowed for the requested URL.
What has happened to put method ?
It will work fine if I change put method on post everywhere in program.

PUT won't work with HTML method attribute.
Allowed values are: method = get|post
You have to use POST in Webforms:
#app.route('/puttest/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
return 'Hello, {}!'.format(request.form['name'])
else:
return '''
<title>Does it work ?</title>
<h1>PUT test</h1>
<form action=http://localhost:8887/puttest/ method=post>
<input type=text name=name>
<input type=submit value=try>
</form>
'''
Further informations at: Using PUT method in HTML form and HTML Standard

Related

How to pass the value to html input by add optional parameters to the link of the website to turn it into an API (flask)

I'm new to flask and I wonder how to pass the value to the HTML by adding optional parameters into the link
Example HTML:
<HTML>
<body>
<form method=post enctype=multipart/form-data>
<input type=text name=link>
<input type=submit value=Open>
</form>
</body>
</HTML>
Code I'm using to call the HTML above:
#app.route('/link', methods=['GET', 'POST'])
def open_link():
if request.method == "POST":
if 'link' != '':
text = request.form['link']
webbrowser.open(text)
return render_template("get_link.html")
Now, I want to add a parameter to the link to automatically pass the value for the input in, so that I can make it into an API
Example
http://192.168.5.107:8000/link/**add_para_here = hi**
Any suggestion? and only sorry for my bad English.Thank you
If I understand you correctly, you would like to use optional url parameters within your request. So that the url can be created in the following way.
http://127.0.0.1:8000/link?param0=value0&param1=1
In this case the form would look like this.
<form action="{{ url_for('link', param0='value1', param1=1) }}" method="post">
<input type="text" name="link">
<input type="submit" value="Open">
</form>
Within the endpoint, the parameters can be queried via request.args. Default values and an optional type conversion can also be specified here.
#app.route('/link', methods=['GET', 'POST'])
def open_link():
param0 = request.args.get('param0')
param1 = request.args.get('param1', 0, type=int)
if request.method == "POST":
if 'link' != '':
text = request.form['link']
# ...
return render_template("get_link.html")
Have fun implementing your project.

How to move variables from python to template and back?

I'm trying to get information from a form to my python file and then put into a template. Thing is, i know the form is working but i couldn't show it into the template.
Form here:
<div class="container" id="cont1">
<form action="http://127.0.0.1:5000/areas" method="POST" enctype="multipart/form-data">
<label for="author">Autor</label>
<input type="text" id="author" name="author"><br><br>
<label for="intro">Introdução</label>
<input type="text" id="intro" name="intro"><br><br>
<label for="content">Conteúdo</label>
<input type="text" id="content" name="content"><br><br>
<input type="file" id="planilha" name="planilha" accept=".csv"><br><br>
<input type="submit" value="Enviar">
</form>
</div>
then i try to get the data in app.py:
#app.route('/areas', methods=['GET', 'POST'])
def areas():
if request.method == "POST":
#app.context_processor
def f1():
aut = request.form.get['author']
intr = request.form['intro']
cont = request.form['content']
return dict(a=aut, i=intr, c=cont)
return render_template("areas.html")
else:
return render_template("areas.html")
I know it's working because i tried it out of the route and it showed what the form had. Now when i try into the route:
AssertionError
AssertionError: A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.
To fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.
The decorator was the solution i found to get the data so i could place into templates like this:
<text>{{a}}</text>
The error is caused by the incorrect usage of the decorator. You don't need a decorator to pass variables to templates. render_template also accepts arguments which you can directly pass into your HTML file.
The following should work:
#app.route('/areas', methods=['GET', 'POST'])
def areas():
if request.method == "POST":
aut = request.form['author']
intr = request.form['intro']
cont = request.form['content']
return render_template("areas.html", a=aut, i=intr, c=cont)
else:
return render_template("areas.html")

Flask form not validating with HTML [duplicate]

This question already has answers here:
Post values from an HTML form and access them in a Flask view
(2 answers)
Form is never valid with WTForms
(1 answer)
Closed 2 years ago.
I've tried looking through the documentation and other posts on here, though I'm still having trouble.
views.py
#bp.route('/')
def index():
return render_template("index.html")
#bp.route('/newSearch', methods=['GET', 'POST'])
def newSearch():
form = NewSearchForm()
if form.validate_on_submit():
# DB code
return redirect(url_for('newPage.html'))
return render_template('newSearch.html', form=form)
Once the user enters a search query and clicks "submit" it should redirect to the results page. However, It's not validating the form correctly with my current form tag.
index.html
<form action="{{ url_for('newSearch') }}" enctype="multipart/form-data" method="post">
<input class="btn btn-primary" type="submit" value="Search"></input>
</form
The button lives in the index.html. It fails to redirect to newPage.html in the case above. What is missing that's causing it to fail validation? any help would be greatly appreciated!

flask request.files empty even though request.args is not

I'm trying to upload a file to a flask server from a form. My HTML (I'm using React) is as follows:
<form action="/" method="post">
<input type="file" id="placesCSV" name="placesCSV"></input>
<input type="submit" />
</form>
But the following code in python:
#app.route('/', methods = ['POST'])
def findRoutes():
if request.method == 'POST':
print(request.args)
print(request.files)
Prints the filename correctly for request.args, but request.files is empty. I'm also getting:
Bad Request
The browser (or proxy) sent a request that this server could not understand.
I've tried the same with 'GET' instead of 'POST' and I have the same result.
I think you should change the request.method to POST
def findRoutes():
if request.method == 'POST':
print(request.args)
print(request.files)

Why does html POST take me to an unexpected page?

I have a simple web application built with Python using flask that has three pages: main, index, and post. I am trying to get to the "if request.method == "POST"" section of the index page. To test this I've asked it to render the post.html page. For some reason when I send a POST method from the index page I'm instead being redirected to my main_page. The python code looks like this:
from flask import Flask, redirect, render_template, request, url_for
app = Flask(__name__)
app.config["DEBUG"] = True
#app.route("/", methods=["GET", "POST"])
def index():
if request.method == "GET":
return render_template("main_page.html")
#implied ELSE here (if it's not GET, do the following for a POST)
return redirect(url_for('index'))
#app.route('/index', methods=['GET', 'POST'])
def new_index():
if request.method == "POST":
#I AM TRYING TO GET HERE
return render_template('post.html')
if request.method == "GET":
return render_template('index.html',)
#app.route('/post')
def post():
return render_template('post.html')
The POST method from index.html comes from this:
<div class="row">
<form role="form" method='POST' action='.'>
<textarea class="form-control" name="contents" placeholder="Enter a comment"></textarea>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
I'm not particularly familiar with HTML but I've tried everything I can think of. Any advice?
When you want to link to the same page in a form action you should actually put a question mark, an empty string, a hash or just leave out the attribute all together. Doing either of these will fix your code.
<form role="form" method='POST' action='?'>
<form role="form" method='POST' action='#'>
<form role="form" method='POST' action=''>
<form role="form" method='POST'>
My personal preference is using.
<form role="form" method='POST' action='#'>
This will validate in XHTML and doesn't open up any known attack vectors.
First thing I did was testing your API using Postman, and that all works fine: GET goes to the GET handler, POST goes to the POST handler.
The error I found is in the html form, in particular the action tag: you should point that to the API handler explicitly, and relative to the hostname. So, for example, setting that to:
<form role="form" method='POST' action='/index'>
will actually perform a POST on the /index API of your Flask app.

Categories