Skip to content

Commit

Permalink
Y2024
Browse files Browse the repository at this point in the history
  • Loading branch information
vprtsingh committed Oct 6, 2024
1 parent 7cfde31 commit 87aaec5
Show file tree
Hide file tree
Showing 14 changed files with 319 additions and 0 deletions.
11 changes: 11 additions & 0 deletions templates/snippets/python/my-node-app/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const { insertData } = require('my-python-npm-package');

const databaseName = 'login-with-vpjs'; // Replace with your database name
const collectionName = 'developers'; // Replace with your collection name
const data = {
name: 'John Doe',
email: '[email protected]',
age: 30
};

insertData(databaseName, collectionName, data);
15 changes: 15 additions & 0 deletions templates/snippets/python/my-node-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "my-node-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"my-python-npm-package": "file:../my-python-npm-package"
}
}
36 changes: 36 additions & 0 deletions templates/snippets/python/my-python-npm-package/data_insert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# data_insert.py
from pymongo import MongoClient
import sys
import json

def insert_data(database_name, collection_name, data):
client = MongoClient('mongodb://localhost:27017/')
db = client[database_name]
collection = db[collection_name]

result = collection.insert_one(data)

response = {
'message': 'Record inserted successfully',
'data': {
'name': data.get('name'),
'email': data.get('email'),
'id': str(result.inserted_id) # Optionally include the inserted ID
}
}
return response

if __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage: python data_insert.py <database_name> <collection_name> <data_json>")
sys.exit(1)

database_name = sys.argv[1]
collection_name = sys.argv[2]
data_json = sys.argv[3]

data = json.loads(data_json)
response = insert_data(database_name, collection_name, data)

# Print the response as a JSON string
print(json.dumps(response))
31 changes: 31 additions & 0 deletions templates/snippets/python/my-python-npm-package/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const { exec } = require('child_process');
const path = require('path');

