Python backend with JS frontend [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm creating a Python-powered web framework aiming to make use of javascript as minimal as it possible. Need to make something lightweight like uilang to pass events to my Python code. I suppose that should be jQuery solution somehow pinging kind of observer object(?).
I have discovered some efforts to create pure-Python interface like Remi but still have no clue how should I reimplement it in my code.
Let's say I make a class like that:
class WebView():
def __init__(self, template, **callbacks):
"""
Callbacks are dict, {'object': callback}
"""
self.template = template
self.customJS = None
for obj, call in callbacks:
self.setCallback(obj, call)
def __call__():
"""
Here I return template
Assume {{customJS}} record in template, to be simple
"""
return bottle.template(self.template, customJS = self.customJS)
def setCallback(self, obj, call):
"""
Build custom js to insert
"""
self.customJS += ('<script ....%s ... %s' % (obj, call))
So, how could I make JS to pass an event from, say, pressing button back to my callback?
I understand that question might be on the edge of being too broad, but I'm solely trying to be as descriptive as possible because I really don't know JS at all.

Thing is you don't need javascript for a python web framework. You would be fine serving pages with flask or django without the single line of JS.
These pages would be pretty static with a few forms but would work perfectly.
Now if you want to have more dynamic content and interaction you'll probably need JS, and use XMLHttpRequests to asynchronously call your python backend on events. But in order to do so properly, you should start by learning JS.

You could probably do it with websockets too, however i don't think it's the best way. You can use websocket-python library on the python side, and on the website, you just send a websocket message on every button click callback.

Related

How can I change a part of my html page based on the response of an api [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Hello I have a website and it is currently running on a shared hosting package meaning I do not have the ability to run node.js on the server, however, I was wondering if I could use normal javascript to change a certain element on my page (Change a p element from Operational to Offline and it from green to red and back again when I receive the up command) I am using healthchecks.io to send either get or post requests to a URL when my monitor goes offline.
If I can't use receive requests from normal javascript how would I be able to change those tiny things on a website using something like Express? Whenever I look I just see the ability to serve static files or just Hello World or something. How could I serve an HTML file with all of its CSS and stuff while changing only one tiny thing?
Your question is very specific to your case and not in a wider context from which everyone could benefit.
The question you should ask for would be more like "how to update HTML code based on AJAX call" or something similar.
In any case I'll leave this answer here because I believe it can help you reach your goal.
I think theoretically what you are talking about are "ajax" (asynchronous JavaScript) requests.
You can use the callbacks from these requests, traditionally the "then" part to update your html code or update let's say CSS classes of an element.
Let's say you do something like :
fetch("http://example.com/movies.json")
.then((response) => response.json())
.then((data) => {
// you can console.log(data) here to see on the console, the structure of the received
// object from the API call
// this is just an example, based on the idea that the API would return a JSON object with
// a property named "online" which would be a boolean (true or false) value
if (data.online) { // if online is true add the CSS class "online"
document.getElementById("IdOfElementToUpdate").classList.add("online");
}else{ // if online is false or not there, remove the CSS class "online"
document.getElementById("IdOfElementToUpdate").classList.remove("online");
}
});
In this case you would have a default css style for the element (let's say for offline) , and then when the element gets added the class "online" you would have some CSS rules to override the default style.

Best way to integrate frontend and backend without ajax or api [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I wanna use php variable in frontend framework like Vue js.
What is the best way of integration frontend and backend framework?
This is my idea, but i think there are better way to do this.
<script id = "data" >
let $user = <?= json_encode($user) ?>
</script >
Some content...
<script >
new Vue({
data: {
user: $user
},
mounted() {
$("#data"). remove ()
}
})
While 'simplicity' is wonderful, 'functionality' is also pretty critical...
Sometimes you can get by with your type of coding (use it for some things that come into the PHP file that are needed to load the page, for example), and what you have may work for this particular situation (and, no, there isn't any way I can see to make it "better"...), though most pages will need more data that is 'fluid', and you will quickly run out of projects where you can write only 'simple' code.
Learn to use ajax (it is pretty simple once you get the hang of it) and copy/paste from your own 'library' (save snippets in a place you remember - you will find MANY things you want to keep... - I keep a 'functions.php' file and over the years it has grown pretty large with great bits-n-pieces.)
Since you are using jQuery already, here's one way to do ajax... (there are others, again, study and find the way you like...)
var url = "https://theURLtoMyAjax.phpPage";
var elements = "theStuff=thatIwantToSend&someMore=somethingElse"; // this is like writing everything in the address bar - again, there are other ways...)
$.post(url, elements, function (data) {
// do all kinds of wonderful things in here!
// the 'data' is what is returned from your call, so you can use it to update data on the page, etc.
});
So, as you can see, only a couple lines of code to add Ajax and tons of things you can do once you do it, so learn it - and use it!
Happy coding!

How many ajax files should I have? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm starting out php.
I'm wondering how many ajax files should I have. Should I have a seperate one for each operation I want to do? each query insert etc,
Or do I like send something in the data, or maybe request that ID's the request so that the server knows what to do?
Is there a good example for that?
I don't know if it matters but I'm using jQuery.
To answer your question, I personally like having as many files as possible (with fewer lines of code), but keeping related functions groupped in an object inside the same file.
For example, you could have one file called userAjax.js which contains the userAjax object:
var userAjax = {
getUserLevel : function (userId) {
$.get // blah, blah, or any ajax request
},
setUsername : function (userId, username) {
$.get // blah, blah, or any ajax request
}
};
In your app you could then use (after including the userAjax.js):
userAjax.setUsername(37, "John");
I like using this method because it keeps code structured, you do not have too much code for too little functionality. I use it in small to medium sized projects and works great :) (both for production & maintanance).
For the server-side, you could either do the same thing, or simply have a file for each command. I also like file-per-command method because if you structure your files in folders it's very easy to maintain the code (you can go directly to the function you want by navigating through the file tree). But again, for larger projects I think you should use a more OOP-approach, like having a class with many functions in a single file.
To sum it up, it all depends, mostly based on the size of the project.
Well, you can create functions for all operations what you want to do, and handle this functions with one file. Or you can create as many as want files for handling requests. If you are using some framework built on MVC architecture, you will probably use only one file (Controller) or more functions in more controllers, it is really variable, depending on usage.
There is lot of tutorials how to use PHP with AJAX. You just need only search for them.

How to make python invoke a JavaScript function? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am rather new at this, so please cut me some slack.
I am working in a web application using google app engine. My server runs using Python, and when the user visits my "/" page, the server gets some HTML source code from a website and places it into a variable called html_code.
Now I would like to pass the html_code variable to the client so he can analyze it using JavaScript. Is this possible? How can I achieve this? Please provide examples if possible.
Thanks in advance, Pedro.
I assume you want to send a piece of html to a browser that won't disrupt the existing layout and functioning of the page, but still take place in DOM (hence be accessible from JS). In that case you may consider a hidden/invisible iframe.
Note, the following is very very quick and dirty way of getting something to the client side.
Based upon https://developers.google.com/appengine/docs/python/gettingstartedpython27/introduction the following makes use of webapp2 and jinja2. "html_code" would be available for usage within a file named index.html. How you render / surface the fetched document is up to you, but as has been previously mentioned an iframe would probably work well in this situation.
import os
from google.appengine.api import urlfetch
import webapp2
import jinja2
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'])
class MainHandler(webapp2.RequestHandler):
def get(self):
html_code = urlfetch.fetch('http://stackoverflow.com/questions/18936253/how-to-make-python-invoke-a-javascript-function')
template_values = {
'html_code': html_code.content
}
template = JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(template_values))
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)

console-like interface on a web page using javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I very like MySQLs mysql cli tool and I don't like phpMyAdmin.
[IMHO]It's a nice thing for a Windows user, but its not so good when you've used to console.[/IMHO].
What I want is to build a web page containing element with console-like input (for example something like this) which should get input from user, send it to PHP script on back-end and show back-end response.
Back-end script is done (it was the easiest part), but I can't find any library for JavaScript implementing console-like input.
I've tried to examine and modify for my needs example I've provided, but it's too bloated (because doesn't use any libraries) and implements specific thing. Also I would like this element to provide some auto-completion for input.
Any ideas on such JS library?
I think you are looking for this: jQueryTerminal
there is shellinabox - javascript terminal.
EDIT:
There is also library xterm.js that's real terminal emulator.
EDIT 2:
My jQuery Terminal library is useful when you need custom behavior and you can write your code in JS or as backend code, but backend need to be simple input -> output, if you want to run for instance interactive backend commands, like vi or emacs, you need proper tty, for this use xterm.js (or implement that in JavaScript) for any other usage jQuery Terminal is better. It have lot of features and you don't need to run process on the server (listen on a port) which usually is forbidden on shared hostings or GitHub pages.
instead of using console.log() use document.write()
It will write text on the webpage just like console.log would in the console
I've made a console library called Simple Console (I'll probably rename it because simple-console is taken on npm)
It handles command history and such for you, and you can use it to implement any kind of console.
var handleCommand = (command)=> {
var req = new XMLHttpRequest();
req.addEventListener("load", ()=> {
con.log(req.responseText);
// TODO: use con.error for errors and con.warn for warnings
// TODO: maybe log a table element to display rows of data
});
// TODO: actually pass the command to the server
req.open("GET", "mysql.php");
req.send();
};
var con = new SimpleConsole({
handleCommand,
placeholder: "Enter MySQL queries",
storageID: "mysql-console"
});
document.body.appendChild(con.element);
Check out the documentation on GitHub for more information.
hmm firebug console ?
http://getfirebug.com/commandline

Categories

Resources