Why am I getting a 500 error with this code? - python

I am trying to create a site with a webform using Flask, but I keep getting a 500 error
Here is my template/main.html
<DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample Page</title>
<meta name="viewport" content="width=device-width"
initial=scale=1/>
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='favicon.ico') }}" rel="shortcut icon">
</head>
<h2>Hello, this site is meant to test my fill_web_form.py script</h2>
<br>
<br>
<h1>Test Form</h1>
<form action="/" method="post" name="login">
{{ render_field(form.test_form) }}<br>
<p><input type="submit" value="Sign In"></p>
</form>
</html>
Here is my init.py file
from flask import Flask, render_template
#import sqlite3
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template("main.html")
if __name__ == "__main__":
app.run()
Here is my form.py file
from flask.ext.wtf import Form
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired
class LoginForm(Form):
test_form = StringField('test_form', validators=[DataRequired()])
Why do I keep getting a 500 error? I cant figure it out.

Run in debug mode app.run(debug=True) to see more information in browser.
You should import form and send to template. You may need secret_key to use csrf. etc.
from form import LoginForm
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
#app.route('/')
def homepage():
return render_template("main.html", form=LoginForm())

Related

How to automatically refresh chat app to be in real-time

I have this very basic chat app, where everyone can chat in one huge group. And when I send messages, other people have to refresh their web page to see new messages. I am just wondering if anyone has any idea how to do this. By the way, the app is made with python Flask and HTML.
from flask import Flask, render_template, request, url_for, redirect
import database as db
app = Flask(__name__)
app.secret_key = 'ItDoesntMatter'
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('/index.html', messages=db.get_messages())
#Else
message = request.form['message']
db.send_message(message)
return redirect(url_for('index'))
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat</title>
</head>
<body>
{% for message in messages %}
<div>At {{ message[1] }}: <strong>{{ message[0] }}</strong></div>
{% endfor %}
<form method="POST" action="/">
<input type="text" placeholder="message" name="message">
<button type="submit" id="btn">Send</button>
</form>
</body>
</html>
I tried to do this with a turbo-flask, but it didn't work. I was also on google for like 1 hour and I didn't find anything.

Flask wtforms not allowing image upload

