how to show html elements from python cgi file into ajax file - python

Please I want to handle the front-end in python as much as possible and make it dynamic by ajax:
this is the client side:
<div id="gene">
<!-- <select id="gene"> -->
<!-- add an empty value -->
<!--<option value="*">-- Select --</option> -->
<!--</select>-->
</div>
And the Ajax function in the same file:
var updateGeneInput = function(){
$.ajax({
url: 'get.py',
type: 'get',
data: {'table':'gene'},
success: function(data){
$("#gene").html(data);
}
});
};
And I want to retrieve the options to populate the drop list using the cgi (get.py):
if (table == "gene"):
query = """
SELECT category
FROM Categories
"""
cursor.execute(query)
rows=cursor.fetchall()
print("""<select >""")
print("""<option value='*'>- Select -</option>""")
for row in rows:
print("""<option value="s%">s%</option>"""%row)
print("""</select>""")
It does show the results but not in drop list.
Thank you very much

Related

Dynamically Read Excel Spreadsheets with Python, Flask without reload the html page

The code works if result=random.random(), but would like to dynamically Read Excel Spreadsheets with Python, Flask without reload the html page
Excel file will change at a specified interval and HTML keeping static
.py
#app.route("/rel")
def rel_country():
z = "test"
book = load_workbook("rel/" + str(z) + ".xlsx")
sheet = book.active
return jsonify(result=sheet)
HTML:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
var $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
var intervalID = setInterval(update_values, 1000);
function update_values() {
$.getJSON($SCRIPT_ROOT + '/rel',
function (data) {
$('#result').text(data.result);
console.log(data)
});
};
function stopTextColor() {
clearInterval(intervalID);
}
</script>
<title>Excel To HTML Table</title>
</head>
<body onload="update_values();">
<h1>Dynamic Update</h1>
<p>
<span id="result">?</span>
<script>
document.getElementById("result").innerHTML;
</script>
<button onclick="stopTextColor();">Stop</button>
</body>
Error:
raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")
TypeError: Object of type Worksheet is not JSON serializable
Use pandas to read the xlsx file. The dataframe that results from that is json serializable.
df = pd.read_excel('tmp.xlsx', index_col=0)
result = df.to_json(orient="records")

Data seem not to update when refreshing the page in python bottle?

I'm running a script that shows up some data in python bottle, one of it is signal strength that I'd like to show in real time. When I refresh the page the value doesn't change so I have to rerun the server in order to update that signal strength. I've tried ajax but it seems that it doesn't work.
What should I use to make this to work?
EDIT: The variables are lists that come from another file.
iplist = [192.168.1.1, 192.168.1.2]
hostlist = [android234567, android677896]
maclist = [a1:b2:c3:d4:e5:f6, a1:b2:c3:d4:e5:f6]
signallist = [-56, 23]
.
#app.route('/')
def index():
info={'iplist': iplist, 'maclist': maclist, 'signallist': signallist, 'hostlist': hostlist}
tpl = '''
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script type="text/javascript">
function ajax(){
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if (req.readyState == 4 && req.status == 200) {
document.getElementById('signallist').innerHTML = req.responseText;
}
}
req.open('REQUEST', '../connectedDevices.py', true);
req.send();
}
(function(){ajax();}, 1000);
</script>
</head>
<body onload="ajax();">
<table>
<tr>
<td>IP address</td>
<td>Hostname</td>
<td>MAC address</td>
<td>Signal</td>
</tr>
%for i in range(len(maclist)):
<tr>
<td>{{iplist[i]}}</td>
<td>{{hostlist[i]}}</td>
<td>{{maclist[i]}}</td>
<td id="signallist">{{signallist[i]}}</td>
</tr>
%end
</table>
</body>
</html>
'''
return template(tpl, info)
This prints a chart where it shows Ip, host, mac and signal which the one that I want to get updated in real time.
Bottle caches the templates. So if you are feeding values in during the template creation, it will cache those values.
from bottle import TEMPLATES
TEMPLATES.clear()
Will reset those.
However, you really should think about where your data is coming and leverage websockets. gevent has a great websocket library and works great with bottle to make your code async. With a little work and javascript you can query your api and feed data real time into your code.

