I'm trying to call Restlet from dojo javascript, but for this part of code: dojo.require("dojox.rpc.Rest");
var restService = dojox.rpc.Rest("http://localhost:9080/SomeApplication"); restService("/something");
I'm getting this error:
..... 127.0.0.1 9080 OPTIONS /SomeApplication/something - 405 487 0 0 http://localhost:9080 .....
HTTP Error 405 Method not allowed
What could be the problem? Why is it called OPTIONS method?
The rest you work with should implement OPTIONS method for resource.
I had the same issue, in my case it was CherryPy frame work, so I added following method to my resource:
#cherrypy.expose
def OPTIONS(self):
cherrypy.response.headers['Allow'] = "GET,PUT,POST,DELETE"
Related
I am calling deployed sagemaker Endpoint from lambda for load testing and lambda is getting called from api gateway integration when I am making call using gate POST rest api(with API Proxy Integration Enabled) from client side. But always rest api with lambda returning 200 even when invoke_endpoint doesn't return anything due to traffic load on SageMaker Endpoint.
#logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
#tracer.capture_lambda_handler
def lambda_handler(event: dict, context: LambdaContext) -> dict:
# return app.resolve(event, context)
try:
print("Received event: " + json.dumps(event, indent=2))
print(type(event), '--> ', event)
payload = event['data']
print(payload)
response = runtime_client.invoke_endpoint(EndpointName=ENDPOINT_NAME,
ContentType='application/json',
Body=json.dumps(payload),
Accept='Accept')
print(response)
print(response.keys())
# if "errorMessage" in str(respone.text):
# return
if "errorMessage" in response.keys() and "502 Bad Gateway" in str(response):
return {'statusCode': 502,'body': response}
elif "errorMessage" in response.keys():
return {'statusCode': 504,'body': response}
result = json.loads(response['Body'].read().decode())
return result
except Exception as e:
print(e)
exception_handler(e)
I enabled API Integration proxy while creating api method in api gateway and using aws-lambda-powertools to resolve the error but still client is getting 200 response always event my SageMaker Endpoint is not responding in the code due to load.
Error example with 200 code is below:
{"errorMessage":"2023-01-16T15:23:25.132Z c1bf04bf-12f7-46ab-b9a3-ffb1865eed26 Task timed out after 3.01 seconds"}
status_code: 200
Can anyone help me out here. Thanks in advance.
PS: I am very new to lambda.
Increase your lambda timeout limit.
I have created a route with type Json in odoo 14.
#http.route('/test', auth='public', methods=['POST'], type="json", csrf=False)
def recieve_data(self, **kw):
headers = request.httprequest.headers
args = request.httprequest.args
data = request.jsonrequest
So when I receive request using this route everything is fine, but suppose I want to return a different status code like 401, I could not do that with the route which type is json.
I have also tried the bellow method but the problem with this method is that it stops all odoo future requests.
from odoo.http import request, Response
#http.route('/test', auth='public', methods=['POST'], type="json", csrf=False)
def recieve_data(self, **kw):
headers = request.httprequest.headers
args = request.httprequest.args
data = request.jsonrequest
Response.status = "401 unauthorized"
return {'error' : 'You are not allowed to access the resource'}
So in the above example If I set the response status code to 401 all other requests even if they are to different routes will be stopped and its status code changes 401 .
I have checked this problem in both odoo14 and odoo13.
You cannot specify the code of the response, as you can see the status code is hardcoded in http.py:
def _json_response(self, result=None, error=None):
# ......
# ......
return Response(
body, status=error and error.pop('http_status', 200) or 200,
headers=[('Content-Type', mime), ('Content-Length', len(body))]
)
If the result is not an error the status code is always 200. but you can change the code of the method directly or use a monkey patch witch if it's not really important to specify the code of status in the result don't do ti ^^.
A simple monkey patch put this in __init__.py of the module that you want this behavior in it.
from odoo.http import JsonRequest
class JsonRequestPatch(JsonRequest):
def _json_response(self, result=None, error=None):
response = {
'jsonrpc': '2.0',
'id': self.jsonrequest.get('id')
}
default_code = 200
if error is not None:
response['error'] = error
if result is not None:
response['result'] = result
# you don't want to remove some key of another result by mistake
if isinstance(response, dict)
defautl_code = response.pop('very_very_rare_key_here', default_code)
mime = 'application/json'
body = json.dumps(response, default=date_utils.json_default)
return Response(
body, status=error and error.pop('http_status', defautl_code ) or defautl_code,
headers=[('Content-Type', mime), ('Content-Length', len(body))]
)
JsonRequest._json_response = JsonRequestPatch._json_response
and in the result of JSON api you can change the code of status like this
def some_controler(self, **kwargs):
result = ......
result['very_very_rare_key_here'] = 401
return result
The risk in monkey patching is you override the method compeletly and if some change is done in Odoo in new version you have to do you it in your method too.
The above code is from odoo 13.0 I did a lot of this when I build a restfull module to work with a website uses axios witch don't allow sending body in GET request. and odoo expect the argument to be inside the body in json request.
I am new to jmeter and i am stuck in a condition . I am running jmeter http sample using a csv file where i am using a pre-processor script in which doing the following-
setting http.method as per request like POST , GET , PUT ,PATCH
setting http.path as "/restpath"
setting request body.json
For Path i am using a "http.path" and passed the same in http sampler like ${http.path}. All above is working fine until i have dependent HTTP request like below use case -
Step 1 - Hit HTTP Request on path "/restpath" . After successful submission , i got a serverId in response and save the same in json extractor variable "serverID".
Step 2- Now i have to hit http request on path "/rest/${serverID}" . when i am trying to pass the same from csv file then the same is not replacing with captured variable in step 1 . Whatever i passed in csv file in http.path got passed and submit.
Expectation -
In Sheet --> http.path == "/restpath/${serverID}"
In HTTP Request submission --> "/restpath/4894rh89r"
Actual -
In Sheet --> http.path == "/restpath/${serverID}"
In HTTP Request submission --> "/restpath/${serverID}"
import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.protocol.http.util.HTTPArgument;
//test input parameters
def httpMethod = vars.get("http.method");
//change the http method as per the data sheet
sampler.setMethod(httpMethod);
//set the HTTP Path
//URL url = new URL(vars.get('http.path'));
//vars.put('http.path',url.getPath());
//set the HTTP request body
if(!vars.get("input.json").equals("")){
def dataToBePosted = new CompoundVariable(new File(vars.get("jmeter.test.home") + vars.get("input.json")).text).execute();
def arg= new HTTPArgument("", dataToBePosted, null, true);
arg.setAlwaysEncoded(false);
sampler.getArguments().addArgument(arg);
//HTTP Body is set to
log.info(dataToBePosted);
}
Tried couple of hit n trial using __V() functions but no luck :(
I think you need to change this line:
def dataToBePosted = new CompoundVariable(new File(vars.get("jmeter.test.home") + vars.get("input.json")).text).execute();
to this one:
def dataToBePosted = ((org.apache.jmeter.engine.util.CompoundVariable)([new File(vars.get("jmeter.test.home") + vars.get("input.json")).text])).execute()
Demo:
More information:
EvalFunction source
CompoundVariable JavaDoc
Apache Groovy - Why and How You Should Use It
I am new to scrapy and this is probably quite trivial. Anyway
I get the following error:
INFO: Ignoring response <404 http://www.geographie.uni
muenchen.de/department/fiona/studium/fuer_studierende/termine/index.html/>:
HTTP status code is not handled or not allowed
I have tried to change the user agent in the settings.py file without success. Does anyone have another idea?
Thank you
my code:
import scrapy
class DepartmentSpider(scrapy.Spider):
name = 'department'
start_urls = ['http://www.geographie.uni-muenchen.de/department/fiona/studium/fuer_studierende/termine/index.html/']
def parse(self, response):
for row in response.xpath('//table[2]/tbody'):
yield {
'Art' : row.xpath('td[1]//text()').extract_first(),
'Belegfrist': row.xpath('td[2]//text()').extract_first(),
'Klausur' : row.xpath('td[3]//text()').extract_first(),
}
You have slash in the end of url in start_urls. Without it everything should work fine.
I am trying to GET response from a login page
Here is the code i tried to use
import http.client
url ="https://accounts.spotify.com/en/login?continue=https:%2F%2Fwww.spotify.com%2Fus%2Faccount%2Foverview%2F"
conn = http.client.HTTPSConnection(url,port=None)
conn.request("GET", "/")
r1 = conn.getresponse()
print(r1.status, r1.reason)
And this is the error i am getting
InvalidURL: nonnumeric port: '%2F%2Fwww.spotify.com%2Fus%2Faccount%2Foverview%2F'
The get url in my code contains : its reading data after that as PORT even after passing an extra argument port=None
Can someone help me out of this
You have to just mention the host name and port in the constructor(
Read more here).
Rest of the request can be given in the request.You can view a lot of examples in the docs page.
You could pass the host name and rest of the request like this.
import http.client
url ="accounts.spotify.com"
conn = http.client.HTTPSConnection(url,port=None)
conn.request("GET", "/en/login?continue=https:%2F%2Fwww.spotify.com%2Fus%2Faccount%2Foverview%2F")
r1 = conn.getresponse()
print(r1.status, r1.reason)
Output
200 OK