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())
Related
My code that was previously working is now causing my main flask app to not run.
The error is coming from my forms.py file.
class selectClass(FlaskForm):
a = current_user.database
conn = sqlite3.connect("C:\\Users\\Lenovo\\PycharmProjects\\spacedonline\\"+a)
c = conn.cursor()
c.execute("SELECT Class FROM Students ")
data = c.fetchall()
listofclasses = []
for clas in data:
if clas[0] not in listofclasses:
listofclasses.append(clas[0])
finallist = []
for clas in listofclasses:
finallist.append((clas, clas))
nameofclass=SelectField(u"Name of Class", choices=finallist)
submit= SubmitField("Select")
On trying to launch the main.py file I get the message:
Traceback (most recent call last):
File "C:/Users/Lenovo/PycharmProjects/spacedonline/forms.py", line 102, in <module>
class selectClass(FlaskForm):
File "C:/Users/Lenovo/PycharmProjects/spacedonline/forms.py", line 104, in selectClass
a = current_user.database
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\werkzeug\local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
AttributeError: 'NoneType' object has no attribute 'database'
As I said, it was not returning this error before, I am at a loss.
you are probably not logged in. so current_user is NoneType. Try:
if current_user: # or current_user.is_active:
a = current_user.database
...
else:
return redirect('/login')
I have been logged in and when the problem code is commented out it, my page shows me as logged on.
I have worked around the problem by creating a function which creates the class:
'''
def selectclassform():
class SelectClass(FlaskForm):
a = current_user.database
conn = sqlite3.connect("C:\\Users\\Lenovo\\PycharmProjects\\spacedonline\\"+a)
c = conn.cursor()
c.execute("SELECT Class FROM Students ")
data = c.fetchall()
listofclasses = []
for clas in data:
if clas[0] not in listofclasses:
listofclasses.append(clas[0])
finallist = []
for clas in listofclasses:
finallist.append((clas, clas))
nameofclass=SelectField(u"Name of Class", choices=finallist)
submit= SubmitField("Select")
return (SelectClass)
'''
And then calling the function in the main apps.py file:
'''
#app.route("/select", methods=["GET", "POST"])
def selectclass():
if current_user.is_authenticated:
form = selectclassform()()
print(form)
if form.validate_on_submit():
print("valid")
session ["nameofclass"]=form.nameofclass.data
#return printtable(form.nameofclass.data, current_user.database)
return redirect(url_for("validate"))
else:
print("bye")
return render_template("select.html", form=form)
else:
return redirect(url_for("login"))
'''
I've had the same issue, and this was actually due to the security keys.
I have set different app security keys and it works now.
app.config['SECRET_KEY'] = 'new key 1'
app.config['SECURITY_PASSWORD_SALT'] = 'new key 2'
It is probably due to a security control that fails when creating a new instance.
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
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 new to GraphQL and using subscriptions in the Flask. But getting the error.
Below are the files, that I have created.
In models.py file, I have the 'Order' table. I am not able to understand in which file, it shows an error. Please let me know if anyone knows the answer.
app.py
app = Flask(__name__)
sockets = Sockets(app)
pubsub = RedisPubsub()
CORS(app)
subscription_mgr = SubscriptionManager(schema, pubsub)
#sockets.route('/socket')
def socket_channel(websocket):
subscription_server = SubscriptionServer(subscription_mgr, websocket)
subscription_server.handle()
return []
#app.teardown_appcontext
def shutdown_session1(exception=None):
db_session_ordermanag.remove()
if __name__ == "__main__":
from geventwebsocket import WebSocketServer
server = WebSocketServer(('', 5000), app)
server.serve_forever()
subscriptions.py
class Subscription(graphene.ObjectType):
orders = graphene_sqlalchemy.SQLAlchemyConnectionField(
Order, active=graphene.Boolean())
def resolve_orders(self, args, context, info):
with app.app_context():
query = Order.get_query(context)
return query.filter_by(id=info.root_value.get('id'))
mutations.py
class CreateOrder(graphene.ClientIDMutation):
class Input:
#id = graphene.Int()
revision = graphene.Int()
name = graphene.String()
statusid = graphene.Int()
ok = graphene.Boolean()
order = graphene.Field(lambda: Order)
#classmethod
def mutate_and_get_payload(cls, args, context, info):
_input = args.copy()
del _input['clientMutationId']
new_order = OrderModel(**_input)
db_session_pg.add(new_order)
db_session_pg.commit()
ok = True
if pubsub.subscriptions:
pubsub.publish('orders', new_order.as_dict())
return CreateOrder(ok=ok, order=new_order)
ERROR:
File "C:\Users\mpal\AppData\Local\Programs\Python\Python37-32\lib\site-packages\graphql\execution\executor.py", line 36, in <module>
from .middleware import MiddlewareManager
File "C:\Users\mpal\AppData\Local\Programs\Python\Python37-32\lib\site-packages\graphql\execution\middleware.py", line 73, in <module>
#promisify
File "C:\Users\mpal\AppData\Local\Programs\Python\Python37-32\lib\site-packages\promise\promise.py", line 444, in promisify
raise TypeError("Object is not a Promise like object.")
TypeError: Object is not a Promise like object.
How to resolve this error?
I'm trying to create a Collection Class in Python to access the various collections in my db. Here's what I've got:
import sys
import os
import pymongo
from pymongo import MongoClient
class Collection():
client = MongoClient()
def __init__(self, db, collection_name):
self.db = db
self.collection_name = collection_name
# self.data_base = getattr(self.client, db)
# self.collObject = getattr(self.data_base, self.collection_name)
def getCollection(self):
data_base = getattr(self.client, self.db)
collObject = getattr(data_base, self.collection_name)
return collObject
def getCollectionKeys(self, collection):
"""Get a set of keys from a collection"""
keys_list = []
collection_list = collection.find()
for document in collection_list:
for field in document.keys():
keys_list.append(field)
keys_set = set(keys_list)
return keys_set
if __name__ == '__main__':
print"Begin Main"
agents = Collection('hkpr_restore','agents')
print "agents is" , agents
agents_collection = agents.getCollection
print agents_collection
print agents.getCollectionKeys(agents_collection)
I get the following output:
Begin Main
agents is <__main__.Collection instance at 0x10ff33e60>
<bound method Collection.getCollection of <__main__.Collection instance at 0x10ff33e60>>
Traceback (most recent call last):
File "collection.py", line 52, in <module>
print agents.getCollectionKeys(agents_collection)
File "collection.py", line 35, in getCollectionKeys
collection_list = collection.find()
AttributeError: 'function' object has no attribute 'find'
The function getCollectionKeys works fine outside of a class. What am I doing wrong?
This line:
agents_collection = agents.getCollection
Should be:
agents_collection = agents.getCollection()
Also, you don't need to use getattr the way you are. Your getCollection method can be:
def getCollection(self):
return self.client[self.db][self.collection_name]