Following is my code in view:
RESULTS= {}
for k in RESULTS_LIST[0].iterkeys():
RESULTS[k] = list(results[k] for results in RESULTS_LIST)
RESULTS.pop('_id',None)
html_table = json2html.convert(json=RESULTS)
return render(request,'homepage.html',{'html_table':html_table})
here I am arranging a data fetched from Mongo Db in a JSON named as RESULTS and by using JSON2HTML package, it is successfully generated html table for data given in JSON. To embedd the html table code in a blank division at html page, I am doing:
<div>{{html_table}}</div>
But it failed to display the table on page. I have tried numerous ways to make it but didn't succeed. Please help me to resolve this issue. if any relevant example, you have done before , then please guide me in a right direction.
JS code is:
angular.module("homeapp",[])
.controller("homecontroller",['$http','$scope',function($http,$scope){
$scope.search= {
'keyword': null,
'option': null,
'startDate':null,
'lastDate': null
};
$scope.search_info=function(){
var search_req = {
url:'/home',
method:'POST',
data:$scope.search
}
$http(search_req) //in case I dont want any response back or
$http(search_req).success(function(response){
window.alert(response)
}) //in case I need to check response
}
}]);
I have got solution to this problem in an easy way via using js, which is given below and it worked.
$http(search_req).success(function(response){
angular.element(".search_results").append(response);
})
Related
I usually use Powershell and have parsed JSONs from HTTP requests, successfully, before. I am now using Python and using the 'Requests' library. I have successfully got the JSON from the API. Here is the format it came through in (I removed some information and other fields).:
{'content': [
{
'ContactCompany': Star,
'ContactEmail': test#company.star,
'ContactPhoneNumber': 123-456-7894,
'assignedGroup': 'TR_Hospital',
'assignedGroupId': 'SGP000000132297',
'serviceClass': None, 'serviceReconId': None
}
]
}
I'm having trouble getting the values inside of the 'content.' With my Powershell experience in the past, I've tried:
tickets_json = requests.get(request_url, headers=api_header).json()
Tickets_Info = tickets_json.content
for tickets in tickets_info:
tickets.assignedGroup
How do I parse the JSON to get the information inside of 'Content' in Python?
tickets_json = requests.get(request_url, headers=api_header).json()
tickets_info = tickets_json['content']
for tickets in tickets_info:
print(tickets['assignedGroup'])
So I am trying to locate and acquire data from an api, I am fine with actually getting the data which is in json format from the api into my python program, however I am having troubles searching through the json for the specific data I want.
Here is a basic idea of what the json file from the api looks like:
{
"data": {
"inventory": {
"object_name": {
"amount": 8,
},
(Obviously the } close, I just didn't copy them)
I am trying to locate the amount within the json file of a specific object.
So far, here is the code I have, however, I have run into the error json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
I have researched the error and it appears to be caused usually by a faulty json file, however as I have imported the json file from an api, it having issues is not the case and must be an issue with some of the converting to strings and such I have done in my code.
data = requests.get('[api]',
headers={
"[api key name]" : "[api key]"
})
dataJson = data.json()
dataStr = str(dataJson)
amt = json.loads(dataStr)['data'].get('inventory').get('object_name').get('amount')
As stated previously, the main issue I have is actually collecting the data I need from the json endpoint, everything is fine with getting the data into the python script.
dataJson = data.json() is already python dict no need to json.loads(dataStr) just use
data = requests.get('[api]',
headers={
"[api key name]" : "[api key]"
})
dataJson = data.json()
amt = dataStr['data'].get('inventory').get('object_name').get('amount')
Summary
I am trying to set my FormData properly using javascript.
I need to be able to upload jpg/png, but I might need to upload some other file types pdf/csv in the future using fetch.
Expected
I expect it to append the data to the form
Error
Working
This snippet is working fine:
const formData = new FormData(document.querySelector('form'));
formData.append("extraField", "This is some extra data, testing");
return fetch('http://localhost:8080/api/upload/multi', {
method: 'POST',
body: formData,
});
Not working
const formData = new FormData();
const input = document.querySelector('input[type="file"]');
formData.append('files', input.files);
Question
Does fetch support multiple file upload natively?
If you want multiples file, you can use this
var input = document.querySelector('input[type="file"]')
var data = new FormData()
for (const file of input.files) {
data.append('files',file,file.name)
}
fetch('http://localhost:8080/api/upload/multi', {
method: 'POST',
body: data
})
The issue with your code is in the lineformData.append('files', input.files);
Instead of that, you should upload each file running a loop with unique keys, like this
const fileList = document.querySelector('input[type="file"]').files;
for(var i=0;i<fileList.length;i++) {
formData.append('file'+i, fileList.item(i));
}
I have created a simple error fiddle here with your code. You can check its' submitted post data here, where you can see that no file has been uploaded.
At the bottom of the page you can find
.
I have corrected the fiddle here with the fix. You can check its'post data from the server, where it shows the details of the two files that I uploaded.
I mentioned this on a similar question: I had the same problem, but with a PHP backend. The unique formData keys work, but I found that the classic HTML notation worked just fine and simply results in an array on the server.
formData.append('file[]', data[i]);
I like that a lot better, since I can use the same methods to process this as with a classic <input type="file" multiple />.
I'm currently trying to save some python objects (websites) via PyRavenDB in a RavenDB database. The problem is that data are saved properly, but when I test it by querying the results, some of the attributes are returned empty.
The code is simple, I can't properly find be the problem.
The JSON object in the database is the following (verified via the DB web UI).
{
"htmlCode": "<code>TEST HTML</code>",
"added": "2017-02-21",
"uniqueid": "262e4584f3e546afa2c67045a0096b54",
"url": "www.example.com",
"myHash": "d41d8cd98f00b204e9800998ecf8427e",
"lastaccessed": "2017-02-21"
}
When I use this code to query
from pyravendb.store import document_store
store = document_store.documentstore(url="http://somewhere:someport", database="websites")
store.initialize()
with store.open_session() as session:
query_result = list(session.query().where_equals("www.example.com", url))
print query_result
print type(query_result)
return query_result
It returns this object :
{
'uniqueid': 'f942e86f965d4709a2d69caca3001f2a',
'url': '',
'myHash': 'd41d8cd98f00b204e9800998ecf8427e',
'htmlCode': '',
'added': '2017-02-21',
'lastaccessed': '2017-02-21'
}
As you can see, url and html code are empty. They should be okey since in DB they are properly stored.
Thanks.
The problem here is that you don't use the where_equal right.
where_equal first argument is the field name you want to query with and then the value (def where_equals(self, field_name, value)).
Just change this line query_result = list(session.query().where_equals("www.example.com", url))
To this query_result = list(session.query().where_equals("url", "www.example.com"))
This will fix your problem
I'm trying to implement server side processing with data from sqlite on my Flask app. I am a newbie, so I can't figure out what's wrong. So far I have come to this:
HTML:
<table id="myTable" class="table table-striped" style="width:100%" >
<thead>
<tr>
<th>Time</th>
<th>Mean Current</th>
<th>Vapour Pressure</th>
<th>Mean Voltage</th>
<th>Temperature</th>
<th>Humidity</th>
<th>Bar Pressure</th>
<th>RPM</th>
<th>Wind Sector</th>
<th>Wind Speed</th>
<th>Air Density</th>
<th>DC Voltage</th>
<th>Power Sector</th>
<th>Furling Angle</th>
<th>Yaw angle</th>
</tr>
</thead>
</table>
Javascript:
$(document).ready(function() {
$('#myTable').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "/page_test"
} );
});
View function:
#app.route('/page_test')
def page_test():
data = json.dumps(meas[2])
print data
return data
meas[2] is my dict:
[dict((c.description[i][0], value) \
for i, value in enumerate(row)) for row in c.fetchall()]
In "print data" everything is printed fine, like this:
{"MeanCurrent": 0.05933, "Temperature": 15.095, "YawAngle": 0.0, "MeanVoltage": 0.67367, "VoltageDC": 3.18309, "PowerSec": 0.06923, "FurlingAngle": -0.2266828184, "WindSpeed": 1.884, "VapourPressure": 1649.25948, "Humidity": 0.4266, "WindSector": 0, "AirDensity": 1.23051, "BarPressure": 1020.259, "time": "2015-04-22 20:58:28", "RPM": 0.0, "ID": 1357}
This is multiplied by the number of rows.
However, when I run the app and insert the query, the table is displayed with only the <th> tags and there is "Processing..." written on top of the table with no data displayed. At the terminal of my flask app, a huge string is displayed, and this is a small sample:
/page_test?draw=2&columns%5B0%5D%5Bdata%5D=0&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=1&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5
And here is a screenshot:
Every time I click on the th tags, the same string comes again. It seems like I'm missing something important but as this is my first app, I can't figure out what it is. Any suggestion for modification of the code would be appreciated.
Server-side processing is a setting that requires you to have a database script capable of replicating a lot of the core functionality of DataTables on your own server/database to manage very large sets of data.
All the information that is being passed to your script (e.g. that long string of info) are the inputs you need to use to query the database to return a result for DataTables to render.
If you would prefer DataTables to load the data from your Flask endpoint and then manage all the processing internally make these modifications: remove the serverSide setting and add column configurations so your data ends up in the right place:
Javascript:
$(document).ready(function() {
$('#myTable').DataTable( {
"processing": true,
"ajax": "/page_test",
// add column definitions to map your json to the table
"columns": [
{data: "time"},
{data: "MeanCurrent"},
...
]
} );
});
DataTable Initialization Options: if you click the "columns" button it shows you the various configurations each "column" accepts, whether it is sortable, orderable, custom rendering, etc...
Python:
from flask import jsonify
#app.route('/page_test')
def page_test():
return jsonify(meas[2])
2 potential issues:
1) Make sure you are not using the slim jQuery version. Slim jQuery doesn't have ajax, so if you inspect in the browser, you will see some error message like "h.ajax if not a function". This will just show "processing..." indefinitely. This had me stumped for awhile, because bootstrap uses the slim version of jQuery by default, and I was using bootstrap.
2) I am not an expert on datatables by any means, but I am playing around with it. To get data to show using server side, the data had to be formatted like this:
return_me = json.dumps({"data": [[1, 1.3478, 23.2223, ...]]})
i.e., I couldn't get it to work when returning a dictionary of column names...I had to specifically call it the dictionary field "data" and then give that all the values. It's possible I have gotten something incorrect here myself, but this is what worked.
Using flask, you will get a faster response than using C#.In Server Side Processing, You can send sorted/searched/header value via form in flask.
In Flask, You can get datatable values using:
Datatabledata= request.form
In SSP,You can send additional data to flask using:
"data":function(data){
data.input="Text"
}