i see "405: Method Not Allowed" when trying following code on Python 3.8.3 - aiohttp

https://tutorialedge.net/python/create-rest-api-python-aiohttp/
from aiohttp import web
import json
async def handle(request):
response_obj = { 'status' : 'success' }
return web.Response(text=json.dumps(response_obj))
async def new_user(request):
try:
print("AT Epoint" )
## happy path where name is set
user = request.query['name']
## Process our new user
print("Creating new user with name: " , user)
response_obj = { 'status' : 'success' }
## return a success json response with status code 200 i.e. 'OK'
return web.Response(text=json.dumps(response_obj), status=200)
except Exception as e:
print("AT EXCEPTION" )
## Bad path where name is not set
response_obj = { 'status' : 'failed', 'reason': str(e) }
## return failed with a status code of 500 i.e. 'Server Error'
return web.Response(text=json.dumps(response_obj), status=500)

Once you have implemented the listener function, register it with the aiohttp instance.
app.router.add_post('/user', new_user)
Source: TutorialEdge

Related

wkhtmltopdf reported an error: Exit with code 1 due to network error: ContentNotFoundError

good day, please im having this error when i click Export to pdf button…………………
‘’’
views.py
#login_required(login_url='loginpage')
#cache_control(no_cache=True, must_rev alidate=True, no_store=True)
def exportToPdf(request, pk):
c = get_object_or_404(candidate, id=pk)
cookies = request.COOKIES
options = {
'page-size': 'Letter',
'encoding': "UTF-8",
'cookie' : [
('csrftoken', cookies ['csrftoken']),
('sessionid', cookies ['sessionid'])
]
}
pdf = pdfkit.from_url('http://127.0.0.1:8000/'+str(c.id), False, options = options)
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-disposition'] = 'attachment; filename=candidate.pdf'
return response
urls.py
path('int:pk/exporttopdf/', views.exportToPdf, name='exporttopdf'),
‘’’

Axios post request is being denied by flask made api. CORS error coming up [duplicate]

This question already has an answer here:
cors enable in Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response
(1 answer)
Closed 2 years ago.
I am trying to add user from my react application through an API made with flask. But the post request is getting in error with the following error.
'http://localhost:5000/api/v1.0/add' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
my axios code is following
const params = {
user_name : '5678234121',
passwd : 'password',
location : 'Kolkata',
pin_code : '700019',
secret_ques: 'What is your mother s maiden name?',
answr : 'aba',
status : 'Active',
remarks : 'test data'
};
const res = await Axios.post(
'http://localhost:5000/api/v1.0/add', params, {
headers: {
'content-type': 'application/json',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
},
});
console.log(res.data);
my flask code is following
#app.route('/api/v1.0/add', methods=["POST"])
def add():
con = None
db = datadir + datafile
try:
_json = request.json
_name = _json['user_name']
_psswd = _json['passwd']
_locatn = _json['location']
_pincd = _json['pin_code']
_secrt = _json['secret_ques']
_ans = _json['answr']
_stat = _json['status']
_remks = _json['remarks']
# validate the received values
if _name and _psswd and _pincd and request.method == 'POST':
#do not save password as a plain text
_hashed_password = base64.b64encode(_psswd.encode("utf-8"))
# save edits
sql = '''INSERT INTO user_mast(user_name, passwd, location, pin_code, secret_ques, answr, status, remarks ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'''
data = (_name, _hashed_password.decode('ASCII'), _locatn, _pincd, _secrt,_ans, _stat, _remks , )
con = sqlite3.connect( db ) # Connection to database
cur = con.cursor()
cur.execute(sql, data)
con.commit()
resp = jsonify({'Status' : 'User added successfully!'})
resp.status_code = 200
else :
resp = jsonify ({'Status' :'Mandatory fields: Name,Password,Pincode missing..'})
resp.status_code = 502
except sqlite3.Error as e:
resp = jsonify({'Status' :'Database Error'})
resp.status_code = 500
except Exception as e:
print(e)
resp = jsonify({'Status' :'Unknown Error : Contact Administrator'})
resp.status_code = 501
finally:
cur.close()
con.close()
return resp
Please help me to fix the error, going clueless about this.
If you're new to this, I'd recommend just adding Flask-CORS to your application and not futzing around with the headers.

