I have the following flask app that takes a 36 slider answers, from a form and outputs a simple multiplication result
flask:
from flask import Flask, render_template, request
import pandas as pd
import jinja2
app = Flask(__name__)
#app.route('/quest')
def index():
# Render the form. Nothing special needs to happen here.
return render_template('/aboutImgFree.html')
#app.route('/results', methods=['POST'])
def results():
if request.method == 'POST':
likertValues = {'C1': [request.values['vol1'], request.values['vol2'],request.values['vol3'], request.values['vol4'],
request.values['vol5'],request.values['vol6']],
'C2': [request.values['vol7'], request.values['vol8'], request.values['vol9'], request.values['vol10'],
request.values['vol11'], request.values['vol12']],
'C3': [request.values['vol13'], request.values['vol14'], request.values['vol15'], request.values['vol16']
, request.values['vol17'], request.values['vol18']],
'C4': [request.values['vol19'], request.values['vol20'], request.values['vol21'], request.values['vol22']
, request.values['vol23'], request.values['vol24']],
'C5': [request.values['vol25'], request.values['vol26'], request.values['vol27'], request.values['vol28']
, request.values['vol29'], request.values['vol30']],
'C6': [request.values['vol31'], request.values['vol32'], request.values['vol33'], request.values['vol34']
, request.values['vol35'], request.values['vol36']]}
io = pd.DataFrame(data=likertValues)
io_t = io.astype('int64')
factor={'factor':[1,2,3,4,5,6]}
f=pd.DataFrame(data=factor)
#return render_template('/results.html',io=io.to_html(),f=type(f.iloc[-1,-1]))
'''
io_table=pd.read_csv(request.files['io_table'])
io_t=io_table
factor=pd.read_csv(request.files['factor'])
f=factor
'''
mdl1=pd.DataFrame(io_t.values+f.values, columns=io_t.columns, index=io_t.columns)
mdl2=pd.DataFrame(io_t.values*f.values, columns=io_t.columns, index=io_t.columns)
c_sum1 = mdl1.sum(axis=0)
r_sum1 = mdl1.sum(axis=1)
c_sum2 = mdl2.sum(axis=0)
r_sum2 = mdl2.sum(axis=1)
mdl1_t=mdl1
mdl2_t=mdl2
io_t.rename(index={0:'C1',1:'C2',2:'C3',3:'C4',4:'C5',5:'C6'},inplace=True)
io_t.rename(columns={0:'C1',1:'C2',2:'C3',3:'C4',4:'C5',5:'C6'},inplace=True)
mdl1_t=mdl1_t.append(c_sum1, ignore_index=True)
mdl1_t.rename(index={0:'C1',1:'C2',2:'C3',3:'C4',4:'C5',5:'C6',6:'Sum Column'},inplace=True)
mdl1_t=pd.concat([mdl1_t, r_sum1], axis=1, ignore_index=True)
mdl1_t.iloc[-1,-1]=mdl1.values.sum()
mdl1_t.rename(columns={0:'C1',1:'C2',2:'C3',3:'C4',4:'C5',5:'C6',6:'Sum Row'},inplace=True)
mdl2_t=mdl2_t.append(c_sum2, ignore_index=True)
mdl2_t.rename(index={0:'C1',1:'C2',2:'C3',3:'C4',4:'C5',5:'C6',6:'Sum Column'},inplace=True)
mdl2_t=pd.concat([mdl2_t, r_sum2], axis=1, ignore_index=True)
mdl2_t.iloc[-1,-1]=mdl2.values.sum()
mdl2_t.rename(columns={0:'C1',1:'C2',2:'C3',3:'C4',4:'C5',5:'C6',6:'Sum Row'},inplace=True)
option = request.form.getlist('model')
if option == ['mdl1']:
return render_template('/results.html', io=io_t.to_html(), mdl1_t=mdl1_t.to_html())
elif option == ['mdl2']:
return render_template('/results.html', io=io_t.to_html(), mdl2_t=mdl2_t.to_html())
elif option == ['mdl1','mdl2']:
return render_template('/results.html', io=io_t.to_html(), mdl1_t=mdl1_t.to_html(), mdl2_t=mdl2_t.to_html())
else:
return render_template('/results.html', io=io_t.to_html())
#results = new_io_table(io_table,factor) # Get some results
if __name__ == "__main__":
app.run(debug=True)
What I want to do is take that code and call it from my djangocms application. Thing is that I can't find anywhere the answer and I don't know what exactly to look for. Is there anyone here that has done something similar?
I'm using django 3.x and flask 1.1.2
UPDATE
I found out about dispatching, which is really awesome, but I can't make it work correctly.
from flask import Flask
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.exceptions import NotFound
from app1.website2 import app as app1
from app2 import app as app2
app = Flask(__name__)
app.wsgi_app = DispatcherMiddleware(NotFound(), {
"/app1": app1,
"/quest": app2
})
if __name__ == "__main__":
app.run()
And I get the following error
Traceback (most recent call last):
File "C:\Users\user\Desktop\CMS\Lib\site-packages\werkzeug\serving.py", line 323, in run_wsgi
execute(self.server.app)
File "C:\Users\user\Desktop\CMS\Lib\site-packages\werkzeug\serving.py", line 312, in execute
application_iter = app(environ, start_response)
File "C:\Users\user\Desktop\CMS\Lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\user\Desktop\CMS\Lib\site-packages\werkzeug\middleware\dispatcher.py", line 66, in __call__
return app(environ, start_response)
TypeError: 'module' object is not callable
Related
This question already has answers here:
Flask view return error "View function did not return a response"
(3 answers)
Closed 11 months ago.
yesterday I started to learn Flask and got into a pitfall for redirection with a variable. I tried without session as well but can't get ahead.
Code is as below -
from flask import Flask, render_template, request, redirect, url_for, session
from flask_wtf import Form
from wtforms import StringField
app = Flask(__name__)
app.config['SECRET_KEY'] = 'our very hard to guess secretfir'
#app.route('/')
def index():
return render_template('index.html')
#app.route('/thank-you')
def thank_you():
if request.method == 'POST':
messages = request.args['translated_text'] # counterpart for url_for()
messages = session['translated_text'] # counterpart for session
return render_template('thank-you.html',messages=messages)
def translate_text(target, text):
import six
from google.cloud import translate_v2 as translate
translate_client = translate.Client()
if isinstance(text, six.binary_type):
text = text.decode("utf-8")
# Text can also be a sequence of strings, in which case this method
# will return a sequence of results for each text.
result = translate_client.translate(text, target_language=target)
output_text = format(result["translatedText"])
return output_text
# approach using WTForms
class RegistrationForm(Form):
input_lang = StringField('Input Language in length(2) ==> ')
output_lang = StringField('Output Language in length(2) ==> ')
input_text = StringField('Input Text ==> ')
#app.route('/translate', methods=['GET', 'POST'])
def translate():
error = ""
form = RegistrationForm(request.form)
if request.method == 'POST':
input_lang = form.input_lang.data
output_lang = form.output_lang.data
input_text = form.input_text.data
if len(input_lang) != 2 or len(output_lang) != 2 or len(input_text) == 0:
error = "Please supply proper inputs! "
else:
translated_text = translate_text(output_lang, input_text)
session['translated_text'] = translated_text
return redirect(url_for('thank_you',transalted_text=translated_text))
return render_template('translate.html', form=form, message=error)
# Run the application
app.run(debug=True)
Whenever, I submit \translate.html, I get an error as :
127.0.0.1 - - [03/Apr/2022 13:35:04] "GET /thank-you?transalted_text=salut HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 2095, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 2080, in wsgi_app
response = self.handle_exception(e)
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 1526, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 1545, in finalize_request
response = self.make_response(rv)
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 1701, in make_response
raise TypeError(
TypeError: The view function for 'thank_you' did not return a valid response. The function either returned None or ended without a return statement.
127.0.0.1 - - [03/Apr/2022 13:35:04] "GET /thank-you?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 304 -
127.0.0.1 - - [03/Apr/2022 13:35:04] "GET /thank-you?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 304 -
127.0.0.1 - - [03/Apr/2022 13:35:04] "GET /thank-you?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 304 -
TypeError: The view function for 'thank_you' did not return a valid response. The function either returned None or ended without a return statement.
If you look at the thank_you func, it only knows how to handle a POST request, but in case of GET is returning None
#app.route('/thank-you')
def thank_you():
if request.method == 'POST':
messages = request.args['translated_text'] # counterpart for url_for()
messages = session['translated_text'] # counterpart for session
return render_template('thank-you.html',messages=messages)
# move the logic for GET request here
return {'msg': 'example'} # I asume that you are working with flask 2.0
And now you are returning for a GET request.
And if you are on flask 2.0, you could also specify the http method in the app decorator. For more clarity:
#app.get('/thank-you')
def thank_you():
return 'Thank you'
First of all I'm getting too many errors for python right now. This situation affected my motivation quite negatively. I'm trying to run an expert system that I found in this error. But I get the following error. I looked at other solutions but it didn't work for me either.
Drug Store Expert System:
https://github.com/enzoftware/pyswipl_drugstore
Code:
from flask import Flask, render_template, flash, request
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from pyswip import Prolog
import os
import time
# App config.
DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176a'
class ReusableForm(Form):
name = TextField('Name:', validators=[validators.required()])
#app.route("/", methods=['GET', 'POST'])
def hello():
form = ReusableForm(request.form)
if request.method == 'POST':
name=request.form['name']
fiebre = request.form.get('fiebre') == 'on'
nausea = request.form.get('nausea') == 'on'
diarrea = request.form.get('diarrea') == 'on'
headache = request.form.get('headache') == 'on'
print(fiebre, nausea, diarrea, headache)
os.system('swipl -q -t "program" console.pl')
if form.validate():
f = open("file.txt", "r")
disease = f.read()
print(disease)
flash('Hola ' + name + ', por tus sintomas podemos deducir que tienes '+ disease)
else:
flash('Error: Debes ingresar tu nombre. ')
return render_template('hello.html', form=form)
if __name__ == "__main__":
app.run()
Error:
ERROR: The system was unable to find the specified registry key or value.
Traceback (most recent call last):
File "c:/Users/BAUM-PC/Desktop/Yeni klasör/pyswipl_drugstore-master/main.py", line 3, in <module>
from pyswip import Prolog
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\__init__.py", line 29, in <module>
from pyswip.prolog import Prolog
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\prolog.py", line 28, in <module>
from pyswip.core import *
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\core.py", line 568, in <module>
(_path, SWI_HOME_DIR) = _findSwipl()
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\core.py", line 411, in _findSwipl
(path, swiHome) = _findSwiplWin()
File "c:\Users\BAUM-PC\Desktop\Yeni klasör\pyswipl_drugstore-master\pyswip\core.py", line 208, in _findSwiplWin
match = pattern.match(ret[-1])
IndexError: list index out of range
core.py
(related section)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces may be \t or spaces in the output)
ret = ret[0].splitlines()
ret = [line.decode("utf-8") for line in ret if len(line) > 0]
pattern = re.compile('[^h]*home[^R]*REG_SZ( |\t)*(.*)$')
match = pattern.match(ret[-1])
if match is not None:
path = match.group(2)
paths = [os.path.join(path, 'bin', dllName)
for dllName in dllNames]
for path in paths:
if os.path.exists(path):
return (path, None)
Windows Solution:
Make sure your Python and SWI Prolog are both 32- or 64-bit.
Go to line 180 of core.py and change the line to this:
paths = [os.path.join(programFiles, r'swipl\bin', dllName)
For first error:
As per official documentation of Pyswip you must take care of version of python and SWI-Prolog.
Make sure the SWI-Prolog architecture is the same as the Python architecture. If you are using a 64bit build of Python, use a 64bit build of SWI-Prolog.
For second error:
When you are accessing ret[-1] in match = pattern.match(ret[-1]) the index of list ret is not available.
I am trying to implement a captcha based on someone elses code using webpy. The code I am starting with is here: https://kzar.co.uk/blog/2009/07/14/web.py-captcha/
The example code there isn't complete, and I need to work out what to do with this app variable. Here is my code:
import web
from captcha import getCaptcha
render = web.template.render('templates/')
urls = (
'/([a-zA-Z]+/[a-zA-Z]+)', 'index',
'/', 'index',
'/captcha.gif', 'captcha'
)
if web.config.get("_session") is None:
session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'captcha': ''})
web.config._session = session
else:
session = web.config._session
vcaptcha = form.Validator('Please enter the code', lambda x:x == session.captcha)
enquiry_form = form.Form(
form.Textbox("captcha", vcaptcha, description="Validation Code", pre="<img src='/captcha.gif' valign=center><br>", class_="standard", style="width:70px;"),
)
class index:
def GET(self, argu = "Anonymous/Person"):
args = argu.split('/')
firstname = args[0]
if (len(args) >= 2):
lastname = args[1]
return render.index(firstname, lastname)
return render.index(firstname, "Snow")
class captcha:
def GET(self):
web.header("Content-Type", "image/gif")
captcha = getCaptcha
session.captcha = captcha[0]
return captcha[1].read()
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
It gives this error when ran:
$ python code.py
Traceback (most recent call last):
File "code.py", line 13, in <module>
session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'captcha': ''})
NameError: name 'app' is not defined
I've been looking at the webpy documentation and API reference, and I can't figure out what to do to properly initialise this 'app' variable.
You're using the as yet undefined app when you call session = web.session.Session(app, ...
Have you seen the documentation on sessions? See how they define app in the example prior to using it.
Just after URLs one is supposed to have this:
app = web.application(urls, globals())
the Flask app I create only able to work if it outside the time range but return error if it is within the time range (the if path)
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.cache import Cache
from datetime import datetime, time
app.config['CACHE_TYPE'] = 'simple'
app.cache = Cache(app)
#app.route('/thtop', methods=['GET'])
#app.cache.cached(timeout=60)
def thtop():
now = datetime.now()
now_time = now.time()
if now_time >= time(3,30) and now_time <= time(16,30):
rv = app.cache.get('last_response')
else:
rv = 'abcc'
app.cache.set('last_response', rv, timeout=3600)
return rv
If the time in the if path, it unable to show the string abcc but shown Internal Server Error.
In WSGI error log, it also shown Exception on /thtop [GET]#012Traceback (most recent call last):#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1687, in wsgi_app#012 response = self.full_dispatch_request()#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1361, in full_dispatch_request#012 response = self.make_response(rv)#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1439, in make_response#012 raise ValueError('View function did not return a response')#012ValueError: View function did not return a response
What is wrong when I am caching?
UPDATE
Use flask_caching module but still same failures
from flask.ext.sqlalchemy import SQLAlchemy
from flask_caching import Cache
from datetime import datetime, time
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
#app.route('/thtop', methods=['GET'])
#cache.cached(timeout=60)
def thtop():
now = datetime.now()
now_time = now.time()
if now_time >= time(3,30) and now_time <= time(14,30):
rv = cache.get('last_response')
else:
rv = 'abcc'
cache.set('last_response', rv, timeout=3600)
return rv
The difference I observed in both different module when I run in console, starting from def thtop(), app.cache.get('last_response') return nothing. However, cache.get('last_response') return abcc.
The problem is when run in web app, it will cause error as shown above.
You're getting the error whenever now_time >= time(3,30) and now_time <= time(14,30) is True and rv = cache.get('last_response') is None. When that happens, you're trying to return None from the view which causes the ValueError.
You need to add some additional logic to check that the cache actually returns data:
from flask import Flask
from flask_caching import Cache
from datetime import datetime, time
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
#app.route('/thtop', methods=['GET'])
#cache.cached(timeout=60)
def thtop():
now = datetime.now()
now_time = now.time()
rv = None
if now_time >= time(3, 30) and now_time <= time(14, 30):
rv = cache.get('last_response')
if not rv:
rv = 'abcc'
cache.set('last_response', rv, timeout=3600)
return rv
if __name__ == '__main__':
app.run()
with this logic your route will always return something so you won't get the ValueError.
Seems like this statement is True: if now_time >= time(3,30) and now_time <= time(16,30)
That is why you are trying to get the last_response value from rv = app.cache.get('last_response') which is equal to None I think.
The Internal Server Error is thrown because you return a NoneType object that is not valid. You should return a function() or 'a string' instead.
Try fixing this Error by changing app.cache.get('last_response') to app.cache.get('last_response', 'FIXED')
PREFACE
Hello all I am getting a very strange error when I am trying to use the flask module for python... First let me explain that I first started writing the program and then it stopped working NO PROBLEM My last copy should work... Right? After I tried to revert back to 2 versions before the current versions code I was still getting the same error I have done everything I can think of doing now it is time to give it to the professionals
Ok so what is happening is that when I try to run my flask applications
Traceback (most recent call last):
File "/Users/me/Desktop/ASL server/router.py", line 47, in <module>
from flask import *
File "/Library/Python/2.7/site-packages/flask/__init__.py", line 17, in <module>
from werkzeug.exceptions import abort
File "/Library/Python/2.7/site-packages/Werkzeug-0.9.4-py2.7.egg/werkzeug/__init__.py", line 154, in <module>
__import__('werkzeug.exceptions')
File "/Library/Python/2.7/site-packages/Werkzeug-0.9.4-py2.7.egg/werkzeug/exceptions.py", line 71, in <module>
from werkzeug.wrappers import Response
File "/Library/Python/2.7/site-packages/Werkzeug-0.9.4-py2.7.egg/werkzeug/wrappers.py", line 26, in <module>
from werkzeug.http import HTTP_STATUS_CODES, \
File "/Library/Python/2.7/site-packages/Werkzeug-0.9.4-py2.7.egg/werkzeug/http.py", line 28, in <module>
from urllib.request import parse_http_list as _parse_list_header
ImportError: No module named request
Currently I have tried to uninstall the module and reinstall it along with all supporting modules. The code is a reverted code that was from before the error occourd and now the error is happening again (No changes have been made to the old code) I do not know what the problem is ...
My python code is
from flask import *
import flask
from flask import render_template
import os
import random
import sys
app = Flask(__name__)
app.secret_key ="REST SECRET"
##############################################
#app.errorhandler(503) #
def page_not_found(e): #
flash('503 Service Unavailable') #
return render_template('500.html'), 500 #
#app.errorhandler(408) #
def page_not_found(e): #
flash('408 Request Timeout') #
return render_template('403.html'), 408 #
#app.errorhandler(401) #
def page_not_found(e): #
flash('401- Restricted') #
return render_template('403.html'), 401 #
##############################################
def getip():
c = request.remote_addr
i = c.encode(encoding='UTF-8',errors='strict')
ip = i.encode(encoding='UTF-8',errors='strict')
#app.route('/')
def home():
ipa = getip()
session[ipa] = ipa
print session
print ipa
return render_template('index.html')
#app.route('/donate')
def donate():
return render_template('donate.html')
#app.route('/learn/fingerspell/end')
def learnfinger():
return render_template('Welcometofinger.html')
#app.route('/learn/fingerspell',methods=["GET","POST"])
def learnfingera():
x = "a"
if request.method == "POST":
if request.form['next'] == "clear":
return redirect('/learn/fingerspell/b')
return render_template("fingerspell.html",error=x)
#app.route('/learn/fingerspell/b',methods=["GET","POST"])
def learnfingerb():
x = "b"
if request.method == "POST":
if request.form['next'] == "clear":
return redirect('/learn/fingerspell/c')
return render_template("fingerspell.html",error=x)
# And so on and on till you get to Z
#app.route('/learn/fingerspell/z',methods=["GET","POST"])
def learnfingerz():
x = "z"
if request.method == "POST":
if request.form['next'] == "clear":
return redirect('/learn/fingerspell/end')
return render_template("fingerspell.html",error=x)
#app.route('/learn/basic-words')
def learnwordb():
return render_template('bwordsmain.html')
#app.route('/learn/basic-words/course')
def learnwordb_course():
flash("Welcome to your first lesson ")
return
#app.route('/learn/basic-words/course/test/id1',methods=["GET","POST"])
def test1baiscstart():
score = 0
if request.method == "POST":
if request.form['a'] == "ASL":
score += 1
return render_template('test1.html')
#app.route('/learn')
def learn():
return render_template('newopt.html')
#app.route('/test/id/1',methods=["POST","GET"])
def testabcs():
score = 100
missq = 0
truea = 5
if request.method == "POST":
ab = request.form['qa']
ba = request.form['qb']
ca = request.form['qc']
da = request.form['qd']
ea = request.form['qe']
a = str(ab).lower()
b = str(ba).lower()
c = str(ca).lower()
d = str(da).lower()
e = str(ea).lower()
if True:
if a != "asl is fun":
score -= 20
missq += 1
elif b != "this isnt hard":
score -= 20
missq += 1
elif c != "its fun":
score -= 20
missq += 1
elif d != "m":
score -= 20
missq += 1
elif e != "t":
score -= 20
missq += 1
else:
flash("DEATH ERROR")
flash("you scored "+ str(score)+"% and missed " + str(missq) + " out of " + str(truea))
return render_template('info.html')
return render_template("abcstest.html")
#app.route('/games')
def games():
return render_template("games.html")
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5001))
app.debug = True
app.run(host='0.0.0.0',port=port)
Actually the 2 statements is doing nearly the same:
from flask import *
import flask
when you try to use a method in flask, you have 2 choices:
1st:
from flask import *
c = request.remote_addr
2nd:
import flask
c = flask.request.remote_addr
Do you notice the different?When using from a_module import *, you can just use the method name in the module.When using import a_module, you have to the compiler which module you use, such as: a_module.method_name
Sometimes directories break... Try copying the files out of the directory and make a new directory and then rerun the server that should work.
I figured this out because it worked before and then it worked again. Your code is just fine!