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)
Related
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 2 years ago.
Improve this question
I'm creating a website where live editing of code (for Java, c,python,javascript ect) is required. I'm aware of codemirror and I want to know how to run code on a website (like W3Schools try it yourself feature) and locally run instead of requiring server infrastructure
For front-end, it's pretty easy to emulate the basics of how Stack Snippets work here on Stack Exchange. The general idea is to create textareas for the different sections (HTML/JS/CSS), then when you want to render it, create an iframe whose content is created by inserting the textarea values:
const [button, html, css, javascript, iframe] = document.querySelectorAll('button, textarea, iframe');
button.addEventListener('click', () => {
const fullHTML = `
<!doctype html><html>
<head><style>${css.value}</style></head>
<body>${html.value}<script>${javascript.value}<\/script></body>
</html>`;
iframe.src = 'data:text/html,' + encodeURIComponent(fullHTML);
});
textarea {
display: block;
}
<button>Run</button>
<textarea><span id="span">a span</span></textarea>
<textarea>span { color: green; }</textarea>
<textarea>span.onclick = () => span.style.color = 'yellow';</textarea>
<iframe sandbox="allow-scripts"></iframe>
The above is tweaked from an example from Kaiido on Meta.
This isn't exactly how Stack Snippets work - they do require a backend to take the form values and construct the HTML response the browser sees - but it's pretty similar.
For anything other than the front-end, it's a lot more complicated - you'll have to retrieve the source text the user has written, send a request to a server to run it in the correct language, then send the request back to the client and render it. For anything that a browser can't run natively already, there's no way around having "server infrastructure" to process and run code.
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 4 years ago.
Improve this question
I found this website with some interesting data I wish to analyze. But the page is really slow and build around .docx files. But it has a preview of each document in HTML
http://www.produktresume.dk/AppBuilder/search?page=0
My current idea for a strategy is:
Wait for the page to load (haven't tried this before)
Dig into the div class="widget_inside"
Grab all the href in <a class="preview_link"
Iterate over all the collected links and parse the HTML into some .json/.csv for later analysis
I'm pretty new when it comes to scraping, and had previously some luck with BeautifulSoup in Python - with a page that don't have a loading. But I have been using nodejs lately, so would prefer to be able to do it in JS with some npm package.
Anybody who can help me out finding the right tools for the job and some pointers/comments on the best strategy?
Bonus info
By decoding one of the filter links to the left this comes up:
http://www.produktresume.dk/AppBuilder/search?expand_all=true&page=0&refinements_token={}&selected_tokens[]={"s":[{"id":"folder-refinement","xPath":"$folders","separator":"\u003e","logic":"OR","s":[{"n":"Human","k":"Human"}]}]}
Don't know if that would be of any use?
so would prefer to be able to do it in JS with some npm package
Although I used Python, this answer shows a very simple and synchronous (slow!) way of grabbing all of those preview links. It took about 1 hour and 15 minutes to go through all 757 pages.
I wasn't sure how exactly you wanted to save the information in each of those preview links so I left that part to you. It would also be trivial to modify this script to simply download all of those .docx files instead of just grabbing the preview links.
import json
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import (
NoSuchElementException,
WebDriverException
)
base_url = 'http://www.produktresume.dk'
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get('{}/AppBuilder/search'.format(base_url))
result = []
while True:
soup = BeautifulSoup(driver.page_source, 'lxml')
preview_links = [base_url + link['href']
for link in soup.find_all('a', class_='preview_link')]
result.extend(preview_links)
try:
element = driver.find_element_by_link_text('Næste')
element.click()
except (NoSuchElementException, WebDriverException):
break
driver.quit()
with open('preview_links.json', 'w') as f:
json.dump(result, f, indent=2)
preview_links.json
https://bpaste.net/show/b597d6910f18
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.
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 7 years ago.
Improve this question
Edited
I've reworded this question as it has been marked as too broad.
I'm using razor engine to create strongly typed email templates and I'd like to find the height of a particular table cell within the generated HTML.
I'm generating the HTML like this
var templateService = new TemplateService();
var emailHtmlBody = templateService.Parse(File.ReadAllText(template.TemplateFilePath), template, null, null);
This creates a string of the html, is there anyway of determining the height (which is dynamic) of a particular html element using mvc or the razor engine or do I need to use a rendering engine to first render the html and then use a technique like a JavaScript query to get the value.
I'm running this in a WCF application so the rendering engine needs to be headless - the standard .net browser control will not work.
I've had success with third party libraries (see my proposed answer), is there a better way to do this without the use of these?
This depands on where you will use the height really. If you need it withing the page, you can always use JavaScript. One way to do this would be to give your table an id attribute and use a simple JavaScript function to determine the height of that table. This function can reside at the end of your layout page.
<script>
var tableHeight = 0;
$( document ).ready(function() {
tableHeight = document.getElementById('tableId').style.offsetheight;
});
</script>
You can access tableHeight in any javascript code globally afterwards. If, on the other hand, you need to use this on the serverside code, then you need to assign it to an input variable that you host in your model and retreive it in an [HttpPost] action method.
The easiest way I've found of doing this is to parse the view, save the generated html (with the required JavaScript) to a web server (or locally, ymmv), then load the page in a headless browser like SimpleBrowser.WebDriver (Alternatives awesomium or webkit.net - apparently you can run these in a headless mode) and then return the rendered html giving you the values you required from the js script.
I'll mark this as the answer, I'd be interested if there are any simpler approaches though.
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.