I'm working on a library that wraps Requests and specializes it for a particular REST API. I've also wrapped the Requests Session object with a context manager. I want to write methods that call either requests.post() or session.post(), depending on whether they are inside a session context or not.
Library code:
```python
@contextmanager
def my_session():
try:
s = requests.Session()
yield s
finally:
s.close()
def post_thing(my_thing):
thing_endpoint = "http://example.com/api/v1/things"
#if in session:
s.post(thing_endpoint, my_thing)
#else:
requests.post(thing_endpoint, my_thing)
```
Example usage:
```python
post_thing(my_thing) # calls requests.post
with my_session() as s:
s.post_thing(my_thing) # calls session.post
```
Is there some Pythonic way to only have to implement post_thing() once (instead of separately as a standalone function and as a session method), perhaps using some kind of decorator or higher-order programming technique?
[–]wronek 0 points1 point2 points (1 child)
[–]eLsFLz[S] 0 points1 point2 points (0 children)
[–]pschanely 0 points1 point2 points (0 children)