I have a controller in Play Framework 1.3.x in which I have defined the following:
public static void plots(Long id) {
//... (Code goes here)
render(list); //Data to render
}
And then in a separate html file in the views folder I want to "display" the result from another html file. I'm trying to do it in the following way:
<script type="text/javascript">
setInterval(function() {
$.get("plots", id, function(${list}){ //I want to give the list needed by the file plots.html
$("#result").html(list); //And then in "result" show the plots obtained
})
}, 1000);
</script>
...
<span id="result"></span>
But it does not display anything at all. This plots file just needs this list and then does a plot with the data but I'm pretty sure I'm not writing code in the right way, I mean, I'm not giving the function the right syntaxis or parameters. Any ideas? Thanks!
PS: My routes file
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / Application.index
# Ignore favicon requests
GET /favicon.ico 404
# Map static resources from the /app/public folder to the /public path
GET /public/ staticDir:public
# Catch all
* /{controller}/{action} {controller}.{action}
you need to define route
GET /plots Application.plots(id:Long)
and
$.get("/plots", id, function(${list})
or according to your code
* /{controller}/{action} {controller}.{action}
use
$.get("Application/plots", id, function(${list}){ //Application is your controller name
but i will suggest to use first one
Related
I'm trying to make a dynamically background that changes images every x seconds. But i want the images to be sourced from a directory in a django project. I have this piece of code but is hardcoded and limited.
var header = $('body');
var backgrounds = new Array(
'url(static/media/backgrounds/1.jpg)'
, 'url(static/media/backgrounds/2.jpg)'
, 'url(static/media/backgrounds/3.jpg)'
, 'url(static/media/backgrounds/4.jpg)'
, 'url(static/media/backgrounds/5.jpg)'
, 'url(static/media/backgrounds/6.jpg)'
, 'url(static/media/backgrounds/7.jpg)'
, 'url(static/media/backgrounds/8.jpg)'
, 'url(static/media/backgrounds/9.jpg)'
, 'url(static/media/backgrounds/10.jpg)'
);
var current = 0;
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 5000);
header.css('background-image', backgrounds[0]);
Firstly you'll need to enumerate the images you want. For simple deployments, where static files will be on your filesystem (in STATIC_ROOT) and served from under /static/, something like
# Get absolute disk paths of files
backgrounds = glob.glob(os.path.join(settings.STATIC_ROOT, 'media', 'backgrounds', '*.jpg'))
# Turn into URLs
background_urls = [f'/static/media/backgrounds/{os.path.basename(bg)}' for bg in backgrounds]
will do; for a more robust solution, you'd probably want to use the staticfiles finders API to enumerate all files and turn them into URLs.
For serving that data to your view, a couple of options I can think of.
List the backgrounds in your view and pass the array into the template
Enumerate all of the background images' URLs into a list, pass it to the template
Render it into a JSON list: {{ background_urls|json_script:"backgrounds" }}
View returning Javascript fragment
Wire up a view that returns a JavaScript fragment with all the background URLs, e.g. var backgrounds = ["/static/foo.jpg"];
Use that in your view: <script src="{% url "background_list_js" %}"></script>
Your script would otherwise work as-is
View returning JSON payload
Wire up a view that returns a JSON object with all the background URLs, e.g. ["/static/foo.jpg"]
Use e.g. fetch() or another AJAX method to load the data before starting to change backgrounds
View returning a random background URL
Wire up a view that returns a JSON object with a single random background URL from the selection, e.g. {"url": "/static/foo.jpg"}
Use e.g. fetch() or another AJAX method to load the data every time you need a new background.
Custom template tag returning a Javascript fragment
Like option 1, but instead of having a separate view, register a simple template tag you can then use to inline the background array: <script>{% dump_backgrounds %}</script>
What I need help with
I want to receive variables from a external .json file in the local directory
using python27
(import doesn't work)
I want to store the variables in the .json like below
value1 = "this_is_value1"
value2 = "this_is_value2"
value3 = "this_is_value3"
and have them being used in a script.
If I can get it to the point of which the .json includes
value1 = "this_is_value1"
and my .py includes
print(value1)
with output
>>>this_is_value1
I can take it from there
My end Task
The idea is that I need to change specific parts of another .yaml file, this program needs to take variables like (ID, System_id, IP) and for this case I need a .json I can change which the python27 script then pulls the information from to change the .yaml file.
I've done this part fine, just need to do this part
Have I researched the issue?
In short, YES.
however, theses answer use .py or other file types.
I've already tried importing the file but since it needs to sit next to the script I can't use import
Other anwser simply give no information back about how they solved the issue.
With a json formatted file (say "my_file.json"), for instance:
{
"x": "this is x",
"y": "this is x",
"z": "this is z"
}
Then in Python:
import json
with open("my_file.json", "r") as f:
my_dict = json.load(f)
print(my_dict["x"])
Yields:
this is x
I generally like to control this process with a method or function. Here is a code snip I use frequently that will read the format of the text file you've shown:
class MainApp(object):
def __init__(self, config_file):
# Initialization stuff from a configuration file.
self.readConfigFile(config_file)
def readConfigFile(self, file):
try:
with open(file, 'r') as cfg:
lines = list(cfg)
print("Read", len(lines), "lines from file", file)
# Set configured attributes in the application
for line in lines:
key, value = line.split('=')
setattr(self, key.strip(), value.strip())
except:
print('Configuration file read error')
raise
if __name__ == '__main__':
# Create an instance of the application.
# It will read the configuration file provided here.
app = MainApp('myconfig.txt')
# Now you can access the attributes of the class (read from config file)
print(app.value1, app.value2, app.value3)
This should work:
>> string1 = 'value1 = "this_is_value1"'
>> exec(string1)
>> print(value1)
"this_is_value1"
If what you really need is a .txt file, then I recommend you to take a look at the documentation:
https://docs.python.org/3/tutorial/inputoutput.html
Go to section: 7.2 Reading and Writing a file
Basically, you'll need is:
lines = [] # for further data manipulation
file = open("c:\path\to\your.txt", "r")
for line in file:
lines.append([line.split("=")])
file.close()
Now if you have in your .txt bar="foo"
Then in the lines list you can do:
lines[0][0] # output "bar"
lines[0][1] # output "foo"
Of course there are some more smater way of doing this, but this is just basic idea.
I am getting files from directory('.public/jsonfiles') in server.js file using node.js. But I am failing to get these list of files to show on my view page using AngularJS with my Node.js service.
Error:
I am getting data.forEach is not a function error(I can see total html content in the console instead of my list of files in my service file on return statement: return $http.get('/public/jsonfiles');
Otherwise if I give: return $http.get('').then(function(data){ console.log(data)}); /giving Main.get() success is not a function and giving total of html content on console
Created repository.
I had a look at your repo. On the request
return $http.get('/public/jsonfiles');
node will return index.html which will then make MainCtrl error on data.forEach as data is not an array.
If you install serve-index and use it to provide directory listing for public it should work.
var serveIndex = require('serve-index');
app.use('/public',serveIndex('public'));
(server.js)
To load the file json add another method to the MainService to get the file.
getFile: function (filename) {
//no public in the path because node is removing when it serves static files
return $http.get('/jsonfiles/' + filename);
}
In MainCtrl you can the load the file contents when the selected file is changed.
$scope.optionChanged = function () {
Main.getFile( $scope.selectedjsoncontent )
.success(function(result){
$scope.textAreaData = result;
});
}
Here is js code in our Rails 3.2 app responding to change of fields whose ids start with 'order_order_items_attributes':
$(function (){
$(document).on('change', "[id^='order_order_items_attributes'][id$='_name']", function (){
$.post(window.location, $('form').serialize(), null, "script");
return false;
});
});
The $.post() causes the error:
"NetworkError: 404 Not Found - http://localhost:3000/po/orders/new?parent_record_id=4&parent_resource=ext_construction_projectx%2Fprojects&project_id=4%22"
Here is the window.location:
If we replace $.post() with $.get(), then the code works fine and fires up the ajax response on the server:
$.get(window.location, $('form').serialize(), null, "script"); #works!
But we have to use $.post() because of the large amount of data being posted to the server. The jquery document shows that $.get() and $.post() have exactly the same format. What we missed here with $.post()?
Update
rake routes output:
Routes for PurchaseOrderx::Engine:
search_order_items GET /order_items/search(.:format) purchase_orderx/order_items#search
search_results_order_items GET /order_items/search_results(.:format) purchase_orderx/order_items#search_results
stats_order_items GET /order_items/stats(.:format) purchase_orderx/order_items#stats
stats_results_order_items GET /order_items/stats_results(.:format) purchase_orderx/order_items#stats_results
order_items GET /order_items(.:format) purchase_orderx/order_items#index
POST /order_items(.:format) purchase_orderx/order_items#create
new_order_item GET /order_items/new(.:format) purchase_orderx/order_items#new
edit_order_item GET /order_items/:id/edit(.:format) purchase_orderx/order_items#edit
order_item GET /order_items/:id(.:format) purchase_orderx/order_items#show
PUT /order_items/:id(.:format) purchase_orderx/order_items#update
DELETE /order_items/:id(.:format) purchase_orderx/order_items#destroy
search_orders GET /orders/search(.:format) purchase_orderx/orders#search
search_results_orders GET /orders/search_results(.:format) purchase_orderx/orders#search_results
stats_orders GET /orders/stats(.:format) purchase_orderx/orders#stats
stats_results_orders GET /orders/stats_results(.:format) purchase_orderx/orders#stats_results
event_action_order GET /orders/:id/event_action(.:format) purchase_orderx/orders#event_action
acct_approve_order PUT /orders/:id/acct_approve(.:format) purchase_orderx/orders#acct_approve
acct_reject_order PUT /orders/:id/acct_reject(.:format) purchase_orderx/orders#acct_reject
gm_approve_order PUT /orders/:id/gm_approve(.:format) purchase_orderx/orders#gm_approve
gm_reject_order PUT /orders/:id/gm_reject(.:format) purchase_orderx/orders#gm_reject
gm_rewind_order PUT /orders/:id/gm_rewind(.:format) purchase_orderx/orders#gm_rewind
submit_order PUT /orders/:id/submit(.:format) purchase_orderx/orders#submit
list_open_process_orders GET /orders/list_open_process(.:format) purchase_orderx/orders#list_open_process
orders GET /orders(.:format) purchase_orderx/orders#index
POST /orders(.:format) purchase_orderx/orders#create
new_order GET /orders/new(.:format) purchase_orderx/orders#new
edit_order GET /orders/:id/edit(.:format) purchase_orderx/orders#edit
order GET /orders/:id(.:format) purchase_orderx/orders#show
PUT /orders/:id(.:format) purchase_orderx/orders#update
DELETE /orders/:id(.:format) purchase_orderx/orders#destroy
root / purchase_orderx/orders#index
Here is the rake routes output for purchase order engine. Most of the routes are not relevant to the question and still listed as it is.
here is routes.rb:
resources :order_items do
collection do
get :search
get :search_results
get :stats
get :stats_results
end
end
resources :orders do
collection do
get :search
get :search_results
get :stats
get :stats_results
end
end
Workflow related actions were removed in routes.rb for easy read.
Your backend routing is not properly routing that URL to a valid controller when using the POST HTTP verb. In the root of your Rails project in the terminal, run rake routes to see all available routes, and where they end up. Without seeing your routes.rb I can't explain exactly what's wrong, but it's definitely a backend routing issue.
I wouldn't recommend what some of the comments are saying, to just "stick this in routes.rb and it will work". Your routes should be well maintained and using the correct Route helper for the job. If you throw misc. routes in there to solve problems as they come up, you'll end up with a pile of spaghetti for your routing, and maintenance of your application will become more difficult over time.
Edit: Updated to reference the update from the question
The current page URL is /po/orders/new. Looking at your rake routes output, this maps to new_order_path, evidenced by this row:
new_order GET /orders/new(.:format) purchase_orderx/orders#new
If you look directly above it, you'll see the real route for the create action:
POST /orders(.:format) purchase_orderx/orders#create
This create action is a POST to orders_path, which resolves as /po/orders/. If you POST to this URL, everything should work. If you want to be able to post to URL you're currently using and have it work, just modify your routes.rb to match this:
resources :order_items do
collection do
get :search
get :search_results
get :stats
get :stats_results
end
end
resources :orders do
# Manually route POSTs to /new to the create action
post "/new", :controller => :orders, :action => :create
collection do
get :search
get :search_results
get :stats
get :stats_results
end
end
Now, when you make a POST to this URL (/po/orders/new, it will hit the OrdersController create method. You can still hit this method by POSTing to /po/orders as well (as I recommended above).
I've been developing a mean.js application. I have an admin theme that I'm trying to integrate with the existing application.
My question is
Can we have multiple Server Layouts, ? If the logged-in user is Regular User, use layout-1 if the user is Admin use layout-2
If we cannot have multiple server layout (I presume it isn't possible). Is there any way to detect the params or scope variable in the Angular Client App and dynamically load a partial inside the main Layout.
Let say I have an Index.html file, if the intended route is Dashboard, I just replace a section of the page view, ( Ruby on Rails Developers would know this)
UPDATE 1 :
I've created 2 files with my required Admin Index, and Layout files.
admin.index.server.view.html
and
admin.layout.server.view.html
I've also added the following code in my core.server.routes.js
module.exports = function(app) {
// Root routing
var core = require('../../app/controllers/core');
app.route('/').get(core.index);
app.route('/admin/').get(core.adminIndex);
};
I've also added the following code in my core.server.controller.js
exports.adminIndex = function(req, res) {
res.render('admin.index', {
user: req.user || null
});
};
and when I hit localhost:3000/admin/ I get Error: Cannot find module 'index'
Rename the two view files from admin.index.server.view.html and admin.layout.server.view.html to admin-index.server.view.html and admin-index.server.view.html respectively.
Also, change this line in your core.server.controller.js file;
res.render('admin.index', {
to this;
res.render('admin-index', {