How to apply subscriptions in graphql-flask? - python

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?

Related

TypeError: <lambda>() missing 1 required positional argument: 'instance' in Locust

I need to loadtest an Odoo Environment and I have written a test class with different methods in it. Currently I'm trying to test this stuff locally but I'm running in a error that I don't understand right now.
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 908, in gevent._gevent_cgreenlet.Greenlet.run
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/users.py", line 175, in run_user
user.run()
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/users.py", line 143, in run
self._taskset_instance.run()
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/task.py", line 365, in run
self.wait()
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/task.py", line 443, in wait
self._sleep(self.wait_time())
File "/home/jhoffmann/ametras_odoo_stress_testing/venv/lib/python3.8/site-packages/locust/user/task.py", line 418, in wait_time
return self.user.wait_time()
TypeError: <lambda>() missing 1 required positional argument: 'instance'
2022-10-20T11:30:13Z <Greenlet at 0x7f49e55376a0: run_user(<__main__.OdooTestCasesUser object at 0x7f49e51f46)> failed with TypeError
I have written the following test classes
class OdooTestCases(TaskSet):
weight = 10
fixed_count = 1
min_wait = 0.5
max_wait = 5.0
#task(20)
def read_partners(self):
customer_model = self.client.get_model("res.partner")
customer_ids = customer_model.search([], limit=80)
#task(10)
def read_product_template_qty(self):
customer_model = self.client.get_model("product.template")
customer_ids = customer_model.search([], limit=80)
#task(10)
def read_sale_orders(self):
so_model = self.client.get_model("sale.order")
so_ids = so_model.search([], limit=100)
#task(20)
def read_stock_pickings(self):
stock_picking_model = self.client.get_model("stock.picking")
stock_pickings = stock_picking_model.search([], limit=100)
#task(20)
def read_stock_movings(self):
stock_moving_model = self.client.get_model("stock.move")
stock_movings = stock_moving_model.search([], limit=100)
#task(30)
def read_stock_locations(self):
stock_location_model = self.client.get_model("stock.location")
stock_locations = stock_location_model.search([], limit=100)
#task(25)
def read_stock_picking_types(self):
stock_picking_type_model = self.client.get_model("stock.picking.type")
stock_picking_types = stock_picking_type_model.search([], limit=100)
def stop(self):
self.interrupt()
class OdooTestCasesUser(OdooLocustUser):
wait_time = between(0.500, 5)
host = "localhost"
database = "demo"
login = "test"
password = "test"
def __init__(self, parent):
super().__init__(parent)
self.login = "test"
self.password = "test"
self.wait_time = between(0.500, 5)
self.tasks = [OdooTestCases]
Another problem is that I don't get test results returned on my CLI.
I tried everything to fix this, what I've found on the internet, but without any success.
I would be really happy if someone could give me a guess or a solution.
Just hit me up if someone needs more information about this case.
Looks like you are using legacy style wait times:
min_wait = 0.5
max_wait = 5.0
AND new style
wait_time = ...
Maybe remove the legacy ones?

Flask current_user is None type

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.

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]

Error when using offlineimap: getfolder() asked for nonexisting folder

