Skip to content

Instantly share code, notes, and snippets.

@puppybits
Last active December 14, 2015 19:39
Show Gist options
  • Save puppybits/5138656 to your computer and use it in GitHub Desktop.
Save puppybits/5138656 to your computer and use it in GitHub Desktop.
HTTP Quickstart

Understand HTTP w/ AJAX in 15 minutes

Setup

Install pip:

curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python

Install bottle:

sudo pip install bottle

Server

Create a file called "app.py" (anywhere you like) and include this code:

import bottle
bottle.debug(True)
import sys, os, datetime
from bottle import route, get, post, put, delete, request, response, run, static_file, abort

@route('')
@route('/index.html')
def launch():
    return static_file('index.html', root='')


@get('/devices')
def read_devices():
    return {'name':'myiPad', 'uuid':1, 'model':'ipad 2 white', 'os':5.1}

# http://bottlepy.org/docs/dev/tutorial.html#quickstart-hello-world
run(host="0.0.0.0", reloader=True)

Run the server:

python app.py

To pull the data into a browser with javascript, create a file called "index.html" and include this:

<html>
<body></body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script type="application/javascript">
    // http://api.jquery.com/jQuery.ajax/
    $.ajax({
           url: '/devices',
           dataType: 'json',
          type: 'GET',
           success: function(json, status, xhr)
          {
              document.body.innerHTML = JSON.stringify(json);
          },
          error: function(xhr)
          {
              document.body.innerHTML = JSON.stringify(xhr);
          }
          });

</script>
</html>

Open a web browser and go to http://127.0.0.1:8080/index.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment