"Missing 1 required positional argument: 'resp'" when invoking Falcon resource responder that has a 'self' argument - python-3.8

I am developing a WSGI application on Windows. I use peewee (which is supposedly unrelated) and:
falcon==2.0.0
waitress==1.4.3
I have the following code in my resources.py:
from models import Board
class BoardResource:
def on_get_collection(self, req, resp):
resp.media = Board.select()
def on_get(self, req, resp):
code = req.get_param('code')
resp.media = Board.get_by_id(code)
I have the following code in my app.py:
import falcon
import models
from resources import BoardResource
def init():
models.init()
api = falcon.API()
api.add_route('/boards', BoardResource, suffix='collection')
api.add_route('/board', BoardResource)
return api
api = init()
I start the app with this command: waitress-serve app:api. When I request /boards from the API, I get this error:
ERROR:waitress:Exception while serving /boards
Traceback (most recent call last):
File "c:\users\pepsiman\.virtualenvs\hsech-api\lib\site-packages\waitress\channel.py", line 349, in service
task.service()
File "c:\users\pepsiman\.virtualenvs\hsech-api\lib\site-packages\waitress\task.py", line 169, in service
self.execute()
File "c:\users\pepsiman\.virtualenvs\hsech-api\lib\site-packages\waitress\task.py", line 439, in execute
app_iter = self.channel.server.application(environ, start_response)
File "c:\users\pepsiman\.virtualenvs\hsech-api\lib\site-packages\falcon\api.py", line 269, in __call__
responder(req, resp, **params)
TypeError: on_get_collection() missing 1 required positional argument: 'resp'
I decided to remove the self argument from the definiton of on_get_collection and the error was gone. I know that self must be there and have no idea why it doesn't work like that. Any ideas how to fix?

I have found the problem myself: when calling api.add_route the responder class must indeed be instantiated, thus the following lines:
api.add_route('/boards', BoardResource, suffix='collection')
api.add_route('/board', BoardResource)
need to be modified like this:
api.add_route('/boards', BoardResource(), suffix='collection')
api.add_route('/board', BoardResource())
Of course it works without removing the self argument from the definitions.
I hope this silly mistake of mine will help someone fix theirs.

Related

How to make Locust test my API endpoint served with FastAPI?

