How can I print something like this:
{
username = admin
email = admin#localhost
id=42
}
With only using a method = ['POST'] and without using render_template?
PS: I already made it run with ['GET']
Here's my code:
from flask import Flask, jsonify, request
app = Flask(__name__)
#app.route('/', methods=['POST'])
def index():
if request.method == 'POST':
return jsonify(username="admin",
email="admin#localhost",
id="42")
else:
if request.method == 'POST':
return jsonify(username="admin",
email="admin#localhost",
id="42")
if __name__ == "__main__":
app.run()
And what I get is a 405 Method error.
Hey make sure your trailing stashes in your html are correct.
you may refer to : Flask - POST Error 405 Method Not Allowed and flask documentation : http://flask.pocoo.org/docs/0.10/quickstart/
this
<form action="/" method="post">
and this is same same but different
<form action="" method="post">
Accessing it without a trailing slash will cause Flask to redirect to the canonical URL with the trailing slash.
Given your error 405, I am suspecting that this is your problem. GET is fine, because you will just be redirected.
Try returning the form (as biobirdman said) on a GET request. Not sure why you need the request.method == 'POST' conditional statement. The parameter methods=['POST'] in the route should suffice.
Try this:
from flask import Flask, jsonify, request
app = Flask(__name__)
#app.route('/', methods=['POST'])
def index():
return jsonify(username="admin", email="admin#localhost", id="42")
#app.route('/', methods=['GET'])
def form():
return "<form action='/' method='POST'>" \
"<input type='submit'>" \
"</form>"
if __name__ == "__main__":
app.run()
Related
i am getting error 404 while running this
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. how do i need to run the server ? please help
from flask import Flask
from flask import render_template
from flask import request
app = Flask(__name__, template_folder="templates/")
app.route("/login", method=['POST', 'GET'])
def index():
greeting = "Hello World"
if request.method == "POST":
name = request.form['name']
greet = request.form['greet']
greeting = f"{greet}, {name}"
return render_template("index.html", greeting=greeting)
else:`enter code here`
return render_template("hello_form.html")
if __name__ == "__main__":
app.run(debug=True)
You need to replace
app.route("/login", method=['POST', 'GET'])
By
#app.route("/login", methods=['POST', 'GET'])
Edit: also, methods
It's the most basic thing to ask but #app.route('/') is not working on my Linux server.
Below is the code :
from flask import Flask, jsonify, request
from app import models
import json
import time
app = Flask(__name__)
app.url_map.strict_slashes = True
#app.route('/')
def blank():
return 'Hello ABC!'
#app.route('/driftking')
def blank2():
return 'Hello driftking!'
# dynamic route
#app.route("/test/<search_query>")
def search(search_query):
return search_query
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return "POST METHOD"
elif request.method == 'GET':
return "GET REQUEST ARE NOT ALLOWED"
if __name__ == '__main__':
app.run(debug=True)
app.run()
Very basic app, all's working fine on local machine but not on my linux server.
E.g. if I load http://xxx.xxx.xxx.xxx/projectname ---- it shows Hello ABC!
If I load http://xxx.xxx.xxx.xxx/projectname/driftking -- it redirects me to http://xxx.xxx.xxx.xxx ( i.e my server's homepage)
If I load http://xxx.xxx.xxx.xxx/projectname/test/search -- 404 error not found
If I load http://xxx.xxx.xxx.xxx/projectname/login -- it redirects me to http://xxx.xxx.xxx.xxx ( i.e my server's homepage)
127.0.0.1 - - [24/Nov/2017 19:37:01] "POST //login HTTP/1.1" 405 -
^^This is what I get on terminal. I don't understand why I get two leading slashes everytime.
But If do http://xxx.xxx.xxx.xxx/projectname/insert-any-word/login , my post req get's executed. At the same time on local machine i dont get two leading slashes // to the path and thus the request get's processed.
There are a couple of things wrong but try this, you'll need a proxy to help with the rerouting.
from flask import Flask, jsonify, request
from app import models
import json
import time
from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
app.url_map.strict_slashes = False
#app.route('/')
def blank():
return 'Hello ABC!'
#app.route('/driftking')
def blank2():
return 'Hello driftking!'
# dynamic route
#app.route("/test/<search_query>")
def search(search_query):
return search_query
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return "POST METHOD"
elif request.method == 'GET':
return "GET REQUEST ARE NOT ALLOWED"
if __name__ == '__main__':
app.run(debug=True)
I am learning Flask and I am having some trouble passing arguments to a URL for use on another page. For example, I have a form on /index and I would like it to redirect to a /results page where I could print the form data. My attempt is this:
from flask import render_template
from flask import redirect
from flask import url_for
from app import app
from .forms import LoginForm
#app.route('/')
#app.route('/index', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
name = form.artistName.data
return redirect(url_for('result', name=name))
else:
return redirect('/index')
return render_template('index.html',
title='Sign In',
form=form)
#app.route('/result/<name>')
def result(name):
return render_template('results.html')
I receive a 405 error Method not allowed for the requested URL when redirecting to the /results page. I would like to construct a URL on /results using the result of the form as an argument.
How can I do this? Many thanks
you defined
#app.route('/result/<name>')
which means its default http method is GET;
when this runs:
if form.validate_on_submit():
# POST method
name = form.artistName.data
# redirect Will use 'POST'
return redirect(url_for('result', name=name))
so , you got Method not allowed for the requested URL.
i think you can add a POST method to #app.route('/result/<name>')
I set username and password in the first request. However, I need to persist the username and password in the second request. How do we do this in python?
I am using python Flask framework.
http://flask.pocoo.org/docs/0.10/quickstart/#sessions
in this articles shows session like this.
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
#app.route('/')
def index():
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form action="" method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''
I tried someting like this.
from flask import Flask, session, redirect, url_for, escape, request
session['username']= 'Tin Tin'
But I get runtime errors. Any hint?
Updated code,
#app.route('/session/')
def session():
session['tmp'] = 'hey it is working'
# print session['tmp']
# session.pop('tmp', None)
# print session['tmp']
return render_template('hello.html', name ='session')
if __name__ == "__main__":
app.secret_key = 'tsdhisiusdfdsfaSecsdfsdfrfghdetkey'
app.run(debug=True)
After setting the key, I get the error
TypeError: 'function' object does not support item assignment
Don't name your routed method "session" - you're conflicting with flask.session.
from flask import Flask, session, render_template
app = Flask(__name__)
#app.route('/session/')
def set_session():
session['tmp'] = 'hey it is working'
return render_template('hello.html', name ='session')
if __name__ == "__main__":
app.secret_key = 'tsdhisiusdfdsfaSecsdfsdfrfghdetkey'
app.run(debug=True)
I am trying to upload a file but the browser spinner rolls forever, server logs don't show updates and the file doesn't get uploaded. It sure is a newbie error but I have no clue what that is:-
static/index.html :-
html
form action="http://127.0.0.1:5000/upload" method="post" enctype="multipart/form-data"
input type="file" name="db"/
input type="submit" value="upload"/
/form
html
app.py
from flask import Flask
from flask import request
from werkzeug import secure_filename
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
#app.route('/upload', methods=['GET', 'POST'])
def upload_file():
print 'upload_file'
if request.method == 'POST':
print 'post'
f = request.files['db']
f.save(secure_filename(f.filename))
if __name__ == '__main__':
app.run(debug=True)
Thanks
Env: Flask 0.9, Jinja2-2.6 and Werkzeug-0.8.3 with Python 2.7 on Win7 x64 with IE9 and Chrome
The docs say you should use enctype="multipart/form-data".
Also, I might try method="POST" (uppercase), if only because defensive coding is a good habit, the defensive maneuver here being not assuming that Flask is bug-free.