Notice: Array to string conversion -json response with doctrine

I want to put a response json after decoding it in database,
my controller code is as follows:
$jsondata = "{\"employees\":[
{ \"lastName\":\"Doe\"},
{ \"lastName\":\"Smith\"},
{\"lastName\":\"Jones\"}
]}";
$data = json_decode($jsondata, true);
// var_dump($data['employees']);
$machinetags = $data['employees'];
if ($machinetags) {
$machinetags = $em->getRepository('VCycleMachineTagsBundle:MachineTag')->findOrCreateByTitles($machinetags);
}
foreach($machinetags as $machinetag) {
$photo->addMachineTag($machinetag);
}
$em->persist($photo);
$em->flush();
But when i run it, it gives me this error:
{
"code": 500,
"message": "An exception occurred while executing 'SELECT t0.id AS id_1, t0.title AS title_2, t0.created_at AS created_at_3 FROM machinetag t0 WHERE t0.title IN (?, ?, ?)' with params [[\"Doe\"], [\"Smith\"], [\"Jones\"]]:\n\nNotice: Array to string conversion"
}
hw to fix it please, such as $machinetags is an array
The function addMachine tag is as follows :
public function addMachineTag(MachineTag $machinetag)
{
$photoMachineTag = new PhotoMachineTag();
$photoMachineTag->setMachineTag($machinetag);
$photoMachineTag->setPhoto($this);
$this->photoMachineTags->add($photoMachineTag);
}

how to send emails with PHPmailer from WordPress Rest API end point

function my_send_email($name,$email, $current_user, $status, $subject, $Message) {
//most of the code here is from https://github.com/PHPMailer/PHPMailer/tree/master/examples
require_once ABSPATH . WPINC . '/class-phpmailer.php';
require_once ABSPATH . WPINC . '/class-smtp.php';
// build message body`enter code here`
$body = '
<html>
<body>
<h1>My Email</h1>
</body>
</html>
';
try {
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
$mail->SMTPDebug = 2;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = "mail.example.com";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 25;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication
$mail->Username = "contact#example.com";
//Password to use for SMTP authentication
$mail->Password = "1234";
//Set who the message is to be sent from
$mail->setFrom('contact#example.com', 'sender_name');
//Set an alternative reply-to address
$mail->addReplyTo('alternative_contact#example.com', 'alternative_contact_name');
//Set who the message is to be sent to
$mail->addAddress($email, $name);
//Set the subject line
$mail->Subject = 'PHPMailer SMTP test';
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
//$mail->msgHTML(file_get_contents(dirname(__FILE__) .'/contents.html'));
$mail->MsgHTML($body);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
$success=$mail->send();
//send the message, check for errors
if ($success) {
return array('mailError' => false, 'message' => 'email sent! ' . $mail->ErrorInfo , 'body'=>$body);
} else {
return array('mailError' => true, 'message' => 'email error! ' . $mail->ErrorInfo , 'body'=>$body);
}
} catch (phpmailerException $e) {
return array('mailError' => false, 'message' => 'email error! ' . $e->errorMessage() , 'body'=>$body); //Pretty error messages from PHPMailer
} catch (Exception $e) {
return array('mailError' => false, 'message' => 'email error! ' . $e->getMessage() , 'body'=>$body); //Boring error messages from anything else!
}
}
function my_register_endpoints(){
register_rest_route(
'my_namespace/v1',
'/abc/',
array(
'methods' => 'POST',
'callback' => 'my_end_point',
'args' => array(
.....
),
'permission_callback' => function (WP_REST_Request $request) {
if(!is_user_logged_in()){
.....
}
return true;
}
)
);
}
add_action('rest_api_init','my_register_endpoints');
//endpoint
function my_end_point(WP_REST_Request $request){
global $current_user;
$sender = wp_get_current_user();
$shortMsg=$request['shortMessage'];
$subject="Some text";
$email_resualt=my_send_email("reciver_name","reciver_email",$sender,$status,$subject,$shortMsg);
if($email_resualt['mailError']==false){
process.. $itemes, $item ..
$message='email sent!';
return array('message' => $message,'items' => $items, 'item'=>$item);
} else {
return new WP_Error('email error',__('some message','email-error'),$request['id']);
}
}
I am using angularJS $http.post to call the API end point, The emails are sent and I can see them on my inbox, but for some reason I am getting back undefined response:
Related errors on Chrome console:
1) SyntaxError: Unexpected token S in JSON at position 0
2) TypeError: Cannot read property 'message' of undefined
I use response.message in my client side code but as I stated above but as the response is empty I am getting errors.
I have other end points in my WordPress PHP code that looks the same but doesn't include send emails with PHPmailer and works fine. and even this end point without the send email functionality was also working fine.
I tried to debug it for two days but still I am not sure where the issue in my code?
I found what the issue was, In my send email function I had the lines:
//Enable SMTP debugging
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
And appears that because debugging was turned on the response from my end point was to match for angular to handle after I commented these two lines the response was well structured for for angular to be able to parse it.
The hint to solve it was in the following post Syntax error: Unexpected number at Object.parse, PHP to AngularJS

