I keep getting this error when trying to insert some simple text into a db.
Method Not Allowed
The method is not allowed for the requested URL."
I'm moving from PHP to python so bear with me here.
The code is:
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:password#localhost/pythontest'
db = SQLAlchemy(app)
app = Flask(__name__)
#app.route('/justadded/')
def justadded():
cur = g.db.execute('select TerminalError, TerminalSolution from Submissions order by id desc')
entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
return render_template('view_all.html', entries=entries)
#app.route('/new', methods= "POST")
def newsolution():
if not request.method == 'POST':
abort(401)
g.db.execute('INSERT INTO Submissions (TerminalError, TerminalSolution, VALUES (?, ?)'
[request.form['TerminalError'], request.form['TerminalSolution']])
g.db.commit()
flash('Succesful')
return redirect(url_for('justadded'))
#app.route('/')
def index():
return render_template('index.html')
#app.route('/viewall/')
def viewall():
return render_template('view_all.html')
if __name__ == '__main__':
app.run()
And the html code for the form is:
<form action="/new" method="POST">
<input name="TerminalError" id="searchbar" type="text" placeholder="Paste Terminal error here...">
<input name="TerminalSolution" id="searchbar" type="text" placeholder="Paste Terminal solution here...">
<button type="submit" id="search" class="btn btn-primary">Contribute</button>
</form>
The error has nothing to do with inserting data into the database, it's the methods argument of your /new route.
Instead of this:
#app.route('/new', methods= "POST")
do this:
#app.route('/new', methods= ["POST"])
The list of valid methods needs to be given as an array.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm keep getting the 405 error, I've changed my code following the other related posts but still not working.
routes.py
from flask import render_template, redirect, flash, url_for, abort, request
from flask_login import current_user, login_user, logout_user, login_required
from flask import Flask
import views.model as mod
app = Flask(__name__)
#app.route('/')
def index():
mod.check_database_init()
return render_template("index.html")
#app.route('/login',methods = ['GET','POST'])
def login():
if(request.method == 'POST'):
print("post")
name = request.form['username']
password = request.form['password']
print(name, password)
return redirect(url_for("index"))
else:
return render_template("login.html")
#app.route('/register', methods = ['GET','POST'])
def register():
return render_template("register.html")
login.html
{% include "header.html" %}
<title>Login</title>
<form action="/login" method="POST">
<label>Username</label>
<input type = "text" placeholder = "username" name="username" required>
<label>Password</label>
<input type = "password" placeholder="password" name = "password" required>
<input type="submit">
<p>
Don't have an acoount? Click me to create a new account
</p>
</form>
Back to homepage
I tried this method, https://stackoverflow.com/a/62464826/13239458, it works but I don't know what went wrong in the code above.
server.py
from flask import Flask
from flask_login import LoginManager
import views.routes as rou
import views.database as db
app = Flask(__name__)
app.add_url_rule('/', view_func=rou.index)
app.add_url_rule('/login', view_func=rou.login)
app.add_url_rule('/register', view_func=rou.register)
if __name__ == "__main__":
app.run(host='127.0.0.1', debug = True)
UPDATE
I just change method type into GET (in login.html) and there will be no error and I can see the input from the console, so I think the login method cannot accept the POST method but I have no idea why is that.
Just find out the issue, I created 2 app instances, I move the instantiation into another file then import it, everything works!
You have not included:
if __name__ == '__main__':
app.run(debug=True)
in the end of routes.py
after click subimit button I have problem like in title, the problem start showing when I separated routes from app to views, when I go to localhost:5000/register/ all is good but when I fill the form and click submit then I have problem 405
app.py
from flask import Flask,render_template,request,redirect,abort
app = Flask(__name__)
import views
app.add_url_rule('/', view_func=views.index)
app.add_url_rule('/login/', view_func=views.login)
app.add_url_rule('/register/', view_func=views.register)
if __name__ == '__main__':
app.run(debug=True)
views.py
from flask import Flask,render_template,request,redirect,abort
app = Flask(__name__)
#app.route('/register/', methods=["GET","POST"])
def register():
if request.method == "POST":
req = request.form
email = req.get("email")
password = req["password"]
phonenumber = request.form["phonenumber"]
if email == "" or password == "" or phonenumber=="":
feedback="Please fill the form"
alert = "fail"
else:
feedback="Account created!"
alert = "good"
return render_template('register.html',feedback=feedback,alert=alert)
return render_template('register.html')
#app.route('/')
def index():
print("CIAO")
return render_template('base.html')
and form
<form class="" method="POST" action="{{ url_for('register') }}">
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="password" minlength="8">
<input type="tel" name="phonenumber" placeholder="Numer Telefonu" minlength="8" maxlength="9">
<input type="submit" name="submit">
</form>
Flask is not finding the POST method handler for the /register/ endpoint. You're mixing add_url_rule and #route. You just need the former if you want pluggable views.
I would recommend using the MethodView approach here. Have a separate class for each template and define the get() and post() methods within that.
app.py:
from flask import Flask
from views import Register, Login, Index
app = Flask(__name__)
app.add_url_rule('/', view_func=Index.as_view("index"))
app.add_url_rule('/login/', view_func=Login.as_view("login"))
app.add_url_rule('/register/', view_func=Register.as_view("register"))
if __name__ == '__main__':
app.run(debug=True)
views.py:
from flask import Flask,render_template,request,redirect,abort
from flask.views import MethodView
class Register(MethodView):
def get(self):
return render_template('register.html')
def post(self):
req = request.form
email = req.get("email")
password = req["password"]
phonenumber = request.form["phonenumber"]
if email == "" or password == "" or phonenumber == "":
feedback = "Please fill the form"
alert = "fail"
else:
feedback = "Account created!"
alert = "good"
return render_template('register.html', feedback=feedback, alert=alert)
class Index(MethodView):
def get(self):
print("CIAO")
return render_template('index.html')
class Login(MethodView):
def get(self):
return render_template('login.html')
I'm pretty new to python flask, Just wanted to check my code below, where I'm doing things wrong.
As when I'm running when on URL like (localhost:5000/submit?name=dial&id=565337) it's running properly, though it's not running when I'm passing values on the form and producing an error.
from flask import Flask, request, redirect, url_for
import Eoc_Summary
import Eoc_Daily
import Eoc_AdSize
import Eoc_Video
import Eoc_Intraction
import EOC_definition
from config import Config
app = Flask(__name__)
form = '''
<html>
<body>
<form action = "http://localhost:5000" method="POST">
<p>Enter Name:</p>
<p><input type = "text" name = "name" /></p>
<p>Enter id:</p>
<p><input type = "text" name = "id" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
'''
#app.route("/")
def index():
if request.method == 'GET':
return form
elif request.method == 'POST':
name = request.form['name']
id = request.form['id']
return submit(name, id)
#app.route('/submit')
def submit():
name = request.args.get('name')
id = request.args.get('id')
c = Config(name, int(id))
obj_summary=Eoc_Summary.Summary(c)
obj_summary.main()
obj_daily=Eoc_Daily.Daily(c)
obj_daily.main()
obj_adSize=Eoc_AdSize.ad_Size(c)
obj_adSize.main()
obj_Video=Eoc_Video.Video(c)
obj_Video.main()
obj_Intraction=Eoc_Intraction.Intraction(c)
obj_Intraction.main()
obj_definition=EOC_definition.definition(c)
obj_definition.main()
c.saveAndCloseWriter()
return 'Report Generated'
if __name__ == '__main__':
app.run()
You have to add the methods in your decorator
#app.route("/", methods=['GET', 'POST'])
def index():
{...}
Also you'll have to add your arguments name and id to submit():
#app.route('/submit')
def submit(name, id):
{...}
Finally, import make_response
from flask import Flask, request, redirect, url_for, make_response
I am new to programming and have setup a small website with a comments section on pythonanywhere.com, relaying heavily on their tutorial. But when I post a comment in the form, the comment is not added to the database and for some reason the program redirects me to the index page (the intention is to redirect to stay on the same page)
Any suggestions as to what I might be doing wrong would be greatly appreciated!
The pyhthon code:
import random
from flask import Flask, request, session, redirect, url_for, render_template, flash
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug.routing import RequestRedirect
app = Flask(__name__)
app.config["DEBUG"] = True
SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}#{hostname}/{databasename}".format(
username="username",
password="password",
hostname="hostname",
databasename="majaokholm$majaokholm",
)
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
db = SQLAlchemy(app)
class Comment(db.Model):
__tablename__ = "comments"
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.String(4096))
#app.route("/")
def index():
return render_template("index_page.html")
#app.route('/post', methods=["GET", "POST"])
def post():
if request.method == "GET":
return render_template("post_page.html", comments=Comment.query.all())
comment = Comment(content=request.form["contents"])
db.session.add(comment)
db.session.commit()
return redirect(url_for('post'))
and the form from the HTML template:
<form action="." method="POST">
<textarea class="form-control" name="contents" placeholder="Enter a
comment"></textarea>
<input type="submit" value="Post comment">
</form>
Thanks a lot in advance!
Currently, the action="." in the form actually points to the root of the current directory, which for /post happens to be just / and thus points to the index.
It's always better to use action="{{ url_for('your_target_view') }}" instead.
get rid of action=".", you can use action=""
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)