HTTP - mwicat/personal GitHub Wiki
curl --header "X-MyHeader: 123" www.google.com
from collections import Counter
import sys
from twisted.internet import reactor, endpoints
from twisted.python import log
from twisted.web import server, resource
PORT = 9999
cnt = Counter()
def combinedLogFormatter(timestamp, request):
client_id = '%s:%s' % (request.client.host, request.client.port)
msg = '%s: %s' % (client_id, cnt[client_id])
cnt[client_id] += 1
return msg
class Simple(resource.Resource):
isLeaf = True
def render_GET(self, request):
return "<html>Hello, world!</html>"
def render_POST(self, request):
return "<html>Hello, world!</html>"
site = server.Site(Simple(), logFormatter=combinedLogFormatter)
log.startLogging(sys.stdout)
endpoint = endpoints.TCP4ServerEndpoint(reactor, PORT)
endpoint.listen(site)
reactor.run()
sudo pip install flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return "Hello World!"
if __name__ == '__main__':
app.run()
import SimpleHTTPServer
import SocketServer
PORT = 9999
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def handle(self):
print 'new connection from', self.client_address
return SimpleHTTPServer.SimpleHTTPRequestHandler.handle(self)
def finish(self):
print 'closed connection from', self.client_address
print
return SimpleHTTPServer.SimpleHTTPRequestHandler.finish(self)
def do_GET(self):
request_path = self.path
print 'GET: ', request_path
print '>>>'
print(request_path)
print(self.headers)
print '<<<'
self.send_response(200)
self.send_header("Set-Cookie", "foo=bar")
def do_POST(self):
request_path = self.path
print 'POST: ', request_path
print '>>>'
request_headers = self.headers
content_length = request_headers.getheaders('content-length')
length = int(content_length[0]) if content_length else 0
print(request_headers)
data = self.rfile.read(length)
print repr(data)
print '<<<'
self.send_response(200)
SocketServer.TCPServer.allow_reuse_address = True
httpd = SocketServer.TCPServer(("", PORT), MyHandler)
print "serving at port", PORT
httpd.serve_forever()
import urllib2
def urlencode(s):
return urllib2.quote(s)
def urldecode(s):
return urllib2.unquote(s).decode('utf8')