I checked every SO question about it, but the answers are mainly on import errors while I do not have such a problem. Mainly I followed this article followed by this one to have a functioning registration.
Instead of using Flask-SQLalchemy I wanted to create my own database (for fun), but when I try to access the database (DButils.py) functions it occurs an internal server error.
The flask code at the top is:
from flask import Flask, render_template, flash, redirect, url_for, session,
from wtforms import Form, StringField, TextAreaField, PasswordField, validators
from functools import wraps
from DButils import *
My folder follows the same order of the git, with DButils.py in the same folder as app.py.
I did not encounter the error when I import the module, but only when I try to call its functions. In DButils.py I have only a signup function:
def signup(nick, email, password):
return True
And when I try to call it in the app.py code like:
#app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm(request.form)
if request.method == 'POST' and form.validate():
email = form.email.data
nick = form.nick.data
password = form.password.data
signup(nick,email,password) #WHEN COMMENTED NO ERROR OCCURS
return redirect(url_for('login'))
return render_template('register.html', form=form)
I get the message "Internal Server Error" with no other clue about it. What can it be? How can I call a function in an external module in Flask?
Thanks for your help!
I found the answer by an trial-error approach. Apparently using pkill --signal SIGHUP uwsgi in combination with sudo systemctl restart nginx.
Related
I have a flask form which works perfect and stores values in my database, but it seems to both succeed (posts values to the database and shows success flash) and fails (shows error and doesn't redirect).
view.py
from flask import render_template, Blueprint, request, redirect, url_for, flash
from project import db
from .models import Items
from .forms import ItemsForm
items_blueprint = Blueprint('items', __name__, template_folder='templates')
#items_blueprint.route('/', methods=['GET', 'POST'])
def all_items():
all_user_items = Items.query.filter_by()
return render_template('all_items.html', items=all_user_items)
#items_blueprint.route('/add', methods=['GET', 'POST'])
def add_item():
form = ItemsForm(request.form)
if request.method == 'POST':
if form.validate_on_submit():
try:
new_item = Items(form.name.data, form.notes.data)
db.session.add(new_item)
db.session.commit()
flash('Item added', 'success')
return redirect(url_for('all_items'))
except:
db.session.rollback()
flash('Something went wrong', 'error')
return render_template('add_item.html', form=form)
Output Example
What might be causing this, as I thought it would be one or the other.
I looked into it because of the #NoCommandLine answer. The point is, that the all_items function is located in the blueprint, not in the base of the application. To redirect to it you want to write redirect(url_for(".all_items") (notice the full stop at the first position of the string).See the documentation for url_for, there is an example for a blueprint containing an index function. The full stop makes it search in the same blueprint the current route is in.
It all depends on where the error occurred. Since it flashed - ('Item added', 'success'), it means your error is on the line redirect(url_for('all_items')).
You should look at the code for redirect(url_for('all_items')) and check if there is an issue with all_user_items = Items.query.filter_by(). Maybe that query is faulty. You can also try to print out the error in the except block to see what it is
I have a flask application, where I want to add a recaptcha field. I use it to verify, that an email can be sent. here is my code so far:
from flask import render_template, request, flash, session, url_for, redirect
from flask import Flask
from flask_mail import Mail, Message
from flask_recaptcha import ReCaptcha
app.config.update({'RECAPTCHA_ENABLED': True,
'RECAPTCHA_SITE_KEY':
'6LdJ4GcUAAAAAN0hnsIFLyzzJ6MWaWb7WaEZ1wKi',
'RECAPTCHA_SECRET_KEY':
'secret-key'})
app=Flask(__name__)
recaptcha = ReCaptcha(app=app)
mail_settings = {
"MAIL_SERVER": 'smtp.gmail.com',
"MAIL_PORT": 465,
"MAIL_USE_SSL": True,
"MAIL_USERNAME": 'USERNAME',
"MAIL_PASSWORD": 'PASSWORD'
}
app.config.update(mail_settings)
mail = Mail(app)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/mail', methods=['GET', 'POST'])
def send_mail():
r = requests.post('https://www.google.com/recaptcha/api/siteverify',
data = {'secret' :
'secret_key',
'response' :
request.form['g-recaptcha-response']})
google_response = json.loads(r.text)
print('JSON: ', google_response)
if google_response['success']:
msg = Message('Thank you for contacting me', sender='kristofferlocktolboll#gmail.com', recipients = [request.form['email']])
msg.body ='sut den'
mail.send(msg)
return render_template('index.html')
else:
return render_template('index.html')
app.run(debug=True)
The problem is that whenever I have the flask_recaptcha import ReCaptcha I get the following error:
it looks like the import statement is incorrect, but since I'm not using WTForms, I don't know what do else. Whenever I remove the import statement it gives a syntax error instead (which makes sense)
Usage: flask run [OPTIONS]
Error: The file/path provided (routes) does not appear to exist.
Please verify the path is correct. If app is not on PYTHONPATH,
ensure the extension is .py
I'm trying to send a post request to my Flask app from one of its own views, but it hangs until I kill the server. If I do the request in JavaScript, it works fine. Why does it not work from the Python code?
from flask import Blueprint, render_template, abort, request, Response, session, url_for
from jinja2 import TemplateNotFound
from flask.ext.wtf import Form
from wtforms import BooleanField, TextField, PasswordField
import requests
login = Blueprint('login', __name__, template_folder='templates')
class LoginForm(Form):
email = TextField('Email')
password = PasswordField('Password')
#login.route('/login', methods=['GET', 'POST'])
def _login():
form = LoginForm(request.form, csrf_enabled=False)
if form.validate_on_submit():
return requests.post(request.url_root + '/api/login', data={"test": True})
return render_template('login.html', form=form)
Prior to 1.0, Flask's development server was single-threaded by default. In that mode, it can only handle one request at a time. Making a request blocks until it receives the response. Your Flask code makes a request in the one thread, and then waits. There are no other threads to handle this second request. So the request never completes, and the original request waits forever.
Enable threads in the dev server to avoid the deadlock and fix the immediate problem.
app.run(threaded=True)
However, making a full HTTP request to the app from within the app should never be necessary and indicates a deeper design issue. For example, observe that the internal request will not have access to the session on the client's browser. Extract the common code and call it internally, rather than making a new request.
def common_login(data):
...
#app.route("/login")
def login():
...
common_login(data)
...
#app.route("/api/login")
def api_login():
...
common_login(data)
...
I'm not familiar with Flask. However this bit of code:
if form.validate_on_submit():
return requests.post(request.url_root + '/api/login', data={"test": True})
Seems like you're accepting a posted form, validating it, and then posting it again. Over and over.
I'm trying to send a post request to my Flask app from one of its own views, but it hangs until I kill the server. If I do the request in JavaScript, it works fine. Why does it not work from the Python code?
from flask import Blueprint, render_template, abort, request, Response, session, url_for
from jinja2 import TemplateNotFound
from flask.ext.wtf import Form
from wtforms import BooleanField, TextField, PasswordField
import requests
login = Blueprint('login', __name__, template_folder='templates')
class LoginForm(Form):
email = TextField('Email')
password = PasswordField('Password')
#login.route('/login', methods=['GET', 'POST'])
def _login():
form = LoginForm(request.form, csrf_enabled=False)
if form.validate_on_submit():
return requests.post(request.url_root + '/api/login', data={"test": True})
return render_template('login.html', form=form)
Prior to 1.0, Flask's development server was single-threaded by default. In that mode, it can only handle one request at a time. Making a request blocks until it receives the response. Your Flask code makes a request in the one thread, and then waits. There are no other threads to handle this second request. So the request never completes, and the original request waits forever.
Enable threads in the dev server to avoid the deadlock and fix the immediate problem.
app.run(threaded=True)
However, making a full HTTP request to the app from within the app should never be necessary and indicates a deeper design issue. For example, observe that the internal request will not have access to the session on the client's browser. Extract the common code and call it internally, rather than making a new request.
def common_login(data):
...
#app.route("/login")
def login():
...
common_login(data)
...
#app.route("/api/login")
def api_login():
...
common_login(data)
...
I'm not familiar with Flask. However this bit of code:
if form.validate_on_submit():
return requests.post(request.url_root + '/api/login', data={"test": True})
Seems like you're accepting a posted form, validating it, and then posting it again. Over and over.
When a user submits input, I'm trying to execute a script that takes the user's input as a parameter and redirects the user back to the home page. When I run the script below, everything seems to work with the exception of the redirection. When I hit submit in the web browser, I get No data submitted.
from flask import Flask, render_template, redirect, request
from Index_generator import index_generator
from Yelp_api import request_yelp
#app.route('/home_city',methods = ['POST'])
def home_city():
CITY=request.form['city']
request_yelp(DEFAULT_LOCATION=CITY) #This function executes the script
return redirect('/')
What if use url_for with redirect?
from flask import Flask, render_template, redirect, request, url_for
from Index_generator import index_generator
from Yelp_api import request_yelp
#app.route('/', methods = ['GET'])
def home():
return 'Hello World'
#app.route('/home_city',methods = ['POST'])
def home_city():
CITY=request.form['city']
request_yelp(DEFAULT_LOCATION=CITY) #This function executes the script
return redirect(url_for('home'))