Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Decode string ?
#1
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?
Reply
#2
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"
JohnnyCoffee likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  code decode, string, image ... teckow 2 2,067 Aug-20-2021, 07:02 PM
Last Post: teckow
  how to encode and decode same value absolut 2 2,361 Sep-08-2020, 09:46 AM
Last Post: TomToad
  struct.decode() and '\0' deanhystad 1 3,238 Apr-09-2020, 04:13 PM
Last Post: TomToad
  Print string after decode martinzeifang 1 1,838 Jan-02-2020, 10:16 AM
Last Post: buran
  Getting decode error. shankar 8 10,408 Sep-20-2019, 10:05 AM
Last Post: tinman
  how to decode UTF-8 in python 3 oco 3 37,435 Jun-05-2018, 11:05 AM
Last Post: wavic
  Ask help for utf-8 decode/encode forfan 12 10,885 Feb-25-2017, 02:04 AM
Last Post: forfan

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020