Skip to content

Commit

Permalink
python-magic is optional (#13)
Browse files Browse the repository at this point in the history
* Update README.md

* variable need not have to be defined first time
  • Loading branch information
cedric05 authored Feb 28, 2021
1 parent 376a77e commit 3296f94
Show file tree
Hide file tree
Showing 7 changed files with 40 additions and 10 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ data({
### From pypi

```shell
pip install dothttp==0.0.4
pip install dothttp-req==0.0.5
```

### From source
Expand Down
33 changes: 26 additions & 7 deletions dothttp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from collections import defaultdict
from dataclasses import dataclass, field
from http.cookiejar import LWPCookieJar
from typing import Union, Dict, List, DefaultDict
from typing import Union, Dict, List, DefaultDict, Optional

import jstyleson as json
import magic
Expand Down Expand Up @@ -215,11 +215,12 @@ def validate_n_gen(prop, cache: Dict[str, Property]):
# like ranga=" ramprasad" --> we should replace with " ramprasad"
value = value[1:-1]
if key in cache:
if value != cache[key].value:
if cache[key].value and value != cache[key].value:
raise HttpFileException(
message=f'property: `{key}` is defaulted with two/more different values, panicked ')
p = cache[key]
p.text.append(prop)
p.value = value
else:
p = Property([prop], key, value)
cache.setdefault(key, p)
Expand Down Expand Up @@ -362,7 +363,7 @@ def get_payload(self):
if not self.http.payload:
return Payload()
elif data := self.http.payload.data:
mimetype = self.http.payload.type if self.http.payload.type else magic.from_buffer(data, mime=True)
mimetype = self.get_mimetype_from_buffer(data, self.http.payload.type)
request_logger.debug(
f'payload for request is `{data}`')
return Payload(data, header=mimetype)
Expand All @@ -378,7 +379,7 @@ def get_payload(self):
request_logger.debug(
f'payload file `{filename}` Not found. ')
raise DataFileNotFoundException(datafile=filename)
mimetype = self.http.payload.type if self.http.payload.type else magic.from_file(filename, mime=True)
mimetype = self.get_mimetype_from_file(filename, self.http.payload.type)
with open(filename, 'rb') as f:
return Payload(data=f.read(), header=mimetype)
elif json_data := self.http.payload.json:
Expand All @@ -392,15 +393,33 @@ def get_payload(self):
if os.path.exists(filetype.path): # probably check valid path, then check for exists
content = open(filetype.path, 'rb')
filename = os.path.basename(filetype.path)
if not mimetype: mimetype = magic.from_file(filetype.path, mime=True)
mimetype = self.get_mimetype_from_file(filetype.path, mimetype)
files[filetype.name] = (filename, content, mimetype)
else:
if not mimetype:
mimetype = magic.from_buffer(filetype.path, mime=True)
mimetype = self.get_mimetype_from_buffer(content, mimetype)
files[filetype.name] = (None, content, mimetype)
return Payload(files=files)
return Payload()

@staticmethod
def get_mimetype_from_file(filename, mimetype: Optional[str]) -> Optional[str]:
if mimetype:
return mimetype
if magic:
return magic.from_file(filename, mime=True)
else:
return None

@staticmethod
def get_mimetype_from_buffer(data, mimetype: Optional[str]) -> Optional[str]:
if mimetype:
return mimetype
else:
if magic:
return magic.from_buffer(data, mime=True)
else:
return None

def get_output(self):
if output := self.http.output:
print(f'output will be written to `{os.path.abspath(output.output)}`')
Expand Down
2 changes: 1 addition & 1 deletion dothttp/parse_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class Payload:
file: Optional[str]
json: Optional
fileswrap: FilesWrap
type: str
type: Optional[str]


@dataclass
Expand Down
4 changes: 4 additions & 0 deletions examples/.dothttp.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,9 @@
},
"headers": {
"x-requested-by": "dothttp"
},
"diff": {
// instead of adam
"name": "prasanth"
}
}
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def requirements():

setup(
name="dothttp_req",
version="0.0.4",
version="0.0.5",
author="prasanth",
author_email="[email protected]",
description=("DotHttp recommended tool for making http requests."),
Expand Down
2 changes: 2 additions & 0 deletions test/core/substitution/definevariableonsecond.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
POST https://{{first_not_defined}}
data("{{first_not_defined=dothttp.dev}}")
5 changes: 5 additions & 0 deletions test/core/test_substition.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ def test_substitution_infile_with_multiple_suages(self):
self.assertEquals("https://google.com/", req.url)
self.assertEquals(b'{"google.com": "google.com"}', req.body)

def test_define_on_second_occurence(self):
req: PreparedRequest = self.get_request(f"{base_dir}/definevariableonsecond.http")
self.assertEquals("https://dothttp.dev/", req.url)
self.assertEquals('dothttp.dev', req.body)

def test_substitution_preference(self):
## command line > env (last env > first env) > infile
req: PreparedRequest = self.get_request(f"{base_dir}/simpleinfile.http", prop=f"{base_dir}/simepleinfile.json")
Expand Down

0 comments on commit 3296f94

Please sign in to comment.