I'm trying to get my emails to work from commandline with mutt. I have been trying to follow these two guides: http://blog.developwithpassion.com/2013/05/02/getting-up-and-running-with-a-sane-mutt-setup/ and http://stevelosh.com/blog/2012/10/the-homely-mutt/#configuring-offlineimap
To do this there are 4 main steps:
1. setup offlineimap to download and keep synced your emails
2. setup mutt (the email user interface)
3. setup notmuch (to be able to search your emails)
4. setup msmtp (to be able to send emails)
Note that I am using Macbook Pro running the OS X 10.9.2. I am stuck at step 1 because I am getting an error with offlineimap! I am able to run offlineimap for a long time, i.e. it will sync all of the emails (36197 of them!) and then right at the end it spits out the following error:
ERROR: getfolder() asked for a nonexisting folder 'Drafts'.
Folder Deleted Items [acc: gloriphobia]:
Establishing connection to imap.gmail.com:993
Account sync gloriphobia:
*** Finished account 'gloriphobia' in 137:16
ERROR: Exceptions occurred during the run!
ERROR: command: UID => socket error: <class 'socket.error'> - [Errno 54] Connection reset by peer
Traceback:
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/folder/IMAP.py", line 219, in getmessage
'(BODY.PEEK[])')
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/imaplib2.py", line 1167, in uid
return self._simple_command('UID', command, *args, **kw)
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/imaplib2.py", line 1615, in _simple_command
return self._command_complete(self._command(name, *args), kw)
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/imaplib2.py", line 1378, in _command_complete
typ, dat = rqb.get_response('command: %s => %%s' % rqb.name)
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/imaplib2.py", line 176, in get_response
raise typ(exc_fmt % str(val))
ERROR: getfolder() asked for a nonexisting folder 'Drafts'.
Traceback:
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/accounts.py", line 241, in syncrunner
self.sync()
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/accounts.py", line 320, in sync
localfolder = self.get_local_folder(remotefolder)
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/accounts.py", line 269, in get_local_folder
replace(self.remoterepos.getsep(), self.localrepos.getsep()))
File "/usr/local/Cellar/offline-imap/6.5.5/libexec/offlineimap/repository/Maildir.py", line 134, in getfolder
OfflineImapError.ERROR.FOLDER)
My .offlineimaprc is:
[general]
accounts = gloriphobia
ui = TTYUI
pythonfile=~/Development/MuttMailPython/offline.py
fsync = False
[Account gloriphobia]
localrepository = gloriphobia_local
remoterepository = gloriphobia_remote
status_backend = sqlite
postsynchook = notmuch new
[Repository gloriphobia_local]
type = Maildir
localfolders = ~/.mail/Test
nametrans = get_remote_name
[Repository gloriphobia_remote]
maxconnections = 1
type = Gmail
cert_fingerprint = 89091347184d41768bfc0da9fad94bfe882dd358
remoteuser = myemailaddress
remotepasseval = get_keychain_pass(account="myemailaddress",server="imap.gmail.com")
realdelete = no
nametrans = get_local_name
folderfilter = is_included
My python file, the one that is called offline.py is:
#!/usr/bin/python
import subprocess
import re
class NameMapping:
def __init__(self, local_name, remote_name):
self.local_name = local_name
self.remote_name = remote_name
class LocalName:
def __init__(self, folder):
self.folder = folder
def matches(self, mapping):
return mapping.remote_name == self.folder
def mapped_folder_name(self, mapping):
return mapping.local_name
class RemoteName:
def __init__(self, folder):
self.folder = folder
def matches(self, mapping):
return mapping.local_name == self.folder
def mapped_folder_name(self, mapping):
return mapping.remote_name
def get_keychain_pass(account=None, server=None):
params = {
'security': '/usr/bin/security',
'command': 'find-internet-password',
'account': account,
'server': server,
'keychain': '/Users/mec07/Library/Keychains/login.keychain',
}
command = "sudo -u mec07 %(security)s -v %(command)s -g -a %(account)s -s %(server)s %(keychain)s" % params
output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
outtext = [l for l in output.splitlines()
if l.startswith('password: ')][0]
return re.match(r'password: "(.*)"', outtext).group(1)
def is_included(folder):
result = True
for pattern in exclusion_patterns:
result = result and (re.search(pattern, folder) == None)
return result
exclusion_patterns = [
"efax",
"earth_class_mail",
"eventbrite",
"gotomeeting",
"moshi_monsters",
"peepcode",
"raini_fowl",
"stuart_know",
"training.*2008",
"training.*2009",
"training.*2010",
"training.*2011",
"training.*2012",
"training.*nbdn",
"training.*nothin_but_bdd",
"unblock_us",
"web_hosting",
"webinars",
"Gmail.*Important"
]
name_mappings = [
NameMapping('inbox', '[Gmail]/Inbox'),
NameMapping('starred', '[Gmail]/Starred'),
NameMapping('important', '[Gmail]/Important'),
NameMapping('sent', '[Gmail]/Sent Mail'),
NameMapping('drafts', '[Gmail]/Drafts'),
NameMapping('archive', '[Gmail]/All Mail'),
NameMapping('spam', '[Gmail]/Spam'),
NameMapping('flagged', '[Gmail]/Starred'),
NameMapping('trash', '[Gmail]/Trash'),
NameMapping('deleted', '[Gmail]/Deleted Items'),
NameMapping('Mum', '[Gmail]/Jana'),
NameMapping('Maggie', '[Gmail]/Maggie'),
NameMapping('papers', '[Gmail]/Scholar Alert'),
NameMapping('sent items', '[Gmail]/Sent Items'),
NameMapping('sent messages', '[Gmail]/Sent Messages')
]
def find_name_mapping(name):
default_mapping = NameMapping(name.folder, name.folder)
for mapping in name_mappings:
if (name.matches(mapping)):
return mapping
return default_mapping
def get_name_mapping(name):
mapping = find_name_mapping(name)
return name.mapped_folder_name(mapping)
def get_remote_name(local_folder_name):
name = RemoteName(local_folder_name)
return get_name_mapping(name)
def get_local_name(remote_folder_name):
name = LocalName(remote_folder_name)
return get_name_mapping(name)
Thanks in advance for your help!
Add:
folderfilter = lambda folder: folder not in ['Drafts,]

Categories

Resources