// Function to insert data
function insertData(databaseName, collectionName, data) {
const dataJson = JSON.stringify(data);
const pythonScriptPath = path.join(__dirname, 'data_insert.py'); // Full path to the Python script
const command = `python "${pythonScriptPath}" ${databaseName} ${collectionName} '${dataJson}'`;

exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Error executing script: ${error}`);
return;
}
if (stderr) {
console.error(`Script stderr: ${stderr}`);
return;
}
try {
const response = JSON.parse(stdout);
const email = response.data.email;
console.log(`Extracted Email: ${email}`);
} catch (parseError) {
console.error(`Could not parse response: ${parseError}`);
}
});
}

module.exports = {
insertData
};
2 changes: 2 additions & 0 deletions templates/snippets/python/my-python-npm-package/install.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/bash
pip install -r requirements.txt
11 changes: 11 additions & 0 deletions templates/snippets/python/my-python-npm-package/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "my-python-npm-package",
"version": "1.0.0",
"description": "An npm package that wraps Python functionality.",
"main": "index.js",
"scripts": {
"install": "./install.sh"
},
"dependencies": {},
"devDependencies": {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pymongo
3 changes: 3 additions & 0 deletions templates/snippets/python/simple_crud_api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
python -m venv env
source env/bin/activate
pip install -r requirements.txt
99 changes: 99 additions & 0 deletions templates/snippets/python/simple_crud_api/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
from urllib.parse import urlparse

# In-memory storage for items
data_store = {}
id_counter = 1

class RequestHandler(BaseHTTPRequestHandler):

def do_GET(self):
parsed_path = urlparse(self.path)
if parsed_path.path == '/items':
self.handle_get_items()
elif parsed_path.path.startswith('/items/'):
self.handle_get_item(parsed_path.path.split('/')[-1])
else:
self.send_response(404)
self.end_headers()

def do_POST(self):
if self.path == '/items':
self.handle_create_item()
else:
self.send_response(404)
self.end_headers()

def do_PUT(self):
if self.path.startswith('/items/'):
self.handle_update_item(self.path.split('/')[-1])
else:
self.send_response(404)
self.end_headers()

def do_DELETE(self):
if self.path.startswith('/items/'):
self.handle_delete_item(self.path.split('/')[-1])
else:
self.send_response(404)
self.end_headers()

def handle_get_items(self):
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(data_store).encode())

def handle_get_item(self, item_id):
if item_id in data_store:
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(data_store[item_id]).encode())
else:
self.send_response(404)
self.end_headers()

def handle_create_item(self):
global id_counter
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
item = json.loads(body)
item_id = str(id_counter)
data_store[item_id] = item
id_counter += 1
self.send_response(201)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({"id": item_id}).encode())

def handle_update_item(self, item_id):
if item_id in data_store:
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
item = json.loads(body)
data_store[item_id] = item
self.send_response(200)
self.end_headers()
else:
self.send_response(404)
self.end_headers()

def handle_delete_item(self, item_id):
if item_id in data_store:
del data_store[item_id]
self.send_response(204)
self.end_headers()
else:
self.send_response(404)
self.end_headers()

def run(server_class=HTTPServer, handler_class=RequestHandler, port=8080):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print(f'Starting httpd on port {port}')
httpd.serve_forever()

if __name__ == "__main__":
run()
36 changes: 36 additions & 0 deletions templates/snippets/python/simple_crud_api/data_insert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# data_insert.py
from pymongo import MongoClient
import sys
import json

def insert_data(database_name, collection_name, data):
client = MongoClient('mongodb://localhost:27017/')
db = client[database_name]
collection = db[collection_name]

result = collection.insert_one(data)

response = {
'message': 'Record inserted successfully',
'data': {
'name': data.get('name'),
'email': data.get('email'),
'id': str(result.inserted_id) # Optionally include the inserted ID
}
}
return response

if __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage: python data_insert.py <database_name> <collection_name> <data_json>")
sys.exit(1)

database_name = sys.argv[1]
collection_name = sys.argv[2]
data_json = sys.argv[3]

data = json.loads(data_json)
response = insert_data(database_name, collection_name, data)

# Print the response as a JSON string
print(json.dumps(response))
22 changes: 22 additions & 0 deletions templates/snippets/python/simple_crud_api/insert_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from pymongo import MongoClient

def insert_data(collection, data):
result = collection.insert_one(data)
print(f'Data inserted with id: {result.inserted_id}')

def main():
client = MongoClient('mongodb://localhost:27017/')
db = client['login-with-vpjs'] # Replace with your database name
collection = db['developers'] # Replace with your collection name

# Data to be inserted
data = {
'name': 'John Doe',
'email': '[email protected]',
'age': 30
}

insert_data(collection, data)

if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions templates/snippets/python/simple_crud_api/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pymongo
15 changes: 15 additions & 0 deletions templates/snippets/python/simple_crud_api/runPython.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const { exec } = require('child_process');

const pythonScriptPath = 'insert_data.py'; // Adjust the path if necessary

exec(`python ${pythonScriptPath}`, (error, stdout, stderr) => {
if (error) {
console.error(`Error executing script: ${error}`);
return;
}
if (stderr) {
console.error(`Script stderr: ${stderr}`);
return;
}
console.log(`Script output: ${stdout}`);
});
36 changes: 36 additions & 0 deletions templates/snippets/python/simple_crud_api/runPython2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const { exec } = require('child_process');

// Function to insert data
function insertData(databaseName, collectionName, data) {
const dataJson = JSON.stringify(data);
const command = `python data_insert.py ${databaseName} ${collectionName} '${dataJson}'`;

exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Error executing script: ${error}`);
return;
}
if (stderr) {
console.error(`Script stderr: ${stderr}`);
return;
}
try {
const response = JSON.parse(stdout)
const email = response.data.email;
console.log(`Extracted Email: ${email}`);
} catch (parseError) {
console.error(`Could not parse response: ${parseError}`);
}
});
}

// Example usage
const databaseName = 'login-with-vpjs'; // Replace with your database name
const collectionName = 'developers'; // Replace with your collection name
const data = {
name: 'John Doe',
email: '[email protected]',
age: 30
};

insertData(databaseName, collectionName, data);

0 comments on commit 87aaec5

Please sign in to comment.