Phalcon 4 data strange symbol during getJsonRawBody - phalcon

I'm using Phalcon 4 and I send a POST in JSON format to Phalcon controller.
The JSON is:
birthday "12/12/2020"
country "ddf"
id "15bbde30-3714-11ec-95e7-8163123e4768"
name "df"
but when I analyze it:
public function post(): ResponseInterface
{
$this->view->disable();
$body = $this->request->getJsonRawBody();
return $this->response->setStatusCode(502)->setContent(json_encode(($body-> birthday)));
the result is:
"12\/12\/2020"
I'm not able to understand why Phalcon add this strange symbol \/
If I do another test like it (I have removed -> birthday):
public function post(): ResponseInterface
{
$this->view->disable();
$body = $this->request->getJsonRawBody();
return $this->response->setStatusCode(502)->setContent(json_encode(($body)));
I have the excepted result:
birthday "12/12/2020"
country "ddf"
id "15bbde30-3714-11ec-95e7-8163123e4768"
name "df"
Have you a solution in order to avoid it?

your issue is not with Phalcon its with php's json_encode()
if you don't want the slashes to be escaped just add the JSON_UNESCAPED_SLASHES flag
return $this->response
->setStatusCode(502)
->setContent(json_encode($body, JSON_UNESCAPED_SLASHES));
check the php's documentation on json_encode() here

Related

JIKAN API - import data with dynamic ID

I am trying to use this for my import with WPAI in Wordpress. But as a non-developer I have problem to find out, how the "my_get_id" function should looks like.
My first function looks like this
function get_dynamic_import_url() { $id = my_get_id(); return sprintf( "https://api.wordpress.org/plugins/info/1.2/?action=query_plugins&request[page]=%s&request[per_page]=400", $id ); }
and my "my_get_id" like this
function my_get_id($opt = ""){ $ids = array(1,2,3); return($ids); }
however "my_get_id" is wrong, because it does not return single ID, but an array.
the ID is from 1 - 221
Any idea where should I look, for such a function with return only one ID after another.
Is it possible to implement Rate Limiting- Per Second | 3 requests, otherwise I get 404
thank you for any hint.
regards

Modified variable name in karate framework [duplicate]

This question already has an answer here:
Karate Http request add param conditionally
(1 answer)
Closed 1 year ago.
I want to modified param variable for my request(GET/POST) dynamically. As I have 2 different environment which takes different parameters for same request.
I tried below code, but not able to replace param variable(name).
I can replace param value successfully.
This function generate the dynamic param name for different enviornment
public static String paramDynamicVariable(String env, String param) {
String paramValue;
if (env.equals("test")) {
paramValue = '$' + param;
} else {
paramValue = param;
}
return paramValue;
}
Now when I am using paramValue in my test--
Scenario: xyz
Given path URLOfRequest
* print paramDynamicVariable(karate.env,'nameParam')
And param random.paramDynamicVariable(karate.env,'nameParam') = 10
It prints correct value, but in the next line it is not replacing for param name.
Please suggest if any solution is there to dynamic param name.
Please do something like this:
* def nameParam = paramDynamicVariable(karate.env, 'nameParam')
* def paramValues = {}
* paramValues[nameParam] = 10
And then:
* params paramValues
Since params accepts any JSON, all you need to do is create the JSON. Since the key is dynamic, it requires you to do a little more work.

Too few arguments to function App\Http\Controllers\ProjectController::index(), 0 passed in C:\xampp\htdocs\ContentBaseApp\

I have error:
ArgumentCountError Too few arguments to function
App\Http\Controllers\ProjectController::index(), 0 passed in
C:\xampp\htdocs\ContentBaseApp\vendor\laravel\framework\src\Illuminate\Routing\Controller.php
on line 54 and exactly 1 expected
In my ProjectController.php How can i solve this
This is my ProjectController.php
public function index($product_id)
{
// $projects = Project::whereIn('product_id',Product::where('user_id',Auth::id())->pluck('id')->toArray())->latest()->paginate(20);
$product = Product::where('user_id', Auth::id())->where('id', $product_id)->firstOrFail();
$projects = Project::where('product_id', $product->id)->latest()->paginate(20);
return view('projects.index', compact('projects'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
I wrote index method code because I want; suppose I have two id 1 & 2 if I click id 1 it will take me to index.blade.php where I can upload new data like data_1 and data_2 those data will show on index.blade.php
And if I click id 2 it will take me to index.blade.php where I don't want to see data of id 1 as I uploaded data1 and data2.
If I upload new data for id 2 I can see those data in index.blde.php
The index function on your ProjectController expects 1 argument ($product_id) as per the error message you're seeing.
Whenever you access of reference the index route, it needs to be provided with the $product_id parameter otherwise an error will be thrown (then one you're seeing).
If you're following convention, what you likely want to do is define two routes:
An index route that displays all resources and takes 0 arguments
A show route that displays information for a single resource and requires 1 argument which identifies a resource.
For example:
web.php
Route::get('/projects', [ProjectController::class, 'index')
->name('projects.index');
Route::get('/projects/{product}', [ProjectController::class, 'show'])
->name('projects.show');
ProjectController.php
public function index()
{
return view('projects.index', [
'projects' => Project::paginate(20),
]);
}
public function show(Product $product)
{
return view('projects.show', [
'projects' => $product->projects()->latest()->paginate(20),
]);
}
If you visit /projects you will return all project resources, but if you visit /projects/2 you will get only the projects related to Product with id of 2.
You can use the route() helper to generate your URLs.
...
That would create a link that would take you to the projects for product 2.

How to convert objectid to string

I want to get the string character from an ObjectId object. I use pymongo.
eg: ObjectId("543b591d91b9e510a06a42e2"), I want to get "543b591d91b9e510a06a42e2".
I see the doc, It says ObjectId.toString(), ObjectId.valueOf().
So I make this code: from bson.objectid import ObjectId.
But when I use ObjectId.valueOf(), It shows:
'ObjectId' object has no attribute 'valueOf'.
How can I get it? Thanks.
ObjectId.toString() and ObjectId.valueOf() are in Mongo JavaScript API.
In Python API (with PyMongo) proper way is to use pythonic str(object_id) as you suggested in comment, see documentation on ObjectId.
ObjectId.toString() returns the string representation of the ObjectId() object.
In pymongo str(o) get a hex encoded version of ObjectId o.
Check this link.
What works for me is to "sanitize" the output so Pydantic doesn't get indigestion from an _id that is of type ObjectId...here's what works for me...
I'm converting _id to a string before returning the output...
# Get One
#router.get("/{id}")
def get_one(id):
query = {"_id": ObjectId(id)}
resp = db.my_collection.find_one(query)
if resp:
resp['_id'] = str(resp['_id'])
return resp
else:
raise HTTPException(status_code=404, detail=f"Unable to retrieve record")
Use str(ObjectId), as already mentined in the comment by #Simon.
#app.route("/api/employee", methods=['POST'])
def create_employee():
json = request.get_json()
result = employee.insert_employee(json)
return { "id": str(result.inserted_id) }
This is an old thread, but as the existing answers didn't help me:
Having run
new_object = collection.insert_one(doc)
I was able to get the ObjectID with the inserted_id property:
print(f"{new_object.inserted_id}")
In python (Pymongo) there's no inbuilt method to do it so iterate over the result you fetched from db and then typecast _id to str(_id)
result = collection.find({query})
for docs in result:
docs[_id] = str(docs[_id])
first you have to assign the Object Id value to a variable
for example:
let objectId = ObjectId("543b591d91b9e510a06a42e2");
then use the toString method like this
let id = objectId.toString();

Yii framework: Trying to get property of non-object

What I have:
public function beforeValidate() {
$offender = Accounts::model()->find(array('select'=>'id','condition'=>'username=:username','params'=>array(':username'=>$this->offender)));
$informer = Accounts::model()->find(array('select'=>'id','condition'=>'username=:username','params'=>array(':username'=>$this->informer)));
$this->offender = $offender->id;
$this->informer = $informer->id;
return parent::beforeValidate();
}
What I get:
PHP Notice, that says, that i'm trying to get property "id" of non-object $offender and $informer.
But those are 100% objects:
var_dump($offender):
object(Accounts)[46]
var_dump($informer):
object(Accounts)[46]
And it actually sets the right id, but shows that notice anyway. What is wrong?
SOLVED
Can't post it as official answer for six more hours, so i just leave it here:
Actually, the problem was in double beforeValidate() call.
AbuseController.php:
if(isset($_POST['AbuseReport']))
{
$model->attributes=$_POST['AbuseReport'];
if($model->validate())
{
$model->save();
}
}
First time it validates on $model->validate(), and replaces $this->offender and $this->informer with correct ID's. Second time it validates on $model->save();, but model returns null this time, because $this->offender is already ID, but it expects username.
The whole solution to this is to disable second validation: $model->save(false);.
use isset or is_object
if(isset($offender->id) || is_object($offender->id)){
$this->offender = $offender->id;
$this->informer = $informer->id;
}