This is a method for quickly creating an HTTP server for a little operation check.
CallbackServer.py
#!/usr/bin/env python
import requests
from BaseHTTPServer import HTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler
import urlparse
def start(port, callback):
def handler(*args):
CallbackServer(callback, *args)
server = HTTPServer(('', int(port)), handler)
server.serve_forever()
class CallbackServer(BaseHTTPRequestHandler):
def __init__(self, callback, *args):
self.callback = callback
BaseHTTPRequestHandler.__init__(self, *args)
def do_GET(self):
parsed_path = urlparse.urlparse(self.path)
query = parsed_path.query
self.send_response(200)
self.end_headers()
result = self.callback(query)
message = '\r\n'.join(result)
self.wfile.write(message)
return
It defines a class that sets a callback function based on HTTPServer. Please install requests with pip etc.
How to use it is like this.
simple_test.py
#!/usr/bin/env python
# coding:utf-8
import sys
import CallbackServer
def callback_method(query):
return ['Hello', 'World!', 'with', query]
if __name__ == '__main__':
port = sys.argv[1]
CallbackServer.start(port, callback_method)
If you receive only the port number and pass the port number and the method (callback_method
) that will be called when there is HTTP access, the HTTP server will go up without permission.
callback_method
receives a GET query (behind the? In the URL) as an argument and returns the character string returned as Response with return.
If you return a list of character strings, it will be broken by CRLF without permission.
Start up
./simple_test.py 12345
After that, if you access http: // localhost: 12345 /? Hoge = 123
from your browser
Hello
World!
with
hoge=123
Is output.
Recommended Posts