how to handle javascript callback return data in python

var req = new XMLHttpRequest();
req.open('GET', '/Search?' + query, async);
if (async) {
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
var response = null;
try {
response = JSON.parse(req.responseText);
} catch (e) {
response = req.responseText;
}
callback(response);
This callback function returns values to my python code (I am using GAE with python 2.7).
class KeywordSearchRPCHandler(webapp2.RequestHandler):
def __init__(self):
webapp2.RequestHandler.__init__(self)
self.methods = RPCMethods()
def get(self):
func = None
action = self.request.get('action')
if action:
if action[0] == '_':
self.error(403) # access denied
return
else:
func = getattr(self.methods, action, None)
if not func:
self.error(404) # file not found
return
else :
args = ()
while True:
key = 'arg%d' % len(args)
val = self.request.get(key)
#print val
if val:
args = (json.loads(val))
else:
break
result = func(*args)
self.response.out.write(json.dumps(result))
This is the code that handles the callback function.
I get the error init() takes exactly 1 argument (3 given)
Could you please help me modify my code. Thanks a lot in advance.
Here is the documentation: Docs
webapp2.RequestHandler.__init__(request=None, response=None) is the signature.
So add request and response as parameters to your init and you should be fine.
Change def __init__ (self) to def __init__(self, request=None, response=None). This will fix the bug.
And you probably want to call super properly instead of calling __init__ on the class here: webapp2.RequestHandler.__init__(self)
This should most likely be super(KeywordSearchRPCHandler, self).__init__(request, response) instead.
The init handler:
class RPCHandler(webapp2.RequestHandler):
""" Allows the functions defined in the RPCMethods class to be RPCed."""
def __init__(self, request, response):
super(RPCHandler, self).__init__(request, response)
self.methods = RPCMethods()
But I do not understand your json.loads(val) in your GET, because you send a query string and not a json request.
Below is an example post, handling a json post:
def post(self):
data = self.request.body
args = loads(data)
if 'action' not in args:
self.error(405) # access denied
return
func = args['action']
if func[0] == '_':
self.error(403) # access denied
return
func = getattr(self.methods, func, None)
if not func:
self.error(404) # file not found
return
# action handler aanroepen
result = func(args)
self.response.out.write(json.dumps(result))
If you use a GET with a query string webapp2 will handle the request. From the docs:
# An iterable with all items in the MultiDict:
# [('check', 'a'), ('check', 'b'), ('name', 'Bob')]
self.request.GET.items()

Resources