1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- #! /usr/bin/env python2
- # -*- coding: utf8 -*-
- import os
- def application(environ, start_response):
- parameters_list = environ['QUERY_STRING'].split("&")
- param_value = {}
- for item in parameters_list:
- param, value = item.split("=")
- param_value[param] = value
- ipv4_file_path = os.path.join(environ['DOCUMENT_ROOT'], "tmp/ipv4_address")
- ipv6_file_path = os.path.join(environ['DOCUMENT_ROOT'], "tmp/ipv6_address")
- try:
- file_v4 = open(ipv4_file_path, "r")
- file_v6 = open(ipv6_file_path, "r")
- except IOError:
- old_ipv4 = ""
- old_ipv6 = ""
- else:
- old_ipv4 = file_v4.readline()
- old_ipv6 = file_v6.readline()
- file_v4.close()
- file_v6.close()
- try:
- new_ipv4 = param_value["ipv4"]
- except KeyError:
- new_ipv4 = ""
- try:
- new_ipv6 = param_value["ipv6"]
- except KeyError:
- new_ipv6 = ""
- response_status = "200 IP didn't change"
- response_body = ""
- error = False
- if new_ipv4 == "" and new_ipv6 == "":
- # TODO: maybe implement some checking if it is a correct IPv4
- # address here
- response_status = "400 Bad Request"
- response_body = "The IP address you defined was empty or " \
- "invalid."
- else:
- if new_ipv4 != old_ipv4 and new_ipv4 != "":
- try:
- file = open(ipv4_file_path, "w")
- except IOError:
- error = True
- else:
- file.write(param_value['ipv4'])
- file.close()
- response_status = "200 OK"
- response_body = "The new IP address has been saved, thanks " \
- "and have a nice day!"
- if new_ipv6 != old_ipv6 and new_ipv6 != "":
- try:
- file = open(ipv6_file_path, "w")
- except IOError:
- error = True
- else:
- file.write(param_value["ipv6"])
- file.close()
- response_status = "200 OK"
- response_body = "The new IP address has been saved, thanks " \
- "and have a nice day!"
- if error is True:
- response_status = "503 Internal server error"
- response_body = "There has been an error serving your request."
- response_headers = [('Content-Type', 'text/plain'),
- ('Content-Length',
- str(len(response_body.encode('utf8'))))]
- start_response(response_status, response_headers)
- return [response_body.encode('utf8')]
|