I have an API served with FastAPI working on:
http://127.0.0.1:8000/predictions
And I want to test it using Locust. My code:
from locust import HttpUser, TaskSet, task
import json
class UserBehavior(TaskSet):
#task(1)
def create_post(self):
headers = {'content-type': 'application/json','Accept-Encoding':'gzip'}
self.client.post("/predictions",data= json.dumps({
"text": "I am tired",
}),
headers=headers,
name = "Create a new post")
class WebsiteUser(HttpUser):
task=[UserBehavior]
I get this error msg while locust is running:
2022-07-23 16:33:32,764] pop-os/ERROR/locust.user.task: No tasks defined on WebsiteUser. use the #task decorator or set the tasks property of the User (or mark it as abstract = True if you only intend to subclass it)
Traceback (most recent call last):
File "/home/statspy/anaconda3/lib/python3.9/site-packages/locust/user/task.py", line 340, in run
self.schedule_task(self.get_next_task())
File "/home/statspy/anaconda3/lib/python3.9/site-packages/locust/user/task.py", line 472, in get_next_task
raise Exception(
Exception: No tasks defined on WebsiteUser. use the #task decorator or set the tasks property of the User (or mark it as abstract = True if you only intend to subclass it)
How can I fix it?
Thanks
Its tasks=[UserBehavior] , not task=[UserBehavior]

Unable to signup user from custom mobile App

Please guide.
Creating a new mobile app, not able to signup! Returns some error while tryting to call /web/signup and also while directly calling res.users create as sudo.
Please see the error message
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File
"/odoo/odoo-server/odoo/http.py", line 640, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception) File
"/odoo/odoo-server/odoo/http.py", line 316, in _handle_exception raise
exception.with_traceback(None) from
new_causepsycopg2.errors.UndefinedFunction: operator does not exist:
integer = booleanLINE 6: AND (p.company_id=false OR p.company_id ...
Seems this error raised from _get_multi function in ir_property.py
Thanks in advance
I use a custom controller for receiving request from mobile app and tries to call Odoo Core signup (do_signup located in auth_signup/controller/main) function. It reaches up to there and exceution moves to ir_property and returns error as mentioned.
Please see the sample code which try to use
user = {
'name' : user_info['name'],
'phone': user_info['phone'],
'email': 'test#example.com',#user_info['email'] ,
'login': user_info['phone'],
'password': password,
'confirm_password': password,
}
user_info = AuthSignupHome().do_signup(user)
But /web/signup it's a website service type='http'. You need a controller type='json' for call it from your custom mobile app.
I hope this answer can help you.

python configparser key error raised when using Globally

When I'm trying to pass the API endpoint values in the post API file, KeryError has unfortunately been raised. In the baseapi.ini file, I wrote [API] endpoint = value
Post API file:
import requests
from APIs.payLoad import addBookPayload
from Utilities.configration import config
from Utilities.resources import *
url = config()['API']['endpoint']+ApiResources.addBook
header = {"Content-Type": "application/json"}
response = requests.post(url, json=addBookPayload("pl74"), headers=header,)
print(response.json())
response_json = response.json()
book_ID = response_json['ID']
Error:
Traceback (most recent call last):
File "C:\Users\Muhammad Azmul Haq\PycharmProjects\BackEndProject\APIs\PostAPI.py", line 8, in <module>
url = config()['API']['endpoint']+ApiResources.addBook
File "C:\Users\Muhammad Azmul Haq\AppData\Local\Programs\Python\Python39\lib\configparser.py", line 960, in __getitem__
raise KeyError(key)
KeyError: 'API'
Does anyone have an idea what I did wrong Kind regards?
You are not initializing your global variable in config before accessing it. Try assigning value in the current file,
or
Put all configure in the separate configuration file and import that configuration file.

Mongos + Pymongo 2.5 ==>No suitable hosts found

Our application is using pymongo. I'm trying to connect to mongos. The code fails on the following line
pymongo.MongoReplicaSetClient(ec2-aa-bbb-124-22.compute-1.amazonaws.com:27017,
replicaSet=self.class_settings['mongo_rs'])
Exception
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/.../server_tornado.py --config=conf/development.conf --port=9001
Traceback (most recent call last):
File "/Users/..../server_tornado.py", line 319, in
BaseCatalog.db_instance = DBInit(config=settings)
File "/Users/..../lib/sc/singleton.py", line 20, in call
cls._instances[cls] = super(Singleton, cls).call(*args, **kwargs)
File "/Users/..../app/models/db_init.py", line 50, in init
raise Exception("init() => " + str(err))
Exception: init() => No suitable hosts found
Process finished with exit code 1`
Found the solution, if at all anyone faces this issue:
Using MongoClient instead of MongoReplicaClient fixes the issue. This is because Mongos acts like a single instance of mongodb.

https with jython2.7 + trusting all certificates does not work. Result: httplib.BadStatusLine

UPDATE: Problem related to bug in jython 2.7b1. See bug report: http://bugs.jython.org/issue2021. jython-coders are working on a fix!
After changing to jython2.7beta1 from Jython2.5.3 I am no longer able to read content of webpages using SSL, http and "trusting all certificates". The response from the https-page is always an empty string, resulting in httplib.BadStatusLine exception from httplib.py in Jython.
I need to be able to read from a webpage which requires authentication and do not want to setup any certificate store since I must have portability. Therefore my solution is to use the excellent implementation provided by http://tech.pedersen-live.com/2010/10/trusting-all-certificates-in-jython/
Example code is detailed below. Twitter might not be the best example, since it does not require certificate trusting; but the result is the same with or without the decorator.
#! /usr/bin/python
import sys
from javax.net.ssl import TrustManager, X509TrustManager
from jarray import array
from javax.net.ssl import SSLContext
class TrustAllX509TrustManager(X509TrustManager):
# Define a custom TrustManager which will blindly
# accept all certificates
def checkClientTrusted(self, chain, auth):
pass
def checkServerTrusted(self, chain, auth):
pass
def getAcceptedIssuers(self):
return None
# Create a static reference to an SSLContext which will use
# our custom TrustManager
trust_managers = array([TrustAllX509TrustManager()], TrustManager)
TRUST_ALL_CONTEXT = SSLContext.getInstance("SSL")
TRUST_ALL_CONTEXT.init(None, trust_managers, None)
# Keep a static reference to the JVM's default SSLContext for restoring
# at a later time
DEFAULT_CONTEXT = SSLContext.getDefault()
def trust_all_certificates(f):
# Decorator function that will make it so the context of the decorated
# method will run with our TrustManager that accepts all certificates
def wrapped(*args, **kwargs):
# Only do this if running under Jython
if 'java' in sys.platform:
from javax.net.ssl import SSLContext
SSLContext.setDefault(TRUST_ALL_CONTEXT)
print "SSLContext set to TRUST_ALL"
try:
res = f(*args, **kwargs)
return res
finally:
SSLContext.setDefault(DEFAULT_CONTEXT)
else:
return f(*args, **kwargs)
return wrapped
##trust_all_certificates
def read_page(host):
import httplib
print "Host: " + host
conn = httplib.HTTPSConnection(host)
conn.set_debuglevel(1)
conn.request('GET', '/example')
response = conn.getresponse()
print response.read()
read_page("twitter.com")
This results in:
Host: twitter.com
send: 'GET /example HTTP/1.1\r\nHost: twitter.com\r\nAccept-Encoding: identity\r\n\r\n'
reply: ''
Traceback (most recent call last):
File "jytest.py", line 62, in <module>
read_page("twitter.com")
File "jytest.py", line 59, in read_page
response = conn.getresponse()
File "/Users/erikiveroth/Workspace/Procera/sandbox/jython/jython2.7.jar/Lib/httplib.py", line 1030, in getresponse
File "/Users/erikiveroth/Workspace/Procera/sandbox/jython/jython2.7.jar/Lib/httplib.py", line 407, in begin
File "/Users/erikiveroth/Workspace/Procera/sandbox/jython/jython2.7.jar/Lib/httplib.py", line 371, in _read_status
httplib.BadStatusLine: ''
Changing back to jython2.5.3 gives me parseable output from twitter.
Have any of you seen this before? Can not find any bug-tickets on jython project page about this nor can I understand what changes could result in this behaviour (more than maybe #1309, but I do not understand if it is related to my problem).
Cheers