Dears,
I have been struggling with uploading an image on a flask form in my application. I have simplified the code to just show if the form has picked up a file by a print statement. The script is as follows:
from flask import Flask, render_template, session, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import SubmitField
from flask_wtf.file import FileField
from PIL import Image
import os
from main import app
class Uploadform(FlaskForm):
picture = FileField('Update Profile Pic')
submit = SubmitField('Submit')
#### route
#app.route('/', methods=['GET', 'POST'])
def upload():
form = Uploadform()
path = app.root_path
if form.validate_on_submit:
print('form submitted')
if form.picture.data:
print('image available')
img = form.picture.data
print(img)
else:
print('no image')
return render_template ('form.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
HTML form goes a follows:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="POST" action="{{url_for('upload')}}">
{{ form.hidden_tag() }}
{{ form.csrf_token }}
{{form.picture.label}} <br>
{{form.picture}} <br>
{{form.submit() }} <br>
</form>
</body>
</html>
When I run the above I get the print statements:
'form submitted' and
'no image'
Many thanks for your help in advance.
<form method="POST" action="{{url_for('upload')}}" enctype="multipart/form-data">
multipart/form-data this value is necessary if the user will upload a file through the form.
if form.validate_on_submit:
needs to be
if form.validate_on_submit():

SQLAlchemy Engine Result Proxy error (Flask Python)

I'm creating a search tool, that uses psycopg, flask and SQLAlchemy to return results from a Postgres database.
I'm getting the error:
sqlalchemy.engine.result.ResultProxy object at....
This is happening when I am searching for the 'job number'.
I'm led to believe that this is due to not interfacing with the ResultProxy, but I cannot figure out where it is wrong?
app.py
from flask import Flask, render_template, request
from sqlalchemy import create_engine
from sqlalchemy import text
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://xx:xx#rx:x/xxx'
engine = create_engine('postgresql+psycopg2://xx:xxx#rx:x/x')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db=SQLAlchemy(app)
#app.route('/', methods=['GET', 'POST'])
def homepage():
if request.method == 'POST':
jn = request.form['jobnumber']
result_set = engine.execute(text("SELECT cost FROM public.options where cast(optionno AS VARCHAR) LIKE :jn"), {"jn": f"%{jn}%"})
result_set.close()
return render_template('main.html', result_set=result_set, jn=jn)
else:
return render_template('main.html')
if __name__ == "__main__":
app.run(debug=True)
Main.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>xx</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>
<body>
<p>x</p>
<form method="POST" id="jobnumber">
<input name="jobnumber" type="textbox" placeholder="jobnumber">
</form>
<table>
<td>
{{result_set}}
</td>
</table>
</body>
</html>
Any help would be greatly appreciated.
Maybe you should use the sqlalchemy to execute
rp = db.session.execute("select * from test")
result_set = rp.fetchall()

Why am I getting a 500 error when trying to connecto to an sqlite database?

I trying to make a site that passes data from a web form to an sqlite database. I keep getting a 500 error. When I type the ip address and get to main.html, it displays the page with no errors, but when I submit the form I get a 500 error.
It doesn't give me the stacktrace is just says The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
It's hard to debug this because when I access the server through a browser, it doesn't give me details about the error. And when I run flask run in putty, it doesn't give me an error, it just gives me this
searching http://127.0.0.1 in my browser doesn't work, I'm guessing because flask run is running on the server and not on my computer.
Here is my code:
__init__.py
from flask import Flask, render_template
from forms import TestForm
import sqlite3
app = Flask(__name__)
#app.route('/')
def homepage():
return render_template("main.html", form=TestForm())
#app.route('/post', methods=['POST'])
def post():
conn = sqlite3.connect("sample.db")//If I remove these two lines
conn.close() //The code works without error
return render_template("test.html")
if __name__ == "__main__":
app.run(debug=True)
forms.py
from flask_wtf import Form
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired
class TestForm(Form):
test_form = StringField('test_form', validators=[DataRequired()])
main.html
<DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample Page</title>
<meta name="viewport" content="width=device-width"
initial=scale=1/>
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='favicon.ico') }}" rel="shortcut icon">
</head>
<h2>Hello, this site is meant to test my fill_web_form.py script</h2>
<br>
<br>
<h1>Test Form</h1>
<form action="/post" method="post" name="test">
{{ form.test_form(size=80) }}
<p>Form</p><br>
<p><input type="submit" value="Test Form"></p>
</form>
</html>
test.html
<DOCTYPE html>
</html>
<head>
<title>test</title>
</head>
<body>
<h1>Testing 123</h1>
</body>
</html>

werkzeug.routing.BuildError with Flask Python

**difference to the suggested repeat, my error stemmed from the following line being missing in the original code session['message']=request.form['message'] wherease in the suggested duplicate was missing the render_template component`
I am trying to create user sessions with Flask, I don't care about authentication. I just want a page where they enter their name, and then they are redirected to the main page. I tried to follow the example in this link here but I get a werkzeug.routing.BuildError. To summarise my python app is:
from flask import Flask, render_template
from flask import request, session, url_for,abort,redirect
app = Flask(__name__)
app.config['SECRET_KEY'] = 'F34TF$($e34D';
#app.route('/')
def home():
return render_template('index.html')
#app.route('/signup', methods=['POST'])
def signup():
session['username'] = request.form['username']
session['message']=request.form['message']
return redirect(url_for('message'))
#app.route("/message")
def message():
return render_template("message.html")
if __name__ == '__main__':
app.run(debug=True)
and index.html is:
{% extends "layout.html" %}
{% block content %}
<h1>Say something</h1>
<form method="post" action="{{ url_for('signup') }}">
<p><label>Username:</label> <input type="text" name="username" required></p>
<p><button type="submit">Send</button></p>
</form>
{% endblock %}
layout.html is:
<!doctype html>
<html lang="en">
<head>
<title>Say somthing</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
You are getting that error because you don't have a route called message and yet you are redirecting to it.
#app.route('/signup', methods=['POST'])
def signup():
session['username'] = request.form['username']
# Create a message route first
return redirect(url_for('message'))
Here's a sample route called message
#app.route("/message")
def message():
return render_template("message.html")

Categories

Resources