I have struggled to get this code to work for some days now. This should be just simple web form where text is added to 2 fields and posted to the Sqlite-database.
I am able to display data from db to index.html but accessing below address results to 405 error -'The method is not allowed for the requested URL' when I try to access
http://localhost:5000/post. What is wrong with app.py file likely relating to @app.route('/post', methods=['POST']) and its method?
app.py
post.html
sql.py
I am able to display data from db to index.html but accessing below address results to 405 error -'The method is not allowed for the requested URL' when I try to access
http://localhost:5000/post. What is wrong with app.py file likely relating to @app.route('/post', methods=['POST']) and its method?
app.py
Code:
from flask import Flask, render_template, request, session, g, redirect, url_for
import sqlite3
app = Flask(__name__)
@app.route('/')
def home():
g.db = sqlite3.connect("sample.db")
cur = g.db.execute('select * from posts')
posts = [dict(title=row[0], description=row[1]) for row in cur.fetchall()]
g.db.close()
return render_template("index.html", posts=posts)
@app.route('/post', methods=['POST'])
def post():
title=request.form['title']
description=request.form['description']
return redirect(url_for('/post'))
if __name__=='__main__':
app.run(debug=True)
Code:
<!DOCTYPE html>
<html>
<head>
<title>Flask post</title>
<!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
</head>
<body
<div>
<form action="/post" method="post">
<div>
<label for="title">title:</label>
<input type="text" id="title" />
</div>
<div>
<label for="description">description:</label>
<input type="text" id="description" />
</div>
<div class="button">
<button type="submit">Add to db</button>
</div>
</form>
</div>
</body>
</html>
Code:
import sqlite3
with sqlite3.connect("sample.db") as connection:
c = connection.cursor()
c.execute("DROP TABLE posts")
c.execute("CREATE TABLE posts(title TEXT, description TEXT)")
c.execute('INSERT INTO posts VALUES("this is title", "this is description.")')
Comment