版权声明:本栏目下的所有文章均为个人学习笔记,部分内容为直接搬运,供学习分享。如有版权问题请联系作者删除。 https://blog.csdn.net/xiaozhenliu/article/details/84192910
Lesson 2: Making a Web Server
Note: this course was based on Python 2.7. The The BaseHTTPServer
module has been merged into http.server
in
Python 3.
Building a Server with HTTPBaseServer
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class webserverHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path.endswith("/hello"):
self.send_response(200)
self.send_header('Content-type', 'text.html')
self.end_headers()
output = ""
ouptut += "<html><body>Hello!</body></html>"
self.wfile.write(output)
print output
return
except IOError:
self.send_error(404, "File Not Found %s" & self.path)
def main():
try:
port = 8080
server = HTTPServer(('',port), webserverHandler)
print "Web server runningh on port %s" % port
server.serve_forever
except KeyboardInterrupt:
print "^C entered, stopping web server..."
server.socket.close()
if __name__== '__main__':
main()
Running a Web Server
python webserver.py
Port Forwarding
(open pages in our browser from the web server from out virtual machine as if they were being run locally)
https://github.com/udacity/fullstack-nanodegree-vm/blob/master/vagrant/Vagrantfile
Responding to Multiple GET Requests
https://github.com/udacity/Full-Stack-Foundations/blob/master/Lesson-2/hola-server/webserver.py
Adding POST to Web Server
def do_POST(self):
try:
self.send_response(301)
self.end_headers()
ctype.pdit = cgi.parse_header(self.headers.getheader('content-type'))
if ctype == 'multipart/form-data':
fields = cgi.parse_multipart(self.rfile, pdict)
messagecontent = fileds.get('message')
output = ""
output += "<html><body>"
output += "<h2> Okay, how about this: </h2>"
output += "<h1> %s </h1>" % messagecontent[0]
output += "<form method='POST' enctype='multipart/form-data' action='/hello'><h2>What would you like me to say?</h2><input name='message' type='text' ><input type='submit' value = 'Submit'> </form>"
output += "</body></html>"
self.wfile.write(output)
print output
except:
pass
Adding CRUD to our website
Objectives
- list out all restaurants
- add edit & delete linkes
- create new restaurants
- rename a restaurant
- delete a restaurant
Tasks
- opening http://localhost:8080/restaurants lists all the restaurant names in the database
- after the name of each database there is a link to edit and delete each restaurant
- there is a page to create new restaurant at http://localhost/8080/restaurants/new with a form for creating a new restaurant.
- Users can rename a restaurant by visiting http://localhost:8080/restaurant/id/edit
- clicking ‘delete’ takes a user to a confirmation page that then sends a post command to the database o delete the selected retaurant
Solutions
https://github.com/udacity/Full-Stack-Foundations/tree/master/Lesson-2