Accessing Python functions with Ajax - python

I’m new to python and web related code so excuse the probably dumb question. I was wondering if it’s possible for me to write some functions in python, and then for them to be used on a website.
Specifically, I have coded a few simple functions that take a users input (string of a musical chord like “Amin7sus2”) and return the notes that make up that chord (A, B, E, G). Now the goal is to have a web app where someone can type the chord, and then it accesses the python functions to return the notes.
I have a friend who does front end, and he mentioned Ajax to me for accessing python through jquery, but I can’t find any examples of it doing something quite like this.
It takes around 10 smaller functions to achieve the conversion from string to a list of notes, as well as accessing several dictionaries within python. I’m essentially looking for a way to feed the input from the web (a simple string) through my series of functions in python to finally return the list of notes.
Below is a very symbolic version of my python code that I wish to feed user input from the web into:
def dict1():
#dict1
return dict1
def func1(input):
#input_to_chord_quality
return input_to_chord_quality
def func2(input_to_chord_quality):
#access dict1
#quality_to_notes
return quality_to_notes
def main():
return func2(func1(input))
Can anyone offer some guidance on how to use python logic for a web app feature?

You should read up about Web frameworks in Python - my personal recommendation would be Flask but there are many. Look for one that is specifically suitable for writing Web APIs (REST or otherwise) - think of a Web API as a method of exposing server-side Python code through a Web (HTTP, or Ajax) interface.
Once you have started experimenting with building a Web API using a Python Web framework, and have specific questions, I suggest you come to StakcOverflow again and ask.
Good luck!

You could do this by learning a python backend like flask or django. But there is also something called brython, which gives you the possibility to execute python code on the frontend.
My recommendation would be to try this tutorial and writing something like this:
<script type="text/python">
from browser import document
def function():
...
return "Test"
document <= function()
</script>

Related

how can i make a front end such that it takes the input performs calculations in python and returns the result to html

I have a machine learning model which is trained to perform classification. I want to provide the test data through a front end(I have web based front end in my mind if there is any other option then please recommend.). So i would require an html page to take the input , pass it to the backend so that calculations can be performed in python and return it back to the html page. How can i do this?
[EDIT] I started with django. I am able to render the html page but how do i pass the data to a python file?
There are a lot of ways you can implement an front end for python but probably the two easiest are:
Using Flask which is an easy to learn web microframework for python.
Using the Django Web Framework which is harder to learn than Flask but provides more functionality.

Execute python functions and read variables from html

First off, I am very new to programming and I have a relatively basic understanding of python, and average understanding of html.
Using what I know in python, I am trying to create a basic strategy game, a bit like the likes of Age of Empires, or Command and Conquer, based on collecting resources and using it to build things, except using a simple text or button-clicking type interface. I can do a text interface fine, but its a bit boring, and I would like to use some images. I have had a 1 hour lecture on tkinter, but I have tried and failed to make anything remotely 'usable' from it. What I can do, is make decent looking html pages which would serve my purpose very well.
What I am wondering is if there is a simple way of executing python functions and calling/displaying python variables through a html page? The python functions do all the logic and present variables which represent current resource levels, production, storage capability, levels of buildings, etc. At the most basic level all I need is a way of displaying these variables, and having buttons which execute a function to say, upgrade a building, which recalculates production and all that, and returns the new set of values.
As a really simple example:
<p> Wheat production: *python integer representing production*</p>
<button type="button" onclick="*execute python variable*">Upgrade Wheat</button>
There would also, I imagine, be a need to somehow update the variables which are changed on the html page. So the button executes a function to upgrade wheat production, python now has a new value for the wheat production variable, and this needs to be updated on the page, whether this is automatic, or by some other method. I guess the simple way would be if pressing the button could also reload the page, but that seems a little clumsy.
Does anyone know of a simple way of doing this? Or perhaps a python library which might help me here?
Yes, there is a way of doing this.
There are two approaches to this. One is to have all the work done on the server, the other approach is to use Javascript.
The first approach is this: write a python script that generates your HTML. If you use Django, you will get a lot of work done for you, but you will also get a lot of stuff you don't want. Django does have a built-in template language. Django is beyond the scope of this answer. You will get to do exactly what you describe above; an example of a template might be <p> Wheat production: {{wheat_production}}</p> - your python code will set up a dict mydict={"wheat_production":10} and you will pass the name of your template file and the dict to a function which will spit out your page. You will also have to learn about HTML forms, if you haven't done so yet.
The other approach is to use Ajax - Javascript that, when your page is displayed (and, perhaps, when buttons are clicked, or at regular intervals) will send/receive some data to allow you to update your page. I suggest looking into JQuery to do some of the lifting for you. This means that you can update bits of the page without having to reload the entire thing. You will still have to write some code on the server to talk to the database, and send the output, usually as JSON, back to the client.
When writing this sort of thing, make sure all of your security is on the server side, and don't trust anything the user tells you. For example, if you store the number of gold pieces in a field on your form, it's going to take someone about 10 seconds to give themselves as much gold as they want. Similarly, if a player can sell a diamond for 20 gold pieces, make sure they have the diamond before giving them the gold pieces - you don't want to end up with a player with 1,000,000 gold pieces and negative a thousand diamonds. Javascript is 100% insecure, anything that Javascript can do, the player can also do.
Take a look at http://pyjs.org/
What is pyjs?
pyjs is a Rich Internet Application (RIA) Development Platform for
both Web and Desktop. With pyjs you can write your JavaScript-powered
web applications entirely in Python.
pyjs contains a Python-to-JavaScript compiler, an AJAX framework and a
Widget Set API. pyjs started life as a Python port of Google Web
Toolkit, the Java-to-JavaScript compiler.
You can compile Python programs to javascript, and also use their Python libraries to generate HTML. Here's an example from their getting started guide:
from pyjamas import Window
from pyjamas.ui import RootPanel, Button
def greet(sender):
Window.alert("Hello, AJAX!")
class Hello:
def onModuleLoad(self):
b = Button("Click me", greet)
RootPanel().add(b)

