1

how can i convert:

GET / HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

to something like

_dict = {
"REQUEST": "/",
"HOST": "localhost",
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": 1,
"GET":"",
"POST":""}

how could i do this with python 3. I don't want to just make a request to a website I want to convert this text to a dictionary.

2 Answers 2

1

you can use the requests module

import requests

r = requests.get("https://www.google.com")
print(r.headers) # returns all the headers in dictionary form

** EDIT **

So since he wants to spit those requests which is string from his created server.
Here is the new code:

request = """GET / HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1""".split('\n')

reqs = {}

for x in request:
    if "GET" in x:
        method, path, http = x.split(" ")
        reqs["REQUESTS"] = path
    else:
        key, val = x.split(": ")
        reqs[key] = val

NOTE
You can make a list for the http methods (so that it didn't only work on GET) and make a 'for in' range for checking if that http method is in the request

Sign up to request clarification or add additional context in comments.

4 Comments

i don't want to make a request. I want to convert a request to a dict
you don't want to make a request but you want to convert a request to a dict? what?
I'm creating a webserver i need to handle the browser request so i need to convert the request to dictionary so i can use the data.
How would i get the get data from the url like /?data=ps&data1=ps1
1

Checkout the following link. Its another Stackoverflow post, which should help you out :D

HTTP requests and JSON parsing in Python

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.