I’m working with node js and django data connection. I have this middleware using node js that can send data using post request
my node.js
const payload = mydata;
//POST payload to django
var obj = { data: payload };
jsonobj = JSON.stringify(obj);
var XMLHttpRequest = require("xhr2");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://127.0.0.1:8000/", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(jsonobj);
And I can access that data in my django project views.py using this following code. It’s printing the data that node js sent.
from django.views.decorators.csrf import csrf_exempt
import json
@csrf_exempt
def overview(request):
if request.method == 'POST':
post_data = json.loads(request.body.decode("utf-8"))
value = post_data.get('data')
print(value)
return render(request, 'myhtml')
In my urls.py
from iot import views as iotviews
urlpatterns = [
path('path/', iotviews.overview),
]
now, I’m trying to use the data in my Plotly Dash. I’m going to use the data to generate a graph. But it’s not working unlike in views.py
graph.py
app = DjangoDash("SimpleExample")
app.layout = html.Div([
html.Div(style={'display': 'flex'}, children=[
dcc.Graph(
id='graph-ph',
figure={
'data': [
{'x': [],
'y': [],
'mode':'lines+markers',
}],
'layout': {
'title': 'pH (pH)',
}},
),
])
@app.callback(Output('graph-ph', 'figure'),
[Input('interval-graph-update', 'n_intervals')],
[State('graph-ph', 'figure')])
def update_extend_traces_traceselect(n_intervals, fig_raw, request):
if request.method == 'POST':
post_data = json.loads(request.body.decode("utf-8"))
value = post_data.get('data')
print(value)
if "SimpleExample" == '__main__':
app.run_server(debug=True)
I think I can’t use request as an argument to every function in django. It has to be a view function. If it is a regular function, it will not recognize request. Is there another way to get the data?