Reputation: 1
I'm trying to modify an active URL in python. I'm able to modify the url of a hard-coded url within my existing code but I would like to modify the URL of the page on my apache server
For example if I'm on:
http://localhost/?foo=stackoverflow
I want my script to modify this to
http://localhost/?foo=Hello stackoverflow
A number of sources I've looked at regarding how to do this all have used hardcoded URLs. For reference here is my code on doing just that, with the modification I'm talking about.
#!"C:/PythonPath"
import cgi
import datetime
import time
def htmlTop():
print("""Content-type: text/html\n\n
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>My server template</title>
</head>
<body>""")
def htmlTail():
print("""</body>
</html>""")
if __name__ == "__main__":
try:
htmlTop()
current_time = str(datetime.datetime.now())
url = 'http://localhost/helloworld/?foo=bar'
print(url)
print("""<br></br>""")
url_array = url.split('?')
base_url = url_array[0] #'http://localhost/helloworld/?foo=bar'
params = url_array[1] # query parameters 'foo'
url_array2 = params.split("=") #['foo', 'bar']
# print through all key values
param_value_dict = {} # {'foo': 'bar'}
for i, str in enumerate(url_array2):
if i % 2 == 0:
param_value_dict[str] = url_array2[i + 1]
former_value = param_value_dict['foo'] # to store old value
param_value_dict['foo'] = 'Hello '+former_value+'! '+current_time
# form the new url from the dictonary
new_url = base_url + '?'
for param_name, param_value in param_value_dict.items():
new_url = new_url + param_name + "=" + param_value
print(new_url.replace("%20", " "))
htmlTail()
except:
cgi.print_exception()
Upvotes: 0
Views: 839
Reputation: 25664
I think you are making this harder than it needs to be.
import datetime
url = 'http://localhost/helloworld/?foo=bar'
url += ' ' + str(datetime.datetime.now())
print url.replace('=', '=Hello ').replace(' ', '%20')
Result
http://localhost/helloworld/?foo=Hello%20bar%202018-08-22 03:53:41.775949
Upvotes: 2