LPTHW Exercises 50-53
(12/19/13 -- 6:30pm EST)
Build your own Website
How does the Internet Work?

- Browsers make requests to a given url (http://enginehere.com/sample/)
- The URL is broken down into parts (protocol, hostname, and path)
- Hostname is converted into an IP address for a computer connected to the internet (server). The browser and server connect.
- The server runs a program to return the resource based on the path (/sample/ in this case). The program can be Python, Ruby, etc.
Internet Architecture Continued

The server program returns the resource at the given path as a response to the browser
The response is just a string (HTML, images, video, etc)
The browser renders this content on the screen
User input via web Forms
In our Python scripts, we often asked for user input
When websites want user input, they use forms
Forms submit data to servers via requests
GET vs. POST
Python Web Server
from some_fake_module import hit_db
from another_fake_module import render
def handle_hello(request):
greeting = request.POST.get("greet")
person = request.POST.get("person")
we_know_them = False
if person and greeting:
# hit database and confirm that we know this person
we_know_them = hit_db(person)
if we_know_them:
template = "my_template_name.html"
html = render(template, {"person": person, "greeting": greeting})
return html
else:
return "We do not know you"
Web Sessions
HTTP is stateless, meaning each request is independent
To keep track of users (i.e. facebook), we need to preserve state
We use a combination of Cookies and databases
Cookies are strings sent by servers to browsers (and vice versa) on each request and can be used to identify a user
Exercise 50: Build your own Website
# from the command line pip install the web server library
sudo pip install lpthw.web
import web
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
greeting = "Hello World"
return greeting
## If you run this module directly (python this_module.py), then run code block
if __name__ == "__main__":
app.run()
When you run this script, it will start a server at the address:
http://localhost:8080 (same as http://127.0.0.1:8080)
Exercises 51 - 53:
Finish these on your own
You have the knowledge to do it!
And wherever you come up short, dive deep with internet searches (Stack Overflow especially)
Next Steps (Deploy to the Cloud)
The final exercises tell you to set up Nginx or Apache
These are classic web servers that you can deploy to machines on the cloud (you've just run local servers so far)
These servers, in turn, run Django Ruby on Rails, Node.js, or other web frameworks
If you are adventurous, you can set this up on AWS
Or you can just use Heroku
LPTHW Exercises 50-53 (12/19/13 -- 6:30pm EST)
By benjaminplesser
LPTHW Exercises 50-53 (12/19/13 -- 6:30pm EST)
- 1,366