Skip to content
Snippets Groups Projects
Commit eeb9430e authored by DHOMBRES Stephanie's avatar DHOMBRES Stephanie
Browse files

Update example

parent 19556750
Branches
No related tags found
1 merge request!1Dev update
# Nanospace-client
# Nanospace Python Client
## Python client
The following scripts demonstrate how to connect to the [Nanospace Back-end](https://gitlab.isae-supaero.fr/nanostar/nanospace/nanospace-back-end/) and how to interact with it to create, read, update or delete components and values, in the Neo4J database.
### Requirement
Request package is needed
## 1. Requirements
A [Nanospace Back-end](https://gitlab.isae-supaero.fr/nanostar/nanospace/nanospace-back-end/) is required,
and the following packages :
```bash
sudo apt install python3 python3-pip python-is-python3
pip install requests
```
> Note: You can also use a virtual environment.
## 2. Scripts
This repository has 3 Python scripts:
1. auth_test.py : To test Authentication to [Nanospace Back-end](https://gitlab.isae-supaero.fr/nanostar/nanospace/nanospace-back-end/)
### 2.1. Authentication Test to Nanospace-Backend (auth_test.py)
To test the connection to the [Nanospace Back-end](https://gitlab.isae-supaero.fr/nanostar/nanospace/nanospace-back-end/):
> You need to update the script according to your url, username, password:
>```
>login_to_api('http://localhost:8888/login', 'test', 'test')
>```
Then run:
```bash
python auth_test.py
```
The response shall be:
```bash
Login successful!
<Response [200]>
```
### 2.2. Authentication Test to Nanospace-Backend (Terminal)
It is possible to request your token using the following command line :
> Note: Replace the url, `<yourLogin>` and `<yourPassword>` by your real url, login and password) :
```bash
curl -s -i \
http://localhost:8888/login \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/json' \
-d '{
"username":"<yourLogin>",
"password":"<yourPassword>"
}' | grep -i "Authorization:"
Response :
```bash
Authorization: Bearer --TokenId-- # Token Result
```
The result is giving you a token to access to your account.
### Simple examle
Check the `simple_example.py` python file.
### 2.2 Simple Example (simple_example.py)
Before try to launch it, change the `username`, `password` and `server` address (End the server address with a '/').
Check the `simple_example.py` Python file. Before try to launch it, change the `username`, `password` and `server` address (End the server address with a `/`).
```python
from nanospace import Nanospace
nanospace = Nanospace('http://server_address/','username', 'password')
print(nanospace.get_string_value(66))
nanospace.update_value(66, 'sma', '9000000')
print(nanospace.get_string_value(66)) # Should print 9000000
print(nanospace.get_formula_value(66))
nanospace.update_value(77, 'sma', '9000000')
print(nanospace.get_formula_value(66)) # Should print 9000000
```
### Creation of element
It is also possible to create component, value and modes from Python. However, we advice to use the UI instead.
#### 2.2.1 Creation of element
To create component, value and modes from Python, we advice to use the `Nanospace Front-End` UI instead.
But it is possible using :
```python
# from nanospace import Nanospace
# nanospace = Nanospace('http://server_address/','username', 'password')
nanospace._create_component(12, 'new_component)
nanospace._create_mode(12, my_new_mode)
nanospace._create_string_value(45, '')
nanospace._create_component(12, 'Orbitography')
nanospace._create_mode(12, 'Recovery')
nanospace._create_string_value(45, 'Earth_mass')
nanospace._create_formula_value(46, 'Earth_standard_gravitational_parameter')
```
If the id is missing, check the Nanospace front-end url or the #id, that can help you to get one.
If the `id` is missing, check the `Nanospace front-end` url or the `#id`, that can help you to get one.
Then each one of the _create_ function are returning a Python dictionary where you can find id.
### Delete a element
#### 2.2.2 Read a value
Even if it is advise to delete element from the UI, the following functions give also the possibilities to delete element from Python.
Read a string using Python:
```python
# from nanospace import Nanospace
# nanospace = Nanospace('http://server_address/','username', 'password')
nanospace._delete_component(12)
nanospace._delete_mode(45)
nanospace._delete_value(63)
print(nanospace.get_string_value(<id>))
```
Note that __delete_value__ is working either if the value is a formula, or a string.
Read a string using Python:
```python
print(nanospace.get_formula_value(<id>))
```
## Bash client
### Get your login
Request (replace yourLogin and yourPassword by your real login and pw) :
```bash
To use Curl, copy-paste the `<your_token>` of the login (from #2.2) and add the `<id>` of the value, you want to get:
curl -X POST \
http://localhost:8888/login \
```bash
curl -s GET http://localhost:8888/value/<id> \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/json' \
-d '{
"username":"'"yourLogin"'",
"password":"'"yourPassword"'"
}' | grep Bearer
```
Response :
```bash
Authorization: Bearer --TokenId-- # Token Result
-H 'Authorization: Bearer <your_token>' | grep value
```
The result is giving you a token to access to your account.
Example:
### Get a value
Copy paste the full result of the login as header and add the number of the value you want to get
```bash
curl GET \
http://localhost:8888/value/71 \
-H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJsdWNpZW4iLCJleHAiOjE1NTYzNjcyODF9.a3iv6yGzOcbPfAs_vHCUpo2zJJtrl23Kn_HA1tn_zBvKI86o2zE0V50H_GqyIzp5VmLSVuU93O8OtBLGClZxRA' \
curl -s GET http://localhost:8888/value/1 \
-H 'Cache-Control: no-cache' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJsdWNpZW4iLCJleHAiOjE1NTg2MjI4Nzl9.4ohO9F55GgxzyKim-K0xQKkBiW-me_v6K74b4YLIOVdg1xiPsrOVkmqg_-VWu7W4_l00XWXXjguccmXLxQi-Ow' | grep value
-H 'Authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0IiwiZXhwIjoxNzQ1NTA1NzA2fQ.GS-iGT6PA-DOpxya5dNLjHY2VOlyKFx9UFEz7ygaHXn1EAVJsIbJMaU3XaIZe0n-z5yi9e-5bIbmmivSYe133w' | grep value
```
Expected response (if the `<id>` exists and the token is valid):
```bash
{"id":1,"creationDateTime":"2019-05-17T17:13:24.497","lastUpdateDateTime":"2025-04-14T12:32:35.761811921","name":"Earth_mass","text":"Earth_mass","description":"","type":"string_value","responsibles":[],"value":"5.9722*10^(24)"}
```
### Update a value
#Todo
### 2.2.3 Update a value
Update a string :
```python
print(nanospace.get_string_value(66))
nanospace.update_value(66, 'string_example', '9000000')
print(nanospace.get_string_value(66)) # Should print 9000000
```
Update a formula :
```python
print(nanospace.get_formula_value(77))
nanospace.update_value(77, 'formula_-_example', '9000000')
print(nanospace.get_formula_value(77)) # Should print 9000000
```
### 2.2.4 Delete a element
To delete element from Python :
```python
# from nanospace import Nanospace
# nanospace = Nanospace('http://server_address/','username', 'password')
nanospace._delete_component(12)
nanospace._delete_mode(45)
nanospace._delete_value(63)
```
> It is advised to delete element from the UI.
> Note : that __delete_value__ is working either if the value is a formula, or a string.
import requests
def login_to_api(username, password):
#======================================================================
#======================================================================
def login_to_api(url, username, password):
"""
Logs in to the API using the provided username and password.
Logs in to the API using the provided url, username and password.
Parameters:
url (str): The Login API URL
username (str): The username for login.
password (str): The password for login.
Returns:
dict: A dictionary containing the API response, including the status code and response text.
dict: A dictionary containing the API response,
including the status code and response text.
"""
# Login API URL
url = 'http://localhost:8888/login'
# Login data
data = {
'username': username,
'password': password
}
# Send POST request
response = requests.post(url, json=data)
# Check response status
if response.status_code == 200:
print("Login successful!")
# Assuming the response contains JSON data.
return response
else:
print(f"Login error: {response.status_code}")
return {'error': response.text, 'status_code': response.status_code}
return {
'error': response.text,
'status_code': response.status_code
}
#======================================================================
#======================================================================
# Example usage
if __name__ == "__main__":
result = login_to_api('test', 'test')
# Test with Login API URL and sample credentials
result = login_to_api('http://localhost:8888/login', 'test', 'test')
print(result)
import paho.mqtt.client as mqtt
client = mqtt.Client()
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost",1884, 60)
client.loop_forever()
\ No newline at end of file
......@@ -7,7 +7,7 @@ username = 'test'
password = 'test'
server = 'http://localhost:8888/'
id = 278 # For test : be sure this value exists
id = 16 # For test : be sure this value exists (Earth_Radius)
# ================================================================================
# ================================================================================
......@@ -34,33 +34,33 @@ print(nanospace.get_string_value(id))
# ================================================================================
print("--------------------------------------------")
print(nanospace._delete_value(393))
print(nanospace._delete_value(17))
# ================================================================================
# ================================================================================
print("--------------------------------------------")
print(nanospace._create_string_value(44, 'test3', 'Hello-world'))
print(nanospace._create_string_value(13, 'Earth_mass', '5.9722*10^(24)'))
# ================================================================================
# ================================================================================
print("--------------------------------------------")
print(nanospace.get_formula_value(444))
nanospace.update_formula_value(444, 'multiplication','5*20')
print(nanospace.get_formula_value(444))
nanospace._create_component(10, 'newComponent')
# ================================================================================
# ================================================================================
print("--------------------------------------------")
nanospace._create_component(85, 'newComponent')
nanospace._create_formula_value(73, 'test1', '5*5')
# ================================================================================
# ================================================================================
print("--------------------------------------------")
nanospace._create_formula_value(73, 'test1', '5*5')
print(nanospace.get_formula_value(444))
nanospace.update_formula_value(444, 'multiplication','5*20')
print(nanospace.get_formula_value(444))
# ================================================================================
# ================================================================================
......@@ -72,7 +72,7 @@ nanospace._create_string_value(73, 'test2', 'Hello-world')
# ================================================================================
print("--------------------------------------------")
nanospace._create_mode(23, 'new_mode_tutu')
nanospace._create_mode(23, 'New Mode')
# ================================================================================
# ================================================================================
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment