Python Forum
Decode string ? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Decode string ? (/thread-39158.html)



Decode string ? - JohnnyCoffee - Jan-11-2023

Simulating a direct http request in the browser address bar for the module (wsgiref), with the following url:

( OvO ) - Http Request :

http://127.0.0.1:8000/'session':'meLNaJb6kdYDjOHRzBdQzAjRArmpEi2r3PWVy0ujUZ4','user':1
( OvO ) - Code Python, module wsgiref :

from wsgiref.simple_server import make_server
# Native Module : wsgiref.static -> ( https://docs.python.org/3/library/wsgiref.html#module-wsgiref.util )
from wsgiref.util import request_uri
# Native Module : urlparse -> ( https://docs.python.org/3/library/urllib.parse.html#module-urllib.parse )
from urllib.parse import urlparse


def wsgirun(environ, start_response):

    # Syntax Objective : Get request uri
    g_uri = request_uri( environ, include_query=True )
    # Syntax Objective : Prepare to handle uri
    h_uri = urlparse( g_uri )
    # Syntax Objective : Get path request
    g_path = h_uri.path
    # Syntax Objective : Assign within an array
    a_path = g_path.split('/')[1]

    status = "200 OK"
    headers = [("Content-type", "text/plain; charset=utf-8")]  
    start_response(status, headers)
    return[str(a_path).encode('utf-8')]

with make_server("", 8000, wsgirun) as httpd:

    print(
        'Running : Test Code\n'
        'Browser Access - http://127.0.0.1:8000\n'
        'Crl+c for pause command or Crl+z for stop'
    )
    # Serve until process is killed
    httpd.serve_forever()
( OvO ) - Http Response, output :

%27session%27%3A%27meLNaJb6kdYDjOHRzBdQzAjRArmpEi2r3PWVy0ujUZ4%27,%27user%27%3A1
( OvO ) - Question :

Why do I get the string with encoded characters ( %27, %27%3A%27, %27%3A1 ) and how can I decode it to the original string of the http request?


RE: Decode string ? - bowlofred - Jan-11-2023

These are URL escape codes. Try using urllib.parse.unquote.

>>> import urllib
>>> s
'%27session%27%3A%27meLNaJb6kdYDjOHRzBdQzAjRArmpEi2r3PWVy0ujUZ4%27,%27user%27%3A1'
>>> urllib.parse.unquote(s)
"'session':'meLNaJb6kdYDjOHRzBdQzAjRArmpEi2r3PWVy0ujUZ4','user':1"