I'm at the section where I change comments = [] to actually connect to the database, and I have an unhandled exception error and I'm not sure what's wrong.
Here's my code: python-
# A very simple Flask Hello World app for you to get started with...
from flask import Flask, redirect, render_template, request, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["DEBUG"] = True
SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
username="4ndy456",
password="<pass>",
hostname="4ndy456.mysql.pythonanywhere-services.com",
databasename="4ndy456$comments",
)
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
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('/', methods=["GET", "POST"])
def index():
if request.method == "GET":
return render_template("main_page.html", comments=Comment.query.all())
comment = Comment(content=request.form["contents"])
db.session.add(comment)
db.session.commit()
return redirect(url_for('index'))
HTML:
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">
<title>My scratchboard page</title>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">My scratchpad</a>
</div>
</div>
</nav>
<div class="container">
{% for comment in comments %}
<div class="row">
{{ comment.content }}
</div>
{% endfor %}
<div class ="row">
<form action="." method="POST">
<textarea class="form-control" name="contents" placeholder="Enter a comment"></textarea>
<input type="submit" class="btn btn-success" value="Post comment">
</form>
</div>
</div><!-- /.container -->
</body>
</html>
[edit by admin: formatting]