I am building a internal web app with Flask that connects to various clusters. 95% of the URLs start with /cluster/cluster_name so I use the following code in my blueprints:
cluster = Blueprint('cluster', __name__, url_prefix='/cluster/<cluster_name>')
#cluster.url_defaults
def add_cluster_name(endpoint, values):
values.setdefault('cluster_name', g.cluster_name)
#cluster.url_value_preprocessor
def pull_cluster_name(endpoint, values):
g.cluster_name = values.pop('cluster_name')
Which then allows me to use the following code to create a connection to the cluster before each request:
#app.before_request
def before_request():
if not hasattr(g, 'manager'):
g.manager = ClusterInterface(g.cluster_name)
This works perfectly and allows me to use {{ g.cluster_name }} in jinja2 templates.
The problem is that I am moving to an AngularJS app for the frontend so I won't be using jinja2 templates/render_template() anymore.
So how can I have this global available to AngularJS templates without returning its value from every Flask views?
Thank you.
Your views will now send JSON data instead of rendered HTML templates in order to communicate with Angular. So make this data available in the JSON response.
return jsonify(cluster_name=g.cluster_name)
More likely, you should just send the default and available names when you first start the Angular app, and let it handle the value on it's end.
Sending g.manager is impossible, since it's a Python object with (probably) complex behavior, not something that is JSON serializable.
Related
I have researched how to send data from Rails to JavaScript in a Slim view template, and the most accepted method is to declare a Ruby section on the Slim template to get the data from the controller, and then declare a JavaScript section to store that data into a window variable, and then load the JavaScript pack that's going to use that data.
The data is needed to build a JavaScript snippet that will go in the <head> of our app.
Here's an example of what I'm doing (this is the app/views/layouts/_my-template.html.slim file):
ruby:
myDataFromRails = #my_data.to_json.html_safe
javascript:
window.myData = #{myDataFromRails};
- include_javascript_pack 'my-pack'
The problem with this method is that all the data coming from the Rails backend is available for anyone that inspects the code or types window.myData in the developer tools console, which is not ideal...
Another option will be to query the backend from the JavaScript snippet itself, using an HTTP request, but this doesn't look like an efficient way of getting the data from the backend.
I have a JSON file 'DealerList.json' and I can access it from my app by importing it using
import DealerList from './json/DealerList'
let tasks = DealerList;
The tasks here contain the JSON and I can easily access it.
Is there any way by which I can update the JSON back like if I update the values OR if I delete the values. I have also tried require("fs") but that too is throwing error.
The JSON file is present in a folder called json in the React App.
No, and this is a good thing. You do not want any web browser to be able to come along and rewrite files on your HTTP server.
Write a web service which will read and update the data based on HTTP requests (with appropriate authentication/authorization to stop undesirables from changing the data). Then interact with it via XMLHttpRequest / fetch / an abstraction library wrapping one of them (like axios).
(Or use localStorage if you want to store the data on a per-browser basis rather than shared between visitors).
Usually Angular get from HTTP request the JSON from server side (like Django).
But, to accelerate rendering, would like to write down on server side the JSON into a Javascript VAR and let proceed Angular on this javascript variable containing the JSON.
My question are:
1) How to pass this javascript var to angular $scope variable ?
(without HTTP).
2) Is writing down the JSON into the HTML a bad/good practice ?
(given my web app is fairly static).
You can do a simple $scope = {{ some_django_tag|safe }}. I can't see why it would be a bad practice if you're 100% sure that the output will be valid JS. I actually do this a bit to instantiate the scope on the page load.
I have ButtonClick.js and TakeData.js files. I defined my json data in TakeData.js as below
var dataObj = {};
var locationsObj = "locations";
dataObj[locationsObj] = {};
dataObj[locationsObj].source = [];
dataObj[locationsObj].target = [];
When I click the button in ButtonClick.js and the code snippet as below
button()
.container(g2)
.text(text2)
.count(1)
.cb(function()
{
console.log(dataObj[locationsObj].source[0]);
console.log(dataObj[locationsObj].source[1]);
console.log(dataObj[locationsObj].target[0]);
console.log(dataObj[locationsObj].target[1]);
console.log("SaveFile");
})();
I want to send json data into the nodejs file writing function as the following.
fs.writeFile('sample.txt', [need to insert my JSON], function(err) {
if(err) return console.log(err);
console.log('Hello JSON > sample.txt');
});
How can I do that? Is there another effective way?
Your backend needs to have an HTTP server listening on some port that is accessible to your frontend. Then your frontend needs to make an AJAX request to your backend (most likely a POST request) and send the required data in the request body.
Now, your backend needs to handle the request, get the data and write it to the file or do whatever you want with that.
Things to keep in mind:
use body-parser if you're using Express
remember about CORS
It's easier if you use a higher level framework on the backend like Express, Hapi, Restify, LoopBack etc. instead of the low level http module in Node.
It's also easier if you use a framework on the frontend like jQuery, Angular, React, Aurelia, Ember etc.
The first step is to set up a RESTful POST operation (an HTTP POST) on your server. This is the typical service mechanism for what is sometimes called an AJAX call. Once you have the server set up to receive a string via the POST, you can serialize your objects on the client side and deserialize (reconstitute) the objects on the server side.
To serialize, you can use stringify on the client side. A simple web search for "stringify" will show you different ways to use stringify in a browser-independent, backward compatible way.
stringify(obj)
On the server side, node.js has a global JSON object. Use parse to reconstitute an object or objects from the string. Other major languages now have similar parser methods. 1
JSON.parse(strJSON)
To get started, you can test the mechanism with just one simple object. Then you can aggregate the objects in a JSON array or associative array and send them all at once in a single POST.
[1] There are frameworks that encapsulate this process, but it may be of value to you to NOT initially use them so you get a clear picture of the mechanics of a RESTful POST over the HTTP protocol. It is the key thing that a browser does when you submit an HTML form, and RESTful operations are key communications elements in today's IT world.
i developed a web application using grails/gorm about traffic reports. Basically, its possible to find for traffic reports like (in road xx there was an accident yyy and the traffic is very slow.)
now i need to integrate the map in the application. My map is in javascript, how can i access gorm objects in js (if it is possible)?
standard groovy i use:
<%
def road1 = packagename.Road.list()
out << road1.name
%>
Can i have the same kind of access in JS ?
typically for this type of thing you make some sort of request to the server, which returns the data to the browser via JSON or XML. If your map is coming from some javascript library, you can use Ajax to query your server for the data. Which JS library are you using? Whatever it is, it probably has a mechanism to make an ajax request -- you would pass the params on the ajax request that the server needs to get the appropriate data, and when the request returns a callback that define will do something with the data.
As a note, its not a bad idea to set up your application code as follows.
You have your domain object, 'Road'
Generate a RoadService, with a method listAllRoads
Generate a RoadController, with an action listAllRoads
The controller calls the service, the service uses the Domain objects to retrieve the list. In your action, you can take the list and render in whatever form you need (json, xml, or as a gsp).
Grails is all about conventions; the above is how you conform to those conventions.