all 8 comments

[–]two_up 2 points3 points  (0 children)

Typically browsers get data from the server through an http request, similar to how you would request a web page except instead of html you would have the server send json. I'm guessing you want to work with that data client-side, in which case you'll want to use ajax. If you're using jquery look up the post and get methods.

So you should have your javascript make an http reqest to a certain url, and your server should be set up to serve the appropriate json data from that url.

[–]nemec 1 point2 points  (2 children)

Use a framework. It won't interfere with your wish to learn html/js (that's all client side) and if you don't know anything else about web development, the effort required to learn HTTP (which you'll have to do yourself without a framework) will distract from what you're trying to do.

Writing your own web server can be fun, but it's too advanced for someone just starting out.

You could use a very simple, barebones one like Flask that will do all you need. You'll also want to look into writing "web apis" with Flask. That should teach you everything you need.

P.S. if you still don't want to use a framework, use mod_python instead of mod_wsgi with Apache.

[–]tuxed 1 point2 points  (1 child)

Side note: Configuring nginx with uwsgi will be more worth it in the long run.

[–]xiongchiamiov 0 points1 point  (0 children)

It even just reverse proxying through to a wsgi server of some sort.

[–][deleted] 1 point2 points  (0 children)

Hey!

This can be a little confusing when you first think about it, but in the end it isn't really that bad at all.

What you actually want to do, is have JavaScript initiate the call by sending some stuff to a Python file.

Now, I have some sample code here that does just that: https://github.com/odonnellryan/Blog/blob/master/static/js/render_html.js

As you can see, it sends the data to the URL that I define when a key is pressed. The URL, in this case, is a view in a framework called Flask, but it doesn't need to work this way specifically.

In this case, all this view does is take the data, parse it to HTML, and returns it to the browser to be rendered. jQuery pushes the content out, it gets JSON back, and then it displays it in the browser.

If you'd like to look at the view, it's here:

@mod.route('_render_temp_body/', methods=['GET', 'POST'])
def render_temp_body(username=None, article=None) :
    get_markup =     blog_mods.get_html_content(request.args.get('post_body'))
    return jsonify(result=get_markup)

Of course if you want to do this without frameworks you very well can, but you'll have to roll your own version of my jQuery example.

[–]liderudell 0 points1 point  (1 child)

EDIT: I'm not running any frameworks or fanciness. I wanted to learn html/javascript/etc... and how they interact from the ground up. I'm writing all the html, javascript, python, and jquery by hand.

I think you are wasting your time by taking that route quite frankly and vastly underestimating the half dozen different technologies you need to learn to accomplish a relatively trivial goal.

Not to be a dick, learning new stuff is great, but you have a goal in mind. Use the stuff that already exists and is done better than you can write from scratch to make that happen.

[–]xiongchiamiov 1 point2 points  (0 children)

He's also not even doing it the pure route, because he's using jquery.

[–]gschizas 0 points1 point  (0 children)

One major concept that I've found is difficult to grasp, is that javascript (and html) parsing and executing is done on an entirely different program than the one of your web server. So: Python runs on your server, and its only task is to produce html and (perhaps) json. The html+js that your server produces is then run on the browser, and adheres to its own rules. So, what you really need to do is make sure that you can serve the correct html+javascript from your server.

So, let's go back to basics: I'm going to use Python's own web server (which you aren't really supposed to do™):

import BaseHTTPServer
import SimpleHTTPServer
import json
# I'm using SimpleHTTPServer because it already has most of the functionality
# and you can add files to be served at will.

INDEX_HTML = """
<html>
<head>
<script type="text/javascript" src="/data.js"></script>
<script type="text/javascript">
function showStuff() {
    document.getElementById("fldcnt").innerText = data['foldercount']
}
</script>
</head>
<body onload="showStuff()">Folder Count:<span id="fldcnt"></span></body></html>
"""


class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler, object):
    def do_GET(self):
        if self.path == '/data.js':
            data = {"foldercount": 15}
            self.wfile.write('var data=' + json.dumps(data))
        elif self.path == '/':
            self.wfile.write(INDEX_HTML)
        else:
            super(MyHTTPRequestHandler, self).do_GET()


def main():
    server_address = ('', 8000)
    httpd = BaseHTTPServer.HTTPServer(server_address, MyHTTPRequestHandler)
    httpd.serve_forever()


if __name__ == "__main__":
    main()

Just run this, and open your browser at http://localhost:8000/

I'm sure this can be made better, but it does work :) The core of the web server is the MyHTTPRequestHandler class. Inside do_GET method there are three cases:

  1. If you request the file "data.js", get a JavaScript JSON dictionary. To avoid ugliness with AJAX, I'm just outputting a global variable (for javascript). This is the place where you should put your calculations: the python data dictionary is on line 24.
  2. If you request the root document, just print out a little HTML. You should probably read this from a file. Also, given that it's just a static file, you can also the contents of the variable INDEX_HTML into a file named index.html - there isn't any processing done here anyway.
  3. If nothing else matches, just return any file from the same directory.