Flask current_user is None type - python

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.

Related

How to apply subscriptions in graphql-flask?

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?

AttributeError: 'builtin_function_or_method' object has no attribute 'translate'

I am using Ubuntu as OS, pymysql, flask, sqlalchemy frameworks. Then I do GET request I have this error:
File "/srv/MSH/venv/local/lib/python2.7/site-packages/pymysql/converters.py", line 73, in _escape_unicode
return value.translate(_escape_table)
AttributeError: 'builtin_function_or_method' object has no attribute 'translate'
My routes.py code:
#app.route('/device/<dev_id>/<name>/<dev_type>/<state>', methods=['GET'])
def device(dev_id, state, dev_type, name):
# This function communicates with device
dev_state = 0
device = Devices.query.filter_by(dev_id=id).first()
# Check state
if state == "0":
state = False
if state == "1":
state = True
if device is None:
# if we don't know device write to database
dev = Devices(dev_id=dev_id, type=dev_type, prev_state=state, name=name)
db.session.add(dev)
db.session.commit()
return "hi"
else:
# Write data to database and return wanted state
device.prev_state = state
if device.state:
dev_state = 1
if not device.state:
dev_state = 0
db.session.commit()
return str(dev_state)
Wrong line here:
device = Devices.query.filter_by(dev_id=id).first()
You are query sql with something identical to internal python function. I think correct string is:
device = Devices.query.filter_by(dev_id=dev_id).first()

trying to run webpy example: app isn't defined

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())

how to return a collection from mongodb using pymongo

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]

NoneType has no attribute Append

I'm new to Python. I can't understand why a variable is None at a certain point in my code:
class UsersInRoom(webapp.RequestHandler):
def get(self):
room_id = self.request.get("room_id")
username = self.request.get("username")
UserInRoom_entities = UserInRoom.gql("WHERE room = :1", room_id).get()
if UserInRoom_entities:
for user_in_room in UserInRoom_entities:
if user_in_room.username == username:
user_in_room.put() # last_poll auto updates to now whenenever user_in_room is saved
else:
user_in_room = UserInRoom()
user_in_room.username = username
user_in_room.put()
// error here, on line 160
UserInRoom_entities = []
UserInRoom_entities.append(user_in_room)
# name is `user_at_room` intead of `user_in_room` to avoid confusion
usernames = [user_at_room.username for user_at_room in UserInRoom_entities]
self.response.out.write(json.dumps(usernames))
The error is:
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 507, in __call__
handler.get(*groups)
File "path\to\chat.py", line 160, in get
AttributeError: 'NoneType' object has no attribute 'append'
How is this possible? I'm setting UserInRoom_entities = [] immediately before that call. Or is something else the None in question?
UPDATE: This code works:
class UsersInRoom(webapp.RequestHandler):
def get(self):
room_id = self.request.get("room_id")
username = self.request.get("username")
UserInRoom_entities = UserInRoom.gql("WHERE room = :1", room_id).get()
if UserInRoom_entities:
for user_in_room in UserInRoom_entities:
if user_in_room.name == username:
user_in_room.put() # last_modified auto updates to now whenenever user_in_room is saved
else:
user_in_room = UserInRoom(room=Key(room_id), name=username)
user_in_room.put()
UserInRoom_entities = []
UserInRoom_entities.append(user_in_room)
# name is `user_at_room` intead of `user_in_room` to avoid confusion
usernames = [user_at_room.name for user_at_room in UserInRoom_entities]
self.response.out.write(json.dumps(usernames))
class ChatRoom(db.Model):
name = db.StringProperty()
last_modified = db.DateTimeProperty(auto_now=True)
message_contents = db.StringListProperty()
message_users = db.StringListProperty()
class UserInRoom(db.Model):
room = db.ReferenceProperty(ChatRoom)
name = db.StringProperty()
last_modified = db.DateTimeProperty(auto_now=True)
Since it appears that my comment to the question had the answer to this, I'll repeat it as an answer, with the hope of gaining some reputation points:
Is the UserInRoom instance initialized properly? I am not familiar with the GAE data model, but I could imagine that the put() ing the instance would require that the room attribute was set, if there is a relationship between UserInRoom and Room (assuming a Room class exists).
To make sure that you're not the one raising exception, you can do something like:
UserInRoom_entities = []
# raised? then your .append is missing otherwise something else is wrong
UserInRoom_entities.append
UserInRoom_entities.append(user_in_room)

Categories

Resources