I can see the statistics from Mongo shell as
db.stats()
or
db.collection_name.stats()
How do I view statistics of a database, or of a collection, from PHP and Python.
EDIT:
I have done it in PHP but still cant do it in Python.
Help?
This is how you do it in Python if you are using the PyMongo driver:
connection = pymongo.Connection(host = "127.0.0.1", port = 27017)
db = connection["test_db"]
test_collection = db["test_collection"]
db.command("dbstats") # prints database stats for "test_db"
db.command("collstats", "test_collection") # prints collection-level stats for "test_collection" under "test_db".
References:
db.command()
MongoDB: how to get db.stats() from API
This is how you do it in PHP
$con= new Mongo()
$stats=$con->dbName->command(array('dbStats' => 1)); // for db.stats()
$stats=$con->dbName->command(array('collStats' => 'collection_name')); // for db.collection_name.stats()
But how to do this in python?
The easiest way I have found to do this with a Mongoengine model was this:
import mongoengine
from models import MyModel
connection = mongoengine.connection.get_connection()
db = connection[MyModel._get_db().name]
stats = db.command("collstats", MyModel._get_collection_name())
This should allow transparent changes in the collection and database using mongoengine's config settings.
This is PHP code to execute dbStats command with new MongoDB driver:
$mongo = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
$cmdstats = new \MongoDB\Driver\Command(['dbStats' => 1]);
$dbstats = $mongo->executeCommand('databaseName', $cmdstats);
$dbstats->setTypeMap(array(
'array' => 'array',
'document' => 'array',
'root' => 'array'
));
// There must be only one item in $dbstats
foreach ($dbstats as $dbs)
{
echo($dbs['dataSize']);
}
Related
Hello I am building an API on python to create a user and insert password in database. The problem is that the application is on Laravel PHP and using bcrypt. For example encrypting "test1234$%" in PYTHON gives "$2b$12$rsGZPtjctbI6bSGzS4P3mOSdrABnJuHfnKxEQwvm4KFu72BN3XNKK" and encrypting same in PHP gives "$2y$10$cO2nvRURLRdlW8j6CbWu8OeVlv7dyeozpBZcxVB2nd8hbyILyg7Xa"
and when trying to login with users created by the api on the app it does not work.
Even if i test with this it does not work the output is invalid:
$hash = '$2b$12$rsGZPtjctbI6bSGzS4P3mOSdrABnJuHfnKxEQwvm4KFu72BN3XNKK';
//validade hash in php
if(password_verify ( "test1234$%", $hash )){
echo "valid";
} else {
echo "invalid";
}
echo("\n".phpversion());
on python side used the following code:
pip install bcrypt
import bcrypt
password = item.password
bpassword = b"password"
hashed = bcrypt.hashpw(bpassword, bcrypt.gensalt())
on PHP side:
if (! function_exists('bcrypt')) {
/**
* Hash the given value against the bcrypt algorithm.
*
* #param string $value
* #param array $options
* #return string
*/
function bcrypt($value, $options = [])
{
return app('hash')->driver('bcrypt')->make($value, $options);
}
}
bcrypt use different salt each runtime that is why its perfect for storing password on database... unless you force it to use the same salt each time it will keep generating different resulting hash
I found a solution in the Python api i call bcrypt in PHP using subprocess
code = """echo password_hash("""'"'+item.password+'"'""",PASSWORD_BCRYPT);"""
hashed_password = await myClass.php(code)
async def php(self, code):
p = subprocess.Popen(["php", "-r", code],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = p.communicate()
if out[1] != b'': raise Exception(out[1].decode('UTF-8'))
return out[0].decode('UTF-8')
On my local PC I want to use Python to both send and receive data on a remote MySQL database, via a PHP file that is located on the same webserver as the MySQL database.
I can already UPDATE the MySQL database when I run the following PHP script on the webserver:
<?php
$host_name = 'host';
$database = 'db';
$user_name = 'user';
$password = 'pass';
$conn = new mysqli($host_name, $user_name, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE test
SET test = 1
WHERE test = 0";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I have searched for hours but so far cannot make any decent attempt at Python code that will send a variable to the PHP code that will in turn update the MySQL database.
The PHP file seems to be publicly accessible so I don't imagine webserver credentials are required in my Python?
Thank you in advance SO!
With a local PHP server running using php -S localhost:8881 receive.php
send.py
import requests
url = 'http://localhost:8881'
myobj = {'key1': 'value1'}
x = requests.post(url, data = myobj)
print (x.text)
receive.php
<?php
var_dump($_POST);
Output of running send.py will be:
array(1) {
["key1"]=>
string(6) "value1"
}
For future potential visitors, below is the combination of Python and PHP that finally wrote a value from my local Python file -> to the remote PHP file -> which wrote successfully to a MySQL database.
I write the integer 6 where the value 2 exists in the database table.
Python:
import requests
url = 'https://url/file_name.php'
myobj = {'key1': 6}
x = requests.post(url, data = myobj)
print (x.text)
PHP on server (file_name.php):
<?php
$host_name = 'hostname';
$database = 'db_name';
$user_name = 'user_name';
$password = 'password';
$conn = new mysqli($host_name, $user_name, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Set variable post_data to equal the value of 'key1', which also had to be converted into an integer
$post_data = intval($_POST['key1']);
// SQL Query
$sql = "UPDATE table_name
SET column_name = $post_data
WHERE value = 2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I get the feeling there's probably a lot of useless information in the PHP file, but I'm a PHP newbie and just glad it's working now :)
i am trying to run a piece of code in python which uses Cosmos DB from Microsoft Azure. I am currently using gremlinpython 3.2.6 and the latest version of Cosmos (default on microsoft azure) but there seems to be some compatibility issues between the two.
When i run my code i get the following error;
GremlinServerError: 498:
ActivityId : 5c05bb15-3aa1-41b8-9c10-ab3015152eab
ExceptionType : GraphMalformedException
ExceptionMessage :
Gremlin Malformed Request: GraphSON v3 IO is not supported.
GremlinRequestId : 5c05bb15-3aa1-41b8-9c10-ab3015152eab
Context : global
GraphInterOpStatusCode : MalformedRequest
HResult : 0x80131500
I have read that I should try using GraphSON v2 instead of V3 but don't know how, can anyone help?
welcome to this community. You just need to ensure that you use the schema of the GraphSON v2, since it is the version supported in Azure Cosmos DB. Check the json you are using and ensure that follows the supported schema. You have some examples in this link.
Using C#, If you put your connection config in Startup.cs you can configure it like this:
services.AddSingleton<GremlinClient>(
(serviceProvider) =>
{
var gremlinServer = new GremlinServer(
hostname: "<account>.gremlin.cosmosdb.azure.com",
port: <port>,
enableSsl: true,
username: "/dbs/<db>/colls/<collection>",
password: ""
);
var connectionPoolSettings = new ConnectionPoolSettings
{
MaxInProcessPerConnection = 32,
PoolSize = 4,
ReconnectionAttempts = 3,
ReconnectionBaseDelay = TimeSpan.FromSeconds(1),
};
var mimeType = "application/vnd.gremlin-v2.0+json";
return new GremlinClient
(
gremlinServer: gremlinServer,
graphSONReader: new GraphSON2Reader(),
graphSONWriter: new GraphSON2Writer(),
mimeType: mimeType,
connectionPoolSettings: connectionPoolSettings
);
}
);
Otherwise you should create the gremlin client with the following reader, writer and mimeType:
var mimeType = "application/vnd.gremlin-v2.0+json";
var client = new GremlinClient
(
gremlinServer: <your server>,
graphSONReader: new GraphSON2Reader(),
graphSONWriter: new GraphSON2Writer(),
mimeType: mimeType,
connectionPoolSettings: <your connection pool>
);
By default gremlin_python uses the GraphSONSerializersV3d0, so you have to explicitly pass the GraphSONSerializersV2d0 when creating the client:
from gremlin_python.driver import client, serializer
client.Client(
message_serializer=serializer.GraphSONSerializersV2d0(),
password="...",
traversal_source='g',
url='wss://...:443/',
username="/dbs/.../colls/...",
)
Provide it as mime type when you create client
var client = new GremlinClient(gremlinServer:gremlinServer,mimeType:GremlinClient.GraphSON2MimeType)
You need to downgrade the version to the supported connector version. This applies to all programming languages. For python as of this writing, it is 3.2.7.
I am trying to listen to documents in collection from Python code using example from Firestore Documentation. I receive correct data when listening root collection, but got nothing when listening subcollection.
Here's my code:
db = firestore.client()
# Create a callback on_snapshot function to capture changes
def on_snapshot(col_snapshot, changes, read_time):
print(col_snapshot, type(col_snapshot))
print(changes, type(col_snapshot))
root_collection = u'shared-streams'
subcollection = u'shared-streams/eFC4T~lLyT/messages'
# Watch the root collection query (1)
col_query = db.collection(root_collection)
query_watch = col_query.on_snapshot(on_snapshot)
# Watch the subcollection query (2)
col_query = db.collection(subcollection)
query_watch = col_query.on_snapshot(on_snapshot)
Subcollection exists in Firestore and non-empty. But in first case (1) I got non-empty lists of elements and changes (and updates), and in other case (2) just two empty lists (and nothing when update subcollection). As I know there are no differences in root/sub- collections, so, please, explain where am I wrong.
UPD: Similar code in node.js works fine, so looks like it is error in python client library.
node.js snippet:
var db = admin.firestore();
var query = db.collection('shared-streams/eFC4T~lLyT/messages')
var observer = query.onSnapshot(querySnapshot => {
console.log(`Received query snapshot of size ${querySnapshot.size}`);
// ...
}, err => {
console.log(`Encountered error: ${err}`);
});
I want to use python client to create a Nessus Security Scanner and check the status by getStatus and get the result by getReport method. While, I have read these helps by php(SoftLayer API Nessus Scan Status / Report via PHP). But how can i use these by python client?
When I call setInitParameter(scan_id) in by python, the exception as flows:
SoftLayerAPIError(Client): Function ("setInitParameter") is not a valid method for this service
i recomend you to read documentation of the client first:
https://github.com/softlayer/softlayer-python
https://softlayer-api-python-client.readthedocs.io/en/latest/
the init parameters are set like this:
clientService.getObject(id=myInitParameter)
here you can find more examples using the client:
https://softlayer.github.io/python/
Here you can find additional documentation:
http://sldn.softlayer.com/blog
And renember that with the Softlayer's python client unlike the php client the data are sending in json format so the request:
$client = SoftLayer_SoapClient::getClient('SoftLayer_Account', null, $apiUsername, $apiKey);
$accountInfo = $client->getObject();
$hardware = $client->getHardware();
foreach ($hardware as $server){
$scanclient = SoftLayer_SoapClient::getClient('SoftLayer_Network_Security_Scanner_Request', '', $apiUsername, $apiKey)
$scantemplate = new stdClass();
$scantemplate->accountId = $accountInfo->id;
$scantemplate->hardwareId = $server->id;
$scantemplate->ipAddress = $server->primaryIpAddress;
try{
// Successfully creates new scan
$scan = $scanclient->createObject($scantemplate);
} catch (Exception $e){
echo $e->getMessage() . "\n\r";
}
would be like this:
clientAccount = client['SoftLayer_Account']
accountInfo = clientAccount.getObject() #for this case we do not need init parameter
hardware = clientAccount.getHardware() #for this case we do not need init parameter
for server in hardware:
scanclient = client['SoftLayer_Network_Security_Scanner_Request']
scantemplate = {
"accountId": accountInfo["id"],
"hardwareId": server["id"],
"ipAddress": server["primaryIpAddress"]
}
scanclient.createObject(scantemplate)