问题
I'm trying to build a simple URL shortener in Python. Save the URLs is easy using a GET request (with the cgi.FieldStorage() method), something like:
http://example.com/shortener.py?url=http://otherwebsite.com/
But how could I get the entire URL when someone try to access the shortened address? Like:
http://example.com/urlcode
I need to deal with the URL as a string and extract only the "urlcode" after the slash.
Edit: I believe that the question was not explained very well. The problem is not parse the URL, is how do I get the URL some user typed or clicked into his browser? All the 404 error requests will be redirected to "index.py". Then I need to deal with what argument caused the 404 error and get the full URL associated to the shortened code.
The question is: how can I read the current URL inside the Python script?
回答1:
Save the url in a dictionary, where "urlcode" is the key and the url "http://otherwebsite.com/" is the value. Then, when the shortened url http://example.com/urlcode is accessed, lookup the url that has the key "urlcode" in the dictionary.
回答2:
Save the long URLs alongwith their shortened codes in a database and then every time you get a short code, just extract the corresponding long URL and redirect to that URL.
来源:https://stackoverflow.com/questions/7094027/python-url-parameters