Get value from textbox input without ng-repeat

I'm new in AngularJS.
I want to get value from input text without ng-repeat where the value is from Python.
Value from Python:
{{user.id}}
My text input:
<form ng-submit="SendHttpPostData()">
<p><input type="text" ng-model="user" value="{{user.id}}"></p>
<input type="submit" value="Submit" />
</form>
My problem is:
The value of user.id doesn't display in input text.
I get undefined result when click Submit button.
Angular, by default, will not read the value attribute of an input when initializing data bindings. However, you can write a directive which will do this for you:
app.directive('value', function () {
return {
restrict: 'A',
require: '?ngModel',
link: function postLink(scope, element, attrs, ngModel) {
if (!ngModel)
return;
var val = attrs.value || element.val() || element.text();
ngModel.$setViewValue(val);
ngModel.$render();
}
};
});
This will ensure that whenever the value attribute appears together with ng-model, it will be used to initialize the bindings. See this Plunker for a demo.
However, please note that this is not the recommended way of passing data to Angular from the backend. Generally, it is best to write a JSON API endpoint and load the data into the client-side using $http or $resource.

Django management - execute command with continuous output

I have a script that I'm building an interface for so people can execute after uploading a CSV file. I'm able to execute everything and have the script run properly, but how do I display a continuous output? What changes should I make to my code?
Below are my files:
scripts.html - Scripts are executed from here and executed on the server via an AJAX call. Output is placed into div#output once the script is done executing.
<div class="table_container">
<form method="post" enctype="multipart/form-data" data-ajax="false">{% csrf_token %}
<h4>Rebilling</h4>
<div class="clear"></div>
<img class="loading-gif" src="{{ STATIC_URL }}img/loading-clear.gif" alt="" />
<table>
<tbody>
<tr>
<td style="width: 180px;"><label>Upload the CSV</label></td>
<td>
<input type="hidden" name="script_type" value="renew_subscriptions">
<input type="file" name="csv_file" />
</td>
</tr>
<tr>
<td style="width: 180px;"></td>
<td>
<input type="submit" name="Execute" />
</td>
</tr>
</tbody>
</table>
</form>
</div>
<h2>Script Output</h2>
<div id="output">
{% autoescape off %}
{% endautoescape %}
</div>
<script type="text/javascript">
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
$('form').on('submit', submitForm);
// Catch the form submit and upload the files
function submitForm(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
$("#output").html("");
var form = $(this);
form.find(".loading-gif").css("display", "block");
form.find("input[type='submit']").prop('disabled', true);
// Create a formdata object and add the files
var data = new FormData(form.get(0));
$.ajax({
url: '/crm/scripts',
type: 'POST',
data: data,
cache: false,
dataType: 'html',
processData: false,
contentType: false,
success: function(data)
{
// console.dir(data);
$("#output").html(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
form.find(".loading-gif").css("display", "none");
form.find("input[type='submit']").prop('disabled', false);
}
});
return false;
}
</script>
views.py - The AJAX is sent here and the command is executed through Django Management
def all_scripts(request): # Accounts page
# c = {}
script_type = None
csv_file = None
out = StringIO()
if request.is_ajax and request.method == 'POST':
csv_file = request.FILES.get('csv_file')
if csv_file:
# print "over here"
### write the csv_file to a temp file
tup = tempfile.mkstemp() # make a tmp file
f = os.fdopen(tup[0], 'w') # open the tmp file for writing
f.write(csv_file.read()) # write the tmp file
f.close()
### return the path of the file
filepath = tup[1] # get the filepath
# print filepath
if 'script_type' in request.POST:
script_type = request.POST['script_type']
if script_type == "change_credit":
credit_amount = None
if 'credit_amount' in request.POST:
credit_amount = request.POST['credit_amount']
if 'function' in request.POST:
function = request.POST['function']
if function == "remove":
management.call_command(script_type, filepath, credit_amount, remove=[True], stdout=out)
else:
management.call_command(script_type, filepath, credit_amount, stdout=out)
elif script_type == "renew_subscriptions":
management.call_command(script_type, filepath, verbosity=1, interactive=False, stdout=out)
print out.getvalue()
return HttpResponse(out.getvalue())
return render_to_response('crm/scripts.html', context_instance=RequestContext(request))
Just need the output to display continuously line by line. Any help is much appreciated.
Cheers,
Zee
“The web request is a scary place, you want to get in and out as quick
as you can” - Rick Branson
What you have done here is created an architectural issue. Basically you are creating additional disk IO when writing your CSV file. You are doing this in the web request. 'Not a good idea'.
However its also the crux of the issue you are describing.
Quick n dirty:
you could get a return value from a django management command like so. Pass that back to the success method of jquery's ajax call as your data.
However: please don't to that!
You need an async task system to hand off the write of that csv file. Additionally you want to write the data somewhere ( dbms / nosql ) that your webpage can listen for via ( polling, streaming or websockets ) This is not a trivial undertaking but the end result is well worth the effort. Here are some proven django-stack choices to solve this type of issue.
Building a Asynchronous Tasking/Queuing System
celery
Rabbit the broker used by celery
memcached / mongoDB / reddis
Polling for that data
what are longpolling and websockets
websockets vs long polling
This pycon talk covers these technologies.
Messaging at Scale at Instagram

HTML drop-down box with Google App Engine

I am creating a Google App Engine web application written in Python, and I would like to create a drop down box that displays different values corresponding to pages of a book that a user could choose from. I would like the action of the drop down box to be to direct the user to the page that corresponds to this link:
<a href='/viewpage/{{bookpage.key}}'>{{ bookpage.page }} </a>
The "bookpage" entity is passed to the html
Thank you!
David
Use a Jump Menu. Here is a pretty straight forward implementation.
Basically you'll just add a bit of JavaScript, and instead of writing an a tag, you'll write an option:
<option value='/viewpage/{{bookpage.key}}'>{{ bookpage.page }} </option>
What about <option value='/viewpage/{{bookpage.key.id}}'>{{bookpage.page}}</option>?
I hope it's not a dumb answer.
I'm not familiar with the google-app-engine but, the following javascript seems to do what you want. The python could generate the array variables on the server side, and then everything else would work properly.
I included the hardcoded arrays so you can see what is going on, but you can replace the arrays with the python code(assuming bookpage is some kind of dictionary):
i = 0
for bp in bookpage.keys():
print("mysites["+str(i)+"] = "+ bookpage[bp])+";"
print("sitenames["+str(i)+"] = "+sitenames[bp])+";"
i+=1
<html>
<body>
<script type="text/javascript">
var mysites= new Array();
mysites[0] = "http://www.google.com"; //Generate this line with python
mysites[1] = "http://www.bing.com"; //Generate this line with python
mysites[2] = "http://www.yahoo.com"; //Generate this line with python
var sitenames = new Array();
sitenames[0] = "Google"; //Generate this line with python
sitenames[1] = "Bing"; //Generate this line with python
sitenames[2] = "Yahoo"; //Generate this line with python
function changeLink(){
var index = document.getElementById("theselect").selectedIndex
document.getElementById("thelink").innerHTML=index;
var newlink = mysites[index];
var newstring = sitenames[index];
document.getElementById("thelink").href=newlink;
document.getElementById("thelink").innerHTML=sitenames[index];
}
</script>
<select id="theselect" onclick="changeLink()">
<option>Google</option>
<option>Bing</option>
<option>Yahoo</option>
</select>
<br />
<a id="thelink" href="http://www.google.com" > Google </a>
</body>
</html>
Clicking on the option box calls the changeLink() function, which then changes the link and the inner html of the tag.

Categories

Resources