Python search script in an HTML webpage

I have an HTML webpage. It has a search textbox. I want to allow the user to search within a dataset. The dataset is represented by a bunch of files on my server. I wrote a python script which can make that search.
Unfortunately, I'm not familiar with how can I unite the HTML page and a Python script.
The task is to put a python script into the html file so, that:
Python code will be run on the server side
Python code can somehow take the values from the HTML page as input
Python code can somehow put the search results to the HTML webpage as output
Question 1 : How can I do this?
Question 2 : How the python code should be stored on the website?
Question 3 : How it should take HTML values as input?
Question 4 : How can it output the results to the webpage? Do I need to install/use any additional frameworks?
Thanks!
There are too many things to get wrong if you try to implement that by yourself with only what the standard library provides.
I would recommend using a web framework, like flask or django. I linked to the quickstart sections of the comprehensive documentation of both. Basically, you write code and URL specifications that are mapped to the code, e.g. an HTTP GET on /search is mapped to a method returning the HTML page.
You can then use a form submit button to GET /search?query=<param> with the being the user's input. Based on that input you search the dataset and return a new HTML page with results.
Both frameworks have template languages that help you put the search results into HTML.
For testing purposes, web frameworks usually come with a simple webserver you can use. For production purposes, there are better solutions like uwsgi and gunicorn
Also, you should consider putting the data into a database, parsing files for each query can be quite inefficient.
I'm sure you will have more questions on the way, but that's what stackoverflow is for, and if you can ask more specific questions, it is easier to provide more focused answers.
I would look at the cgi library in python.
You should check out Django, its a very flexible and easy Python web-framework.

Re-accessing python variables AFTER initial html get() call

I am making a data-plotting tool using google app engine and google docs/gdata and have run into a python/js/html communication issue.
I want a very simple layout for the webpage -- just a series of dropdown menu sections and then the final graphs. My current dilemma involves the dropdown menus.
There are total of 4 dropdown menus, and the fields of each one depends on the previous selection. I have found JS/HTML code that has all of the needed logic, but it assumes that you have pre-loaded all of the selection fields. Due to the scale of the project, it is impossible to load everything on start-up, and the data is dynamic/changing, so I can't just declare static files with the menu selection data contained.
Currently, I have methods to get all of the menu selections/data I need from google docs (using gdata). Ideally, I would like to just call each one in series (html selection1 -> python method1 to get next selection set -> html selection2 -> python method2 to get next selection set-> etc) but from what I can gather it seems this is not possible (return to python, ie 'post', without reloading the entire page).
So, is there a way to access python variables/methods in a google-app-engine JS code AFTER the initial template render or without 'posting'? Or, more open-endedly, if anyone has insight/suggestions/ideas I'd appreciate it.
Thanks
Two step process:
Create some server side code to return your data as JSON - the defacto method of transferring data on the web.
In your javascript code, call your server (from step 1) and then parse the result. Use the result to populate your dropdown.
The good news is that Google already provides json as an alternate format for their gdata APIs. See this link for a primer on how to use gdata and return JSON.
For the second part, almost all javascript client side libraries (and you really should be using one) provide an easy way to request data using ajax. As this is a common task, there are plenty of questions on StackOverflow on this - this one in particular has an example that shows you how to populate a dropdown using jquery and ajax.
Assuming you can use javascript and replicate whatever functionality your Python code is providing, the above will work for you. If you have some specific logic that you don't want to transfer to the client side, then your Python code will have to return json (in effect, you would be acting like the gdata api for your javascript code).
Since you didn't highlight which Python framework you are using - here is an example using flask, a simple framework for Python web development:
from flask import Flask, jsonify
app = Flask(__name__)
#app.route('/the-question')
def the_answer():
return jsonify(answer=42)
A more comprehensive example is available in the documentation under AJAX with jQuery.
If you are using webapp2, Google provides excellent documentation to do the same thing.

How do I create a web interface to a simple python script?

I am learning python. I have created some scripts that I use to parse various websites that I run daily (as their stats are updated), and look at the output in the Python interpreter. I would like to create a website to display the results. What I want to do is run my script when I go to the site, and display a sortable table of the results.
I have looked at Django and am part way through the tutorial, but it seems like an awful lot of overhead for what should be a simple problem. I know that I could just write a Python script to output simple HTML, but is that really the best way? I would like to be able to sort the table by various columns.
I have years of programming experience (C, Java, etc.), but have very little web development experience.
Thanks in advance.
Have you considered Flask? Like Tornado, it is both a "micro-framework" and a simple web server, so it has everything you need right out of the box. http://flask.pocoo.org/
This example (right off the homepage) pretty much sums up how simple the code can be:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
If you are creating non-interactive pages, you can easily setup any modern web server to execute your python script as a CGI. Instead of loading a static file, your web server will return the output of your python script.
This isn't very sophisticated, but if you are simply returning the output without needing browser submitted date, this is the easiest way (scaling under load is a different story).
You don't even need the "cgi" module from python, if you aren't receiving any data from the browser. Anything more complicated than this and you should use a web framework.
Examples and other methods
Simple Example: hardest part is webserver configuration
mod_python: Cut down on CGI overhead (otherwise, apache execs the python interpreter for each hit)
python module cgi: sending data to your python script from the browser.
Sorting
Javascript side sorting: I've used this javascript library to add sortable tables. This is the easiest way to add sorting without requiring additional work or another HTTP GET.
Instructions:
Download this file
Add to your HTML
Add class="sortable" to any table you'd like to make sortable
Click on the headers to sort
You might consider Tornado if Django is too much overhead. I've used both and agree that, if you have something simple/small to do and don't already know Django, it's going to exponentially increase your time to production. On the other hand, you can 'get' Tornado in a couple of hours and get something relatively simple done in a day or two with no prior experience with it. At least, that's been my experience with it.
Note that Tornado is still a tradeoff: you get a lot of simplicity in exchange for the huge cornucopia of features and shortcuts you get w/ Django.
PS - in addition to being a 'micro-framework', Tornado is also its own web server, so there's no mucking with wsgi/mod-cgi/fcgi.... just write your request handlers and run it. Be sure to see the demos included in the distribution.
Have you seen bottle framework? It is a micro framework and very simple.
If I correctly understood your requirements you might find Wooey very interesting.
Wooey is a A Django app that creates automatic web UIs for Python scripts:
http://wooey.readthedocs.org
Here you can check a demo:
https://wooey.herokuapp.com/
Django is a big webframework, meant to include loads of things becaus eyou often needs them, even though sometimes you don't.
Look at Pyramid, earlier known as BFG. It's much smaller.
http://pypi.python.org/pypi/pyramid/1.0a1
Other microframeworks to check out are here: http://wiki.python.org/moin/WebFrameworks
On the other hand, in this case it's probably also overkill. sounds like you can run the script once every ten minites, and write a static HTML file, and just use Apache.
If you are not willing to write your own tool, there is a pretty advanced tool for executing your scripts: http://rundeck.org/
It's pretty simple to start and can be configured for complex scenarios as well.
For the requirement of custom view (with sortable results), I believe you can implement a simple plugin for translating script output into html elements.
Also, for simple setups I could recommend my own tool: https://github.com/bugy/script-server. It doesn't have tons of features, but very easy for end-users and supports interactive execution.
If you don't need any input from the browser, this sounds like an almost-static webpage that just happens to change once a day. You'll only need some way to get html out of your script, in a place where your webserver can access it.)
So you'd use some form of templating; if you'll need some structure above the single page, there's static site / blog generators that you can feed your output in, say, Markdown format, and call their make html or the like.
You can use DicksonUI https://dicksonui.gitbook.io
DicksonUI is better
Or Remi gui(search in google)
DicksonUI is better.
I am the author of DicksonUI

Categories

Resources